code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
import sessionStore from '@/stores/sessionStore' import { createRouter, createWebHistory } from 'vue-router' import settingsStore from './stores/settingsStore' const routes = [ { path: '/setup', name: 'Setup', component: () => import('@/setup/Setup.vue'), meta: { hideSidebar: true, }, }, { path: '/login', name: 'Login', component: () => import('@/pages/Login.vue'), meta: { hideSidebar: true, isGuestView: true, }, }, { path: '/', name: 'Home', component: () => import('@/home/Home.vue'), }, { path: '/dashboard', name: 'Dashboards', component: () => import('@/dashboard/DashboardList.vue'), }, { props: true, name: 'Dashboard', path: '/dashboard/:name', component: () => import('@/dashboard/Dashboard.vue'), }, { props: true, name: 'PublicDashboard', path: '/public/dashboard/:public_key', component: () => import('@/dashboard/PublicDashboard.vue'), meta: { hideSidebar: true, isGuestView: true, }, }, { props: true, name: 'PublicChart', path: '/public/chart/:public_key', component: () => import('@/query/PublicChart.vue'), meta: { hideSidebar: true, isGuestView: true, }, }, { path: '/data-source', name: 'DataSourceList', component: () => import('@/datasource/DataSourceList.vue'), }, { props: true, name: 'DataSource', path: '/data-source/:name', component: () => import('@/datasource/DataSource.vue'), }, { props: true, name: 'DataSourceRelationships', path: '/data-source/:name/relationships', component: () => import('@/datasource/DataSourceRelationships.vue'), }, { props: true, name: 'DataSourceTable', path: '/data-source/:name/:table', component: () => import('@/datasource/DataSourceTable.vue'), }, { path: '/query', name: 'QueryList', component: () => import('@/query/QueryList.vue'), }, { props: true, name: 'Query', path: '/query/build/:name', component: () => import('@/query/Query.vue'), }, { path: '/users', name: 'Users', component: () => import('@/pages/Users.vue'), meta: { isAllowed(): boolean { return sessionStore().user.is_admin && settingsStore().settings.enable_permissions }, }, }, { path: '/teams', name: 'Teams', component: () => import('@/pages/Teams.vue'), meta: { isAllowed(): boolean { return sessionStore().user.is_admin && settingsStore().settings.enable_permissions }, }, }, { path: '/notebook', name: 'NotebookList', component: () => import('@/notebook/NotebookList.vue'), }, { props: true, path: '/notebook/:notebook', name: 'Notebook', component: () => import('@/notebook/Notebook.vue'), }, { props: true, path: '/notebook/:notebook/:name', name: 'NotebookPage', component: () => import('@/notebook/NotebookPage.vue'), }, { path: '/settings', name: 'Settings', component: () => import('@/pages/Settings.vue'), }, { path: '/no-permission', name: 'No Permission', component: () => import('@/pages/NoPermission.vue'), meta: { hideSidebar: true, }, }, { path: '/trial-expired', name: 'Trial Expired', component: () => import('@/pages/TrialExpired.vue'), meta: { hideSidebar: true, }, }, { path: '/:pathMatch(.*)*', name: 'Not Found', component: () => import('@/pages/NotFound.vue'), meta: { hideSidebar: true, }, }, ] let router = createRouter({ history: createWebHistory('/insights_v2'), routes, }) router.beforeEach(async (to, _, next) => { const session = sessionStore() !session.initialized && (await session.initialize()) if (to.meta.isGuestView && !session.isLoggedIn && to.name !== 'Login') { // if page is allowed for guest, and is not login page, allow return next() } // route to login page if not logged in if (!session.isLoggedIn) { // if in dev mode, open login page if (import.meta.env.DEV) { return to.fullPath === '/login' ? next() : next('/login') } // redirect to frappe login page, for oauth and signup window.location.href = '/login' return next(false) } if (!session.isAuthorized && to.name !== 'No Permission') { return next('/no-permission') } if (session.isAuthorized && to.name === 'No Permission') { return next() } if (to.meta.isAllowed && !to.meta.isAllowed()) { return next('/no-permission') } const settings = settingsStore() if (!settings.initialized) { await settings.initialize() } // redirect to /setup if setup is not complete const setupComplete = settings.settings.setup_complete if (!setupComplete && to.name !== 'Setup') { return next('/setup') } // redirect to / if setup is complete and user is on /setup if (setupComplete && to.name === 'Setup') { return next('/') } to.path === '/login' ? next('/') : next() }) router.afterEach((to, from) => { const TRACKED_RECORDS = ['Query', 'Dashboard', 'NotebookPage'] const toName = to.name as string if ( TRACKED_RECORDS.includes(toName) && toName !== from.name && to.params.name !== from.params.name ) { sessionStore().createViewLog(toName, to.params.name as string) } }) const _fetch = window.fetch window.fetch = async function () { const res = await _fetch(...arguments) if (res.status === 403 && (!document.cookie || document.cookie.includes('user_id=Guest'))) { sessionStore().resetSession() router.push('/login') } return res } export default router
2302_79757062/insights
frontend/src/router.ts
TypeScript
agpl-3.0
5,348
<script setup> import settingsStore from '@/stores/settingsStore' import { computed, markRaw, provide, reactive, ref } from 'vue' import SetupQuestions from './SetupQuestions.vue' import SourceConnectionStep from './SourceConnectionStep.vue' import SourceTypeStep from './SourceTypeStep.vue' import { useRouter } from 'vue-router' const setupState = reactive({ sourceType: null, // 'erpnext', 'mariadb', 'postgresql', 'file', 'sample' }) provide('setupState', setupState) const titleBySourceType = { erpnext: 'Setup ERPNext', mariadb: 'Setup MariaDB', postgresql: 'Setup PostgreSQL', file: 'Setup Spreadsheet', sample: 'Select Sample Dataset', } const descriptionBySourceType = { erpnext: 'Insights is already connected to your ERPNext site. You can optionally give a title to your site to help you identify it as a data source.', mariadb: 'You need to enter your MariaDB database details to connect to your database. If you are not sure about your database details, please contact your database administrator.', postgresql: 'You need to enter your PostgreSQL database details to connect to your database. If you are not sure about your database details, please contact your database administrator.', file: 'You need to upload a spreadsheet to connect to your data. Insights supports only .csv files.', sample: 'You can choose from one of the sample datasets to connect to Insights.', } const connectStepTitle = computed(() => { return titleBySourceType[setupState.sourceType] || 'Connect to Data' }) const connectStepDescription = computed(() => { return descriptionBySourceType[setupState.sourceType] }) const steps = ref([ { title: 'Welcome to Insights', description: ` To get started, you need to connect some data. You can connect to ERPNext, a SQL database, a spreadsheet, or you can explore our sample datasets to get a feel for how Insights works. `, component: markRaw(SourceTypeStep), }, { title: connectStepTitle, description: connectStepDescription, component: markRaw(SourceConnectionStep), }, { title: 'Help Us Improve', description: ` Insights is under active development so we’d like to ask you a few questions that will help us improve your experience in the future. `, component: markRaw(SetupQuestions), }, ]) const currentStep = ref(0) const settings = settingsStore() const router = useRouter() async function handleNext() { if (currentStep.value === steps.value.length - 1) { settings.settings.setup_complete = 1 await settings.update({ setup_complete: 1 }, false) router.replace({ path: '/' }) return } currentStep.value += 1 } function handlePrev() { if (currentStep.value === 0) { return } currentStep.value -= 1 } </script> <template> <div class="flex h-full w-full bg-white pt-[7rem] text-lg"> <div class="mx-auto flex w-[40rem] flex-col overflow-hidden"> <div class="mx-auto w-fit"> <div class="flex items-center space-x-2 py-1"> <template v-for="(step, index) in steps"> <div class="flex h-3 w-3 cursor-default items-center justify-center rounded-full transition-all" :class="[ currentStep < index ? 'bg-gray-200' : 'bg-gray-800', currentStep === index ? 'ring-4 ring-gray-400' : '', ]" ></div> <div v-if="index !== steps.length - 1" class="w-7 border-b transition-all" :class="currentStep - 1 < index ? 'border-gray-400' : 'border-gray-800'" ></div> </template> </div> </div> <div class="mt-8"> <div class="text-3xl font-bold leading-9 text-gray-900"> {{ steps[currentStep].title }} </div> <div class="text-base leading-5 text-gray-700"> {{ steps[currentStep].description }} </div> </div> <div class="relative flex flex-col overflow-hidden"> <transition name="fade" mode="out-in"> <component :is="steps[currentStep].component" @next="handleNext" @prev="handlePrev" /> </transition> <div class="absolute bottom-0 left-0"> <Button variant="outline" @click="handlePrev" v-if="currentStep > 0"> Back </Button> </div> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/setup/Setup.vue
Vue
agpl-3.0
4,166
<script setup> import { inject, reactive, ref } from 'vue' import { call } from 'frappe-ui' const emit = defineEmits(['next', 'prev']) const questions = reactive([ { question: 'What type of data/database system(s) are you planning to connect with Insights?', answerOptions: [ 'I plan to connect to ERPNext', 'I plan to use a SQL database (e.g., MySQL, PostgreSQL).', 'I plan to use spreadsheets (e.g., Excel, Google Sheets).', 'I plan to use a mix of different databases.', "I'm not sure yet.", ], multipleAnswers: true, selectedAnswerIndexes: [], }, { question: 'What is your level of familiarity with SQL and data analytics?', answerOptions: [ "I'm a complete beginner with no experience in SQL or data analytics.", "I have some familiarity with data analytics, but I'm new to SQL.", "I've used SQL before but am not an expert.", "I'm quite comfortable with SQL and have done some data analysis.", "I'm an expert in SQL and have significant experience in data analytics.", ], multipleAnswers: false, selectedAnswerIndexes: [], }, { question: 'Which of the following best describes your role or use-case for Insights?', answerOptions: [ "I'm a business owner/manager looking to monitor and understand key metrics.", "I'm a data analyst/scientist performing in-depth data exploration.", "I'm part of a team that needs to share data and reports with stakeholders.", "I'm in a tech role, exploring tools for our organization's data visualization needs.", "I'm just exploring and learning about data visualization and business intelligence tools.", ], multipleAnswers: false, selectedAnswerIndexes: [], }, ]) function toggleAnswer(question, index) { if (question.multipleAnswers) { if (question.selectedAnswerIndexes.includes(index)) { question.selectedAnswerIndexes = question.selectedAnswerIndexes.filter( (selectedIndex) => selectedIndex !== index ) } else { question.selectedAnswerIndexes.push(index) } } else { question.selectedAnswerIndexes = [index] } } const $notify = inject('$notify') const sendingResponses = ref(false) async function validateAndContinue() { if (questions.some((question) => question.selectedAnswerIndexes.length === 0)) { $notify({ title: 'Please answer all questions', message: 'You must select at least one answer for each question.', variant: 'error', }) } else { sendingResponses.value = true const surveyResponses = questions.reduce((responses, question) => { responses[question.question] = question.selectedAnswerIndexes.map( (index) => question.answerOptions[index] ) return responses }, {}) await call('insights.api.setup.submit_survey_responses', { responses: surveyResponses, }) sendingResponses.value = false emit('next') } } function skipAndContinue() { emit('next') } </script> <template> <div class="mt-6 space-y-4"> <div v-for="question in questions" :key="question.question" class="space-y-3"> <div class="font-bold text-gray-900">{{ question.question }}</div> <div> <div v-if="question.multipleAnswers" v-for="(answerOption, index) in question.answerOptions" class="flex items-center space-x-2" > <input type="checkbox" :id="`${question.question}-${index}`" :checked="question.selectedAnswerIndexes.includes(index)" @change="toggleAnswer(question, index)" class="h-4 w-4 rounded border-gray-300" /> <label class="text-gray-700" :for="`${question.question}-${index}`"> {{ answerOption }} </label> </div> <Input v-else type="select" :value="question.selectedAnswerIndexes[0]" @change="(value) => toggleAnswer(question, value)" :options=" question.answerOptions.map((option, index) => ({ label: option, value: index, })) " /> </div> </div> <div class="mt-6 flex justify-end space-x-3"> <Button variant="outline" @click="skipAndContinue"> Skip </Button> <Button variant="solid" @click="validateAndContinue" :loading="sendingResponses" :disabled=" sendingResponses || questions.some((question) => question.selectedAnswerIndexes.length === 0) " > Continue </Button> </div> </div> </template>
2302_79757062/insights
frontend/src/setup/SetupQuestions.vue
Vue
agpl-3.0
4,300
<script setup> import { call } from 'frappe-ui' import { inject, ref } from 'vue' import FileSourceForm from '../datasource/FileSourceForm.vue' import MariaDBForm from '../datasource/MariaDBForm.vue' import PostgreSQLForm from '../datasource/PostgreSQLForm.vue' import SampleDatasetList from '../datasource/SampleDatasetList.vue' const emit = defineEmits(['next', 'prev']) const setupState = inject('setupState') const sitename = window.location.hostname const erpnextSiteTitle = ref(sitename) async function updateERPNextSourceTitle() { if (erpnextSiteTitle.value === '') { $notify({ title: 'Please enter a title', message: 'Please enter a title to continue', type: 'error', }) return } await call('insights.api.setup.update_erpnext_source_title', { title: erpnextSiteTitle.value, }) emit('next') } </script> <template> <div class="mt-4 flex flex-col overflow-hidden"> <div class="flex flex-1 flex-col overflow-y-auto"> <div v-if="setupState.sourceType == 'erpnext'"> <Input v-model="erpnextSiteTitle" label="Title" /> <div class="mt-6 flex flex-shrink-0 justify-end space-x-3"> <Button variant="solid" @click="updateERPNextSourceTitle"> Continue </Button> </div> </div> <div v-if="setupState.sourceType == 'mariadb'"> <MariaDBForm @submit="emit('next')" submitLabel="Continue" /> </div> <div v-if="setupState.sourceType == 'postgresql'"> <PostgreSQLForm @submit="emit('next')" submitLabel="Continue" /> </div> <div v-if="setupState.sourceType == 'file'"> <FileSourceForm @submit="emit('next')" /> </div> <div v-if="setupState.sourceType == 'sample'"> <SampleDatasetList @submit="emit('next')" /> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/setup/SourceConnectionStep.vue
Vue
agpl-3.0
1,726
<script setup> import { inject, reactive, ref } from 'vue' const emit = defineEmits(['next']) const selectedOption = ref(null) const options = reactive([ { title: 'ERPNext', description: 'Connect to your ERPNext site', img: 'ERPNextIcon.png', }, { title: 'MariaDB', description: 'Connect to MariaDB database', img: 'MariaDBIcon.png', }, { title: 'PostgreSQL', description: 'Connect to PostgreSQL database', img: 'PostgreSQLIcon.png', }, { title: 'Spreadsheet', description: 'Connect or Upload a spreadsheet', img: 'SheetIcon.png', }, { title: 'Sample Dataset', description: 'Explore Insights with sample data', img: 'SampleDataIcon.png', }, ]) const $notify = inject('$notify') const setupState = inject('setupState') function validateAndContinue() { if (selectedOption.value === null) { $notify({ title: 'Please select an option', message: 'Please select an option to continue', type: 'error', }) return } if (selectedOption.value === 0) { setupState.sourceType = 'erpnext' } else if (selectedOption.value === 1) { setupState.sourceType = 'mariadb' } else if (selectedOption.value === 2) { setupState.sourceType = 'postgresql' } else if (selectedOption.value === 3) { setupState.sourceType = 'file' } else if (selectedOption.value === 4) { setupState.sourceType = 'sample' } emit('next') } </script> <template> <div class="mt-6"> <!-- card for each source (erpnext, database, file) --> <div class="grid grid-cols-2 gap-4 px-1"> <div v-for="(option, index) in options" class="col-span-1 flex cursor-pointer items-center rounded border border-gray-300 px-4 py-3 transition-all" :class=" selectedOption === index ? ' border-gray-500 ring-2 ring-gray-400' : 'hover:border-gray-500' " @click="selectedOption = index" > <div v-if="option.img" class="mr-2 flex w-10 items-center justify-center"> <img v-if="option.img === 'SheetIcon.png'" src="../assets/SheetIcon.png" /> <img v-if="option.img === 'ERPNextIcon.png'" src="../assets/ERPNextIcon.png" /> <img v-if="option.img === 'MariaDBIcon.png'" src="../assets/MariaDBIcon.png" /> <img v-if="option.img === 'PostgreSQLIcon.png'" src="../assets/PostgreSQLIcon.png" /> <img v-if="option.img === 'SampleDataIcon.png'" src="../assets/SampleDataIcon.png" /> </div> <div> <div class="font-bold leading-6 text-gray-900"> {{ option.title }} </div> <div class="text-sm text-gray-700">{{ option.description }}</div> </div> </div> </div> <div class="mt-6 flex justify-end space-x-3"> <Button variant="solid" :disabled="selectedOption === null" @click="validateAndContinue" > Continue </Button> </div> </div> </template>
2302_79757062/insights
frontend/src/setup/SourceTypeStep.vue
Vue
agpl-3.0
2,812
import { io } from 'socket.io-client' import { socketio_port } from '../../../../sites/common_site_config.json' export function initSocket() { let host = window.location.hostname let siteName = import.meta.env.DEV ? host : window.site_name let port = window.location.port ? `:${socketio_port}` : '' let protocol = port ? 'http' : 'https' let url = `${protocol}://${host}${port}/${siteName}` let socket = io(url, { withCredentials: true, reconnectionAttempts: 5, }) return socket }
2302_79757062/insights
frontend/src/socket.js
JavaScript
agpl-3.0
495
import { DataSource } from '@/datasource/useDataSource' import { DataSourceTable } from '@/datasource/useDataSourceTable' import { defineStore } from 'pinia' import { ref } from 'vue' type DataSourceCache = Record<string, DataSource> type TableCache = Record<string, DataSourceTable> const useCacheStore = defineStore('insights:cache', () => { const dataSourceCache = ref<DataSourceCache>({}) function getDataSource(name: string) { return dataSourceCache.value[name] } function setDataSource(name: string, dataSource: DataSource) { dataSourceCache.value[name] = dataSource } const tableCache = ref<TableCache>({}) function getTable(name: string) { return tableCache.value[name] } function setTable(name: string, table: DataSourceTable) { tableCache.value[name] = table } return { getDataSource, setDataSource, getTable, setTable, } }) export default useCacheStore
2302_79757062/insights
frontend/src/stores/cacheStore.ts
TypeScript
agpl-3.0
897
import * as api from '@/api' import dayjs from '@/utils/dayjs' import { defineStore } from 'pinia' import { computed } from 'vue' const useDataSourceStore = defineStore('insights:data_sources', () => { const listResource = api.getListResource({ doctype: 'Insights Data Source', cache: 'dataSourceList', filters: {}, fields: [ 'name', 'title', 'status', 'creation', 'modified', 'is_site_db', 'database_type', 'allow_imports', ], orderBy: 'creation desc', pageLength: 100, auto: true, }) const list = computed<DataSourceListItem[]>( () => listResource.list.data?.map((dataSource: DataSourceListItem) => { dataSource.created_from_now = dayjs(dataSource.creation).fromNow() dataSource.modified_from_now = dayjs(dataSource.modified).fromNow() dataSource.title = dataSource.is_site_db && dataSource.title == 'Site DB' ? window.location.hostname : dataSource.title return dataSource }) || [] ) const dropdownOptions = computed<DropdownOption[]>(() => list.value.map(makeDropdownOption)) function makeDropdownOption(dataSource: DataSourceListItem): DropdownOption { return { label: dataSource.title, value: dataSource.name, description: dataSource.database_type, } } return { list, dropdownOptions, loading: listResource.list.loading, testing: api.testDataSourceConnection.loading, creating: api.createDataSource.loading, deleting: listResource.delete.loading, create: (args: any) => api.createDataSource.submit(args).then(() => listResource.list.reload()), delete: (name: string) => listResource.delete.submit(name).then(() => listResource.list.reload()), testConnection: (args: any) => api.testDataSourceConnection.submit(args), getDropdownOptions: (filters: any) => { // filters = {is_site_db: 1} const filteredDataSources = list.value.filter((dataSource: DataSourceListItem) => { for (const key in filters) { const k = key as keyof DataSourceListItem if (dataSource[k] != filters[k]) { return false } } return true }) return filteredDataSources.map(makeDropdownOption) }, } }) export default useDataSourceStore export type DataSourceStore = ReturnType<typeof useDataSourceStore>
2302_79757062/insights
frontend/src/stores/dataSourceStore.ts
TypeScript
agpl-3.0
2,253
import * as api from '@/api' import dayjs from '@/utils/dayjs' import { VALID_CHARTS } from '@/widgets/widgets' import { defineStore } from 'pinia' import { computed } from 'vue' type QueryListItem = { name: string title: string status: string is_assisted_query: boolean is_native_query: boolean is_script_query: boolean is_stored: boolean data_source: string data_source_title: string creation: string created_from_now: string owner: string owner_name: string owner_image: string chart_type: string } const useQueryStore = defineStore('insights:queries', () => { const listResource = api.getListResource({ url: 'insights.api.queries.get_queries', doctype: 'Insights Query', cache: 'queryList', fields: FIELDS.map((f) => f.value), filters: {}, auto: true, pageLength: 50, orderBy: 'creation desc', }) const list = computed<QueryListItem[]>( () => listResource.list.data?.map((query: QueryListItem) => { query.created_from_now = dayjs(query.creation).fromNow() return query }) || [] ) const dropdownOptions = computed<DropdownOption[]>(() => list.value.map(makeDropdownOption)) function makeDropdownOption(query: QueryListItem): DropdownOption { return { label: query.title, value: query.name, description: query.data_source, } } async function createQuery(args: any) { return api.createQuery.submit(args).then((doc) => { listResource.list.reload() return doc }) } async function deleteQuery(name: string) { return listResource.delete.submit(name).then(() => { listResource.list.reload() }) } function reloadWithFilters(filters: any) { listResource.filters = filters listResource.list.reload() } return { list, dropdownOptions, loading: listResource.list.loading, creating: api.createQuery.loading, deleting: listResource.delete.loading, reload: () => listResource.list.reload(), create: createQuery, delete: deleteQuery, getFilterableFields: () => FIELDS, applyFilters: (filters: any) => reloadWithFilters(filters), getDropdownOptions: () => dropdownOptions.value, } }) const FIELDS = [ { label: 'Name', value: 'name', fieldname: 'name', fieldtype: 'Data', }, { label: 'Title', value: 'title', fieldname: 'title', fieldtype: 'Data', }, { label: 'Status', value: 'status', fieldname: 'status', fieldtype: 'Select', options: 'Pending Execution\nExecution Successful\nExecution Failed', }, { label: 'Is Assisted Query', value: 'is_assisted_query', fieldname: 'is_assisted_query', fieldtype: 'Check', }, { label: 'Is Native Query', value: 'is_native_query', fieldname: 'is_native_query', fieldtype: 'Check', }, { label: 'Is Script Query', value: 'is_script_query', fieldname: 'is_script_query', fieldtype: 'Check', }, { label: 'Is Stored', value: 'is_stored', fieldname: 'is_stored', fieldtype: 'Check', }, { label: 'Data Source', value: 'data_source', fieldname: 'data_source', fieldtype: 'Link', options: 'Insights Data Source', }, { label: 'Creation', value: 'creation', fieldname: 'creation', fieldtype: 'Datetime', }, { label: 'Owner', value: 'owner', fieldname: 'owner', fieldtype: 'Link', options: 'User', }, { label: 'Owner Name', value: 'owner_name', fieldname: 'owner_name', fieldtype: 'Data', }, { label: 'Owner Image', value: 'owner_image', fieldname: 'owner_image', fieldtype: 'Data', }, { label: 'Chart Type', value: 'chart_type', fieldname: 'chart_type', fieldtype: 'Select', options: VALID_CHARTS.join('\n'), }, ] export default useQueryStore export type QueryStore = ReturnType<typeof useQueryStore>
2302_79757062/insights
frontend/src/stores/queryStore.ts
TypeScript
agpl-3.0
3,679
import * as api from '@/api' import { defineStore } from 'pinia' import { computed, ref } from 'vue' const emptyUser: SessionUser = { email: '', first_name: '', last_name: '', full_name: '', user_image: '', is_admin: false, is_user: false, country: '', locale: 'en-US', is_v2_user: false, default_version: '', } const sessionStore = defineStore('insights:session', function () { const initialized = ref(false) const user = ref(emptyUser) const isLoggedIn = computed(() => user.value.email && user.value.email !== 'Guest') const isAuthorized = computed(() => user.value.is_admin || user.value.is_user) async function initialize(force: boolean = false) { if (initialized.value && !force) return Object.assign(user.value, getSessionFromCookies()) isLoggedIn.value && (await fetchSessionInfo()) isLoggedIn.value && api.trackActiveSite() initialized.value = true } async function fetchSessionInfo() { if (!isLoggedIn.value) return const userInfo: SessionUser = await api.fetchUserInfo() Object.assign(user.value, { ...userInfo, is_admin: Boolean(userInfo.is_admin), is_user: Boolean(userInfo.is_user), is_v2_user: Boolean(userInfo.is_v2_user), }) } async function login(email: string, password: string) { resetSession() const userInfo = await api.login(email, password) if (!userInfo) return Object.assign(user.value, userInfo) window.location.reload() } async function logout() { resetSession() await api.logout() window.location.reload() } function resetSession() { Object.assign(user, emptyUser) } // should be moved to some other store, but where? 🤔 async function createViewLog(recordType: string, recordName: string) { if (!isLoggedIn) return await api.createLastViewedLog(recordType, recordName) } function updateDefaultVersion(version: SessionUser['default_version']) { user.value.default_version = version return api.updateDefaultVersion(version) } return { user: user, initialized, isLoggedIn, isAuthorized, initialize, fetchSessionInfo, login, logout, resetSession, createViewLog, updateDefaultVersion, } }) function getSessionFromCookies() { return document.cookie .split('; ') .map((c) => c.split('=')) .reduce((acc, [key, value]) => { key = key == 'user_id' ? 'email' : key acc[key] = decodeURIComponent(value) return acc }, {} as any) } export default sessionStore export type sessionStore = ReturnType<typeof sessionStore>
2302_79757062/insights
frontend/src/stores/sessionStore.ts
TypeScript
agpl-3.0
2,478
import * as api from '@/api' import { createToast } from '@/utils/toasts' import { defineStore } from 'pinia' import { computed } from 'vue' type InsightsSettings = { setup_complete: boolean enable_permissions: boolean allow_subquery: boolean auto_execute_query: boolean query_result_expiry: number query_result_limit: number telegram_api_token: string fiscal_year_start: string } const settingsStore = defineStore('insights:settings', () => { const insightsSettings = api.getDocumentResource('Insights Settings') const initialized = computed(() => insightsSettings.doc?.name) async function initialize() { if (initialized.value) return await insightsSettings.get.fetch() } const loading = computed(() => insightsSettings.loading) const settings = computed({ get: () => insightsSettings.doc, set(value: InsightsSettings) { insightsSettings.doc = value }, }) function update(settings: InsightsSettings, showToast: boolean = true) { return insightsSettings.setValue.submit({ ...settings }).then(() => { showToast && createToast({ title: 'Settings Updated', message: 'Your settings have been updated successfully', variant: 'success', }) }) } return { initialized, settings, loading, initialize, update, } }) export default settingsStore export type SettingsStore = ReturnType<typeof settingsStore>
2302_79757062/insights
frontend/src/stores/settingsStore.ts
TypeScript
agpl-3.0
1,374
import { createResource, call } from 'frappe-ui' import { reactive } from 'vue' const subscription = reactive({ trialExpired: null, fetchTrialStatus, }) async function fetchTrialStatus() { subscription.trialExpired = await call('insights.api.subscription.trial_expired') return subscription.trialExpired } export async function getLoginLink() { return await call('insights.api.subscription.get_login_link') } export async function getTrialStatus() { if (import.meta.env.DEV) return false return subscription.trialExpired !== null ? subscription.trialExpired : await fetchTrialStatus() } export default subscription
2302_79757062/insights
frontend/src/subscription/index.js
JavaScript
agpl-3.0
627
export const COLOR_MAP = { blue: '#318AD8', pink: '#F683AE', green: '#48BB74', red: '#F56B6B', yellow: '#FACF7A', purple: '#44427B', teal: '#5FD8C4', orange: '#F8814F', cyan: '#15CCEF', grey: '#A6B1B9', '#449CF0': '#449CF0', '#ECAD4B': '#ECAD4B', '#761ACB': '#761ACB', '#CB2929': '#CB2929', '#ED6396': '#ED6396', '#29CD42': '#29CD42', '#4463F0': '#4463F0', '#EC864B': '#EC864B', '#4F9DD9': '#4F9DD9', '#39E4A5': '#39E4A5', '#B4CD29': '#B4CD29', } const LIGHT_COLOR_MAP = { 'light-pink': '#FED7E5', 'light-blue': '#BFDDF7', 'light-green': '#48BB74', 'light-grey': '#F4F5F6', 'light-red': '#F6DFDF', 'light-yellow': '#FEE9BF', 'light-purple': '#E8E8F7', 'light-teal': '#D3FDF6', 'light-cyan': '#DDF8FD', 'light-orange': '#FECDB8', } export const randomColor = (num = 1) => { const colors = [] let hue = Math.floor(Math.random() * 360) let lightness = '65%' let alpha = 1 for (let i = 0; i < num; i++) { const color = `hsla(${hue}, 50%, ${lightness}, ${alpha})` colors.push(color) hue = Math.floor(Math.random() * 360) } return colors } export const getColors = (num = Object.keys(COLOR_MAP).length) => { if (num == 1) { return randomColor() } const colors = [] const _colors = Object.values(COLOR_MAP) for (let i = 0; i < num; i++) { colors.push(_colors[i % _colors.length]) } return colors } export const generateColorPalette = (shade: string, num = 5) => { const colors = [] const hueByShade: { [key: string]: number } = { blue: 200, green: 140, teal: 180, yellow: 60, }; const hue = hueByShade[shade]; const minLightness = 30; const maxLightness = 70; const lightnessStep = (maxLightness - minLightness) / num; // generate light to dark colors for (let i = 0; i < num; i++) { const lightness = minLightness + lightnessStep * i; colors.push(`hsl(${hue}, 65%, ${lightness}%)`); } return colors.reverse(); } export function getRGB(color: HashString | RGBString | string | null): HashString { if (!color) { return '#ffffff' } if (color.startsWith('rgb')) { return RGBToHex(color as RGBString) } else if (!color.startsWith('#') && color.match(/\b[a-fA-F0-9]{3,6}\b/g)) { return `#${color}` as HashString } return color as HashString } export function RGBToHex(rgb: RGBString): HashString { const [r, g, b] = rgb .replace('rgb(', '') .replace(')', '') .split(',') .map((x) => parseInt(x)) return `#${[r, g, b].map((x) => x.toString(16).padStart(2, '0')).join('')}` } export function HSVToHex(h: number, s: number, v: number): HashString { s /= 100 v /= 100 h /= 360 let r = 0, g = 0, b = 0 let i = Math.floor(h * 6) let f = h * 6 - i let p = v * (1 - s) let q = v * (1 - f * s) let t = v * (1 - (1 - f) * s) switch (i % 6) { case 0: ;(r = v), (g = t), (b = p) break case 1: ;(r = q), (g = v), (b = p) break case 2: ;(r = p), (g = v), (b = t) break case 3: ;(r = p), (g = q), (b = v) break case 4: ;(r = t), (g = p), (b = v) break case 5: ;(r = v), (g = p), (b = q) break } r = Math.round(r * 255) g = Math.round(g * 255) b = Math.round(b * 255) return `#${[r, g, b].map((x) => x.toString(16).padStart(2, '0')).join('')}` } export function HexToHSV(color: HashString): { h: number; s: number; v: number } { const [r, g, b] = color .replace('#', '') .match(/.{1,2}/g) ?.map((x) => parseInt(x, 16)) || [0, 0, 0] const max = Math.max(r, g, b) const min = Math.min(r, g, b) const v = max / 255 const d = max - min const s = max === 0 ? 0 : d / max const h = max === min ? 0 : max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4 return { h: h * 60, s, v } }
2302_79757062/insights
frontend/src/utils/colors.ts
TypeScript
agpl-3.0
3,699
import { reactive } from 'vue' import { useRouter } from 'vue-router' const commandPalette = reactive({ isOpen: false, commands: [], open, close, search, }) function open() { commandPalette.isOpen = true } function close() { commandPalette.isOpen = false } function search(searchTerm) { return commandPalette.commands.filter((command) => { return command.title.toLowerCase().includes(searchTerm.toLowerCase()) }) } function initNavigationCommands(commandPalette) { const router = useRouter() commandPalette.commands = [] commandPalette.commands.push({ title: 'Query', description: 'Go to query list', icon: 'arrow-right', action: () => { router.push('/query') }, }) commandPalette.commands.push({ title: 'Dashboard', description: 'Go to dashboard list', icon: 'arrow-right', action: () => { router.push('/dashboard') }, }) commandPalette.commands.push({ title: 'Data Source', description: 'Go to data source list', icon: 'arrow-right', action: () => { router.push('/data-source') }, }) commandPalette.commands.push({ title: 'Settings', description: 'Go to settings', icon: 'arrow-right', action: () => { router.push('/settings') }, }) } export default function useCommandPalette() { initNavigationCommands(commandPalette) return commandPalette }
2302_79757062/insights
frontend/src/utils/commandPalette.js
JavaScript
agpl-3.0
1,325
import dayjs from 'dayjs' import relativeTime from 'dayjs/esm/plugin/relativeTime' import quarterOfYear from 'dayjs/esm/plugin/quarterOfYear' import advancedFormat from 'dayjs/esm/plugin/advancedFormat' import customParseFormat from 'dayjs/esm/plugin/customParseFormat' dayjs.extend(relativeTime) dayjs.extend(quarterOfYear) dayjs.extend(advancedFormat) dayjs.extend(customParseFormat) export default dayjs
2302_79757062/insights
frontend/src/utils/dayjs.js
JavaScript
agpl-3.0
409
function toLogicalExpression(binaryExpression) { // converts a binary expression with logical operators to a logical expression // logical expression schema // { // type: "LogicalExpression", // operator: "&&" | "||", // conditions: [ left, right ] // } function isLogicalOperator(operator) { return operator === '&&' || operator === '||' } if (!isLogicalOperator(binaryExpression.operator)) { return binaryExpression } function shouldConvert(expression) { return ( expression.type == 'BinaryExpression' && isLogicalOperator(expression.operator) && binaryExpression.left && binaryExpression.right ) } if (shouldConvert(binaryExpression)) { const { left, right } = binaryExpression binaryExpression.type = 'LogicalExpression' binaryExpression.conditions = binaryExpression.conditions || [] delete binaryExpression.left delete binaryExpression.right binaryExpression.conditions.push( isLogicalOperator(left.operator) ? toLogicalExpression(left) : left ) binaryExpression.conditions.push( isLogicalOperator(right.operator) ? toLogicalExpression(right) : right ) return binaryExpression } if ( binaryExpression.type == 'LogicalExpression' && isLogicalOperator(binaryExpression.operator) && binaryExpression.conditions.length > 0 ) { binaryExpression.conditions.forEach((condition, idx) => { binaryExpression.conditions[idx] = toLogicalExpression(condition) }) } return binaryExpression } function mergeConditions(ast) { // merges sub conditions with same logical operator into parent condition // eg. // A > B A > B // | AND - A > C A > C // AND - AND - B > C // | AND - B > C B > D // B > D if (ast.type !== 'LogicalExpression' || ast.conditions.length == 0) { return ast } function shouldMerge(condition) { return condition.conditions.some((c) => c.operator == condition.operator) } if (shouldMerge(ast)) { const replaceConditionMap = {} ast.conditions.forEach((condition, idx) => { if (condition.type == 'LogicalExpression' && condition.operator == ast.operator) { replaceConditionMap[idx] = condition.conditions } }) Object.keys(replaceConditionMap).forEach((idx) => { ast.conditions.splice(idx, 1, ...replaceConditionMap[idx]) }) } ast.conditions.forEach((c) => mergeConditions(c)) return ast } function setLevelAndPosition(filters) { function _setLevelAndPosition(tree) { tree.conditions?.forEach((condition, idx) => { if (condition.type == 'LogicalExpression') { condition.level = tree.level + 1 condition.position = idx + 1 if (condition.conditions.length > 0) { _setLevelAndPosition(condition) } } }) return tree } filters.level = 1 filters.position = 1 return _setLevelAndPosition(filters) } export function convertIntoQueryFilters(ast) { if (ast.type !== 'LogicalExpression') { return ast } let filters = ast filters = toLogicalExpression(filters) filters = mergeConditions(filters) filters = setLevelAndPosition(filters) return filters }
2302_79757062/insights
frontend/src/utils/expressions/filter.js
JavaScript
agpl-3.0
3,143
import tokenize from '@/utils/expressions/tokenize' import { TOKEN_TYPES } from '@/utils/expressions/tokenize' const MAX_PRECEDENCE = 5 function getPrecedence(tokenType) { switch (tokenType) { case TOKEN_TYPES.NUMBER: case TOKEN_TYPES.STRING: case TOKEN_TYPES.COLUMN: case TOKEN_TYPES.FUNCTION: case TOKEN_TYPES.OPEN_PARENTHESIS: case TOKEN_TYPES.CLOSE_PARENTHESIS: case TOKEN_TYPES.BACKTICK: return MAX_PRECEDENCE case TOKEN_TYPES.OPERATOR_MUL: case TOKEN_TYPES.OPERATOR_DIV: return 4 case TOKEN_TYPES.OPERATOR_ADD: case TOKEN_TYPES.OPERATOR_SUB: return 3 case TOKEN_TYPES.OPERATOR_GT: case TOKEN_TYPES.OPERATOR_LT: case TOKEN_TYPES.OPERATOR_EQ: case TOKEN_TYPES.OPERATOR_NEQ: case TOKEN_TYPES.OPERATOR_GTE: case TOKEN_TYPES.OPERATOR_LTE: return 2 case TOKEN_TYPES.LOGICAL_AND: return 1 case TOKEN_TYPES.LOGICAL_OR: return 0 default: return 100 } } export function parse(expression) { const tokens = tokenize(expression) let cursor = 0 let currentToken = tokens[cursor] let errorMessage = null function parseTokens(precedence) { if (precedence < MAX_PRECEDENCE) { let left = parseTokens(precedence + 1) while ( getPrecedence(currentToken.type) == precedence && currentToken.type !== TOKEN_TYPES.EOF ) { const operator = currentToken.value currentToken = tokens[++cursor] const right = parseTokens(precedence + 1) left = { type: 'BinaryExpression', operator, left, right } } return left } // precedence == MAX_PRECEDENCE switch (currentToken.type) { case TOKEN_TYPES.NUMBER: return parseNumber() case TOKEN_TYPES.STRING: return parseString() case TOKEN_TYPES.OPEN_PARENTHESIS: return parseParenthesis() case TOKEN_TYPES.BACKTICK: return parseColumn() case TOKEN_TYPES.FUNCTION: return parseFunction() case TOKEN_TYPES.EOF: return { type: 'EOF' } default: errorMessage = `Unexpected token: ${currentToken.value}` throw new Error( `Failed to Parse Expression ${expression}: Unexpected token: ${currentToken.type}` ) } } function parseNumber() { const value = currentToken.value currentToken = tokens[++cursor] return { type: 'Number', value: parseFloat(value) } } function parseString() { const value = currentToken.value currentToken = tokens[++cursor] return { type: 'String', value } } function parseParenthesis() { currentToken = tokens[++cursor] if (!checkForClosingParenthesis()) { errorMessage = `Missing closing parenthesis for opening parenthesis` throw new Error(`Failed to Parse Expression ${expression}: Missing closing parenthesis`) } const expr = parseTokens(0) currentToken = tokens[++cursor] return expr } function parseColumn() { currentToken = tokens[++cursor] if (currentToken.type !== TOKEN_TYPES.COLUMN) { errorMessage = `Missing column name` throw new Error( `Failed to Parse Expression ${expression}: Expected column reference, got: ${currentToken.type}` ) } const column = currentToken.value if (!column.table || !column.column) { errorMessage = `Invalid column reference` throw new Error( `Failed to Parse Expression ${expression}: Invalid column reference: ${column}` ) } currentToken = tokens[++cursor] if (currentToken.type !== TOKEN_TYPES.BACKTICK) { errorMessage = `Missing closing backtick` throw new Error( `Failed to Parse Expression ${expression}: Expected closing backtick, got: ${currentToken.type}` ) } currentToken = tokens[++cursor] return { type: 'Column', value: column } } function parseFunction() { const name = currentToken.value currentToken = tokens[++cursor] if (currentToken.type !== TOKEN_TYPES.OPEN_PARENTHESIS) { errorMessage = `Expected opening parenthesis after ${name} function` throw new Error( `Failed to Parse Expression ${expression}: Expected opening parenthesis, got: ${currentToken.type}` ) } currentToken = tokens[++cursor] if (!checkForClosingParenthesis()) { errorMessage = `Missing closing parenthesis for ${name} function` throw new Error( `Failed to Parse Expression ${expression}: Missing closing parenthesis for ${name} function` ) } const args = [] while ( currentToken.type !== TOKEN_TYPES.CLOSE_PARENTHESIS && currentToken.type !== TOKEN_TYPES.EOF ) { args.push(parseTokens(0)) if (currentToken.type === TOKEN_TYPES.ARGUMENT_SEPARATOR) { currentToken = tokens[++cursor] } } currentToken = tokens[++cursor] return { type: 'CallExpression', function: name, arguments: args } } function checkForClosingParenthesis() { // find the closing parenthesis after the opening one if not found, throw error let closingParenthesisIndex = -1 for (let i = cursor; i < tokens.length; i++) { if (tokens[i].type === TOKEN_TYPES.CLOSE_PARENTHESIS) { closingParenthesisIndex = i break } } if (closingParenthesisIndex !== -1) { return true } } let ast = null try { ast = parseTokens(0) } catch (error) { console.groupCollapsed('Failed to Parse Expression') console.error(error) console.groupEnd() } return { ast, errorMessage, tokens: tokens, } }
2302_79757062/insights
frontend/src/utils/expressions/index.js
JavaScript
agpl-3.0
5,217
export const TOKEN_TYPES = { EOF: 'EOF', NUMBER: 'NUMBER', OPEN_PARENTHESIS: 'OPEN_PARENTHESIS', CLOSE_PARENTHESIS: 'CLOSE_PARENTHESIS', OPERATOR_ADD: 'OPERATOR_ADD', OPERATOR_SUB: 'OPERATOR_SUB', OPERATOR_MUL: 'OPERATOR_MUL', OPERATOR_DIV: 'OPERATOR_DIV', OPERATOR_GT: 'OPERATOR_GT', OPERATOR_LT: 'OPERATOR_LT', OPERATOR_EQ: 'OPERATOR_EQ', OPERATOR_NEQ: 'OPERATOR_NEQ', OPERATOR_GTE: 'OPERATOR_GTE', OPERATOR_LTE: 'OPERATOR_LTE', BACKTICK: 'BACKTICK', COLUMN: 'COLUMN', FUNCTION: 'FUNCTION', ARGUMENT_SEPARATOR: 'ARGUMENT_SEPARATOR', FUNCTION_ARGUMENTS: 'FUNCTION_ARGUMENTS', STRING: 'STRING', LOGICAL_AND: 'LOGICAL_AND', LOGICAL_OR: 'LOGICAL_OR', } const FUNCTION_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$' function isParenthesis(char) { return /^[()]$/.test(char) } function isWhiteSpace(char) { return /^\s$/.test(char) } function isNumber(char) { return /^[0-9]$/.test(char) } function isBackTick(char) { return char === '`' } function isArgumentSeparator(char) { return char === ',' } function isQuote(char) { return char === '"' || char === "'" } function isOperator(char) { return ( char === '+' || char === '-' || char === '*' || char === '/' || char === '>' || char === '<' || char === '=' || char === '!' ) } function getOperatorTokenType(operator) { switch (operator) { case '+': return TOKEN_TYPES.OPERATOR_ADD case '-': return TOKEN_TYPES.OPERATOR_SUB case '*': return TOKEN_TYPES.OPERATOR_MUL case '/': return TOKEN_TYPES.OPERATOR_DIV case '>': return TOKEN_TYPES.OPERATOR_GT case '<': return TOKEN_TYPES.OPERATOR_LT case '=': return TOKEN_TYPES.OPERATOR_EQ case '!=': return TOKEN_TYPES.OPERATOR_NEQ case '>=': return TOKEN_TYPES.OPERATOR_GTE case '<=': return TOKEN_TYPES.OPERATOR_LTE default: console.warn(`Unknown operator: ${operator}`) } } function isLogicalOperator(char) { return char === '&' || char === '|' } export default function tokenize(expression, offset = 0) { // remove tabs, form-feed, carriage returns, and newlines expression = expression?.replace(/\t\f\r\n/g, '') if (!expression) return [] let cursor = 0 let tokens = [] let char = expression[cursor] let nextChar = expression[cursor + 1] function advance() { char = expression[++cursor] nextChar = expression[cursor + 1] } function processOperatorToken() { let operator = '' while (isOperator(char)) { operator += char advance() } tokens.push({ type: getOperatorTokenType(operator), value: operator, }) } function processNumberToken() { let number = '' while (isNumber(char) || (char == '.' && isNumber(expression[cursor + 1]))) { number += char advance() } tokens.push({ type: TOKEN_TYPES.NUMBER, value: number, }) } function processColumnToken() { tokens.push({ type: TOKEN_TYPES.BACKTICK, }) advance() let columnStr = '' while (char != '`' && cursor < expression.length) { columnStr += char advance() } if (columnStr.length) { const start = offset + cursor - columnStr.length const [table, column] = columnStr.split('.') tokens.push({ type: TOKEN_TYPES.COLUMN, start: start, end: offset + cursor, value: { table: column ? table : null, column: column ? column : table, }, }) } if (char === '`') { tokens.push({ type: TOKEN_TYPES.BACKTICK, }) advance() } } function processFunctionToken() { let fn = '' while (FUNCTION_CHARS.includes(char) && cursor < expression.length) { fn += char advance() } if (!fn) return const fnToken = { type: TOKEN_TYPES.FUNCTION, start: offset + cursor - fn.length, end: offset + cursor, value: fn, } let openParenToken = null if (char === '(') { openParenToken = { type: TOKEN_TYPES.OPEN_PARENTHESIS, } advance() } let argsStart = cursor let closeParenthesis = findMatchingParenthesis(expression, cursor - 1) let argsEnd = closeParenthesis !== -1 ? closeParenthesis : expression.length let argsStr = expression.substring(argsStart, argsEnd) if (!argsStr) { fnToken.end = offset + cursor tokens.push(fnToken) openParenToken && tokens.push(openParenToken) return } let fnArgs = tokenize(argsStr, offset + argsStart).filter( (token) => token.type !== TOKEN_TYPES.EOF ) cursor = argsEnd - 1 advance() let closeParenToken = null if (char === ')') { closeParenToken = { type: TOKEN_TYPES.CLOSE_PARENTHESIS, } advance() } fnToken.end = offset + cursor tokens.push(fnToken) openParenToken && tokens.push(openParenToken) tokens = tokens.concat(fnArgs) closeParenToken && tokens.push(closeParenToken) } function processStringToken() { let quote = char advance() let string = '' while (char != quote && cursor < expression.length) { string += char advance() } if (char == quote) { tokens.push({ type: TOKEN_TYPES.STRING, value: string, }) advance() } } function processLogicalOperatorToken() { tokens.push({ type: char == '&' ? TOKEN_TYPES.LOGICAL_AND : TOKEN_TYPES.LOGICAL_OR, value: char + nextChar, }) advance() advance() } while (cursor < expression.length) { if (isWhiteSpace(char)) { advance() continue } if (isOperator(char)) { processOperatorToken() continue } if (isParenthesis(char)) { tokens.push({ type: char == '(' ? TOKEN_TYPES.OPEN_PARENTHESIS : TOKEN_TYPES.CLOSE_PARENTHESIS, }) advance() continue } if (isArgumentSeparator(char)) { tokens.push({ type: TOKEN_TYPES.ARGUMENT_SEPARATOR, value: char, }) advance() continue } if (isNumber(char)) { processNumberToken() continue } if (isBackTick(char)) { processColumnToken() continue } if (isQuote(char)) { processStringToken() continue } if (isLogicalOperator(char) && isLogicalOperator(char) == isLogicalOperator(nextChar)) { processLogicalOperatorToken() continue } if (FUNCTION_CHARS.includes(char)) { processFunctionToken() continue } console.warn(`Unexpected character: ${char} while parsing expression: ${expression}`) break } tokens.push({ type: TOKEN_TYPES.EOF, }) return tokens } function findMatchingParenthesis(str, start) { if (str[start] !== '(') return -1 let open = 0 for (let i = start; i < str.length; i++) { if (str[i] == '(') open++ if (str[i] == ')') open-- if (open == 0) return i } return -1 }
2302_79757062/insights
frontend/src/utils/expressions/tokenize.js
JavaScript
agpl-3.0
6,515
import dayjs from './dayjs' export const dateFormats = [ { label: 'January 12, 2020 1:14 PM', value: 'Minute' }, { label: 'January 12, 2020 1:00 PM', value: 'Hour' }, { label: '1:00 PM', value: 'Hour of Day' }, { label: '12th January, 2020', value: 'Day' }, { label: '12th Jan, 20', value: 'Day Short' }, { label: '12th January, 2020', value: 'Week' }, { label: 'January, 2020', value: 'Month' }, { label: 'Jan 20', value: 'Mon' }, { label: 'Q1, 2020', value: 'Quarter' }, { label: '2020', value: 'Year' }, { label: 'Monday', value: 'Day of Week' }, { label: 'January', value: 'Month of Year' }, { label: 'Q1', value: 'Quarter of Year' }, ] export function getFormattedDate(date, dateFormat) { if (!date) return '' if (dateFormat === 'Day of Week') { return date } if (dateFormat === 'Month of Year') { if (isNaN(date)) return date return dayjs(date, 'MM').format('MMMM') } if (dateFormat === 'Quarter of Year') { return `Q${date}` } if (dateFormat === 'Hour of Day') { return dayjs(date, 'HH:mm').format('h:mm A') } const dayjsFormat = { Minute: 'MMMM D, YYYY h:mm A', Hour: 'MMMM D, YYYY h:00 A', Day: 'MMMM D, YYYY', Week: 'MMM Do, YYYY', Mon: 'MMM YY', Month: 'MMMM, YYYY', Year: 'YYYY', Quarter: '[Q]Q, YYYY', 'Day Short': 'Do MMM, YY', }[dateFormat] if (!dayjsFormat) return date return dayjs(date).format(dayjsFormat) }
2302_79757062/insights
frontend/src/utils/format.js
JavaScript
agpl-3.0
1,389
import sessionStore from '@/stores/sessionStore' import { createToast } from '@/utils/toasts' import { watchDebounced } from '@vueuse/core' import domtoimage from 'dom-to-image' import { call } from 'frappe-ui' import { Baseline, Calendar, CalendarClock, Clock, Hash, ShieldQuestion, ToggleLeft, Type, } from 'lucide-vue-next' import { computed, unref, watch } from 'vue' export const COLUMN_TYPES = [ { label: 'String', value: 'String' }, { label: 'Text', value: 'Text' }, { label: 'Integer', value: 'Integer' }, { label: 'Decimal', value: 'Decimal' }, { label: 'Date', value: 'Date' }, { label: 'Time', value: 'Time' }, { label: 'Datetime', value: 'Datetime' }, ] export const fieldtypesToIcon = { Integer: Hash, Decimal: Hash, Date: Calendar, Datetime: CalendarClock, Time: Clock, Text: Type, String: Baseline, 'Long Text': Type, } export const returnTypesToIcon = { number: Hash, string: Type, boolean: ToggleLeft, date: Calendar, datetime: CalendarClock, any: ShieldQuestion, } const NumberTypes = ['Integer', 'Decimal'] const TextTypes = ['Text', 'String'] const DateTypes = ['Date', 'Datetime', 'Time'] export const FIELDTYPES = { NUMBER: NumberTypes, TEXT: TextTypes, DATE: DateTypes, MEASURE: NumberTypes, DIMENSION: TextTypes.concat(DateTypes), DISCRETE: TextTypes, CONTINUOUS: NumberTypes.concat(DateTypes), } export const AGGREGATIONS = [ { label: 'Unique', value: 'group by', description: 'Group by' }, { label: 'Count of Records', value: 'count', description: 'Count' }, { label: 'Sum of', value: 'sum', description: 'Sum' }, { label: 'Average of', value: 'avg', description: 'Average' }, { label: 'Cumulative Count of Records', value: 'cumulative count', description: 'Cumulative Count', }, { label: 'Cumulative Sum of', value: 'cumulative sum', description: 'Cumulative Sum' }, { label: 'Unique values of', value: 'distinct', description: 'Distinct' }, { label: 'Unique count of', value: 'distinct_count', description: 'Distinct Count' }, { label: 'Minimum of', value: 'min', description: 'Minimum' }, { label: 'Maximum of', value: 'max', description: 'Maximum' }, ] export const GRANULARITIES = [ { label: 'Minute', value: 'Minute', description: 'January 12, 2020 1:14 PM' }, { label: 'Hour', value: 'Hour', description: 'January 12, 2020 1:00 PM' }, { label: 'Hour of Day', value: 'Hour of Day', description: '1:00 PM' }, { label: 'Day', value: 'Day', description: '12th January, 2020' }, { label: 'Day Short', value: 'Day Short', description: '12th Jan, 20' }, { label: 'Week', value: 'Week', description: '12th January, 2020' }, { label: 'Month', value: 'Month', description: 'January, 2020' }, { label: 'Mon', value: 'Mon', description: 'Jan 20' }, { label: 'Quarter', value: 'Quarter', description: 'Q1, 2020' }, { label: 'Year', value: 'Year', description: '2020' }, { label: 'Day of Week', value: 'Day of Week', description: 'Monday' }, { label: 'Month of Year', value: 'Month of Year', description: 'January' }, { label: 'Quarter of Year', value: 'Quarter of Year', description: 'Q1' }, ] export function getOperatorOptions(columnType) { let options = [ { label: 'equals', value: '=' }, { label: 'not equals', value: '!=' }, { label: 'is', value: 'is' }, ] if (!columnType) { return options } if (FIELDTYPES.TEXT.includes(columnType)) { options = options.concat([ { label: 'contains', value: 'contains' }, { label: 'not contains', value: 'not_contains' }, { label: 'starts with', value: 'starts_with' }, { label: 'ends with', value: 'ends_with' }, { label: 'one of', value: 'in' }, { label: 'not one of', value: 'not_in' }, ]) } if (FIELDTYPES.NUMBER.includes(columnType)) { options = options.concat([ { label: 'one of', value: 'in' }, { label: 'not one of', value: 'not_in' }, { label: 'greater than', value: '>' }, { label: 'smaller than', value: '<' }, { label: 'greater than equal to', value: '>=' }, { label: 'smaller than equal to', value: '<=' }, { label: 'between', value: 'between' }, ]) } if (FIELDTYPES.DATE.includes(columnType)) { options = options.concat([ { label: 'greater than', value: '>' }, { label: 'smaller than', value: '<' }, { label: 'greater than equal to', value: '>=' }, { label: 'smaller than equal to', value: '<=' }, { label: 'between', value: 'between' }, { label: 'within', value: 'timespan' }, ]) } return options } // a function to resolve the promise when a ref has a value export async function whenHasValue(refOrGetter) { return new Promise((resolve) => { function onValue(value) { if (!value) return resolve(value) unwatch() } const unwatch = watch(refOrGetter, onValue, { deep: true }) const value = typeof refOrGetter === 'function' ? refOrGetter() : unref(refOrGetter) onValue(value) }) } export function isDimensionColumn(column) { return FIELDTYPES.TEXT.includes(column.type) || FIELDTYPES.DATE.includes(column.type) } export function moveCaretToEnd(el) { if (typeof window.getSelection != 'undefined' && typeof document.createRange != 'undefined') { var range = document.createRange() range.selectNodeContents(el) range.collapse(false) var sel = window.getSelection() sel.removeAllRanges() sel.addRange(range) } else if (typeof document.body.createTextRange != 'undefined') { var textRange = document.body.createTextRange() textRange.moveToElementText(el) textRange.collapse(false) textRange.select() } } export function isEmptyObj(...args) { return args.some((arg) => { if (arg === null || arg === undefined) { return true } return Object.keys(arg).length === 0 }) } export function safeJSONParse(str, defaultValue = null) { if (str === null || str === undefined) { return defaultValue } if (typeof str !== 'string') { return str } try { return JSON.parse(str) } catch (e) { console.groupCollapsed('Error parsing JSON') console.log(str) console.error(e) console.groupEnd() createToast({ message: 'Error parsing JSON', variant: 'error', }) return defaultValue } } export function formatDate(value) { if (!value) { return '' } return new Date(value).toLocaleString('en-US', { month: 'short', year: 'numeric', day: 'numeric', }) } export function isEqual(a, b) { if (a === b) { return true } if (Array.isArray(a) && Array.isArray(b)) { return a.length === b.length && a.every((item, index) => isEqual(item, b[index])) } } export function updateDocumentTitle(meta) { watch( () => meta, (meta) => { if (!meta.value.title) return if (meta.value.title && meta.value.subtitle) { document.title = `${meta.value.title} | ${meta.value.subtitle}` return } if (meta.value.title) { document.title = `${meta.value.title} | Frappe Insights` return } }, { immediate: true, deep: true } ) } export function fuzzySearch(arr, { term, keys }) { // search for term in all keys of arr items and sort by relevance const lowerCaseTerm = term.toLowerCase() const results = arr.reduce((acc, item) => { const score = keys.reduce((acc, key) => { const value = item[key] if (value) { const match = value.toLowerCase().indexOf(lowerCaseTerm) if (match !== -1) { return acc + match + 1 } } return acc }, 0) if (score) { acc.push({ item, score }) } return acc }, []) return results.sort((a, b) => a.score - b.score).map((item) => item.item) } export function ellipsis(value, length) { if (value && value.length > length) { return value.substring(0, length) + '...' } return value } export function getShortNumber(number, precision = 0) { const session = sessionStore() const locale = session.user?.country == 'India' ? 'en-IN' : session.user?.locale let formatted = new Intl.NumberFormat(locale || 'en-US', { notation: 'compact', maximumFractionDigits: precision, }).format(number) if (locale == 'en-IN') { formatted = formatted.replace('T', 'K') } return formatted } export function formatNumber(number, precision = 2) { if (isNaN(number)) return number precision = precision || guessPrecision(number) const session = sessionStore() const locale = session.user?.country == 'India' ? 'en-IN' : session.user?.locale return new Intl.NumberFormat(locale || 'en-US', { maximumFractionDigits: precision, }).format(number) } export function guessPrecision(number) { // eg. 1.0 precision = 1, 1.00 precision = 2 const str = number.toString() const decimalIndex = str.indexOf('.') if (decimalIndex === -1) return 0 return Math.min(str.length - decimalIndex - 1, 2) } export async function getDataURL(type, data) { const blob = new Blob([data], { type }) return new Promise((resolve) => { const fr = new FileReader() fr.addEventListener('loadend', () => { resolve(fr.result) }) fr.readAsDataURL(blob) }) } export async function convertFileToDataURL(file, type) { const buffer = await file.arrayBuffer() const array = new Uint8Array(buffer) return await getDataURL(type, array) } export function getQueryLink(table) { if (!table) return '' // returns a link to the query if the table is a query eg. Query Store queries if (table.startsWith('QRY')) { return `/insights/query/build/${table}` } return '' } export function copyToClipboard(text) { if (navigator.clipboard) { navigator.clipboard.writeText(text) createToast({ variant: 'success', title: 'Copied to clipboard', }) } else { // try to use execCommand const textArea = document.createElement('textarea') textArea.value = text textArea.style.position = 'fixed' document.body.appendChild(textArea) textArea.focus() textArea.select() try { document.execCommand('copy') createToast({ variant: 'success', title: 'Copied to clipboard', }) } catch (err) { createToast({ variant: 'error', title: 'Copy to clipboard not supported', }) } finally { document.body.removeChild(textArea) } } } export function setOrGet(obj, key, generator, generatorArgs) { if (!obj.hasOwnProperty(key)) { obj[key] = generator(...generatorArgs) } return obj[key] } export function useAutoSave(watchedFields, options = {}) { if (!options.saveFn) throw new Error('saveFn is required') const fields = computed(() => { if (!watchedFields.value) return return JSON.parse(JSON.stringify(watchedFields.value)) }) function saveIfChanged(newFields, oldFields) { if (!oldFields || !newFields) return if (JSON.stringify(newFields) == JSON.stringify(oldFields)) return options.saveFn() } const interval = options.interval || 1000 watchDebounced(fields, saveIfChanged, { deep: true, debounce: interval, }) } export function isInViewport(element) { if (!element) return false const rect = element.getBoundingClientRect() return ( rect.top > 0 && rect.left > 0 && rect.bottom < (window.innerHeight || document.documentElement.clientHeight) && rect.right < (window.innerWidth || document.documentElement.clientWidth) ) } export function downloadImage(element, filename, options = {}) { return domtoimage .toBlob(element, { bgcolor: 'rgb(248, 248, 248)', ...options, }) .then(function (blob) { const link = document.createElement('a') link.download = filename link.href = URL.createObjectURL(blob) link.click() }) } export function getImageSrc(element) { return domtoimage .toBlob(element, { bgcolor: 'rgb(248, 248, 248)', }) .then((blob) => URL.createObjectURL(blob)) } export function areDeeplyEqual(obj1, obj2) { if (obj1 === obj2) return true if (Array.isArray(obj1) && Array.isArray(obj2)) { if (obj1.length !== obj2.length) return false return obj1.every((elem, index) => { return areDeeplyEqual(elem, obj2[index]) }) } if (typeof obj1 === 'object' && typeof obj2 === 'object' && obj1 !== null && obj2 !== null) { if (Array.isArray(obj1) || Array.isArray(obj2)) return false const keys1 = Object.keys(obj1) const keys2 = Object.keys(obj2) if (keys1.length !== keys2.length || !keys1.every((key) => keys2.includes(key))) return false for (let key in obj1) { let isEqual = areDeeplyEqual(obj1[key], obj2[key]) if (!isEqual) { return false } } return true } return false } export function createTaskRunner() { const queue = [] let running = false const run = async () => { if (running) return running = true while (queue.length) { await queue.shift()() } running = false } return async (fn) => { queue.push(fn) await run() } } // a util function that is similar to watch but only runs the callback when the value is truthy and changes export function wheneverChanges(getter, callback, options = {}) { let prevValue = null function onChange(value) { if (areDeeplyEqual(value, prevValue)) return prevValue = value callback(value) } return watchDebounced(getter, onChange, options) } export async function run_doc_method(method, doc, args = {}) { return call('run_doc_method', { method, dt: doc.doctype, dn: doc.name, args: args, }) } export function makeColumnOption(column) { return { ...column, description: column.type, value: `${column.table}.${column.column}`, } } export default { isEmptyObj, safeJSONParse, formatDate, isEqual, updateDocumentTitle, fuzzySearch, formatNumber, getShortNumber, copyToClipboard, ellipsis, areDeeplyEqual, }
2302_79757062/insights
frontend/src/utils/index.js
JavaScript
agpl-3.0
13,393
import { reactive } from 'vue' let prompt = reactive({ show: false, options: {}, }) export default function usePrompt() { return prompt } export function showPrompt(promptOptions) { prompt.show = true prompt.options = { title: promptOptions.title, message: promptOptions.message, icon: promptOptions.icon, actions: [ { ...promptOptions.primaryAction, label: promptOptions.primaryAction.label, handler: promptOptions.primaryAction.action, }, { ...promptOptions.secondaryAction, label: promptOptions.secondaryAction?.label || 'Cancel', handler: promptOptions.secondaryAction?.action, }, ], } }
2302_79757062/insights
frontend/src/utils/prompt.js
JavaScript
agpl-3.0
647
import { FIELDTYPES, isEqual, safeJSONParse } from '@/utils' import { useStorage } from '@vueuse/core' import { computed, watch } from 'vue' export function useQueryColumns(query) { const data = computed(() => query.doc?.columns.map((column) => { return { ...column, format_option: column.format_option ? safeJSONParse(column.format_option) : null, aggregation_condition: column.aggregation_condition ? safeJSONParse(column.aggregation_condition) : null, expression: column.is_expression ? safeJSONParse(column.expression) : null, } }) ) // if tables changes then update columns options const tables = () => query.tables.data?.reduce((acc, row) => { acc.push(row.table) if (row.join && row.join.with.value) { acc.push(row.join.with.value) } return acc }, []) const fetchColumns = (newVal, oldVal) => { if (newVal?.length && !isEqual(newVal, oldVal)) { query.fetchColumns.submit() } } watch(tables, fetchColumns, { immediate: true }) const options = computed(() => query.fetchColumns.data?.map((c) => { return { ...c, value: c.column, // calc value key for autocomplete options description: c.table_label, } }) ) watch(options, updateColumnOptionsCache) const indexOptions = computed(() => { return query.results.columns .filter((c) => !FIELDTYPES.NUMBER.includes(c.type)) .map((c) => { return { label: c.label, value: c.column || c.label, } }) }) const valueOptions = computed(() => { return query.results.columns .filter((c) => FIELDTYPES.NUMBER.includes(c.type)) .map((c) => { return { label: c.label, value: c.column || c.label, } }) }) return { data, options, indexOptions, valueOptions } } const cachedColumns = useStorage('insights:columns', {}) function updateColumnOptionsCache(columns) { cachedColumns.value = columns.reduce((acc, column) => { const key = `${column.table}_${column.column}` if (!acc[key]) { acc[key] = column } return acc }, cachedColumns.value) } export function getColumn(column) { return cachedColumns.value[`${column.table}_${column.column}`] }
2302_79757062/insights
frontend/src/utils/query/columns.js
JavaScript
agpl-3.0
2,155
import { FIELDTYPES, safeJSONParse } from '@/utils' import { convertIntoQueryFilters } from '@/utils/expressions/filter' import { getColumn } from '@/utils/query/columns' import { computed, reactive } from 'vue' const DEFAULT_FILTERS = { type: 'LogicalExpression', level: 1, position: 1, operator: '&&', conditions: [], } export function useQueryFilters(query) { const data = computed(() => safeJSONParse(query.doc.filters, DEFAULT_FILTERS)) const addNextFilterAt = reactive({ level: 1, position: 1, }) const editFilterAt = reactive({ level: 1, position: 1, idx: -1, }) const add = (filter) => { const expression = getLogicalExpressionAt({ ...addNextFilterAt, filters: data.value, }) expression.conditions.push(filter) updateFilters() } const edit = (filter) => { const expression = getLogicalExpressionAt({ ...editFilterAt, filters: data.value, }) expression.conditions[editFilterAt.idx] = filter Object.assign(editFilterAt, { level: 1, position: 1, idx: -1, }) updateFilters() } const remove = (level, position, idx) => { if (level == 1 && typeof idx == 'number') { // remove the filter from root level data.value.conditions.splice(idx, 1) } if (level > 1 && position && typeof idx == 'number') { // remove the filter at `idx` from the filter group at `level` & `position` const expression = getLogicalExpressionAt({ filters: data.value, level, position, }) expression.conditions.splice(idx, 1) } updateFilters() } const toggleOperator = (level, position) => { const expression = getLogicalExpressionAt({ filters: data.value, level, position, }) expression.operator = expression.operator == '&&' ? '||' : '&&' updateFilters() } const updateFilters = () => { let filters = convertIntoQueryFilters(data.value) query.updateFilters.submit({ filters }) } return { data, addNextFilterAt, editFilterAt, add, edit, remove, toggleOperator, convertIntoExpression, convertIntoSimpleFilter, isSimpleFilter, } } function getLogicalExpressionAt({ filters, level, position, parentIdx }) { if (level == 1 && position == 1) { return filters } let expression = null for (let i = 0; i < filters.conditions.length; i++) { let exp = filters.conditions[i] if (exp.type !== 'LogicalExpression') continue if (exp.level == level && (exp.position == position || i == parentIdx)) { expression = exp break } if (exp.conditions?.length > 0) { let _exp = getLogicalExpressionAt({ filters: exp, level, position }) if (_exp) { expression = _exp break } } } return expression } // utility functions to convert a simple filter into expression and vice versa export const BINARY_OPERATORS = { '=': 'equals', '!=': 'not equals', '>': 'greater than', '>=': 'greater than equal to', '<': 'less than', '<=': 'less than equal to', } export const FILTER_FUNCTIONS = { is: 'is', in: 'one of', not_in: 'not one of', between: 'between', timespan: 'within', starts_with: 'starts with', ends_with: 'ends with', contains: 'contains', not_contains: 'not contains', } function getOperatorFromCallFunction(functionName) { if (FILTER_FUNCTIONS[functionName]) { return functionName } if (functionName.indexOf('set') > -1) { return 'is' } // is not a simple filter call function return null } function isBinaryOperator(operator) { return Boolean(BINARY_OPERATORS[operator]) } function isCallFunction(functionName) { return Boolean(FILTER_FUNCTIONS[getOperatorFromCallFunction(functionName)]) } function convertIntoBinaryExpression(simpleFilter) { const { column, operator, value } = simpleFilter return { type: 'BinaryExpression', operator: operator.value, left: { type: 'Column', value: { column: column.column, table: column.table, }, }, right: { type: FIELDTYPES.NUMBER.includes(column.type) ? 'Number' : 'String', value: value.value, }, } } function convertIntoCallExpression(simpleFilter) { const { column, operator, value } = simpleFilter const operatorFunction = operator.value == 'is' ? (value.value == 'set' ? 'is_set' : 'is_not_set') : operator.value function makeArgs() { if (operator.value == 'is') return [] if (operator.value == 'between') { const values = value.value.split(',') return values.map((v) => ({ type: FIELDTYPES.NUMBER.includes(column.type) ? 'Number' : 'String', value: v, })) } if (['in', 'not_in'].includes(operator.value)) { return value.value.map((v) => ({ type: 'String', value: v })) } return [{ type: 'String', value: value.value }] } return { type: 'CallExpression', function: operatorFunction, arguments: [ { type: 'Column', value: { column: column.column, table: column.table, }, }, ...makeArgs(), ], } } export function convertIntoExpression(simpleFilter) { const operator = simpleFilter.operator.value if (isBinaryOperator(operator)) { return convertIntoBinaryExpression(simpleFilter) } if (isCallFunction(operator)) { return convertIntoCallExpression(simpleFilter) } } function areLiterals(args) { return args.every((arg) => arg.type == 'String' || arg.type == 'Number') } function makeValueFromCallFunction(expression) { if (!areLiterals(expression.arguments.slice(1))) return [] if (expression.function == 'is_set') return ['Set', 'Set'] if (expression.function == 'is_not_set') return ['Not Set', 'Not Set'] if (expression.function == 'between') { const value = expression.arguments[1].value + ', ' + expression.arguments[2].value return [value, value] } if (['in', 'not_in'].includes(expression.function)) { const values = expression.arguments.slice(1).map((a) => a.value) const label = values.length > 1 ? values.length + ' values' : values[0] return [label, values] } const value = expression.arguments[1].value return [value, value] } export function isSimpleFilter(expression) { // an expression is a simple filter if it can be converted into a simple filter // with proper column, operator and value const simpleFilter = convertIntoSimpleFilter(expression) if (!simpleFilter) return false const { column, operator, value } = simpleFilter if (!column || !operator || !value) return false if (!column.value || !operator.value || !value.value) return false return true } export function convertIntoSimpleFilter(expression) { if (isBinaryOperator(expression.operator)) { const column = getColumn(expression.left.value) const operator = { label: BINARY_OPERATORS[expression.operator], value: expression.operator, } const value = { label: expression.right.value, value: expression.right.value, } return { column, operator, value } } if (isCallFunction(expression.function)) { const operator = getOperatorFromCallFunction(expression.function) const column = getColumn(expression.arguments[0].value) const [label, value] = makeValueFromCallFunction(expression) return { column: column, operator: { label: FILTER_FUNCTIONS[operator], value: operator, }, value: { label: label || value, value: value, }, } } }
2302_79757062/insights
frontend/src/utils/query/filters.js
JavaScript
agpl-3.0
7,170
export const FUNCTIONS = { // Comparison Operators in: { syntax: 'in(column_name, "value1", "value2", ...)', description: 'Checks if column contains any of the provided values.', example: 'in(`order.status`, "Closed", "Resolved")', returnType: 'boolean', }, not_in: { syntax: 'not_in(column_name, "value1", "value2", ...)', description: 'Checks if column excludes the provided values.', example: 'not_in(`order.status`, "Closed", "Resolved")', returnType: 'boolean', }, is_set: { syntax: 'is_set(column_name)', description: 'Checks if column has a value.', example: 'is_set(`order.status`)', returnType: 'boolean', }, is_not_set: { syntax: 'is_not_set(column_name)', description: 'Checks if column lacks a value.', example: 'is_not_set(`order.status`)', returnType: 'boolean', }, between: { syntax: 'between(column_name, "value1", "value2")', description: 'Checks if column value is between two values.', example: 'between(`user.age`, 10, 30)', returnType: 'boolean', }, contains: { syntax: 'contains(column_name, "value")', description: 'Checks if column contains the specified value.', example: 'contains(`order.customer`, "John")', returnType: 'boolean', }, not_contains: { syntax: 'not_contains(column_name, "value")', description: 'Checks if column excludes the specified value.', example: 'not_contains(`order.customer`, "John")', returnType: 'boolean', }, ends_with: { syntax: 'ends_with(column_name, "value")', description: 'Checks if column ends with the specified value.', example: 'ends_with(`order.customer`, "Souza")', returnType: 'boolean', }, starts_with: { syntax: 'starts_with(column_name, "value")', description: 'Checks if column starts with the specified value.', example: 'starts_with(`order.customer`, "John")', returnType: 'boolean', }, // String Functions lower: { syntax: 'lower(string_column)', description: 'Converts string to lowercase.', example: 'lower(`product.category`)', returnType: 'string', }, upper: { syntax: 'upper(string_column)', description: 'Converts string to uppercase.', example: 'upper(`product.category`)', returnType: 'string', }, concat: { syntax: 'concat(column1, column2, ...)', description: 'Combines values from columns or strings.', example: 'concat(`user.first_name`, " ", `user.last_name`)', returnType: 'string', }, replace: { syntax: 'replace(column_name, "search", "replace")', description: 'Replaces occurrences in the column.', example: 'replace(`product.category`, "_", "-")', returnType: 'string', }, substring: { syntax: 'substring(column_name, start, end)', description: 'Extracts part of the column value.', example: 'substring(`order.customer`, 0, 5)', returnType: 'string', }, // Arithmetic Functions abs: { syntax: 'abs(number_column)', description: 'Returns absolute value of the column.', example: 'abs(`order.paid_amount`)', returnType: 'number', }, sum: { syntax: 'sum(number_column)', description: 'Sums values of the column.', example: 'sum(`order.paid_amount`)', returnType: 'number', }, min: { syntax: 'min(number_column)', description: 'Finds minimum value of the column.', example: 'min(`order.paid_amount`)', returnType: 'number', }, max: { syntax: 'max(number_column)', description: 'Finds maximum value of the column.', example: 'max(`order.paid_amount`)', returnType: 'number', }, avg: { syntax: 'avg(number_column)', description: 'Calculates average value of the column.', example: 'avg(`order.paid_amount`)', returnType: 'number', }, round: { syntax: 'round(number_column)', description: 'Rounds the column value.', example: 'round(`order.paid_amount`)', returnType: 'number', }, floor: { syntax: 'floor(number_column)', description: 'Rounds the column value down.', example: 'floor(`order.paid_amount`)', returnType: 'number', }, ceil: { syntax: 'ceil(number_column)', description: 'Rounds the column value up.', example: 'ceil(`order.paid_amount`)', returnType: 'number', }, // Date & Time Functions timespan: { syntax: 'timespan(column_name, "timespan")', description: 'Checks if column value is within the timespan.', example: 'timespan(`invoice.creation`, "Last 7 Days")', returnType: 'boolean', }, now: { syntax: 'now()', description: 'Gets current date and time.', example: '`invoice.posting_date` = now()', returnType: 'datetime', }, today: { syntax: 'today()', description: 'Gets current date.', example: '`invoice.posting_date` = today()', returnType: 'date', }, format_date: { syntax: 'format_date(date, "format")', description: 'Formats date to the given format.', example: 'format_date(`invoice.posting_date`, "DD-MM-YYYY")', returnType: 'string', }, start_of: { syntax: 'start_of(unit, date)', description: 'Finds start of the given unit (e.g., Month, Year).', example: 'start_of("Month", today())', returnType: 'date', }, time_elapsed: { syntax: 'time_elapsed(unit, date1, date2)', description: 'Calculates time between two dates.', example: 'time_elapsed("day", `invoice.posting_date`, today())', returnType: 'number', }, // Other Functions case: { syntax: 'case(condition1, "value1", ..., "default_value")', description: 'Returns matched condition value or default.', example: 'case(`invoice.amount` > 0, "Unpaid", `invoice.amount` < 0, "Return", "Paid")', returnType: 'any', }, count: { syntax: 'count(column_name)', description: 'Counts rows based on column.', example: 'count(`invoice.id`)', returnType: 'number', }, coalesce: { syntax: 'coalesce(column1, column2, ...)', description: 'Returns first non-null value from columns.', example: 'coalesce(`user.first_name`, `user.last_name`)', returnType: 'any', }, if_null: { syntax: 'if_null(column_name, "default_value")', description: 'Provides default if column is null.', example: 'if_null(`product.category`, "No Category")', returnType: 'any', }, distinct: { syntax: 'distinct(column_name)', description: 'Lists distinct values of the column.', example: 'distinct(`user.customer`)', returnType: 'any', }, distinct_count: { syntax: 'distinct_count(column_name)', description: 'Counts distinct values of the column.', example: 'distinct_count(`user.customer`)', returnType: 'number', }, count_if: { syntax: 'count_if(condition)', description: 'Counts rows that satisfy the condition.', example: 'count_if(`order.amount` > 0)', returnType: 'number', }, sum_if: { syntax: 'sum_if(condition, column_name)', description: 'Sums values of the column that satisfy the condition.', example: 'sum_if(`order.customer` = "John", `grand_total`)', returnType: 'number', }, descendants: { syntax: 'descendants("value", "doctype", "fieldname")', description: 'Lists all descendants of the given value.', example: 'descendants("India", "tabTerritory", `territory`)', returnType: 'boolean', }, descendants_and_self: { syntax: 'descendants_and_self("value", "doctype", "fieldname")', description: 'Lists all descendants and self of the given value.', example: 'descendants_and_self("India", "tabTerritory", `territory`)', returnType: 'boolean', }, sql: { syntax: 'sql("query")', description: 'Write raw SQL queries.', example: 'sql("MONTH(invoice.posting_date)")', returnType: 'any', }, }
2302_79757062/insights
frontend/src/utils/query/index.js
JavaScript
agpl-3.0
7,427
import { FIELDTYPES, safeJSONParse } from '@/utils' import { getFormattedDate } from '../format' function applyColumnFormatOption(formatOption, cell) { if (!formatOption) return cell if (formatOption.prefix) { return `${formatOption.prefix} ${cell}` } if (formatOption.suffix) { return `${cell} ${formatOption.suffix}` } if (formatOption.date_format) { return getFormattedDate(cell, formatOption.date_format) } return cell } export function getFormattedResult(data) { if (!data || !data.length) return [] const columns = data[0] const columnTypes = data[0].map((c) => c.type) return data.map((row, index) => { if (index == 0) return row // header row return row.map((cell, idx) => { const columnType = columnTypes[idx] if (FIELDTYPES.NUMBER.includes(columnType)) { if (columnType == 'Integer') { cell = parseInt(cell) cell = isNaN(cell) ? 0 : cell } if (columnType == 'Decimal') { cell = parseFloat(cell) cell = isNaN(cell) ? 0 : cell } } if (FIELDTYPES.DATE.includes(columnType)) { // only use format options for dates const formatOption = columns[idx]?.options if (formatOption) { cell = applyColumnFormatOption(safeJSONParse(formatOption), cell) } } return cell }) }) }
2302_79757062/insights
frontend/src/utils/query/results.js
JavaScript
agpl-3.0
1,277
import { safeJSONParse } from '@/utils' import { computed } from 'vue' export function useQueryTables(query) { query.fetchTables.submit() const data = computed(() => query.doc?.tables.map((table) => { return { ...table, value: table.table, join: table.join ? safeJSONParse(table.join) : null, } }) ) const sourceTables = computed(() => query.fetchTables.data ?.filter((t) => t.table != query.doc.name) .map((table) => ({ ...table, value: table.table, description: table.is_query_based ? 'Query' : '', })) ) const joinOptions = computed(() => { // any two table/query can be joined from the same data source return sourceTables.value }) const newTableOptions = computed(() => { if (query.doc?.tables?.length == 0) { return sourceTables.value } // only return tables that are already selected in the query // to ensure correct chaining of joins const tables = query.doc?.tables.map((t) => ({ label: t.label, value: t.table })) const joinedTables = query.doc?.tables.reduce((acc, table) => { if (table.join) { const join = safeJSONParse(table.join) acc.push({ label: join.with.label, value: join.with.table }) } return acc }, []) return [...tables, ...joinedTables] }) return { data, newTableOptions, joinOptions, validateRemoveTable({ table, label }) { const columnsFromTable = query.doc.columns.filter((c) => c.table === table) // allow removing table if it has been selected twice const tableCount = query.doc.tables.filter((t) => t.table === table).length if (columnsFromTable.length > 0 && tableCount == 1) { return { title: 'Cannot remove table', message: `Remove dimensions and metrics associated with ${label} table and try again`, variant: 'warning', } } }, } }
2302_79757062/insights
frontend/src/utils/query/tables.js
JavaScript
agpl-3.0
1,817
import { ref, unref, reactive, computed } from 'vue' export default function useResizer({ handle, target, direction, limits, inverse, disabled, start, stop, onResize, }) { const isDragging = ref(false) const startX = ref(0) const startY = ref(0) const state = reactive({ startWidth: 0, startHeight: 0, newWidth: 0, newHeight: 0, }) const disableDragging = computed(() => unref(disabled)) const $target = unref(target) function onMouseDown(e) { if (disableDragging.value) { return } // e.preventDefault() start && start() isDragging.value = true startX.value = e.clientX startY.value = e.clientY state.startWidth = parseInt(document.defaultView.getComputedStyle($target).width, 10) state.startHeight = parseInt(document.defaultView.getComputedStyle($target).height, 10) document.addEventListener('mousemove', onMouseMove) document.addEventListener('mouseup', onMouseUp) } function onMouseMove(e) { if (isDragging.value) { const dx = e.clientX - startX.value const dy = e.clientY - startY.value if (!direction || direction == 'x') { state.newWidth = inverse ? state.startWidth - dx : state.startWidth + dx if (limits) { if (state.newWidth < limits.minWidth) { state.newWidth = limits.minWidth } else if (state.newWidth > limits.maxWidth) { state.newWidth = limits.maxWidth } } $target.style.width = state.newWidth + 'px' } if (!direction || direction == 'y') { state.newHeight = inverse ? state.startHeight - dy : state.startHeight + dy if (limits) { if (state.newHeight < limits.minHeight) { state.newHeight = limits.minHeight } else if (state.newHeight > limits.maxHeight) { state.newHeight = limits.maxHeight } } $target.style.height = `${state.newHeight}px` } } } function onMouseUp() { isDragging.value = false document.removeEventListener('mousemove', onMouseMove) document.removeEventListener('mouseup', onMouseUp) stop && stop() onResize && onResize(state.newWidth, state.newHeight) } unref(handle).addEventListener('mousedown', onMouseDown) }
2302_79757062/insights
frontend/src/utils/resizer.js
JavaScript
agpl-3.0
2,138
import { createDocumentResource } from 'frappe-ui' const resource = createDocumentResource({ doctype: 'System Settings', name: 'System Settings', auto: false, }) export default resource
2302_79757062/insights
frontend/src/utils/systemSettings.js
JavaScript
agpl-3.0
191
import { useStorage } from '@/vueuse/core' import { call } from 'frappe-ui' import '../../../frappe/public/js/lib/posthog.js' const APP = 'insights' const SITENAME = window.location.hostname const telemetry = useStorage('insights:telemetry', { enabled: false, project_id: undefined, telemetry_host: undefined, }) async function initialize() { await set_enabled() if (!telemetry.enabled) return try { await set_credentials() posthog.init(telemetry.project_id, { api_host: telemetry.telemetry_host, autocapture: false, capture_pageview: false, capture_pageleave: false, advanced_disable_decide: true, }) posthog.identify(SITENAME) } catch (e) { console.trace('Failed to initialize telemetry', e) telemetry.enabled = false } } async function set_enabled() { if (telemetry.enabled) return return await call('insights.api.telemetry.is_enabled').then((res) => { telemetry.enabled = res }) } async function set_credentials() { if (!telemetry.enabled) return if (telemetry.project_id && telemetry.telemetry_host) return return await call('insights.api.telemetry.get_credentials').then((res) => { telemetry.project_id = res.project_id telemetry.telemetry_host = res.telemetry_host }) } function capture(event) { if (!telemetry.enabled) return posthog.capture(`${APP}_${event}`) } function disable() { telemetry.enabled = false posthog.opt_out_capturing() } export default { initialize, capture, disable, }
2302_79757062/insights
frontend/src/utils/telemetry.js
JavaScript
agpl-3.0
1,456
import Toast from '@/components/Toast.vue' import { h, markRaw } from 'vue' import { toast } from 'vue-sonner' export function createToast(toastOptions) { const options = {} if (toastOptions.message && toastOptions.title) { options.message = toastOptions.message options.title = toastOptions.title } else if (toastOptions.message && !toastOptions.title) { options.message = toastOptions.message options.title = titleCase(toastOptions.variant) } else if (!toastOptions.message && toastOptions.title) { options.message = '' options.title = toastOptions.title } const component = h(Toast, { ...toastOptions, ...options }) toast.custom(markRaw(component)) } function titleCase(str) { return str .toLowerCase() .split(' ') .map(function (word) { return word.charAt(0).toUpperCase() + word.slice(1) }) .join(' ') }
2302_79757062/insights
frontend/src/utils/toasts.js
JavaScript
agpl-3.0
844
export const slideDownTransition = { enterActiveClass: 'transition duration-200 ease-out', leaveActiveClass: 'transition duration-150 ease-in', enterFromClass: 'translate-y-1 opacity-0', enterToClass: 'translate-y-0 opacity-100', leaveFromClass: 'translate-y-0 opacity-100', leaveToClass: 'translate-y-1 opacity-0', } export const slideRightTransition = { enterActiveClass: 'transition duration-200 ease-out', leaveActiveClass: 'transition duration-150 ease-in', enterFromClass: 'translate-x-1 opacity-0', enterToClass: 'translate-x-0 opacity-100', leaveFromClass: 'translate-x-0 opacity-100', leaveToClass: 'translate-x-1 opacity-0', }
2302_79757062/insights
frontend/src/utils/transitions.js
JavaScript
agpl-3.0
650
import { reactive, computed } from 'vue' import { createDocumentResource, createResource, debounce } from 'frappe-ui' import { showPrompt } from './prompt' import { useUsers } from './useUsers' const users = useUsers() const teamListResource = createResource( 'insights.insights.doctype.insights_team.insights_team_client.get_teams' ) export function useTeams() { const teams = reactive({ list: computed(() => teamListResource.data), loading: computed(() => teamListResource.loading), error: computed(() => teamListResource.error), refresh: () => teamListResource.fetch(), }) return teams } export function useTeam(teamname) { const team = createDocumentResource({ doctype: 'Insights Team', name: teamname, whitelistedMethods: { get_members_and_resources: 'get_members_and_resources', search_team_members: 'search_team_members', search_team_resources: 'search_team_resources', add_team_member: 'add_team_member', add_team_members: 'add_team_members', remove_team_member: 'remove_team_member', add_team_resource: 'add_team_resource', add_team_resources: 'add_team_resources', remove_team_resource: 'remove_team_resource', delete_team: 'delete_team', }, }) team.get_members_and_resources.fetch() team.members = computed(() => team.get_members_and_resources.data?.members) team.resources = computed(() => team.get_members_and_resources.data?.resources) team.searchMembers = debounce((query) => { if (!query && query !== '') { team.memberOptions = [] return } return team.search_team_members.submit({ query }).then((data) => { team.memberOptions = data || [] }) }, 500) team.searchMembers('') team.addMember = (member) => { return team.add_team_member .submit({ user: member }) .then(team.get_members_and_resources.fetch) .then(users.refresh) } team.addMembers = (members) => { return team.add_team_members .submit({ users: members }) .then(team.get_members_and_resources.fetch) .then(users.refresh) } team.removeMember = (member) => { showPrompt({ title: 'Remove Member', message: `Are you sure you want to remove ${member} from this team?`, icon: { name: 'trash', variant: 'danger' }, primaryAction: { label: 'Remove', variant: 'danger', action: ({ close }) => { return team.remove_team_member .submit({ user: member }) .then(team.get_members_and_resources.fetch) .then(users.refresh) .then(close) }, }, }) } team.searchResources = debounce((resource_type, query) => { if (!query && query !== '') { team.resourceOptions = [] return } return team.search_team_resources.submit({ resource_type, query }).then((data) => { team.resourceOptions = data || [] }) }, 500) team.addResource = (resource) => { return team.add_team_resource .submit({ resource }) .then(team.get_members_and_resources.fetch) } team.addResources = (resources) => { return team.add_team_resources .submit({ resources }) .then(team.get_members_and_resources.fetch) } team.removeResource = (resource) => { return team.remove_team_resource .submit({ resource }) .then(team.get_members_and_resources.fetch) } team.deleteTeam = () => { return team.delete_team.submit().then(teamListResource.fetch).then(users.refresh) } return team }
2302_79757062/insights
frontend/src/utils/useTeams.js
JavaScript
agpl-3.0
3,327
import { reactive, computed } from 'vue' import { createResource } from 'frappe-ui' const userListResource = createResource('insights.api.user.get_users') const addUserResource = createResource({ url: 'insights.api.user.add_insights_user', }) export function useUsers() { const users = reactive({ list: computed(() => userListResource.data), loading: computed(() => userListResource.loading), error: computed(() => userListResource.error), refresh: () => userListResource.fetch(), add: (user) => addUserResource.submit({ user }).then(() => userListResource.fetch()), }) return users }
2302_79757062/insights
frontend/src/utils/useUsers.js
JavaScript
agpl-3.0
602
<script setup> import Autocomplete from '@/components/Controls/Autocomplete.vue' import ColorPalette from '@/components/Controls/ColorPalette.vue' import DraggableList from '@/components/DraggableList.vue' import DraggableListItemMenu from '@/components/DraggableListItemMenu.vue' import { FIELDTYPES } from '@/utils' import { computed } from 'vue' import SeriesOption from '../SeriesOption.vue' const emit = defineEmits(['update:modelValue']) const options = defineModel('options') const props = defineProps({ seriesType: { type: String }, options: { type: Object, required: true }, columns: { type: Array, required: true }, }) if (!options.value.xAxis) options.value.xAxis = [] if (!options.value.yAxis) options.value.yAxis = [] if (typeof options.value.xAxis === 'string') { options.value.xAxis = [{ column: options.value.xAxis }] } if (typeof options.value.yAxis === 'string') { options.value.yAxis = [{ column: options.value.yAxis }] } if (Array.isArray(options.value.xAxis) && typeof options.value.xAxis[0] === 'string') { options.value.xAxis = options.value.xAxis.map((column) => ({ column })) } if (Array.isArray(options.value.yAxis) && typeof options.value.yAxis[0] === 'string') { options.value.yAxis = options.value.yAxis.map((column) => ({ column })) } options.value.yAxis.forEach((item) => { if (!item.series_options) item.series_options = {} }) const indexOptions = computed(() => { return props.columns ?.filter((column) => !FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) const valueOptions = computed(() => { return props.columns ?.filter((column) => FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) function updateYAxis(columnOptions) { if (!columnOptions) { options.value.yAxis = [] return } options.value.yAxis = columnOptions.map((option) => { const existingColumn = options.value.yAxis?.find((c) => c.column === option.value) const series_options = existingColumn ? existingColumn.series_options : {} return { column: option.value, series_options } }) } function updateXAxis(columnOptions) { if (!columnOptions) { options.value.xAxis = [] return } options.value.xAxis = columnOptions.map((option) => { return { column: option.value } }) } </script> <template> <FormControl type="text" label="Title" class="w-full" v-model="options.title" placeholder="Title" /> <div> <div class="mb-1 flex items-center justify-between"> <label class="block text-xs text-gray-600">X Axis</label> <Autocomplete :multiple="true" :options="indexOptions" :modelValue="options.xAxis?.map((item) => item.column) || []" @update:model-value="updateXAxis" > <template #target="{ togglePopover }"> <Button variant="ghost" icon="plus" @click="togglePopover" /> </template> </Autocomplete> </div> <DraggableList group="xAxis" item-key="column" empty-text="No columns selected" v-model:items="options.xAxis" /> </div> <div> <div class="mb-1 flex items-center justify-between"> <label class="block text-xs text-gray-600">Y Axis</label> <Autocomplete :multiple="true" :options="valueOptions" :modelValue="options.yAxis?.map((item) => item.column) || []" @update:model-value="updateYAxis" > <template #target="{ togglePopover }"> <Button variant="ghost" icon="plus" @click="togglePopover" /> </template> </Autocomplete> </div> <DraggableList group="yAxis" item-key="column" empty-text="No columns selected" v-model:items="options.yAxis" > <template #item-suffix="{ item, index }"> <DraggableListItemMenu> <SeriesOption :seriesType="props.seriesType" :modelValue="item.series_options || {}" @update:modelValue="options.yAxis[index].series_options = $event" /> </DraggableListItemMenu> </template> </DraggableList> </div> <div v-if="options.yAxis?.length == 2" class="space-y-2 text-gray-600"> <Checkbox v-model="options.splitYAxis" label="Split Y Axis" /> </div> <div> <label class="mb-1.5 block text-xs text-gray-600">Reference Line</label> <Autocomplete :modelValue="options.referenceLine" :options="['Average', 'Median', 'Min', 'Max']" @update:modelValue="options.referenceLine = $event?.value" /> </div> <ColorPalette v-model="options.colors" /> </template>
2302_79757062/insights
frontend/src/widgets/AxisChart/AxisChartOptions.vue
Vue
agpl-3.0
4,505
import { formatNumber, getShortNumber, ellipsis } from '@/utils' import { getColors as getDefaultColors } from '@/utils/colors' import { graphic } from 'echarts/core' export default function getAxisChartOptions({ chartType, options, data }) { const xAxisColumns = getXAxisColumns(options, data) const xAxisValues = getXAxisValues(xAxisColumns, data) const datasets = makeDatasets(options, data, xAxisColumns, xAxisValues) return makeOptions(chartType, xAxisValues, datasets, options) } function getXAxisColumns(options, data) { if (!options.xAxis || !options.xAxis.length) return [] const xAxisOptions = handleLegacyAxisOptions(options.xAxis) // remove the columns that might be removed from the query but not the chart return xAxisOptions .filter((xAxisOption) => data[0]?.hasOwnProperty(xAxisOption.column)) .map((op) => op.column) } function getXAxisValues(xAxisColumns, data) { if (!data?.length) return [] if (!xAxisColumns.length) return [] let firsXAxisColumn = xAxisColumns[0] if (typeof firsXAxisColumn !== 'string') { return console.warn('Invalid X-Axis option. Please re-select the X-Axis option.') } const values = data.map((d) => d[firsXAxisColumn]) return [...new Set(values)] } function makeDatasets(options, data, xAxisColumns, xAxisValues) { let yAxis = options.yAxis if (!data?.length || !yAxis?.length) return [] yAxis = handleLegacyAxisOptions(yAxis) const validYAxisOptions = yAxis // to exclude the columns that might be removed from the query but not the chart .filter( (yAxisOption) => data[0].hasOwnProperty(yAxisOption?.column) || data[0].hasOwnProperty(yAxisOption) ) if (xAxisColumns.length == 1) { // even if data has multiple points for each xAxisColumn // for eg. Oct has 3 price for each category // Month Category Price // Oct A 10 // Oct B 20 // Oct C 30 // so, we need to sum up the prices of each unique month const xAxisColumn = xAxisColumns[0] return validYAxisOptions.map((option) => { const column = option.column || option const seriesOptions = option.series_options || {} const _data = xAxisValues.map((xAxisValue) => { const points = data.filter((d) => d[xAxisColumn] === xAxisValue) const sum = points.reduce((acc, curr) => acc + curr[column], 0) return sum }) return { label: column, data: _data, series_options: seriesOptions, } }) } // if multiple xAxis columns are selected // then consider first xAxis column as labels // and other xAxis columns' values as series const datasets = [] const firstAxisColumn = xAxisColumns[0] const restAxisColumns = xAxisColumns.slice(1) for (let yAxisOption of validYAxisOptions) { const datamap = {} const column = yAxisOption.column || yAxisOption // "count" const seriesOptions = yAxisOption.series_options || {} // { type: "bar" } for (let xAxisOption of restAxisColumns) { // ["fruit"] let subXAxisValues = [...new Set(data.map((d) => d[xAxisOption]))] // fruit = ["apple", "banana"] for (let subXAxisValue of subXAxisValues) { // "Apple" let subXAxisData = data.filter((d) => d[xAxisOption] === subXAxisValue) // row with Apple for (let xAxisValue of xAxisValues) { // ["Monday", "Tuesday"] let dataSetStack = subXAxisData.find( (row) => row[firstAxisColumn] == xAxisValue ) // row with Apple and Monday // check if datamap has key subXAxisValue // add subXAxisValue: [dataSetStack.column] // if not dataSetStack.column, append 0 to datamap[subXAxisValue] let value = dataSetStack?.[column] || 0 if (subXAxisValue in datamap) { datamap[subXAxisValue].push(value) } else { datamap[subXAxisValue] = [value] } } } } for (const [label, data] of Object.entries(datamap)) { datasets.push({ label, data, series_options: seriesOptions, }) } } return datasets } function makeOptions(chartType, labels, datasets, options) { if (!datasets?.length) return {} const colors = options.colors?.length ? [...options.colors, ...getDefaultColors()] : getDefaultColors() return { animation: false, color: colors, grid: { top: 15, bottom: 35, left: 25, right: 35, containLabel: true, }, xAxis: { axisType: 'xAxis', type: 'category', axisTick: false, data: labels, splitLine: { show: chartType == 'scatter', lineStyle: { type: 'dashed' }, }, axisLabel: { rotate: options.rotateLabels, formatter: (value, _) => (!isNaN(value) ? getShortNumber(value, 1) : ellipsis(value, 20)), }, }, yAxis: datasets.map((dataset) => ({ name: options.splitYAxis ? dataset.label : undefined, nameGap: 45, nameLocation: 'middle', nameTextStyle: { color: 'transparent' }, type: 'value', splitLine: { lineStyle: { type: 'dashed' }, }, axisLabel: { formatter: (value, _) => (!isNaN(value) ? getShortNumber(value, 1) : ellipsis(value, 20)), }, min: options.yAxisMin, max: options.yAxisMax, })), series: datasets.map((dataset, index) => ({ name: dataset.label, data: dataset.data, type: chartType || dataset.series_options.type || 'bar', yAxisIndex: options.splitYAxis ? index : 0, color: dataset.series_options.color || colors[index], markLine: getMarkLineOption(options), // line styles smoothMonotone: 'x', smooth: dataset.series_options.smoothLines || options.smoothLines ? 0.4 : false, showSymbol: dataset.series_options.showPoints || options.showPoints, symbolSize: chartType == 'scatter' ? 10 : 5, areaStyle: dataset.series_options.showArea || options.showArea ? { color: new graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: dataset.series_options.color || colors[index] }, { offset: 1, color: '#fff' }, ]), opacity: 0.2, } : undefined, // bar styles itemStyle: { borderRadius: options.roundedBars != undefined && index == datasets.length - 1 ? [4, 4, 0, 0] : 0, }, barMaxWidth: 50, stack: options.stack ? 'stack' : null, })), legend: { icon: 'circle', type: 'scroll', bottom: 'bottom', pageIconSize: 12, pageIconColor: '#64748B', pageIconInactiveColor: '#C0CCDA', pageFormatter: '{current}', pageButtonItemGap: 2, }, tooltip: { trigger: 'axis', confine: true, appendToBody: false, valueFormatter: (value) => (isNaN(value) ? value : formatNumber(value)), }, } } function getMarkLineOption(options) { return options.referenceLine ? { data: [ { name: options.referenceLine, type: options.referenceLine.toLowerCase(), label: { position: 'middle', formatter: '{b}: {c}' }, }, ], } : {} } function handleLegacyAxisOptions(axisOptions) { // if axisOptions = 'column1' if (typeof axisOptions === 'string') { axisOptions = [{ column: axisOptions }] } // if axisOptions = ['column1', 'column2'] if (Array.isArray(axisOptions) && typeof axisOptions[0] === 'string') { axisOptions = axisOptions.map((column) => ({ column })) } return axisOptions }
2302_79757062/insights
frontend/src/widgets/AxisChart/getAxisChartOptions.js
JavaScript
agpl-3.0
7,138
<script setup> import BaseChart from '@/components/Charts/BaseChart.vue' import { computed } from 'vue' import getAxisChartOptions from '../AxisChart/getAxisChartOptions' import getBarChartOptions from './getBarChartOptions' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const barChartOptions = computed(() => { return getAxisChartOptions({ chartType: 'bar', options: props.options, data: props.data, }) }) </script> <template> <BaseChart :title="props.options.title" :options="barChartOptions" /> </template>
2302_79757062/insights
frontend/src/widgets/Bar/Bar.vue
Vue
agpl-3.0
592
<script setup> import AxisChartOptions from '@/widgets/AxisChart/AxisChartOptions.vue' const options = defineModel() const props = defineProps({ columns: { type: Array, required: true }, }) </script> <template> <div class="space-y-4"> <AxisChartOptions seriesType="bar" v-model:options="options" :columns="props.columns" /> <FormControl type="select" label="Rotate Labels" v-model="options.rotateLabels" :options="['0', '45', '90']" /> <Checkbox v-model="options.stack" label="Stack Values" /> <Checkbox v-model="options.roundedBars" label="Rounded Bars" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Bar/BarOptions.vue
Vue
agpl-3.0
605
import { formatNumber } from '@/utils' import { getColors } from '@/utils/colors' import { inject } from 'vue' export default function getBarChartOptions(labels, datasets, options) { const $utils = inject('$utils') if (!labels?.length || !datasets?.length) { return {} } const markLine = options.referenceLine ? { data: [ { name: options.referenceLine, type: options.referenceLine.toLowerCase(), label: { position: 'middle', formatter: '{b}: {c}' }, }, ], } : {} const axes = [ { type: 'category', data: options.invertAxis ? labels.reverse() : labels, axisTick: false, axisLabel: { rotate: options.rotateLabels, // interval: 0, formatter: (value, index) => !isNaN(value) ? $utils.getShortNumber(value, 1) : $utils.ellipsis(value, 20), }, }, { type: 'value', splitLine: { lineStyle: { type: 'dashed' }, }, axisLabel: { formatter: (value, index) => !isNaN(value) ? $utils.getShortNumber(value, 1) : $utils.ellipsis(value, 20), }, }, ] const colors = options.colors?.length ? [...options.colors, ...getColors()] : getColors() return { animation: false, color: colors, grid: { top: 15, bottom: 35, left: 25, right: 35, containLabel: true, }, xAxis: options.invertAxis ? axes[1] : axes[0], yAxis: options.invertAxis ? axes[0] : axes[1], series: datasets.map((dataset, index) => ({ type: 'bar', name: dataset.label, barMaxWidth: 50, data: options.invertAxis ? dataset.data.reverse() : dataset.data, itemStyle: { borderRadius: options.invertAxis ? [0, 4, 4, 0] : [4, 4, 0, 0], }, markLine: markLine, stack: options.stack ? 'stack' : null, color: dataset.series_options.color || colors[index], })), tooltip: { trigger: 'axis', confine: true, appendToBody: false, valueFormatter: (value) => (isNaN(value) ? value : formatNumber(value)), }, legend: { icon: 'circle', type: 'scroll', bottom: 'bottom', pageIconSize: 12, pageIconColor: '#64748B', pageIconInactiveColor: '#C0CCDA', pageFormatter: '{current}', pageButtonItemGap: 2, }, } }
2302_79757062/insights
frontend/src/widgets/Bar/getBarChartOptions.js
JavaScript
agpl-3.0
2,161
<script setup> import SimpleFilter from '@/dashboard/SimpleFilter.vue' import { computed, inject, provide } from 'vue' const props = defineProps({ item_id: { required: true }, options: { type: Object, required: true }, }) provide('item_id', props.item_id) const dashboard = inject('dashboard') const filterState = computed(() => dashboard.filterStates[props.item_id]) function saveFilterState(state) { dashboard.setFilterState(props.item_id, state) } </script> <template> <div class="flex w-full items-center" :class="[!filterState?.operator ? '!text-gray-600' : '']"> <SimpleFilter :disable-columns="true" :label="props.options.label" :column="props.options.column" :operator="filterState?.operator" :value="filterState?.value" @apply="saveFilterState" @reset="saveFilterState" ></SimpleFilter> </div> </template>
2302_79757062/insights
frontend/src/widgets/Filter/Filter.vue
Vue
agpl-3.0
848
<script setup> import { getQueriesColumn, getQueryColumns } from '@/dashboard/useDashboards' import FilterValueSelector from '@/query/visual/FilterValueSelector.vue' import { getOperatorOptions } from '@/utils' import { computed, inject, reactive, ref, watch } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, }) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) if (!options.value.links) options.value.links = {} if (!options.value.column) options.value.column = {} function updateOptions(key, value) { options.value = { ...options.value, [key]: value } } const dashboard = inject('dashboard') const charts = dashboard.doc.items.filter((item) => dashboard.isChart(item)) const queries = charts.map((i) => i.options.query) const filterColumnOptions = ref([]) getQueriesColumn(queries).then((columns) => { filterColumnOptions.value = columns.map((column) => { return { label: column.label, column: column.column, type: column.type, table: column.table, data_source: column.data_source, description: `${column.type} - ${column.table_label}`, value: `${column.table}.${column.column}`, } }) }) charts.forEach((chart) => { if (options.value.links[chart.item_id]) { setColumnOptions(chart) } }) async function handleCheck(checked, chartItem) { const links = options.value.links if (checked) { links[chartItem.item_id] = {} if (!chartColumnOptions[chartItem.options.query]) { // fetch and set the column options for this chart await setColumnOptions(chartItem) } // if there is a column named the same as the filter column, select it const column = chartColumnOptions[chartItem.options.query]?.find( (c) => c.column?.toLowerCase() === options.value.column.column?.toLowerCase() && c.table?.toLowerCase() === options.value.column.table?.toLowerCase() ) if (column) { links[chartItem.item_id] = column } } else { delete links[chartItem.item_id] } updateOptions('links', links) } const chartColumnOptions = reactive({}) async function setColumnOptions(chartItem) { const filter_column = options.value.column if (!filter_column?.column) return const columns = await getQueryColumns(chartItem.options.query) chartColumnOptions[chartItem.options.query] = columns.map((column) => { return { label: column.label, column: column.column, table: column.table, type: column.type, table_label: column.table_label, data_source: column.data_source, description: `${column.type} - ${column.table_label}`, value: `${column.table}.${column.column}`, } }) } const operatorOptions = computed(() => { const _options = getOperatorOptions(options.value.column?.type) return _options .filter((option) => option.value !== 'is') .concat([ { label: 'is set', value: 'is_set' }, { label: 'is not set', value: 'is_not_set' }, ]) }) // prettier-ignore watch(() => options.value.defaultOperator?.value, (newVal, oldVal) => { if (newVal !== oldVal) { options.value.defaultValue = {} } }) // watch(() => options.value.column?.column, () => { // // select all the charts that have this column // const links = options.value.links // const column = options.value.column // if (!column?.column) return // debugger // charts.forEach((chart) => { // if (chart.options.query && chartColumnOptions[chart.options.query]) { // const chartColumn = chartColumnOptions[chart.options.query].find( // (c) => c.column === column.column // ) // if (chartColumn) { // links[chart.item_id] = chartColumn // } // } // }) // updateOptions('links', links) // }) </script> <template> <div class="space-y-4"> <Input type="text" label="Label" v-model="options.label" placeholder="Enter filter label" ></Input> <div> <span class="mb-2 block text-sm leading-4 text-gray-700">Column</span> <Autocomplete v-model="options.column" :options="filterColumnOptions" placeholder="Select a column" ></Autocomplete> </div> <div> <span class="mb-2 block text-sm leading-4 text-gray-700">Default Operator</span> <Autocomplete v-model="options.defaultOperator" placeholder="Default Operator" :options="operatorOptions" ></Autocomplete> </div> <div v-if="options.column?.value"> <FilterValueSelector label="Default Value" :column="options.column" :operator="options.defaultOperator" :modelValue="options.defaultValue" :data-source="options.column?.data_source" @update:modelValue="options.defaultValue = $event" /> </div> <div v-if="options.column?.column"> <div class="mb-2 space-y-1"> <span class="block text-sm leading-4 text-gray-700">Links</span> <span class="block text-xs leading-4 text-gray-600"> Select charts to link to this filter. The filter will be applied to the selected column in the linked charts. </span> </div> <div class="max-h-[20rem] space-y-2 overflow-y-auto"> <div class="flex h-8 w-full items-center" v-for="chartItem in charts" :key="chartItem.item_id" > <Input type="checkbox" class="flex-shrink-0 focus:ring-0" @change="handleCheck($event, chartItem)" :value="options.links[chartItem.item_id]" ></Input> <span class="mx-2 flex-1 truncate text-base font-medium" :class="[ options.links[chartItem.item_id] ? 'text-gray-900' : 'font-normal text-gray-600', ]" > {{ chartItem.options.title }} </span> <Autocomplete v-if="options.links[chartItem.item_id] && chartItem.options.query" class="w-28 flex-shrink-0" placeholder="Select Column" :options="chartColumnOptions[chartItem.options.query]" v-model="options.links[chartItem.item_id]" empty-text="No matching columns found" ></Autocomplete> </div> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/widgets/Filter/FilterOptions.vue
Vue
agpl-3.0
6,002
<script setup> import BaseChart from '@/components/Charts/BaseChart.vue' import { computed } from 'vue' import getFunnelChartOptions from './getFunnelChartOptions' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const labels = computed(() => { if (!props.data?.length || !props.options.xAxis) return [] return props.data.map((d) => d[props.options.xAxis]) }) const dataset = computed(() => { if (!props.data?.length || !props.options.yAxis) return {} return { label: props.options.yAxis, data: props.data.map((d) => d[props.options.yAxis]), } }) const funnelChartOptions = computed(() => { return getFunnelChartOptions(labels.value, dataset.value, props.options) }) </script> <template> <BaseChart :title="props.options.title" :options="funnelChartOptions" /> </template>
2302_79757062/insights
frontend/src/widgets/Funnel/Funnel.vue
Vue
agpl-3.0
855
<script setup> import ColorPalette from '@/components/Controls/ColorPalette.vue' import { FIELDTYPES } from '@/utils' import { computed } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, columns: { type: Array, required: true }, }) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) const indexOptions = computed(() => { return props.columns ?.filter((column) => !FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) const valueOptions = computed(() => { return props.columns ?.filter((column) => FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) </script> <template> <div class="space-y-4"> <FormControl type="text" label="Title" class="w-full" v-model="options.title" placeholder="Title" /> <div> <label class="mb-1.5 block text-xs text-gray-600">X Axis</label> <Autocomplete :options="indexOptions" :modelValue="options.xAxis" @update:modelValue="options.xAxis = $event?.value" /> </div> <div> <label class="mb-1.5 block text-xs text-gray-600">Y Axis</label> <Autocomplete :options="valueOptions" :modelValue="options.yAxis" @update:modelValue="options.yAxis = $event?.value" /> </div> <ColorPalette v-model="options.colors" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Funnel/FunnelOptions.vue
Vue
agpl-3.0
1,575
import { formatNumber } from '@/utils' import { getColors } from '@/utils/colors' export default function getFunnelChartOptions(labels, dataset, options) { if (!labels?.length || !dataset?.data?.length) { return {} } const colors = options.colors?.length ? [...options.colors, ...getColors()] : getColors() return { animation: false, color: colors, tooltip: { trigger: 'item', confine: true, appendToBody: false, formatter: (value) => (isNaN(value) ? value : formatNumber(value)), }, legend: { data: labels, orient: 'vertical', left: '5%', top: 'center', formatter: (name) => { const index = labels.indexOf(name) const value = dataset.data[index] const percent = ((value / dataset.data[0]) * 100).toFixed(2) return `${name} (${percent}%)` }, }, series: [ { name: dataset.label, type: 'funnel', colorBy: 'data', orient: 'vertical', funnelAlign: 'center', top: 'center', left: '30%', width: '60%', height: '80%', min: 0, max: 100, minSize: '10%', maxSize: '100%', sort: 'descending', label: { show: true, position: 'inside', formatter: '{c}', }, gap: 14, data: dataset.data?.map((value, index) => ({ name: labels[index], value: value, itemStyle: { color: colors[index], borderColor: colors[index], borderWidth: 10, borderCap: 'round', borderJoin: 'round', }, emphasis: { itemStyle: { color: colors[index], borderColor: colors[index], borderWidth: 15, borderCap: 'round', borderJoin: 'round', }, }, })), }, ], } }
2302_79757062/insights
frontend/src/widgets/Funnel/getFunnelChartOptions.js
JavaScript
agpl-3.0
1,687
<script setup> const props = defineProps({ icon: { type: String, default: 'alert-triangle' }, iconClass: { type: String, default: 'text-yellow-400' }, title: { type: String, required: true, default: 'Invalid Widget' }, message: { type: String, default: 'Remove this widget and try adding a new one.', }, }) </script> <template> <div class="flex h-full w-full flex-col items-center justify-center"> <!-- Invalid Widget --> <FeatherIcon :name="icon" class="h-6 w-6" :class="iconClass" /> <span class="mt-2 text-gray-600">{{ title }}</span> <span class="text-center font-light text-gray-500">{{ message }}</span> </div> </template>
2302_79757062/insights
frontend/src/widgets/InvalidWidget.vue
Vue
agpl-3.0
649
<script setup> import BaseChart from '@/components/Charts/BaseChart.vue' import { computed } from 'vue' import getAxisChartOptions from '../AxisChart/getAxisChartOptions' import getLineChartOptions from './getLineChartOptions' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const lineChartOptions = computed(() => { return getAxisChartOptions({ chartType: 'line', options: props.options, data: props.data, }) }) </script> <template> <BaseChart :title="props.options.title" :options="lineChartOptions" /> </template>
2302_79757062/insights
frontend/src/widgets/Line/Line.vue
Vue
agpl-3.0
597
<script setup> import AxisChartOptions from '@/widgets/AxisChart/AxisChartOptions.vue' const options = defineModel() const props = defineProps({ columns: { type: Array, required: true }, }) </script> <template> <div class="space-y-4"> <AxisChartOptions seriesType="line" v-model:options="options" :columns="props.columns" /> <div class="space-y-2 text-gray-600"> <Checkbox v-model="options.smoothLines" label="Enable Curved Lines" /> </div> <div class="space-y-2 text-gray-600"> <Checkbox v-model="options.showPoints" label="Show Data Points" /> </div> <div class="space-y-2 text-gray-600"> <Checkbox v-model="options.showArea" label="Show Area" /> </div> </div> </template>
2302_79757062/insights
frontend/src/widgets/Line/LineOptions.vue
Vue
agpl-3.0
706
import { formatNumber } from '@/utils' import { getColors } from '@/utils/colors' import { graphic } from 'echarts/core' import { inject } from 'vue' import { getShortNumber } from '@/utils' export default function getLineChartOptions(labels, datasets, options) { if (!datasets || !datasets.length) { return {} } const markLine = options.referenceLine ? { data: [ { name: options.referenceLine, type: options.referenceLine.toLowerCase(), label: { position: 'middle', formatter: '{b}: {c}' }, }, ], } : {} const colors = options.colors?.length ? [...options.colors, ...getColors()] : getColors() return { animation: false, color: colors, grid: { top: 15, bottom: 35, left: 25, right: 35, containLabel: true, }, xAxis: { axisType: 'xAxis', type: 'category', axisTick: false, data: labels, }, yAxis: datasets.map((dataset) => ({ name: options.splitYAxis ? dataset.label : undefined, type: 'value', splitLine: { lineStyle: { type: 'dashed' }, }, axisLabel: { formatter: (value, index) => getShortNumber(value, 1), }, })), series: datasets.map((dataset, index) => ({ name: dataset.label, data: dataset.data, type: 'line', yAxisIndex: options.splitYAxis ? index : 0, color: dataset.series_options.color || colors[index], smooth: dataset.series_options.smoothLines || options.smoothLines ? 0.4 : false, smoothMonotone: 'x', showSymbol: dataset.series_options.showPoints || options.showPoints, markLine: markLine, areaStyle: dataset.series_options.showArea || options.showArea ? { color: new graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: dataset.series_options.color || colors[index] }, { offset: 1, color: '#fff' }, ]), opacity: 0.2, } : undefined, })), legend: { icon: 'circle', type: 'scroll', bottom: 'bottom', pageIconSize: 12, pageIconColor: '#64748B', pageIconInactiveColor: '#C0CCDA', pageFormatter: '{current}', pageButtonItemGap: 2, }, tooltip: { trigger: 'axis', confine: true, appendToBody: false, valueFormatter: (value) => (isNaN(value) ? value : formatNumber(value)), }, } }
2302_79757062/insights
frontend/src/widgets/Line/getLineChartOptions.js
JavaScript
agpl-3.0
2,254
<script setup> import BaseChart from '@/components/Charts/BaseChart.vue' import { computed } from 'vue' import getAxisChartOptions from '../AxisChart/getAxisChartOptions' import getMixedAxisChartOptions from './getMixedAxisChartOptions' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const mixedAxisChartOptions = computed(() => { return getAxisChartOptions({ chartType: undefined, options: props.options, data: props.data, }) }) </script> <template> <BaseChart :title="props.options.title" :options="mixedAxisChartOptions" /> </template>
2302_79757062/insights
frontend/src/widgets/MixedAxis/MixedAxis.vue
Vue
agpl-3.0
620
<script setup> import AxisChartOptions from '@/widgets/AxisChart/AxisChartOptions.vue' const options = defineModel() const props = defineProps({ columns: { type: Array, required: true }, }) </script> <template> <div class="space-y-4"> <AxisChartOptions v-model:options="options" :columns="props.columns" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/MixedAxis/MixedAxisOptions.vue
Vue
agpl-3.0
333
import { formatNumber, getShortNumber } from '@/utils' import { getColors } from '@/utils/colors' export default function getMixedAxisChartOptions(labels, datasets, options) { if (!datasets || !datasets.length) { return {} } const markLine = options.referenceLine ? { data: [ { name: options.referenceLine, type: options.referenceLine.toLowerCase(), label: { position: 'middle', formatter: '{b}: {c}' }, }, ], } : {} const colors = options.colors?.length ? [...options.colors, ...getColors()] : getColors() return { animation: false, color: colors, grid: { top: 15, bottom: 35, left: 25, right: 35, containLabel: true, }, xAxis: { axisType: 'xAxis', type: 'category', axisTick: false, data: labels, }, yAxis: datasets.map((dataset) => ({ name: options.splitYAxis ? dataset.label : undefined, nameLocation: 'middle', nameGap: 45, nameTextStyle: { color: 'transparent' }, type: 'value', splitLine: { lineStyle: { type: 'dashed' }, }, axisLabel: { formatter: (value, index) => getShortNumber(value, 1), }, })), series: datasets.map((dataset, index) => ({ name: dataset.label, data: dataset.data, type: dataset.series_options.type || 'line', color: dataset.series_options.color || colors[index], yAxisIndex: options.splitYAxis ? index : 0, smooth: dataset.series_options.smoothLines ? 0.4 : false, smoothMonotone: 'x', showSymbol: dataset.series_options.showPoints, markLine: markLine, areaStyle: dataset.series_options.showArea || options.showArea ? { color: new graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: dataset.series_options.color || colors[index] }, { offset: 1, color: '#fff' }, ]), opacity: 0.2, } : undefined, itemStyle: { borderRadius: options.invertAxis ? [0, 4, 4, 0] : [4, 4, 0, 0], }, barMaxWidth: 50, })), legend: { icon: 'circle', type: 'scroll', bottom: 'bottom', pageIconSize: 12, pageIconColor: '#64748B', pageIconInactiveColor: '#C0CCDA', pageFormatter: '{current}', pageButtonItemGap: 2, }, tooltip: { trigger: 'axis', confine: true, appendToBody: false, valueFormatter: (value) => (isNaN(value) ? value : formatNumber(value)), }, } }
2302_79757062/insights
frontend/src/widgets/MixedAxis/getMixedAxisChartOptions.js
JavaScript
agpl-3.0
2,349
<script setup> import { computed, inject } from 'vue' const $utils = inject('$utils') const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const formattedValue = computed(() => { if (!props.data?.length) return if (!props.options.column) return const _value = props.data.reduce((acc, row) => { return acc + row[props.options.column] }, 0) if (!props.options.hasOwnProperty('shorten') || props.options.shorten) { return $utils.getShortNumber(_value, props.options.decimals) } return $utils.formatNumber(_value, props.options.decimals) }) </script> <template> <div v-if="formattedValue" class="flex h-full w-full items-center justify-center overflow-hidden px-8 py-4" > <div class="mx-auto flex h-full max-h-[10rem] w-full min-w-40 max-w-[20rem] flex-col justify-center overflow-y-auto" > <div class="w-full"> <span class="truncate font-medium leading-6">{{ props.options.title }}</span> </div> <div class="text-[28px] font-medium leading-10"> {{ props.options.prefix }}{{ formattedValue }}{{ props.options.suffix }} </div> </div> </div> <template v-else> <slot name="placeholder"></slot> </template> </template>
2302_79757062/insights
frontend/src/widgets/Number/Number.vue
Vue
agpl-3.0
1,229
<script setup> import { FIELDTYPES } from '@/utils' import { computed } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, columns: { type: Array, required: true }, }) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) const columnOptions = computed(() => { return props.columns ?.filter((column) => FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) </script> <template> <div class="space-y-4"> <FormControl type="text" label="Title" class="w-full" v-model="options.title" placeholder="Title" /> <div> <span class="mb-2 block text-sm leading-4 text-gray-700">Number Column</span> <Autocomplete :options="columnOptions" :modelValue="options.column" @update:modelValue="options.column = $event?.value" /> </div> <div> <span class="mb-2 block text-sm leading-4 text-gray-700">Prefix</span> <Input type="text" v-model="options.prefix" placeholder="Enter a prefix..." /> </div> <div> <span class="mb-2 block text-sm leading-4 text-gray-700">Suffix</span> <Input type="text" v-model="options.suffix" placeholder="Enter a suffix..." /> </div> <div> <span class="mb-2 block text-sm leading-4 text-gray-700">Decimals</span> <Input type="number" v-model="options.decimals" placeholder="Enter a number..." /> </div> <Checkbox v-model="options.shorten" label="Shorten Numbers" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Number/NumberOptions.vue
Vue
agpl-3.0
1,615
<script setup> import BaseChart from '@/components/Charts/BaseChart.vue' import { computed } from 'vue' import getPieChartOptions from './getPieChartOptions' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const labels = computed(() => { if (!props.data?.length || !props.options.xAxis) return [] return props.data.map((d) => d[props.options.xAxis]) }) const dataset = computed(() => { if (!props.data?.length || !props.options.yAxis) return {} return { label: props.options.yAxis, data: props.data.map((d) => d[props.options.yAxis]), } }) const pieChartOptions = computed(() => { return getPieChartOptions(labels.value, dataset.value, props.options) }) </script> <template> <BaseChart :title="props.options.title" :options="pieChartOptions" /> </template>
2302_79757062/insights
frontend/src/widgets/Pie/Pie.vue
Vue
agpl-3.0
840
<script setup> import ColorPalette from '@/components/Controls/ColorPalette.vue' import { FIELDTYPES } from '@/utils' import { computed } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, columns: { type: Array, required: true }, }) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) const indexOptions = computed(() => { return props.columns ?.filter((column) => !FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) const valueOptions = computed(() => { return props.columns ?.filter((column) => FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) </script> <template> <div class="space-y-4"> <FormControl type="text" label="Title" class="w-full" v-model="options.title" placeholder="Title" /> <div> <label class="mb-1.5 block text-xs text-gray-600">Label Column</label> <Autocomplete :options="indexOptions" :modelValue="options.xAxis" @update:modelValue="options.xAxis = $event?.value" /> </div> <div> <label class="mb-1.5 block text-xs text-gray-600">Value Column</label> <Autocomplete :options="valueOptions" :modelValue="options.yAxis" @update:modelValue="options.yAxis = $event?.value" /> </div> <div> <label class="mb-1.5 block text-xs text-gray-600">Max Slices</label> <FormControl v-model="options.maxSlices" type="number" min="1" /> </div> <ColorPalette v-model="options.colors" /> <div v-show="!options.inlineLabels"> <label class="mb-1.5 block text-xs text-gray-600">Label Position</label> <Autocomplete v-model="options.labelPosition" :options="['Top', 'Left', 'Bottom', 'Right']" /> </div> <Checkbox v-model="options.inlineLabels" label="Inline Labels" /> <Checkbox v-model="options.scrollLabels" label="Paginate Labels" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Pie/PieOptions.vue
Vue
agpl-3.0
2,119
import { ellipsis, formatNumber } from '@/utils' import { getColors } from '@/utils/colors' export default function getPieChartOptions(labels, dataset, options) { const MAX_SLICES = 9 if (!labels?.length || !dataset?.data?.length) { return {} } const colors = options.colors?.length ? [...options.colors, ...getColors()] : getColors() const slices = dataset.data.slice(0, parseInt(options.maxSlices) || MAX_SLICES) const otherSlices = dataset.data .slice(parseInt(options.maxSlices) || 9) .reduce((a, b) => a + b, 0) const data = slices.map((value, index) => { return { name: labels[index], value: value, itemStyle: { color: colors[index], }, } }) if (otherSlices) { data.push({ name: 'Others', value: otherSlices, itemStyle: { color: colors[slices.length] }, }) } const legendOptions = { type: 'plain', bottom: 0 } let center = ['50%', '50%'] let radius = ['40%', '70%'] if (!options.inlineLabels && options.labelPosition) { const position = options.labelPosition updateLegendOptions(position.value ?? position) } function updateLegendOptions(position) { legendOptions.type = options.scrollLabels ? 'scroll' : 'plain' legendOptions.orient = position === 'Top' || position === 'Bottom' ? 'horizontal' : 'vertical' switch (position) { case 'Top': radius = ['40%', '70%'] legendOptions.top = 0 legendOptions.left = 'center' center = ['50%', '60%'] legendOptions.padding = 20 break case 'Bottom': radius = ['40%', '70%'] legendOptions.bottom = 0 legendOptions.left = 'center' center = ['50%', '43%'] legendOptions.padding = [20, 20, 10, 20] break case 'Right': radius = ['45%', '80%'] center = ['33%', '50%'] legendOptions.left = '63%' legendOptions.top = 'middle' legendOptions.padding = [20, 0, 20, 0] break case 'Left': radius = ['45%', '80%'] center = ['67%', '50%'] legendOptions.right = '63%' legendOptions.top = 'middle' legendOptions.padding = [20, 0, 20, 0] break } } function formatLabel({ name, percent }) { return `${ellipsis(name, 20)} (${percent.toFixed(0)}%)` } function formatLegend(name) { let total = dataset.data.reduce((a, b) => a + b, 0) const labelIndex = labels.indexOf(name) if (labelIndex === -1 && name == 'Others') { const otherSlicesTotal = dataset.data .slice(parseInt(options.maxSlices) || MAX_SLICES) .reduce((a, b) => a + b, 0) const percent = (otherSlicesTotal / total) * 100 return `${ellipsis(name, 20)} (${percent.toFixed(0)}%)` } const percent = (dataset.data[labelIndex] / total) * 100 return `${ellipsis(name, 20)} (${percent.toFixed(0)}%)` } function appendPercentage(value) { let total = dataset.data.reduce((a, b) => a + b, 0) const percent = (value / total) * 100 return `${formatNumber(value, 2)} (${percent.toFixed(0)}%)` } return { animation: false, color: colors, series: [ { type: 'pie', name: dataset.label, data: data, center: center, radius: radius, labelLine: { show: options.inlineLabels, lineStyle: { width: 2, }, length: 10, length2: 20, smooth: true, }, label: { show: options.inlineLabels, formatter: formatLabel, }, emphasis: { scaleSize: 5, }, }, ], tooltip: { trigger: 'item', confine: true, appendToBody: false, valueFormatter: appendPercentage, }, legend: !options.inlineLabels ? { type: 'plain', icon: 'circle', pageIconSize: 12, pageIconColor: '#64748B', pageIconInactiveColor: '#C0CCDA', pageFormatter: '{current}', pageButtonItemGap: 2, ...legendOptions, formatter: formatLegend, } : undefined, } }
2302_79757062/insights
frontend/src/widgets/Pie/getPieChartOptions.js
JavaScript
agpl-3.0
3,783
<script setup> import ChartTitle from '@/components/Charts/ChartTitle.vue' import TanstackTable from '@/components/Table/TanstackTable.vue' import { watchDebounced } from '@vueuse/core' import { call } from 'frappe-ui' import { computed, ref, watch } from 'vue' import { convertToNestedObject, convertToTanstackColumns } from './utils' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const _data = computed(() => props.data) watch(_data, reloadPivotData, { deep: true }) const indexColumns = computed(() => props.options.rows?.map((column) => column.value) || []) const pivotColumns = computed(() => props.options.columns?.map((column) => column.value) || []) const valueColumns = computed(() => props.options.values?.map((column) => column.value) || []) const pivotedData = ref([]) watchDebounced( [indexColumns, pivotColumns, valueColumns], (newVal, oldVal) => { if (JSON.stringify(newVal) == JSON.stringify(oldVal)) return reloadPivotData() }, { deep: true, immediate: true, debounce: 500, } ) function reloadPivotData() { call('insights.api.queries.pivot', { data: _data.value, indexes: indexColumns.value, columns: pivotColumns.value, values: valueColumns.value, }).then((data) => (pivotedData.value = sortIndexKeys(data))) } function sortIndexKeys(data) { // move the index columns (keys) to the front of the object return data.map((row) => { const indexKeyValues = indexColumns.value.reduce((acc, key) => { acc[key] = row[key] return acc }, {}) return { ...indexKeyValues, ...row } }) } const tanstackColumns = computed(() => { if (!pivotedData.value.length) return [] const firstPivotedRow = pivotedData.value[0] if (!firstPivotedRow) return [] const nestedRowObject = convertToNestedObject(firstPivotedRow) return convertToTanstackColumns(nestedRowObject) }) </script> <template> <div class="flex h-full w-full flex-col"> <ChartTitle :title="props.options.title" /> <TanstackTable v-if="props.options?.columns?.length || props.data?.length" :data="pivotedData" :columns="tanstackColumns" :showFooter="Boolean(props.options.showTotal)" :showFilters="Boolean(props.options.filtersEnabled)" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/PivotTable/PivotTable.vue
Vue
agpl-3.0
2,265
<script setup> import { computed } from 'vue' import DraggableList from '@/components/DraggableList.vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, columns: { type: Array, required: true }, }) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) if (!options.value.rows) options.value.rows = [] if (!options.value.columns) options.value.columns = [] if (!options.value.values) options.value.values = [] const columnOptions = computed(() => { return props.columns?.map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) </script> <template> <div class="space-y-4"> <FormControl type="text" label="Title" class="w-full" v-model="options.title" placeholder="Title" /> <div> <div class="mb-1 flex items-center justify-between"> <label class="block text-xs text-gray-600">Rows</label> <Autocomplete :multiple="true" v-model="options.rows" :options="columnOptions"> <template #target="{ togglePopover }"> <Button variant="ghost" icon="plus" @click="togglePopover"></Button> </template> </Autocomplete> </div> <DraggableList v-model:items="options.rows" group="columnOptions" empty-text="No rows selected" > </DraggableList> </div> <div> <div class="mb-1 flex items-center justify-between"> <label class="block text-xs text-gray-600">Columns</label> <Autocomplete :multiple="true" v-model="options.columns" :options="columnOptions"> <template #target="{ togglePopover }"> <Button variant="ghost" icon="plus" @click="togglePopover"></Button> </template> </Autocomplete> </div> <DraggableList v-model:items="options.columns" group="columnOptions" emtpy-text="No columns selected" > </DraggableList> </div> <div> <div class="mb-1 flex items-center justify-between"> <label class="block text-xs text-gray-600">Values</label> <Autocomplete :multiple="true" v-model="options.values" :options="columnOptions"> <template #target="{ togglePopover }"> <Button variant="ghost" icon="plus" @click="togglePopover"></Button> </template> </Autocomplete> </div> <DraggableList v-model:items="options.values" group="columnOptions" emtpy-text="No values selected" > </DraggableList> </div> <Checkbox v-model="options.showTotal" label="Show Total Row" /> <Checkbox v-model="options.filtersEnabled" label="Show Filter Row" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/PivotTable/PivotTableOptions.vue
Vue
agpl-3.0
2,617
import { getFormattedCell } from '@/components/Table/utils' import { formatNumber } from '@/utils' import { createColumnHelper } from '@tanstack/vue-table' /** * A recursive function to convert a flat dict to a nested dict * Input: { * "Date": "2018-01-01", * "OK___No___Price": 100, * "OK___No___Quantity": 10, * ... * } * * Output: { * "Date": "2018-01-01", * "OK": { * "No": { * "Price": 100, * "Quantity": 10 * } * } * } */ export function convertToNestedObject(pivotedRow, seperator = '___') { if (!pivotedRow) return {} const new_obj = {} for (const key in pivotedRow) { if (!key.includes(seperator)) { new_obj[key] = pivotedRow[key] continue } const [new_key, ...rest] = key.split(seperator) new_obj[new_key] = new_obj[new_key] || {} const rest_key = rest.join(seperator) new_obj[new_key][rest_key] = pivotedRow[key] } for (const key in new_obj) { if (typeof new_obj[key] === 'object') { new_obj[key] = convertToNestedObject(new_obj[key]) } } return new_obj } /** * A recursive function to convert a nested dict to a tanstack column * Input: { * "Date": "2018-01-01", * "OK": { * "No": { * "Price": 100, * "Quantity": 10 * } * } * } * * Output: [ * { header: "Date", id: "Date" }, * { header: "OK", children: [ * { header: "No", children: [ * { header: "Price", id: "OK___No___Price" }, * { header: "Quantity", id: "OK___No___Quantity" } * ]} * ]} * ] */ export function convertToTanstackColumns(pivotedRow, idPrefix = '', seperator = '___') { const columnHelper = createColumnHelper() return _convertToTanstackColumns(columnHelper, pivotedRow, idPrefix, seperator) } function _convertToTanstackColumns(columnHelper, pivotedRow, idPrefix = '', seperator = '___') { const columns = [] for (const key in pivotedRow) { if (typeof pivotedRow[key] === 'object') { const children = _convertToTanstackColumns( columnHelper, pivotedRow[key], idPrefix + key + seperator ) columns.push(columnHelper.group({ header: key, columns: children })) } else { const valueIsNumber = typeof pivotedRow[key] === 'number' columns.push( columnHelper.accessor(idPrefix + key, { header: key, isNumber: valueIsNumber, filterFn: 'filterFunction', cell: (props) => valueIsNumber && props.getValue() == 0 ? '' : getFormattedCell(props.getValue()), footer: (props) => { if (!valueIsNumber) return '' const filteredRows = props.table.getFilteredRowModel().rows const values = filteredRows.map((row) => row.getValue(idPrefix + key)) return formatNumber( values.reduce((acc, curr) => acc + curr, 0), 2 ) }, }) ) } } return columns }
2302_79757062/insights
frontend/src/widgets/PivotTable/utils.js
JavaScript
agpl-3.0
2,769
<script setup> import { getShortNumber } from '@/utils' import { computed } from 'vue' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const progress = computed(() => { if (!props.options.progress) return 0 return props.data.reduce((acc, row) => acc + row[props.options.progress], 0) }) const target = computed(() => { if (!props.options.target) return 0 if (props.options.targetType === 'Value') return parseInt(props.options.target) return props.data.reduce((acc, row) => acc + row[props.options.target], 0) }) function formatValue(value) { if (props.options.shorten) { return getShortNumber(value, props.options.decimals) } return Number(value).toLocaleString(undefined, { maximumFractionDigits: props.options.decimals, }) } const progressPercent = computed(() => { const percent = ((progress.value * 100) / target.value).toFixed(2) return percent > 100 ? 100 : percent < 0 ? 0 : percent }) </script> <template> <div class="flex h-full w-full items-center justify-center rounded p-6"> <div class="h-fit w-full max-w-[22rem]"> <div> <div class="w-full overflow-hidden text-ellipsis whitespace-nowrap font-medium leading-6" > {{ props.options.title }} </div> <div class="text-[28px] font-medium leading-8"> {{ props.options.prefix }}{{ formatValue(progress) }}{{ props.options.suffix }} </div> </div> <div class="my-2"> <div class="flex justify-between text-xs tracking-wide text-gray-600"> <div>{{ progressPercent }}%</div> <div> {{ props.options.prefix }}{{ formatValue(target) }}{{ props.options.suffix }} </div> </div> <div class="mt-1 rounded-full bg-blue-100"> <div class="h-1.5 rounded-full bg-blue-500" :style="{ width: progressPercent > 100 ? '100%' : progressPercent + '%' }" ></div> </div> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/widgets/Progress/Progress.vue
Vue
agpl-3.0
1,942
<script setup> import InputWithTabs from '@/components/Controls/InputWithTabs.vue' import { FIELDTYPES } from '@/utils' import { computed } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, columns: { type: Array, required: true }, }) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) const valueOptions = computed(() => { return props.columns ?.filter((column) => FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) if (!options.value.targetType) { options.value.targetType = 'Column' } </script> <template> <div class="space-y-4"> <FormControl type="text" label="Title" class="w-full" v-model="options.title" placeholder="Title" /> <div> <label class="mb-1.5 block text-xs text-gray-600">Progress Column</label> <Autocomplete :options="valueOptions" :modelValue="options.progress" @update:modelValue="options.progress = $event?.value" /> </div> <div> <label class="mb-1.5 block text-xs text-gray-600">Target</label> <InputWithTabs :value="options.targetType" :tabs="{ Column: options.targetType === 'Column', Value: options.targetType === 'Value', }" @tab-change="options.targetType = $event" > <template #inputs> <div class="w-full"> <Autocomplete v-if="options.targetType === 'Column'" placeholder="Select a column..." :options="valueOptions" :modelValue="options.target" @update:modelValue="options.target = $event?.value" /> <FormControl v-if="options.targetType === 'Value'" v-model="options.target" placeholder="Enter a value..." type="number" /> </div> </template> </InputWithTabs> </div> <FormControl label="Prefix" type="text" v-model="options.prefix" placeholder="Enter a prefix..." /> <FormControl label="Suffix" type="text" v-model="options.suffix" placeholder="Enter a suffix..." /> <FormControl label="Decimals" type="number" v-model="options.decimals" placeholder="Enter a number..." /> <Checkbox v-model="options.shorten" label="Shorten Numbers" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Progress/ProgressOptions.vue
Vue
agpl-3.0
2,381
<script setup> import BaseChart from '@/components/Charts/BaseChart.vue' import { computed } from 'vue' import getAxisChartOptions from '../AxisChart/getAxisChartOptions' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const rowChartOptions = computed(() => { const barChartOptions = getAxisChartOptions({ chartType: 'bar', options: props.options, data: props.data, }) if (!barChartOptions.xAxis || !barChartOptions.yAxis) { return barChartOptions } const yAxis = barChartOptions.yAxis || {} const xAxis = barChartOptions.xAxis || {} xAxis.data = xAxis.data?.reverse() const datasets = barChartOptions.series.map((dataset) => { dataset.data = dataset.data.reverse() dataset.itemStyle.borderRadius = [0, 4, 4, 0] return dataset }) return { ...barChartOptions, xAxis: yAxis, yAxis: xAxis, series: datasets, } }) </script> <template> <BaseChart :title="props.options.title" :options="rowChartOptions" /> </template>
2302_79757062/insights
frontend/src/widgets/Row/Row.vue
Vue
agpl-3.0
1,021
<script setup> import AxisChartOptions from '@/widgets/AxisChart/AxisChartOptions.vue' const options = defineModel() const props = defineProps({ columns: { type: Array, required: true }, }) </script> <template> <div class="space-y-4"> <AxisChartOptions seriesType="bar" v-model:options="options" :columns="props.columns" /> <Checkbox v-model="options.stack" label="Stack Values" /> <Checkbox v-model="options.roundedBars" label="Rounded Bars" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Row/RowOptions.vue
Vue
agpl-3.0
476
import { formatNumber } from '@/utils' import { getColors } from '@/utils/colors' import { inject } from 'vue' export default function getBarChartOptions(labels, datasets, options) { const axes = [ { type: 'category', data: options.invertAxis ? labels.reverse() : labels, axisTick: false, axisLabel: { rotate: options.rotateLabels, // interval: 0, formatter: (value, index) => !isNaN(value) ? $utils.getShortNumber(value, 1) : $utils.ellipsis(value, 20), }, }, { type: 'value', splitLine: { lineStyle: { type: 'dashed' }, }, axisLabel: { formatter: (value, index) => !isNaN(value) ? $utils.getShortNumber(value, 1) : $utils.ellipsis(value, 20), }, }, ] const colors = options.colors?.length ? [...options.colors, ...getColors()] : getColors() return { animation: false, color: colors, grid: { top: 15, bottom: 35, left: 25, right: 35, containLabel: true, }, xAxis: options.invertAxis ? axes[1] : axes[0], yAxis: options.invertAxis ? axes[0] : axes[1], series: datasets.map((dataset, index) => ({ type: 'bar', name: dataset.label, barMaxWidth: 50, data: options.invertAxis ? dataset.data.reverse() : dataset.data, itemStyle: { borderRadius: options.invertAxis ? [0, 4, 4, 0] : [4, 4, 0, 0], }, markLine: markLine, stack: options.stack ? 'stack' : null, color: dataset.series_options.color || colors[index], })), tooltip: { trigger: 'axis', confine: true, appendToBody: false, valueFormatter: (value) => (isNaN(value) ? value : formatNumber(value)), }, legend: { icon: 'circle', type: 'scroll', bottom: 'bottom', pageIconSize: 12, pageIconColor: '#64748B', pageIconInactiveColor: '#C0CCDA', pageFormatter: '{current}', pageButtonItemGap: 2, }, } }
2302_79757062/insights
frontend/src/widgets/Row/getRowChartOptions.js
JavaScript
agpl-3.0
1,828
<script setup> import BaseChart from '@/components/Charts/BaseChart.vue' import { computed } from 'vue' import getScatterChartOptions from './getScatterChartOptions' import getAxisChartOptions from '../AxisChart/getAxisChartOptions' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const scatterChartOptions = computed(() => { return getAxisChartOptions({ chartType: 'scatter', options: props.options, data: props.data, }) }) </script> <template> <BaseChart :title="props.options.title" :options="scatterChartOptions" /> </template>
2302_79757062/insights
frontend/src/widgets/Scatter/Scatter.vue
Vue
agpl-3.0
612
<script setup> import ColorPalette from '@/components/Controls/ColorPalette.vue' import AxisChartOptions from '@/widgets/AxisChart/AxisChartOptions.vue' const emit = defineEmits(['update:modelValue']) const options = defineModel() const props = defineProps({ columns: { type: Array, required: true }, }) </script> <template> <div class="space-y-4"> <AxisChartOptions v-model:options="options" :columns="props.columns" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Scatter/ScatterOptions.vue
Vue
agpl-3.0
447
import { formatNumber } from '@/utils' import { getColors } from '@/utils/colors' import { inject } from 'vue' export default function getScatterChartOptions(labels, datasets, options) { const $utils = inject('$utils') if (!labels?.length || !datasets?.length) { return {} } const colors = options.colors?.length ? [...options.colors, ...getColors()] : getColors() return { animation: false, color: colors, grid: { top: 15, bottom: 35, left: 25, right: 35, containLabel: true, }, xAxis: { axisType: 'xAxis', type: 'category', axisTick: false, data: labels, splitLine: { show: true, lineStyle: { type: 'dashed' }, }, }, yAxis: { axisType: 'yAxis', type: 'value', splitLine: { lineStyle: { type: 'dashed' }, }, axisLabel: { formatter: (value, index) => $utils.getShortNumber(value, 1), }, }, series: datasets.map((dataset, index) => ({ name: dataset.label, data: dataset.data, color: colors[index], type: 'scatter', symbolSize: 10, })), legend: { icon: 'circle', type: 'scroll', bottom: 'bottom', pageIconSize: 12, pageIconColor: '#64748B', pageIconInactiveColor: '#C0CCDA', pageFormatter: '{current}', pageButtonItemGap: 2, }, tooltip: { trigger: 'axis', confine: true, appendToBody: true, valueFormatter: (value) => (isNaN(value) ? value : formatNumber(value)), }, } }
2302_79757062/insights
frontend/src/widgets/Scatter/getScatterChartOptions.js
JavaScript
agpl-3.0
1,427
<script setup> import ColorInput from '@/components/Controls/ColorInput.vue' import { computed } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { required: true }, seriesType: { type: String }, }) const series = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) if (props.seriesType) series.value.type = props.seriesType if (!series.value.type) series.value.type = 'bar' </script> <template> <div class="flex flex-col gap-3"> <div v-if="!props.seriesType"> <FormControl label="Axis Type" type="select" :options="[ { label: 'Line', value: 'line' }, { label: 'Bar', value: 'bar' }, ]" v-model="series.type" /> </div> <ColorInput label="Color" v-model="series.color" placement="right-start" /> <template v-if="series.type == 'line'"> <Checkbox v-model="series.smoothLines" label="Enable Curved Lines" /> <Checkbox v-model="series.showPoints" label="Show Data Points" /> <Checkbox v-model="series.showArea" label="Show Area" /> </template> </div> </template>
2302_79757062/insights
frontend/src/widgets/SeriesOption.vue
Vue
agpl-3.0
1,115
<script setup> import ChartTitle from '@/components/Charts/ChartTitle.vue' import TanstackTable from '@/components/Table/TanstackTable.vue' import { getCellComponent } from '@/components/Table/utils' import { formatNumber } from '@/utils' import { computed } from 'vue' const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const columns = computed(() => { if (!props.options.columns?.length) return [] if (typeof props.options.columns[0] === 'string') { return props.options.columns.map((column) => ({ column, column_options: {}, })) } return props.options.columns.map((column) => ({ column: column.column || column.label || column.value, column_options: column.column_options || {}, })) }) const numberColumns = computed(() => { if (!columns.value?.length || !props.data?.length) return [] return columns.value .filter((column) => props.data.every((row) => typeof row[column.column] == 'number')) .map((column) => column.column) }) const tanstackColumns = computed(() => { if (!columns.value?.length) return [] if (columns.value.some((c) => !c.column)) return [] const indexColumn = { id: '__index', header: '#', accessorKey: '__index', enableColumnFilter: false, cell: (props) => props.row.index + 1, footer: 'Total', } const cols = columns.value.map((column) => { return { id: column.column, header: column.column, accessorKey: column.column, filterFn: 'filterFunction', isNumber: numberColumns.value.includes(column.column), cell: (props) => getCellComponent(props, column), footer: (props) => { const isNumberColumn = numberColumns.value.includes(column.column) if (!isNumberColumn) return '' const filteredRows = props.table.getFilteredRowModel().rows const values = filteredRows.map((row) => row.getValue(column.column)) return formatNumber( values.reduce((acc, curr) => acc + curr, 0), 2 ) }, } }) return props.options.index ? [indexColumn, ...cols] : cols }) </script> <template> <div class="flex h-full w-full flex-col"> <ChartTitle v-if="props.options.title" :title="props.options.title" /> <TanstackTable v-if="columns.length || props.data?.length" :data="props.data" :columns="tanstackColumns" :showFooter="props.options.showTotal" :showFilters="Boolean(props.options.filtersEnabled)" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Table/Table.vue
Vue
agpl-3.0
2,418
<script setup> import { FIELDTYPES } from '@/utils' import { dateFormats } from '@/utils/format' import { computed } from 'vue' const props = defineProps({ modelValue: { type: Object, required: true }, column: { type: Object, required: true }, }) if (!props.modelValue.column_type) { props.modelValue.column_type = FIELDTYPES.NUMBER.includes(props.column?.type) ? 'Number' : FIELDTYPES.DATE.includes(props.column?.type) ? 'Date' : 'Text' } const emit = defineEmits(['update:modelValue']) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) const columnTypeOptions = computed(() => { if (!props.column?.type) return [] if (FIELDTYPES.NUMBER.includes(props.column?.type)) { return ['Number', 'Text', 'Link'] } if (FIELDTYPES.TEXT.includes(props.column?.type)) { return ['Text', 'Link'] } if (FIELDTYPES.DATE.includes(props.column?.type)) { return ['Text', 'Date'] } return [] }) </script> <template> <div class="flex flex-col gap-3"> <FormControl label="Column Type" type="select" :options="columnTypeOptions" v-model="options.column_type" /> <FormControl v-if="options.column_type === 'Link'" type="text" label="Link URL" autocomplete="off" placeholder="eg. https://github.com/{{ value }}" description="Use {{ value }} to substitute the value of the column" v-model="options.link_url" /> <FormControl v-if="options.column_type === 'Number'" type="text" label="Prefix" autocomplete="off" v-model="options.prefix" placeholder="Enter a prefix..." /> <FormControl v-if="options.column_type === 'Number'" type="text" label="Suffix" autocomplete="off" v-model="options.suffix" placeholder="Enter a suffix..." /> <FormControl v-if="options.column_type === 'Number'" type="number" label="Decimals" autocomplete="off" v-model="options.decimals" placeholder="Enter a number..." /> <Checkbox v-if="options.column_type === 'Number'" v-model="options.show_inline_bar_chart" label="Show Inline Bar Chart" /> <FormControl v-if="options.column_type === 'Date'" type="select" label="Date Format" autocomplete="off" v-model="options.date_format" placeholder="Select a date format..." :options="dateFormats" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Table/TableColumnOptions.vue
Vue
agpl-3.0
2,346
<script setup> import Autocomplete from '@/components/Controls/Autocomplete.vue' import DraggableList from '@/components/DraggableList.vue' import DraggableListItemMenu from '@/components/DraggableListItemMenu.vue' import { computed } from 'vue' import TableColumnOptions from './TableColumnOptions.vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, columns: { type: Array, required: true }, }) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) if (!options.value.columns) { options.value.columns = [] } // handle legacy columns format if (Array.isArray(options.value.columns) && typeof options.value.columns[0] === 'string') { options.value.columns = options.value.columns.map((column) => ({ column, column_options: {}, })) } options.value.columns.forEach((item) => { if (!item.column) item.column = item.label || item.value if (!item.column_options) item.column_options = {} }) const columnOptions = computed(() => { return props.columns?.map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) function updateColumns(columnOptions) { options.value.columns = columnOptions.map((option) => { const existingColumn = options.value.columns.find((c) => c.label === option.value) const column_options = existingColumn ? existingColumn.column_options : {} return { column: option.value, column_options, } }) } </script> <template> <div> <div class="mb-1 flex items-center justify-between"> <label class="block text-xs text-gray-600">Columns</label> <Autocomplete :multiple="true" :options="columnOptions" :modelValue="options.columns" @update:model-value="updateColumns" > <template #target="{ togglePopover }"> <Button variant="ghost" icon="plus" @click="togglePopover"></Button> </template> </Autocomplete> </div> <DraggableList group="columns" item-key="column" empty-text="No columns selected" v-model:items="options.columns" > <template #item-suffix="{ item, index }"> <DraggableListItemMenu> <TableColumnOptions v-if="item.column_options && props.columns" :model-value="item.column_options" :column="props.columns.find((col) => col.label === item.column)" @update:model-value="options.columns[index].column_options = $event" /> </DraggableListItemMenu> </template> </DraggableList> </div> <FormControl type="text" label="Title" class="w-full" v-model="options.title" placeholder="Title" /> <Checkbox v-model="options.index" label="Show Index Row" /> <Checkbox v-model="options.showTotal" label="Show Total Row" /> <Checkbox v-model="options.filtersEnabled" label="Show Filter Row" /> </template>
2302_79757062/insights
frontend/src/widgets/Table/TableOptions.vue
Vue
agpl-3.0
2,844
<script setup> import { TextEditor } from 'frappe-ui' import { inject } from 'vue' const props = defineProps({ item_id: { required: true }, options: { type: Object, required: true }, }) const dashboard = inject('dashboard') </script> <template> <div v-if="options.markdown" class="relative flex h-full w-full items-center px-2" :class="[dashboard.editing ? 'rounded border-2 border-dashed border-gray-300' : '']" > <TextEditor editor-class="h-fit prose-sm flex flex-col justify-end" :content="options.markdown" :editable="false" /> </div> <template v-else> <slot name="placeholder"></slot> </template> </template> <style lang="scss"> .prose-sm { & > h1, & > h2, & > h3, & > h4, & > h5, & > h6 { @apply my-1; } } </style>
2302_79757062/insights
frontend/src/widgets/Text/Text.vue
Vue
agpl-3.0
760
<script setup> import { TextEditor } from 'frappe-ui' import { computed } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, }) const options = computed({ get() { return props.modelValue }, set(value) { emit('update:modelValue', value) }, }) </script> <template> <div class="space-y-2"> <span class="block text-sm leading-4 text-gray-700">Content</span> <TextEditor ref="textEditor" :editable="true" :content="options.markdown" editor-class="h-[8rem] prose-sm cursor-text bg-gray-100 rounded p-2" @change="(val) => (options.markdown = val)" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Text/TextOptions.vue
Vue
agpl-3.0
680
<script setup> import BaseChart from '@/components/Charts/BaseChart.vue' import { computed, inject } from 'vue' const $utils = inject('$utils') const props = defineProps({ data: { type: Object, required: true }, options: { type: Object, required: true }, }) const values = computed(() => { if (!props.options.valueColumn) return return props.data.map((row) => row[props.options.valueColumn]) }) const currentValue = computed(() => { if (!values.value?.length) return return values.value[values.value.length - 1] }) const previousValue = computed(() => { if (!values.value?.length) return return values.value[values.value.length - 2] }) const delta = computed(() => { if (currentValue.value === undefined || previousValue.value === undefined) return return props.options.reverseDelta ? previousValue.value - currentValue.value : currentValue.value - previousValue.value }) const percentDelta = computed(() => { if (currentValue.value === undefined || previousValue.value === undefined) return return (delta.value / previousValue.value) * 100 }) const formatNumber = (val, decimals = 0) => { if (!props.options.hasOwnProperty('shorten') || props.options.shorten) { return $utils.getShortNumber(val, decimals) } return $utils.formatNumber(val, decimals) } const dateValues = computed(() => { if (!props.options.dateColumn) return return props.data.map((row) => row[props.options.dateColumn]) }) const trendLineOptions = computed(() => { return { animation: false, grid: { top: 0, left: 0, right: 0, bottom: 0, }, xAxis: { show: false, type: 'category', data: dateValues.value, boundaryGap: false, splitLine: false, axisLabel: false, }, yAxis: { show: false, type: 'value', splitLine: false, axisLabel: false, }, series: [ { data: values.value, type: 'line', showSymbol: false, areaStyle: { opacity: 0.1, }, }, ], } }) </script> <template> <div v-if="props.data?.length" class="flex h-full w-full items-center justify-center overflow-hidden py-4 px-6" > <div class="mx-auto flex w-full min-w-40 max-w-[20rem] flex-col overflow-y-auto" :class="options.showTrendLine ? 'h-[10rem]' : 'h-fit'" > <div class="flex w-full justify-between space-x-4"> <div class="overflow-hidden text-ellipsis whitespace-nowrap font-medium leading-6 text-gray-600" > {{ options.title }} </div> <Badge :theme="delta >= 0 ? 'green' : 'red'" size="md"> <span class="-mr-1"> {{ delta >= 0 ? '+' : '-' }} </span> <span class="tnum"> {{ formatNumber(Math.abs(percentDelta), 2) }}% </span> </Badge> </div> <div class="flex items-baseline space-x-2"> <div class="tnum flex-shrink-0 overflow-hidden text-ellipsis whitespace-nowrap text-[28px] font-medium leading-10" > {{ options.prefix }}{{ formatNumber(currentValue, 2) }}{{ options.suffix }} </div> <div class="tnum flex-shrink-0 overflow-hidden text-ellipsis whitespace-nowrap text-[14px] text-sm leading-5 text-gray-600" > from {{ options.prefix }}{{ formatNumber(previousValue, 2) }}{{ options.suffix }} </div> </div> <BaseChart v-if="options.showTrendLine" class="!px-0" :options="trendLineOptions" /> </div> </div> </template>
2302_79757062/insights
frontend/src/widgets/Trend/Trend.vue
Vue
agpl-3.0
3,304
<script setup> import { FIELDTYPES } from '@/utils' import { computed } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: { type: Object, required: true }, columns: { type: Array, required: true }, }) const options = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }) const dateOptions = computed(() => { return props.columns ?.filter((column) => FIELDTYPES.DATE.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) const valueOptions = computed(() => { return props.columns ?.filter((column) => FIELDTYPES.NUMBER.includes(column.type)) .map((column) => ({ label: column.label, value: column.label, description: column.type, })) }) </script> <template> <div class="space-y-4"> <FormControl type="text" label="Title" class="w-full" v-model="options.title" placeholder="Title" /> <div> <label class="mb-1.5 block text-xs text-gray-600">Date Column</label> <Autocomplete :options="dateOptions" :modelValue="options.dateColumn" @update:modelValue="options.dateColumn = $event?.value" /> </div> <div> <label class="mb-1.5 block text-xs text-gray-600">Value Column</label> <Autocomplete :options="valueOptions" :modelValue="options.valueColumn" @update:modelValue="options.valueColumn = $event?.value" /> </div> <FormControl label="Prefix" type="text" v-model="options.prefix" placeholder="Enter a prefix..." /> <FormControl label="Suffix" type="text" v-model="options.suffix" placeholder="Enter a suffix..." /> <Checkbox v-model="options.showTrendLine" label="Show Trend Line" /> <Checkbox v-model="options.shorten" label="Shorten Numbers" /> <Checkbox v-model="options.reverseDelta" label="Reverse Colors" /> </div> </template>
2302_79757062/insights
frontend/src/widgets/Trend/TrendOptions.vue
Vue
agpl-3.0
1,929
import { FIELDTYPES } from '@/utils' import { getFormattedResult } from '@/utils/query/results' import { reactive } from 'vue' /** * @param {Object} options * @param {Object} options.query * @param {Object} options.resultsFetcher * @returns {Object} chartData * @returns {Array} chartData.data * @returns {Boolean} chartData.loading * @returns {Boolean} chartData.error * @returns {Function} chartData.reload * * @example * const chartData = useChartData(options) * chartData.load(query) **/ export default function useChartData(options = {}) { const state = reactive({ query: null, data: [], rawData: [], recommendedChart: {}, loading: false, error: null, }) function load(query) { if (!query) return state.loading = true return options .resultsFetcher() .then((results) => { state.loading = false state.rawData = getFormattedResult(results) state.data = convertResultToObjects(state.rawData) }) .catch((error) => { state.loading = false state.error = error }) } if (options.query) { load(options.query) } function getGuessedChart(chart_type) { return guessChart(state.rawData, chart_type) } return Object.assign(state, { load, getGuessedChart, }) } export function guessChart(dataset, chart_type) { const [columns, ...rows] = dataset const numberColumns = columns.filter((col) => FIELDTYPES.NUMBER.includes(col.type)) const dateColumns = columns.filter((col) => FIELDTYPES.DATE.includes(col.type)) const stringColumns = columns.filter((col) => FIELDTYPES.TEXT.includes(col.type)) // if there is only one number column, it's a number chart const hasOnlyOneNumberColumn = columns.length === 1 && numberColumns.length === 1 const autoGuessNumberChart = chart_type === 'Auto' && hasOnlyOneNumberColumn const shouldGuessNumberChart = chart_type === 'Number' && numberColumns.length >= 1 if (autoGuessNumberChart || shouldGuessNumberChart) { return { type: 'Number', options: { column: numberColumns[0].label, shorten: false, }, } } // if there is at least one date column and one number column, it's a line chart const hasAtLeastOneDateAndNumberColumn = dateColumns.length >= 1 && numberColumns.length >= 1 const autoGuessLineChart = chart_type === 'Auto' && hasAtLeastOneDateAndNumberColumn const shouldGuessLineChart = chart_type === 'Line' && hasAtLeastOneDateAndNumberColumn if (autoGuessLineChart || shouldGuessLineChart) { let splitYAxis = false if (numberColumns.length === 2) { try { const numberColumnIndexes = numberColumns.map((col) => columns.findIndex((c) => c === col) ) const maxValue1 = Math.max(...rows.map((row) => row[numberColumnIndexes[0]])) const maxValue2 = Math.max(...rows.map((row) => row[numberColumnIndexes[1]])) // if maxValue1 is 10 times bigger than maxValue2, then split the y-axis const biggerMaxValue = Math.max(maxValue1, maxValue2) const smallerMaxValue = Math.min(maxValue1, maxValue2) splitYAxis = Boolean(biggerMaxValue / smallerMaxValue > 10) } catch (e) { console.log(e) } } return { type: 'Line', options: { xAxis: [{ column: dateColumns[0].label }], yAxis: numberColumns.map((col) => ({ column: col.label })), splitYAxis: splitYAxis, }, } } const hasAtLeastOneStringAndNumberColumn = stringColumns.length >= 1 && numberColumns.length >= 1 const stringColIndex = columns.findIndex((col) => FIELDTYPES.TEXT.includes(col.type)) const uniqueValuesCount = new Set(rows.map((row) => row[stringColIndex])).size // if there is only one string column and one number column, // and there are less than 10 unique values, it's a pie chart const hasLessThan10UniqueValues = uniqueValuesCount <= 10 const hasOnlyOneStringAndNumberColumn = stringColumns.length === 1 && numberColumns.length === 1 const autoGuessPieChart = chart_type === 'Auto' && hasOnlyOneStringAndNumberColumn && hasLessThan10UniqueValues const shouldGuessPieChart = chart_type === 'Pie' if (autoGuessPieChart || shouldGuessPieChart) { return { type: 'Pie', options: { xAxis: stringColumns[0]?.label, yAxis: numberColumns[0]?.label, }, } } // if there is at least one string column and one number column, it's a bar chart const hasAtLeastOneDateOrStringColumn = dateColumns.length >= 1 || stringColumns.length >= 1 const autoGuessBarChart = chart_type === 'Auto' && hasAtLeastOneDateOrStringColumn const shouldGuessBarChart = chart_type === 'Bar' if (autoGuessBarChart || shouldGuessBarChart) { const xAxis = stringColumns.length ? stringColumns[0].label : dateColumns.length ? dateColumns[0].label : '' const uniqueXValuesCount = new Set(rows.map((row) => row[xAxis])).size return { type: 'Bar', options: { xAxis: xAxis, yAxis: numberColumns.map((col) => col.label), rotateLabels: uniqueXValuesCount > 10 ? '90' : '0', }, } } const shouldGuessPivotChart = chart_type === 'Pivot Table' if (shouldGuessPivotChart) { return { type: 'Pivot Table', options: { rows: [...dateColumns, ...stringColumns].map((col) => ({ label: col.label, value: col.label, })), values: [...numberColumns].map((col) => ({ label: col.label, value: col.label })), }, } } const autoGuessTableChart = chart_type === 'Auto' const shouldGuessTableChart = chart_type === 'Table' if (autoGuessTableChart || shouldGuessTableChart) { return { type: 'Table', options: { columns: columns.map((col) => col.label) }, } } return { type: chart_type, options: {} } } export function convertResultToObjects(results) { if (!results?.length) return [] // results first row is an list of dicts with label and type // return list of plain objects with first row's labels as keys // return [{ label1: value1, label2: value2 }, ...}] return results.slice(1).map((row) => { return results[0].reduce((obj, { label, name }, index) => { obj[label || name] = row[index] return obj }, {}) }) }
2302_79757062/insights
frontend/src/widgets/useChartData.js
JavaScript
agpl-3.0
6,003
import ComboChartIcon from '@/components/Icons/ComboChartIcon.vue' import { AlignLeft, BarChart3, BarChartHorizontal, BatteryMedium, DollarSign, GitBranch, LineChart, ListFilter, PieChart, ScatterChart, Sparkles, Square, Table, TextCursorInput, TrendingUp, } from 'lucide-vue-next' import { defineAsyncComponent } from 'vue' import defaultWidgetDimensions from './widgetDimensions.json' export const VALID_CHARTS = [ 'Number', 'Line', 'Bar', 'Row', 'Pie', 'Table', 'Progress', 'Scatter', 'Funnel', 'Trend', 'Mixed Axis', 'Pivot Table', ] as const const WIDGETS = { Auto: { type: 'Auto', icon: Sparkles, component: undefined, optionsComponent: undefined, options: {}, }, Number: { type: 'Number', icon: DollarSign, component: defineAsyncComponent(() => import('./Number/Number.vue')), optionsComponent: defineAsyncComponent(() => import('./Number/NumberOptions.vue')), options: {}, ...defaultWidgetDimensions.Number, }, Trend: { type: 'Trend', icon: TrendingUp, component: defineAsyncComponent(() => import('./Trend/Trend.vue')), optionsComponent: defineAsyncComponent(() => import('./Trend/TrendOptions.vue')), options: {}, ...defaultWidgetDimensions.Trend, }, Line: { type: 'Line', icon: LineChart, component: defineAsyncComponent(() => import('./Line/Line.vue')), optionsComponent: defineAsyncComponent(() => import('./Line/LineOptions.vue')), options: {}, ...defaultWidgetDimensions.Line, }, Scatter: { type: 'Scatter', icon: ScatterChart, component: defineAsyncComponent(() => import('./Scatter/Scatter.vue')), optionsComponent: defineAsyncComponent(() => import('./Scatter/ScatterOptions.vue')), options: {}, ...defaultWidgetDimensions.Scatter, }, Bar: { type: 'Bar', icon: BarChart3, component: defineAsyncComponent(() => import('./Bar/Bar.vue')), optionsComponent: defineAsyncComponent(() => import('./Bar/BarOptions.vue')), options: {}, ...defaultWidgetDimensions.Bar, }, Row: { type: 'Row', icon: BarChartHorizontal, component: defineAsyncComponent(() => import('./Row/Row.vue')), optionsComponent: defineAsyncComponent(() => import('./Row/RowOptions.vue')), options: {}, ...defaultWidgetDimensions.Row, }, Pie: { type: 'Pie', icon: PieChart, component: defineAsyncComponent(() => import('./Pie/Pie.vue')), optionsComponent: defineAsyncComponent(() => import('./Pie/PieOptions.vue')), options: {}, ...defaultWidgetDimensions.Pie, }, Funnel: { type: 'Funnel', icon: ListFilter, component: defineAsyncComponent(() => import('./Funnel/Funnel.vue')), optionsComponent: defineAsyncComponent(() => import('./Funnel/FunnelOptions.vue')), options: {}, ...defaultWidgetDimensions.Funnel, }, Table: { type: 'Table', icon: Table, component: defineAsyncComponent(() => import('./Table/Table.vue')), optionsComponent: defineAsyncComponent(() => import('./Table/TableOptions.vue')), options: {}, ...defaultWidgetDimensions.Table, }, Progress: { type: 'Progress', icon: BatteryMedium, component: defineAsyncComponent(() => import('./Progress/Progress.vue')), optionsComponent: defineAsyncComponent(() => import('./Progress/ProgressOptions.vue')), options: {}, ...defaultWidgetDimensions.Progress, }, 'Mixed Axis': { type: 'Mixed Axis', icon: ComboChartIcon, component: defineAsyncComponent(() => import('./MixedAxis/MixedAxis.vue')), optionsComponent: defineAsyncComponent(() => import('./MixedAxis/MixedAxisOptions.vue')), options: {}, ...defaultWidgetDimensions['Mixed Axis'], }, Filter: { type: 'Filter', icon: TextCursorInput, component: defineAsyncComponent(() => import('./Filter/Filter.vue')), optionsComponent: defineAsyncComponent(() => import('./Filter/FilterOptions.vue')), options: {}, ...defaultWidgetDimensions.Filter, }, Text: { type: 'Text', icon: AlignLeft, component: defineAsyncComponent(() => import('./Text/Text.vue')), optionsComponent: defineAsyncComponent(() => import('./Text/TextOptions.vue')), options: {}, ...defaultWidgetDimensions.Text, }, 'Pivot Table': { type: 'Pivot Table', icon: GitBranch, component: defineAsyncComponent(() => import('./PivotTable/PivotTable.vue')), optionsComponent: defineAsyncComponent(() => import('./PivotTable/PivotTableOptions.vue')), options: {}, ...defaultWidgetDimensions['Pivot Table'], }, } const UnknownWidget = { type: 'Unknown', component: defineAsyncComponent(() => import('@/widgets/InvalidWidget.vue')), optionsComponent: null, options: {}, defaultWidth: 5, defaultHeight: 4, } export type WidgetType = keyof typeof WIDGETS export type ChartType = typeof VALID_CHARTS[number] function get(itemType: WidgetType) { return WIDGETS[itemType] || UnknownWidget } function getComponent(itemType: WidgetType) { return get(itemType).component } function getOptionComponent(itemType: WidgetType) { return get(itemType).optionsComponent } function getChartOptions() { return VALID_CHARTS.map((chart) => ({ value: chart, label: chart, })) } export function getIcon(itemType: WidgetType) { return get(itemType).icon } export default { ...WIDGETS, list: Object.values(WIDGETS), get, getComponent, getOptionComponent, getChartOptions, getIcon, }
2302_79757062/insights
frontend/src/widgets/widgets.ts
TypeScript
agpl-3.0
5,264
<template> <div class="flex h-screen w-screen overflow-hidden bg-white text-base antialiased"> <div v-if="!route.meta.hideSidebar" class="h-full border-r bg-gray-50"> <AppSidebar /> </div> <div class="flex h-full flex-1 flex-col overflow-auto"> <RouterView /> </div> <Toaster :visible-toasts="2" position="bottom-right" /> <component v-for="dialog in dialogs" :is="dialog" :key="dialog.id" /> </div> </template> <script setup> import AppSidebar from './components/AppSidebar.vue' import { dialogs } from './helpers/confirm_dialog' import { inject, onBeforeUnmount } from 'vue' import { useRoute } from 'vue-router' import { Toaster } from 'vue-sonner' import session from './session' const route = useRoute() if (!route.meta.isGuestView) { const $socket = inject('$socket') const $notify = inject('$notify') $socket.on('insights_notification', (data) => { if (data.user == session.user.email) { $notify({ title: data.title || data.message, message: data.title ? data.message : '', variant: data.type, }) } }) onBeforeUnmount(() => { $socket.off('insights_notification') }) } </script>
2302_79757062/insights
frontend/src2/App.vue
Vue
agpl-3.0
1,138
<template> <LoginBox class="bg-gray-50" title="Log in to your account"> <form class="flex flex-col" @submit.prevent="makeLoginRequest"> <FormControl label="Email" placeholder="johndoe@mail.com" v-model="email" name="email" autocomplete="email" :type="email !== 'Administrator' ? 'email' : 'text'" required /> <FormControl class="mt-4" label="Password" type="password" placeholder="•••••" v-model="password" name="password" autocomplete="current-password" required /> <ErrorMessage :error="errorMessage" class="!mt-2" /> <Button class="mt-4" variant="solid" :disabled="loggingIn" :loading="loggingIn" @click="makeLoginRequest" > Log in with email </Button> </form> </LoginBox> </template> <script setup> import { onMounted, ref } from 'vue' import { useRoute, useRouter } from 'vue-router' import session from '../session' import LoginBox from './LoginBox.vue' const loggingIn = ref(null) const email = ref(null) const password = ref(null) const errorMessage = ref(null) const redirectRoute = ref(null) const route = useRoute() const router = useRouter() onMounted(() => { if (route?.query?.route) { redirectRoute.value = route.query.route router.replace({ query: null }) } }) const makeLoginRequest = async () => { if (!email.value || !password.value) { return } try { errorMessage.value = null loggingIn.value = true let res = await session.login(email.value, password.value) if (res) { router.push(redirectRoute.value || '/') } } catch (error) { console.error(error) errorMessage.value = error.messages.join('\n') } finally { loggingIn.value = false } } </script>
2302_79757062/insights
frontend/src2/auth/Login.vue
Vue
agpl-3.0
1,726
<template> <div class="h-full w-full pt-4 sm:pt-16"> <div class="relative z-10"> <div class="flex"> <img src="../assets/insights-logo-new.svg" class="mx-auto h-12" /> </div> <div class="mx-auto bg-white px-4 py-8 sm:mt-6 sm:w-96 sm:rounded-lg sm:px-8 sm:shadow-xl" > <div class="mb-6 text-center"> <span class="text-base text-gray-900">{{ props.title }}</span> </div> <slot></slot> </div> </div> <div class="fixed bottom-4 z-[1] flex w-full justify-center"> <FrappeLogo class="h-4" /> </div> </div> </template> <script setup> import FrappeLogo from '../components/Icons/FrappeLogo.vue' const props = defineProps(['title']) </script>
2302_79757062/insights
frontend/src2/auth/LoginBox.vue
Vue
agpl-3.0
687
<template> <div class="mt-40 h-full w-full"> <div class="flex flex-col items-center justify-center"> <p class="text-2xl font-semibold text-blue-600">404</p> <h1 class="mt-1 text-[48px] font-bold tracking-tight text-gray-900">Not Found</h1> <div class="text-xl font-light">The page you are looking for does not exist.</div> <router-link to="/" class="mt-2 text-lg text-blue-600 underline"> Home </router-link> </div> </div> </template>
2302_79757062/insights
frontend/src2/auth/NotFound.vue
Vue
agpl-3.0
453
<script setup lang="ts"> import { useMagicKeys, watchDebounced, whenever } from '@vueuse/core' import { onBeforeUnmount, provide } from 'vue' import InlineFormControlLabel from '../components/InlineFormControlLabel.vue' import LoadingOverlay from '../components/LoadingOverlay.vue' import { WorkbookChart, WorkbookQuery } from '../types/workbook.types' import useChart from './chart' import ChartBuilderTable from './components/ChartBuilderTable.vue' import ChartConfigForm from './components/ChartConfigForm.vue' import ChartFilterConfig from './components/ChartFilterConfig.vue' import ChartQuerySelector from './components/ChartQuerySelector.vue' import ChartRenderer from './components/ChartRenderer.vue' import ChartSortConfig from './components/ChartSortConfig.vue' import ChartTypeSelector from './components/ChartTypeSelector.vue' import { RefreshCcw } from 'lucide-vue-next' const props = defineProps<{ chart: WorkbookChart; queries: WorkbookQuery[] }>() const chart = useChart(props.chart) provide('chart', chart) window.chart = chart chart.refresh() if (!chart.doc.config.order_by) { chart.doc.config.order_by = [] } watchDebounced( () => chart.doc.config, () => chart.refresh(), { deep: true, debounce: 500, } ) const keys = useMagicKeys() const cmdZ = keys['Meta+Z'] const cmdShiftZ = keys['Meta+Shift+Z'] const stopUndoWatcher = whenever(cmdZ, () => chart.history.undo()) const stopRedoWatcher = whenever(cmdShiftZ, () => chart.history.redo()) onBeforeUnmount(() => { stopUndoWatcher() stopRedoWatcher() }) </script> <template> <div class="relative flex h-full w-full divide-x overflow-hidden"> <div class="relative flex h-full w-full flex-col overflow-hidden"> <LoadingOverlay v-if="chart.dataQuery.executing" /> <div class="flex min-h-[24rem] flex-1 flex-shrink-0 items-center justify-center overflow-hidden p-5" > <ChartRenderer :chart="chart" :show-download="true" /> </div> <ChartBuilderTable /> </div> <div class="relative flex w-[17rem] flex-shrink-0 flex-col gap-2.5 overflow-y-auto bg-white p-3" > <ChartQuerySelector v-model="chart.doc.query" :queries="props.queries" /> <hr class="border-t border-gray-200" /> <ChartTypeSelector v-model="chart.doc.chart_type" /> <ChartConfigForm v-if="chart.doc.query" :chart="chart" /> <hr class="border-t border-gray-200" /> <ChartFilterConfig v-model="chart.doc.config.filters" :column-options="chart.baseQuery.result?.columnOptions || []" /> <hr class="border-t border-gray-200" /> <ChartSortConfig v-model="chart.doc.config.order_by" :column-options="chart.dataQuery.result?.columnOptions || []" /> <hr class="border-t border-gray-200" /> <InlineFormControlLabel label="Limit" class="!w-1/2"> <FormControl v-model="chart.doc.config.limit" type="number" /> </InlineFormControlLabel> <hr class="border-t border-gray-200" /> <div> <Button @click="chart.refresh([], true)" class="w-full"> <template #prefix> <RefreshCcw class="h-4 text-gray-700" stroke-width="1.5" /> </template> Refresh Chart </Button> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/charts/ChartBuilder.vue
Vue
agpl-3.0
3,150
import { useDebouncedRefHistory, UseRefHistoryReturn, watchDebounced } from '@vueuse/core' import { computed, reactive, ref, unref, watch } from 'vue' import { copy, getUniqueId, waitUntil, wheneverChanges } from '../helpers' import { createToast } from '../helpers/toasts' import { column, count } from '../query/helpers' import { getCachedQuery, makeQuery, Query } from '../query/query' import { AXIS_CHARTS, AxisChartConfig, DountChartConfig, NumberChartConfig, TableChartConfig, } from '../types/chart.types' import { FilterArgs, GranularityType, Operation } from '../types/query.types' import { WorkbookChart } from '../types/workbook.types' const charts = new Map<string, Chart>() export default function useChart(workbookChart: WorkbookChart) { const existingChart = charts.get(workbookChart.name) if (existingChart) return existingChart const chart = makeChart(workbookChart) charts.set(workbookChart.name, chart) return chart } export function getCachedChart(name: string) { return charts.get(name) } function makeChart(workbookChart: WorkbookChart) { const chart = reactive({ doc: workbookChart, baseQuery: computed(() => { if (!workbookChart.query) return {} as Query return getCachedQuery(workbookChart.query) as Query }), dataQuery: makeQuery({ name: getUniqueId(), operations: [], }), refresh, getGranularity, updateGranularity, history: {} as UseRefHistoryReturn<any, any>, }) wheneverChanges( () => chart.doc.query, () => resetConfig() ) function resetConfig() { chart.doc.config = {} as WorkbookChart['config'] chart.doc.config.order_by = [] chart.dataQuery.reset() } // when chart type changes from axis to non-axis or vice versa reset the config watch( () => chart.doc.chart_type, (newType: string, oldType: string) => { if (newType === oldType) return if (!newType || !oldType) return if ( (AXIS_CHARTS.includes(newType) && !AXIS_CHARTS.includes(oldType)) || (!AXIS_CHARTS.includes(newType) && AXIS_CHARTS.includes(oldType)) ) { resetConfig() } } ) async function refresh(filters?: FilterArgs[], force = false) { if (!workbookChart.query) return if (!chart.doc.chart_type) return if (chart.baseQuery.executing) { await waitUntil(() => !chart.baseQuery.executing) } prepareBaseQuery() setCustomFilters(filters || []) setChartFilters() let prepared = false if (AXIS_CHARTS.includes(chart.doc.chart_type)) { const _config = unref(chart.doc.config as AxisChartConfig) prepared = prepareAxisChartQuery(_config) } else if (chart.doc.chart_type === 'Number') { const _config = unref(chart.doc.config as NumberChartConfig) prepared = prepareNumberChartQuery(_config) } else if (chart.doc.chart_type === 'Donut') { const _config = unref(chart.doc.config as DountChartConfig) prepared = prepareDonutChartQuery(_config) } else if (chart.doc.chart_type === 'Table') { const _config = unref(chart.doc.config as TableChartConfig) prepared = prepareTableChartQuery(_config) } else { console.warn('Unknown chart type: ', chart.doc.chart_type) } if (prepared) { applySortOrder() applyLimit() return executeQuery(force) } } function prepareAxisChartQuery(config: AxisChartConfig) { if (!config.x_axis || !config.x_axis.column_name) { console.warn('X-axis is required') return false } if (config.x_axis.column_name === config.split_by?.column_name) { createToast({ message: 'X-axis and Split by cannot be the same', variant: 'error', }) return false } let values = [...config.y_axis, ...(config.y2_axis || [])] values = values.length ? values : [count()] if (config.split_by) { chart.dataQuery.addPivotWider({ rows: [config.x_axis], columns: [config.split_by], values: values, }) } else { chart.dataQuery.addSummarize({ measures: values, dimensions: [config.x_axis], }) } return true } function prepareNumberChartQuery(config: NumberChartConfig) { if (!config.number_columns?.length) { console.warn('Number column is required') return false } chart.dataQuery.addSummarize({ measures: config.number_columns, dimensions: config.date_column?.column_name ? [config.date_column] : [], }) return true } function prepareDonutChartQuery(config: DountChartConfig) { if (!config.label_column) { console.warn('Label is required') return false } if (!config.value_column) { console.warn('Value is required') return false } const label = config.label_column const value = config.value_column if (!label) { console.warn('Label column not found') return false } if (!value) { console.warn('Value column not found') return false } chart.dataQuery.addSummarize({ measures: [value], dimensions: [label], }) chart.dataQuery.addOrderBy({ column: column(value.measure_name), direction: 'desc', }) return true } function prepareTableChartQuery(config: TableChartConfig) { if (!config.rows.length) { console.warn('Rows are required') return false } let rows = config.rows let columns = config.columns let values = config.values if (!columns?.length) { chart.dataQuery.addSummarize({ measures: values || [count()], dimensions: rows, }) } if (columns?.length) { chart.dataQuery.addPivotWider({ rows: rows, columns: columns, values: values || [count()], }) } return true } function applySortOrder() { if (!chart.doc.config.order_by) return chart.doc.config.order_by.forEach((sort) => { if (!sort.column.column_name || !sort.direction) return chart.dataQuery.addOrderBy({ column: column(sort.column.column_name), direction: sort.direction, }) }) } function applyLimit() { if (chart.doc.config.limit) { chart.dataQuery.addLimit(chart.doc.config.limit) } } function prepareBaseQuery() { chart.dataQuery.autoExecute = false chart.dataQuery.setOperations([]) chart.dataQuery.setSource({ query: chart.baseQuery.doc.name }) chart.dataQuery.doc.use_live_connection = chart.baseQuery.doc.use_live_connection } function setCustomFilters(filters: FilterArgs[]) { const _filters = new Set(filters) if (_filters.size) { chart.dataQuery.addFilterGroup({ logical_operator: 'And', filters: Array.from(_filters), }) } } const lastExecutedQueryOperations = ref<Operation[]>([]) async function executeQuery(force = false) { if ( !force && JSON.stringify(lastExecutedQueryOperations.value) === JSON.stringify(chart.dataQuery.currentOperations) ) { return Promise.resolve() } return chart.dataQuery.execute().then(() => { lastExecutedQueryOperations.value = copy(chart.dataQuery.currentOperations) }) } function getGranularity(column_name: string) { const column = Object.entries(chart.doc.config).find(([_, value]) => { if (!value) return false if (Array.isArray(value)) { return value.some((v) => v.column_name === column_name) } if (typeof value === 'object') { return value.column_name === column_name } return false }) if (!column) return if (Array.isArray(column[1])) { const granularity = column[1].find((v) => v.column_name === column_name)?.granularity return granularity } const granularity = column[1].granularity return granularity } function updateGranularity(column_name: string, granularity: GranularityType) { Object.entries(chart.doc.config).forEach(([_, value]) => { if (Array.isArray(value)) { const index = value.findIndex((v) => v.column_name === column_name) if (index > -1) { value[index].granularity = granularity } } if (value.column_name === column_name) { value.granularity = granularity } }) } function setChartFilters() { if (!chart.doc.config.filters?.filters?.length) return chart.dataQuery.addFilterGroup(chart.doc.config.filters) } chart.history = useDebouncedRefHistory( // @ts-ignore computed({ get: () => chart.doc, set: (value) => Object.assign(chart.doc, value), }), { deep: true, max: 100, debounce: 500, } ) return chart } export type Chart = ReturnType<typeof makeChart>
2302_79757062/insights
frontend/src2/charts/chart.ts
TypeScript
agpl-3.0
8,217
export const COLOR_MAP = { blue: '#318AD8', pink: '#F683AE', green: '#48BB74', red: '#F56B6B', yellow: '#FACF7A', purple: '#44427B', teal: '#5FD8C4', orange: '#F8814F', cyan: '#15CCEF', grey: '#A6B1B9', '#449CF0': '#449CF0', '#ECAD4B': '#ECAD4B', '#761ACB': '#761ACB', '#CB2929': '#CB2929', '#ED6396': '#ED6396', '#29CD42': '#29CD42', '#4463F0': '#4463F0', '#EC864B': '#EC864B', '#4F9DD9': '#4F9DD9', '#39E4A5': '#39E4A5', '#B4CD29': '#B4CD29', } export const getColors = (num = Object.keys(COLOR_MAP).length) => { const colors = [] const _colors = Object.values(COLOR_MAP) for (let i = 0; i < num; i++) { colors.push(_colors[i % _colors.length]) } return colors }
2302_79757062/insights
frontend/src2/charts/colors.ts
TypeScript
agpl-3.0
695
<script setup lang="ts"> import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' import { AxisChartConfig } from '../../types/chart.types' import { DimensionOption, MeasureOption } from './ChartConfigForm.vue' const props = defineProps<{ dimensions: DimensionOption[] measures: MeasureOption[] }>() const config = defineModel<AxisChartConfig>({ required: true, default: () => ({ x_axis: {}, y_axis: [], y2_axis: [], y2_axis_type: 'line', split_by: {}, show_data_labels: false, }), }) </script> <template> <InlineFormControlLabel label="X Axis"> <Autocomplete class="w-full" :showFooter="true" :options="props.dimensions" :modelValue="config.x_axis?.column_name" @update:modelValue="config.x_axis = $event" /> </InlineFormControlLabel> <InlineFormControlLabel label="Y Axis"> <Autocomplete :multiple="true" :options="props.measures" :modelValue="config.y_axis?.map((measure) => measure.measure_name)" @update:modelValue="config.y_axis = $event" /> </InlineFormControlLabel> <InlineFormControlLabel label="Split By"> <Autocomplete :showFooter="true" :options="props.dimensions" :modelValue="config.split_by?.column_name" @update:modelValue="config.split_by = $event" /> </InlineFormControlLabel> <InlineFormControlLabel label="Right Y Axis"> <Autocomplete :multiple="true" :options="props.measures" :modelValue="config.y2_axis?.map((measure) => measure.measure_name)" @update:modelValue="config.y2_axis = $event" /> </InlineFormControlLabel> <InlineFormControlLabel v-if="config.y2_axis?.length" label="Right Axis Type" class="!w-1/2"> <Switch v-model="config.y2_axis_type" :tabs="[ { label: 'Bar', value: 'bar', default: true }, { label: 'Line', value: 'line' }, ]" /> </InlineFormControlLabel> <InlineFormControlLabel label="Show Labels" class="!w-1/2"> <Switch v-model="config.show_data_labels" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> </template>
2302_79757062/insights
frontend/src2/charts/components/AxisChartConfigForm.vue
Vue
agpl-3.0
2,092
<script setup lang="ts"> import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' import { BarChartConfig } from '../../types/chart.types' import AxisChartConfigForm from './AxisChartConfigForm.vue' import { DimensionOption, MeasureOption } from './ChartConfigForm.vue' const props = defineProps<{ dimensions: DimensionOption[] measures: MeasureOption[] }>() const config = defineModel<BarChartConfig>({ required: true, default: () => ({ x_axis: '', y_axis: [], y2_axis: [], y2_axis_type: 'line', split_by: '', stack: true, show_data_labels: false, swap_axes: false, normalize: false, }), }) </script> <template> <AxisChartConfigForm v-model="config" :dimensions="props.dimensions" :measures="props.measures" /> <InlineFormControlLabel label="Stack" class="!w-1/2"> <Switch v-model="config.stack" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> <InlineFormControlLabel label="Normalize Data" class="!w-1/2"> <Switch v-model="config.normalize" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> <InlineFormControlLabel label="Swap X & Y" class="!w-1/2"> <Switch v-model="config.swap_axes" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> </template>
2302_79757062/insights
frontend/src2/charts/components/BarChartConfigForm.vue
Vue
agpl-3.0
1,482
<script setup> import * as echarts from 'echarts' import { onBeforeUnmount, onMounted, ref, watch } from 'vue' import { areDeeplyEqual } from '../../helpers' import ChartTitle from './ChartTitle.vue' const props = defineProps({ title: { type: String, required: false }, subtitle: { type: String, required: false }, options: { type: Object, required: true }, }) let eChart = null const chartRef = ref(null) onMounted(() => { eChart = echarts.init(chartRef.value, 'light', { renderer: 'svg' }) Object.keys(props.options).length && eChart.setOption(props.options) const resizeObserver = new ResizeObserver(() => eChart.resize()) setTimeout(() => chartRef.value && resizeObserver.observe(chartRef.value), 1000) onBeforeUnmount(() => chartRef.value && resizeObserver.unobserve(chartRef.value)) }) watch( () => props.options, (newOptions, oldOptions) => { if (!eChart) return if (JSON.stringify(newOptions) === JSON.stringify(oldOptions)) return if (areDeeplyEqual(newOptions, oldOptions)) return eChart.clear() eChart.setOption(props.options) }, { deep: true } ) defineExpose({ downloadChart }) function downloadChart() { const image = new Image() const type = 'png' image.src = eChart.getDataURL({ type, pixelRatio: 2, backgroundColor: '#fff', }) const link = document.createElement('a') link.href = image.src link.download = `${props.title}.${type}` link.click() } </script> <template> <div class="flex h-full w-full flex-col rounded"> <ChartTitle v-if="title" :title="title" /> <div ref="chartRef" class="w-full flex-1 overflow-hidden"> <slot></slot> </div> </div> </template>
2302_79757062/insights
frontend/src2/charts/components/BaseChart.vue
Vue
agpl-3.0
1,628
<script setup lang="ts"> import { inject } from 'vue' import DataTable from '../../components/DataTable.vue' import { Chart } from '../chart' import ChartBuilderTableColumn from './ChartBuilderTableColumn.vue' const chart = inject('chart') as Chart </script> <template> <div v-if="chart.doc.chart_type != 'Table'" class="flex h-[18rem] flex-col divide-y border"> <DataTable class="bg-white" :columns="chart.dataQuery.result.columns" :rows="chart.dataQuery.result.formattedRows" > <template #column-header="{ column }"> <ChartBuilderTableColumn :chart="chart" :column="column" /> </template> </DataTable> </div> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartBuilderTable.vue
Vue
agpl-3.0
652
<script setup lang="ts"> import ContentEditable from '../../components/ContentEditable.vue' import { FIELDTYPES } from '../../helpers/constants' import { ArrowDownWideNarrow, ArrowUpDown, ArrowUpNarrowWide, Calendar, Check, XIcon, } from 'lucide-vue-next' import { computed, h, inject } from 'vue' import { column } from '../../query/helpers' import { QueryResultColumn } from '../../types/query.types' import { Chart } from '../chart' const props = defineProps<{ chart: Chart; column: QueryResultColumn }>() const chart = props.chart const currentSortOrder = computed(() => { return chart.doc.config.order_by.find((order) => order.column.column_name === props.column.name) }) const sortOptions = [ { label: 'Sort Ascending', icon: h(ArrowUpNarrowWide, { class: 'h-4 w-4 text-gray-700', strokeWidth: 1.5 }), onClick: () => onSort('asc'), }, { label: 'Sort Descending', icon: h(ArrowDownWideNarrow, { class: 'h-4 w-4 text-gray-700', strokeWidth: 1.5 }), onClick: () => onSort('desc'), }, { label: 'Remove Sort', icon: h(XIcon, { class: 'h-4 w-4 text-gray-700', strokeWidth: 1.5 }), onClick: () => onSort(''), }, ] function onSort(sort_order: 'asc' | 'desc' | '') { const existingOrder = chart.doc.config.order_by.find( (order) => order.column.column_name === props.column.name ) if (existingOrder) { if (sort_order) { existingOrder.direction = sort_order } else { chart.doc.config.order_by = chart.doc.config.order_by.filter( (order) => order.column.column_name !== props.column.name ) } } else { if (!sort_order) return chart.doc.config.order_by.push({ column: column(props.column.name), direction: sort_order, }) } } const dateGranularityOptions = computed(() => { const options = [ // { label: 'Second', onClick: () => chart.updateGranularity(props.column.name, 'second') }, // { label: 'Minute', onClick: () => chart.updateGranularity(props.column.name, 'minute') }, // { label: 'Hour', onClick: () => chart.updateGranularity(props.column.name, 'hour') }, { label: 'Day', onClick: () => chart.updateGranularity(props.column.name, 'day') }, { label: 'Week', onClick: () => chart.updateGranularity(props.column.name, 'week') }, { label: 'Month', onClick: () => chart.updateGranularity(props.column.name, 'month') }, { label: 'Quarter', onClick: () => chart.updateGranularity(props.column.name, 'quarter') }, { label: 'Year', onClick: () => chart.updateGranularity(props.column.name, 'year') }, ] options.forEach((option: any) => { option.icon = option.label.toLowerCase() === chart.getGranularity(props.column.name) ? h(Check, { class: 'h-4 w-4 text-gray-700', strokeWidth: 1.5, }) : h('div', { class: 'h-4 w-4' }) }) return options }) </script> <template> <div class="flex w-full items-center pl-2"> <div class="flex items-center"> <ContentEditable :modelValue="props.column.name" placeholder="Column Name" class="flex h-6 items-center whitespace-nowrap rounded-sm px-0.5 text-sm focus:ring-1 focus:ring-gray-700 focus:ring-offset-1" disabled /> </div> <div class="flex"> <!-- Sort --> <Dropdown :options="sortOptions"> <Button variant="ghost" class="rounded-none"> <template #icon> <component :is=" !currentSortOrder ? ArrowUpDown : currentSortOrder.direction === 'asc' ? ArrowUpNarrowWide : ArrowDownWideNarrow " class="h-3.5 w-3.5 text-gray-700" stroke-width="1.5" /> </template> </Button> </Dropdown> <!-- Granularity --> <Dropdown v-if="FIELDTYPES.DATE.includes(props.column.type)" :options="dateGranularityOptions" > <Button variant="ghost" class="rounded-none"> <template #icon> <Calendar class="h-3.5 w-3.5 text-gray-700" stroke-width="1.5" /> </template> </Button> </Dropdown> </div> </div> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartBuilderTableColumn.vue
Vue
agpl-3.0
3,929
<script setup lang="ts"> import { computed } from 'vue' import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' import { Dimension, Measure } from '../../types/query.types' import { Chart } from '../chart' import BarChartConfigForm from './BarChartConfigForm.vue' import DonutChartConfigForm from './DonutChartConfigForm.vue' import LineChartConfigForm from './LineChartConfigForm.vue' import NumberChartConfigForm from './NumberChartConfigForm.vue' import TableChartConfigForm from './TableChartConfigForm.vue' const props = defineProps<{ chart: Chart }>() const chart = props.chart export type DimensionOption = Dimension & { label: string; value: string } const dimensions = computed<DimensionOption[]>(() => { return chart.baseQuery.dimensions.map((dimension) => ({ ...dimension, label: dimension.column_name, value: dimension.column_name, })) }) export type MeasureOption = Measure & { label: string; value: string } const measures = computed<MeasureOption[]>(() => { return chart.baseQuery.measures.map((measure) => ({ ...measure, label: measure.measure_name, value: measure.measure_name, })) }) </script> <template> <InlineFormControlLabel label="Title"> <FormControl v-model="chart.doc.title" /> </InlineFormControlLabel> <NumberChartConfigForm v-if="chart.doc.chart_type == 'Number'" v-model="chart.doc.config" :dimensions="dimensions" :measures="measures" /> <DonutChartConfigForm v-if="chart.doc.chart_type == 'Donut'" v-model="chart.doc.config" :dimensions="dimensions" :measures="measures" /> <TableChartConfigForm v-if="chart.doc.chart_type == 'Table'" v-model="chart.doc.config" :dimensions="dimensions" :measures="measures" /> <BarChartConfigForm v-if="chart.doc.chart_type == 'Bar'" v-model="chart.doc.config" :dimensions="dimensions" :measures="measures" /> <LineChartConfigForm v-if="chart.doc.chart_type == 'Line'" v-model="chart.doc.config" :dimensions="dimensions" :measures="measures" /> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartConfigForm.vue
Vue
agpl-3.0
2,022
<script setup lang="ts"> import { Plus, X } from 'lucide-vue-next' import { ref } from 'vue' import DataTypeIcon from '../../query/components/DataTypeIcon.vue' import FiltersSelectorDialog from '../../query/components/FiltersSelectorDialog.vue' import { ColumnOption, FilterArgs, FilterGroupArgs } from '../../types/query.types' const props = defineProps<{ columnOptions: ColumnOption[] }>() const filterGroup = defineModel<FilterGroupArgs>({ default: () => { return { logical_operator: 'And', filters: [], } }, }) const showFiltersSelectorDialog = ref(false) function getColumnType(column_name: string) { const column = props.columnOptions.find((column) => column.value === column_name) if (!column) { return 'String' } return column.data_type } function getFilterLabel(filter: FilterArgs) { if ('column' in filter) { return `${filter.column.column_name} ${filter.operator} ${filter.value}` } return filter.expression } </script> <template> <div> <div class="mb-1 flex items-center justify-between"> <label class="inline-flex flex-shrink-0 text-xs leading-7 text-gray-700">Filters</label> <div> <button class="cursor-pointer rounded p-1 transition-colors hover:bg-gray-100" @click="showFiltersSelectorDialog = true" > <Plus class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </button> </div> </div> <div class="flex flex-col gap-1"> <div v-for="(filter, idx) in filterGroup.filters" :key="idx" class="flex rounded"> <div class="flex-1 overflow-hidden"> <Button class="w-full !justify-start rounded-r-none [&>span]:truncate" @click="showFiltersSelectorDialog = true" > <template #prefix> <DataTypeIcon v-if="'column' in filter" :column-type="getColumnType(filter.column.column_name)" /> </template> {{ getFilterLabel(filter) }} </Button> </div> <Button class="flex-shrink-0 rounded-l-none border-l" @click="filterGroup.filters.splice(idx, 1)" > <template #icon> <X class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> </div> </div> </div> <FiltersSelectorDialog v-if="showFiltersSelectorDialog" v-model="showFiltersSelectorDialog" :filter-group="filterGroup" :column-options="props.columnOptions" @select="filterGroup = $event" /> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartFilterConfig.vue
Vue
agpl-3.0
2,378
<script setup lang="ts"> import { AreaChart, BarChart3, BarChartHorizontal, BatteryMedium, Filter, Hash, LifeBuoy, LineChart, ScatterChart, Table2, } from 'lucide-vue-next' import { computed } from 'vue' import { ChartType } from '../../types/chart.types' const props = defineProps<{ chartType: ChartType }>() const icon = computed(() => { switch (props.chartType) { case 'Bar': return BarChart3 case 'Line': return LineChart case 'Row': return BarChartHorizontal case 'Scatter': return ScatterChart case 'Area': return AreaChart case 'Donut': return LifeBuoy case 'Funnel': return Filter case 'Table': return Table2 case 'Number': return Hash default: return BarChart3 } }) </script> <template> <component :is="icon" class="h-4 w-4 text-gray-700" stroke-width="1.5" v-bind="$attrs" /> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartIcon.vue
Vue
agpl-3.0
863
<script setup lang="ts"> import { Edit, Plus, X } from 'lucide-vue-next' import { inject, ref } from 'vue' import DataTypeIcon from '../../query/components/DataTypeIcon.vue' import NewColumnSelectorDialog from '../../query/components/NewColumnSelectorDialog.vue' import { ExpressionMeasure, MeasureDataType, MutateArgs } from '../../types/query.types' import { Chart } from '../chart' const chart = inject('chart') as Chart const showNewColumnSelectorDialog = ref(false) const activeEditMeasure = ref<ExpressionMeasure>() function setActiveEditMeasure(measure: ExpressionMeasure) { activeEditMeasure.value = measure showNewColumnSelectorDialog.value = true } function toMutateArgs(measure: ExpressionMeasure): MutateArgs { return { new_name: measure.measure_name, expression: measure.expression, data_type: measure.data_type, } } function updateMeasure(args: MutateArgs) { const measure = { measure_name: args.new_name, expression: args.expression, data_type: args.data_type as MeasureDataType, } if (!activeEditMeasure.value) { chart.baseQuery.addMeasure(measure) } else { chart.baseQuery.updateMeasure(activeEditMeasure.value.measure_name, measure) } } </script> <template> <div v-if="chart.doc.query"> <div class="flex items-center justify-between"> <label class="inline-flex flex-shrink-0 text-xs leading-7 text-gray-700">Columns</label> <div> <button class="cursor-pointer rounded p-1 transition-colors hover:bg-gray-100" @click="showNewColumnSelectorDialog = true" > <Plus class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </button> </div> </div> <div v-for="dimension in chart.baseQuery.dimensions" :key="dimension.column_name" class="flex h-7 cursor-grab items-center gap-2 rounded px-1 text-gray-700 hover:bg-gray-100" > <DataTypeIcon :column-type="dimension.data_type" /> <span class="flex-1 truncate">{{ dimension.column_name }}</span> </div> <hr class="my-2 border-t border-gray-200" /> <div v-for="measure in chart.baseQuery.measures" :key="measure.measure_name" class="group flex h-7 cursor-grab items-center gap-2 rounded px-1 text-gray-700 hover:bg-gray-100" > <DataTypeIcon :column-type="measure.data_type" /> <span class="flex-1 truncate">{{ measure.measure_name }}</span> <div class="invisible ml-auto flex-shrink-0 group-hover:visible"> <button v-if="'expression' in measure" class="group cursor-pointer p-1" @click.prevent.stop="setActiveEditMeasure(measure)" > <Edit class="h-3.5 w-3.5 text-gray-500 transition-all group-hover:text-gray-700" stroke-width="1.5" /> </button> <button v-if="'expression' in measure" class="group cursor-pointer p-1" @click.prevent.stop="chart.baseQuery.removeMeasure(measure.measure_name)" > <X class="h-3.5 w-3.5 text-gray-500 transition-all group-hover:text-gray-700" stroke-width="1.5" /> </button> </div> </div> </div> <NewColumnSelectorDialog v-if="showNewColumnSelectorDialog" v-model="showNewColumnSelectorDialog" :mutation="activeEditMeasure ? toMutateArgs(activeEditMeasure) : undefined" @select="updateMeasure" /> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartQueryColumns.vue
Vue
agpl-3.0
3,220
<script setup lang="ts"> import { Table2 } from 'lucide-vue-next' import { WorkbookQuery } from '../../types/workbook.types' import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' const query = defineModel() const props = defineProps<{ queries: WorkbookQuery[] }>() if (!query.value && props.queries.length === 1) { query.value = props.queries[0].name } </script> <template> <InlineFormControlLabel label="Query"> <Autocomplete :showFooter="true" :options=" props.queries.map((q) => { return { label: q.title, value: q.name, } }) " :modelValue="query" @update:modelValue="query = $event?.value" > <template #prefix> <Table2 class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Autocomplete> </InlineFormControlLabel> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartQuerySelector.vue
Vue
agpl-3.0
834
<script setup lang="ts"> import { computed, ref } from 'vue' import { downloadImage } from '../../helpers' import { Chart } from '../chart' import { getBarChartOptions, getDonutChartOptions, getLineChartOptions } from '../helpers' import BaseChart from './BaseChart.vue' import NumberChart from './NumberChart.vue' import TableChart from './TableChart.vue' const props = defineProps<{ chart: Chart; showDownload?: boolean }>() const chart = props.chart const eChartOptions = computed(() => { if (!chart.dataQuery.result.columns?.length) return if (chart.doc.chart_type === 'Bar') { return getBarChartOptions(chart) } if (chart.doc.chart_type === 'Line') { return getLineChartOptions(chart) } if (chart.doc.chart_type === 'Donut') { return getDonutChartOptions( chart.dataQuery.result.columns, chart.dataQuery.result.formattedRows ) } }) const chartEl = ref<HTMLElement | null>(null) function downloadChart() { if (!chartEl.value || !chartEl.value.clientHeight) { console.log(chartEl.value) console.warn('Chart element not found') return } return downloadImage(chartEl.value, chart.doc.title, 2, { filter: (element: HTMLElement) => { return !element?.classList?.contains('absolute') }, }) } </script> <template> <div ref="chartEl" class="relative h-full w-full"> <BaseChart v-if="eChartOptions" class="rounded bg-white py-1 shadow" :title="chart.doc.title" :options="eChartOptions" /> <NumberChart v-if="chart.doc.chart_type == 'Number'" :chart="chart" /> <TableChart v-if="chart.doc.chart_type == 'Table'" :chart="chart" /> <div v-if="props.showDownload && chartEl && eChartOptions" class="absolute top-3 right-3"> <Button variant="outline" icon="download" @click="downloadChart"></Button> </div> </div> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartRenderer.vue
Vue
agpl-3.0
1,788
<script setup lang="ts"> import { Plus, SortAscIcon, SortDescIcon, X } from 'lucide-vue-next' import { computed } from 'vue' import DraggableList from '../../components/DraggableList.vue' import { column } from '../../query/helpers' import { ColumnOption, OrderByArgs } from '../../types/query.types' const props = defineProps<{ columnOptions: ColumnOption[] }>() const sortColumns = defineModel<OrderByArgs[]>({ default: () => [], }) const listItems = computed(() => { return sortColumns.value.map((order) => ({ ...order, value: order.column.column_name, })) }) function addSortColumn(column_name: string) { const existing = sortColumns.value.find((s) => s.column.column_name === column_name) if (existing) return sortColumns.value.push({ column: column(column_name), direction: 'asc', }) } function removeSortColumn(index: number) { sortColumns.value.splice(index, 1) } function updateSortColumn(index: number, column_name: string) { const existing = sortColumns.value[index] sortColumns.value.splice(index, 1, { column: column(column_name), direction: existing?.direction || 'asc', }) } function toggleSortDirection(index: number) { const existing = sortColumns.value[index] if (!existing) return sortColumns.value.splice(index, 1, { ...existing, direction: existing.direction === 'asc' ? 'desc' : 'asc', }) } function moveSortColumn(from: number, to: number) { if (!sortColumns.value) return const toMove = sortColumns.value.splice(from, 1) sortColumns.value.splice(to, 0, ...toMove) } </script> <template> <div> <div class="mb-1 flex items-center justify-between"> <label class="inline-flex flex-shrink-0 text-xs leading-7 text-gray-700">Sort By</label> <div> <Autocomplete :options="props.columnOptions" @update:modelValue="addSortColumn($event.value)" > <template #target="{ togglePopover }"> <button class="cursor-pointer rounded p-1 transition-colors hover:bg-gray-100" @click="togglePopover" > <Plus class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </button> </template> </Autocomplete> </div> </div> <DraggableList group="sortColumns" :show-empty-state="false" :items="listItems" @sort="moveSortColumn" > <template #item="{ item, index }"> <div class="flex rounded"> <Button class="flex-shrink-0 rounded-r-none border-r" @click="toggleSortDirection(index)" > <template #icon> <SortAscIcon v-if="item.direction == 'asc'" class="h-4 w-4 text-gray-700" stroke-width="1.5" /> <SortDescIcon v-else class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> <div class="flex-1 overflow-hidden"> <Autocomplete :showFooter="true" :options="props.columnOptions" :modelValue="item.value" @update:modelValue="updateSortColumn(index, $event.value)" > <template #target="{ togglePopover }"> <Button class="w-full !justify-start rounded-none [&>span]:truncate" @click="togglePopover" > {{ item.column.column_name }} </Button> </template> </Autocomplete> </div> <Button class="flex-shrink-0 rounded-l-none border-l" @click="removeSortColumn(index)" > <template #icon> <X class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> </div> </template> </DraggableList> </div> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartSortConfig.vue
Vue
agpl-3.0
3,521
<script setup> const props = defineProps({ title: { type: String, required: false }, }) </script> <template> <div class="px-4 py-2 font-medium leading-6 text-gray-800"> {{ title }} </div> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartTitle.vue
Vue
agpl-3.0
206
<script setup lang="ts"> import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' import { CHARTS, ChartType } from '../../types/chart.types' import ChartIcon from './ChartIcon.vue' const chartType = defineModel<ChartType>() </script> <template> <InlineFormControlLabel label="Chart Type"> <div class="grid grid-cols-2 gap-2"> <Button v-for="item in CHARTS" :key="item" variant="subtle" class="!justify-start" :class="chartType === item ? 'bg-white shadow hover:bg-white' : ''" @click="chartType = item" > <div class="flex items-center gap-1.5"> <ChartIcon :chartType="item" class="!h-3.5 !w-3.5" /> <div class="text-sm">{{ item == 'Number' ? 'KPI' : item }}</div> </div> </Button> </div> </InlineFormControlLabel> </template>
2302_79757062/insights
frontend/src2/charts/components/ChartTypeSelector.vue
Vue
agpl-3.0
810
<script setup lang="ts"> import { FIELDTYPES } from '../../helpers/constants' import { computed } from 'vue' import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' import { DountChartConfig } from '../../types/chart.types' import { DimensionOption, MeasureOption } from './ChartConfigForm.vue' const props = defineProps<{ dimensions: DimensionOption[] measures: MeasureOption[] }>() const config = defineModel<DountChartConfig>({ required: true, default: () => ({ label_column: {}, value_column: {}, }), }) const discrete_dimensions = computed(() => props.dimensions.filter((d) => FIELDTYPES.DISCRETE.includes(d.data_type)) ) </script> <template> <InlineFormControlLabel label="Label"> <Autocomplete :showFooter="true" :options="discrete_dimensions" :modelValue="config.label_column?.column_name" @update:modelValue="config.label_column = $event" /> </InlineFormControlLabel> <InlineFormControlLabel label="Value"> <Autocomplete :showFooter="true" :options="props.measures" :modelValue="config.value_column?.measure_name" @update:modelValue="config.value_column = $event" /> </InlineFormControlLabel> </template>
2302_79757062/insights
frontend/src2/charts/components/DonutChartConfigForm.vue
Vue
agpl-3.0
1,189
<script setup lang="ts"> import { LineChartConfig } from '../../types/chart.types' import AxisChartConfigForm from './AxisChartConfigForm.vue' import { DimensionOption, MeasureOption } from './ChartConfigForm.vue' import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' const props = defineProps<{ dimensions: DimensionOption[] measures: MeasureOption[] }>() const config = defineModel<LineChartConfig>({ required: true, default: () => ({ x_axis: {}, y_axis: [], y2_axis: [], y2_axis_type: 'line', split_by: {}, show_data_labels: false, }), }) </script> <template> <AxisChartConfigForm v-model="config" :dimensions="props.dimensions" :measures="props.measures" /> <InlineFormControlLabel label="Enable Curved Lines" class="!w-1/2"> <Switch v-model="config.smooth" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> <InlineFormControlLabel label="Show Data Points" class="!w-1/2"> <Switch v-model="config.show_data_points" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> <InlineFormControlLabel label="Show Area" class="!w-1/2"> <Switch v-model="config.show_area" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> </template>
2302_79757062/insights
frontend/src2/charts/components/LineChartConfigForm.vue
Vue
agpl-3.0
1,455
<script setup lang="ts"> import { computed } from 'vue' import { formatNumber, getShortNumber } from '../../helpers' import { NumberChartConfig } from '../../types/chart.types' import { Measure } from '../../types/query.types' import { Chart } from '../chart' import Sparkline from './Sparkline.vue' const props = defineProps<{ chart: Chart }>() const title = computed(() => props.chart.doc.title) const config = computed(() => props.chart.doc.config as NumberChartConfig) const dateValues = computed(() => { if (!config.value.date_column) return [] const date_column = config.value.date_column.column_name return props.chart.dataQuery.result.rows.map((row: any) => row[date_column]) }) const numberValuesPerColumn = computed(() => { if (!config.value.number_columns?.length) return {} if (!props.chart.dataQuery.result?.rows) return {} return config.value.number_columns .map((c) => c.measure_name) .reduce((acc: any, column: string) => { acc[column] = props.chart.dataQuery.result.rows.map((row: any) => row[column]) return acc }, {}) }) const cards = computed(() => { if (!config.value.number_columns?.length) return [] if (!props.chart.dataQuery.result?.rows) return [] return config.value.number_columns.map((column: Measure) => { const numberValues = numberValuesPerColumn.value[column.measure_name] const currentValue = numberValues[numberValues.length - 1] const previousValue = numberValues[numberValues.length - 2] const delta = config.value.negative_is_better ? previousValue - currentValue : currentValue - previousValue const percentDelta = (delta / previousValue) * 100 return { column, currentValue: getFormattedValue(currentValue), previousValue: getFormattedValue(previousValue), delta, percentDelta: getFormattedValue(percentDelta), } }) }) const getFormattedValue = (value: number) => { if (isNaN(value)) return 0 if (config.value.shorten_numbers) { return getShortNumber(value, config.value.decimal) } return formatNumber(value, config.value.decimal) } </script> <template> <div class="grid w-full grid-cols-[repeat(auto-fill,214px)] gap-4"> <div v-for="{ column, currentValue, delta, percentDelta } in cards" :key="column.measure_name" class="flex h-[140px] items-center gap-2 overflow-y-auto rounded bg-white py-4 px-6 shadow" > <div class="flex w-full flex-col"> <span class="truncate text-sm font-medium"> {{ column.measure_name }} </span> <div class="flex-1 flex-shrink-0 text-[24px] font-semibold leading-10"> {{ config.prefix }}{{ currentValue }}{{ config.suffix }} </div> <div v-if="config.comparison" class="flex items-center gap-1 text-xs font-medium" :class="delta >= 0 ? 'text-green-500' : 'text-red-500'" > <span class=""> {{ delta >= 0 && !config.negative_is_better ? '↑' : '↓' }} </span> <span> {{ percentDelta }}% </span> </div> <div v-if="config.sparkline" class="mt-2 h-[18px] w-[80px]"> <Sparkline :dates="dateValues" :values="numberValuesPerColumn[column.measure_name]" /> </div> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/charts/components/NumberChart.vue
Vue
agpl-3.0
3,155