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
<script setup> import widgets from '@/widgets/widgets' import { inject } from 'vue' const props = defineProps({ onClose: Function }) const chart = inject('chart') const chartOptions = [ { label: 'Select a chart type', value: undefined, }, ].concat(widgets.getChartOptions()) </script> <template> <div class="flex h-full w-full flex-col p-3"> <div class="relative flex flex-shrink-0 justify-between pb-3 text-base"> <span class="font-code text-sm uppercase text-gray-600"> Options </span> <FeatherIcon name="x" class="h-4 w-4 cursor-pointer text-gray-500 transition-all hover:text-gray-800" @click.prevent.stop="onClose && onClose()" ></FeatherIcon> </div> <div v-if="chart?.doc.chart_type" class="flex w-full flex-1 flex-col gap-4 overflow-y-auto pt-0 !text-base" > <!-- Widget Options --> <Input type="select" label="Chart Type" class="w-full" v-model="chart.doc.chart_type" :options="chartOptions" /> <component v-if="chart.doc.chart_type" :is="widgets.getOptionComponent(chart.doc.chart_type)" :key="chart.doc.chart_type" v-model="chart.doc.options" :columns="chart.columns" /> </div> </div> </template>
2302_79757062/insights
frontend/src/notebook/blocks/chart/ChartOptions.vue
Vue
agpl-3.0
1,210
<script setup> import UsePopover from '@/components/UsePopover.vue' import { inject, ref } from 'vue' import ChartOptions from './ChartOptions.vue' const targetElement = ref(null) const chart = inject('chart') </script> <template> <div ref="targetElement" class="flex h-full w-full items-center px-2"> <div class="flex items-center space-x-1.5"> <FeatherIcon name="settings" class="h-3.5 w-3.5 text-gray-500"></FeatherIcon> <span class="text-sm">Options</span> </div> </div> <UsePopover v-if="targetElement" :targetElement="targetElement" placement="bottom-end"> <template #default="{ toggle }"> <div class="h-[22rem] w-[15rem] overflow-y-auto rounded bg-white text-base shadow"> <ChartOptions :onClose="() => toggle(false)" /> </div> </template> </UsePopover> </template>
2302_79757062/insights
frontend/src/notebook/blocks/chart/ChartOptionsDropdown.vue
Vue
agpl-3.0
802
<script setup> import NativeQueryEditor from '@/query/NativeQueryEditor.vue' import ResultSection from '@/query/ResultSection.vue' import ResultFooter from '@/query/visual/ResultFooter.vue' import useQuery from '@/query/resources/useQuery' import useQueryStore from '@/stores/queryStore' import { provide, reactive } from 'vue' import QueryBlockHeader from './QueryBlockHeader.vue' const emit = defineEmits(['setQuery', 'remove']) const props = defineProps({ query: String }) let query = null if (!props.query) { const queryDoc = await useQueryStore().create() emit('setQuery', queryDoc.name) query = useQuery(queryDoc.name) await query.reload() } else { query = useQuery(props.query) await query.reload() } await query.convertToNative() provide('query', query) const state = reactive({ dataSource: '', minimizeResult: true, minimizeQuery: false, showQueryActions: false, query: query, }) provide('state', state) state.removeQuery = () => { useQueryStore() .delete(query.doc.name) .then(() => emit('remove')) } </script> <template> <div ref="blockRef" v-if="query.doc.name" class="relative my-6 overflow-hidden rounded border bg-white" > <QueryBlockHeader /> <transition name="fade" mode="out-in"> <div v-show="state.query.doc.name && !state.minimizeQuery" class="flex min-h-[10rem] w-full flex-1 overflow-hidden border-t" > <NativeQueryEditor></NativeQueryEditor> </div> </transition> <div v-if="state.query.results?.formattedResults?.length > 1 && !state.minimizeResult" class="group relative flex max-h-80 flex-col overflow-hidden border-t bg-white" > <ResultSection> <template #footer> <ResultFooter></ResultFooter> </template> </ResultSection> </div> </div> <div v-else class="flex h-20 w-full flex-col items-center justify-center"> <LoadingIndicator class="mb-2 w-6 text-gray-300" /> </div> </template>
2302_79757062/insights
frontend/src/notebook/blocks/query/QueryBlock.vue
Vue
agpl-3.0
1,903
<script setup lang="jsx"> import ResizeableInput from '@/components/ResizeableInput.vue' import useDataSourceStore from '@/stores/dataSourceStore' import { copyToClipboard } from '@/utils' import { debounce } from 'frappe-ui' import { Component as ComponentIcon } from 'lucide-vue-next' import { computed, inject, ref } from 'vue' import { useRouter } from 'vue-router' import QueryDataSourceSelector from '@/query/QueryDataSourceSelector.vue' const state = inject('state') const debouncedUpdateTitle = debounce((title) => state.query.updateTitle(title), 1500) const show_sql_dialog = ref(false) const formattedSQL = computed(() => { return state.query.doc.sql .replaceAll('\n', '<br>') .replaceAll(' ', '&ensp;&ensp;&ensp;&ensp;') }) const page = inject('page') const router = useRouter() function duplicateQuery() { state.query.duplicate().then((name) => { if (page?.addQuery) { page.addQuery('query-editor', name) } else { router.push(`/query/build/${name}`) } }) } const sources = useDataSourceStore() const SourceOption = (props) => { return ( <div class="group flex w-full cursor-pointer items-center justify-between rounded-md px-2 py-2 text-sm hover:bg-gray-100" onClick={() => changeDataSource(props.name)} > <span>{props.label}</span> <FeatherIcon v-show={props.active} name="check" class="h-4 w-4 text-gray-600" /> </div> ) } const currentSource = computed(() => { return sources.list.find((source) => source.name === state.query.doc.data_source) }) const dataSourceOptions = computed(() => { return sources.list.map((source) => ({ component: (props) => ( <SourceOption name={source.name} label={source.title} active={source.name === state.query.doc.data_source} /> ), })) }) function changeDataSource(sourceName) { state.query.changeDataSource(sourceName).then(() => { $notify({ title: 'Data source updated', variant: 'success', }) state.query.doc.data_source = sourceName }) } </script> <template> <div class="flex items-center justify-between rounded-t-lg p-1 pl-3 text-base"> <div class="flex items-center font-mono text-sm"> <div v-if="state.query.doc.is_stored" class="mr-1"> <ComponentIcon class="h-3 w-3 text-gray-600" fill="currentColor" /> </div> <ResizeableInput v-model="state.query.doc.title" class="-ml-2 cursor-text" @update:model-value="debouncedUpdateTitle" ></ResizeableInput> <p class="text-gray-600">({{ state.query.doc.name }})</p> </div> <div class="flex items-center space-x-1"> <QueryDataSourceSelector></QueryDataSourceSelector> <Dropdown :button="{ icon: 'more-vertical', variant: 'outline', }" :options="[ { label: state.minimizeResult ? 'Show Results' : 'Hide Results', icon: state.minimizeResult ? 'maximize-2' : 'minimize-2', onClick: () => (state.minimizeResult = !state.minimizeResult), }, { label: 'Duplicate', icon: 'copy', onClick: duplicateQuery, loading: state.query.duplicating, }, { label: 'View SQL', icon: 'code', onClick: () => (show_sql_dialog = true), loading: state.query.duplicating, }, { label: 'Delete', icon: 'trash', onClick: state.removeQuery, loading: state.query.deleting, }, ]" /> </div> </div> <Dialog :options="{ title: 'Generated SQL', size: '3xl' }" v-model="show_sql_dialog" :dismissable="true" > <template #body-content> <div class="relative"> <p class="rounded border bg-gray-100 p-2 text-base text-gray-600" style="font-family: 'Fira Code'" v-html="formattedSQL" ></p> <Button icon="copy" variant="ghost" class="absolute bottom-2 right-2" @click="copyToClipboard(state.query.doc.sql)" ></Button> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src/notebook/blocks/query/QueryBlockHeader.vue
Vue
agpl-3.0
3,877
<template> <TextEditor ref="tiptap" editorClass="max-w-full prose-h1:font-semibold prose-h1:mt-5 prose-h1:mb-3 prose-h2:font-semibold prose-h2:mt-4 prose-h2:mb-2 prose-p:!my-0 prose-p:py-1 prose-p:text-[16px] prose-p:leading-6 prose-code:before:content-[''] prose-code:after:content-[''] prose-ul:my-0 prose-ol:my-0 prose-li:my-0 prose-th:py-1 prose-td:py-1 prose-blockquote:my-3" @change="updateContent" :bubble-menu="bubbleMenu" :bubble-menu-options="{ shouldShow: (opts) => { // Don't show when the selection is empty if (opts.from === opts.to) return false return !opts.editor.isActive('query-editor') && !opts.editor.isActive('chart') }, }" :placeholder="placeholderByNode" :extensions="[SlashCommand.configure({ suggestion }), QueryEditor, Chart]" ></TextEditor> </template> <script setup> import { safeJSONParse } from '@/utils' import { TextEditor } from 'frappe-ui' import { Code, RemoveFormatting, Strikethrough } from 'lucide-vue-next' import { onMounted, ref, watch } from 'vue' import Chart from './extensions/Chart' import QueryEditor from './extensions/QueryEditor' import SlashCommand from './slash-command/commands' import suggestion from './slash-command/suggestion' const emit = defineEmits(['update:content']) const props = defineProps(['content']) const tiptap = ref(null) const updateContent = () => { const contentJSON = tiptap.value.editor.getJSON() emit('update:content', contentJSON) } onMounted(() => { const content = safeJSONParse(props.content) tiptap.value.editor.commands.setContent(content) }) watch( () => props.content, (newContent) => { const _newContent = safeJSONParse(newContent) if (!_newContent) return const editorContent = tiptap.value.editor.getJSON() if (JSON.stringify(_newContent) !== JSON.stringify(editorContent)) { tiptap.value.editor.commands.setContent(_newContent) } } ) function placeholderByNode({ node }) { if (node.type.name === 'heading') { return `Heading ${node.attrs.level}` } return 'Type / to insert a block' } const bubbleMenu = [ 'Bold', 'Italic', { label: 'Strikethrough', icon: Strikethrough, action: (editor) => editor.chain().focus().toggleStrike().run(), isActive: (editor) => editor.isActive('strike'), }, 'Blockquote', { label: 'Code', icon: Code, action: (editor) => editor.chain().focus().toggleCode().run(), isActive: (editor) => editor.isActive('code'), }, 'Link', { label: 'Remove Formatting', icon: RemoveFormatting, action: (editor) => editor.chain().focus().unsetAllMarks().run(), isActive: () => false, }, ] </script> <style lang="scss"> /* Placeholder */ .prose [data-placeholder].is-empty::before { content: attr(data-placeholder); float: left; pointer-events: none; height: 0; align-self: center; font-size: inherit; @apply absolute text-gray-300; } .prose :where(blockquote p:first-of-type):not(:where([class~='not-prose'] *)) { &::before { content: ''; } &::after { content: ''; } } .prose :where(code):not(:where([class~='not-prose'] *)) { @apply rounded bg-gray-100 px-1.5 py-1 text-gray-700; } .prose :where(pre):not(:where([class~='not-prose'] *)) { @apply bg-gray-100 text-gray-800; } .prose table p { @apply text-base; } .ProseMirror:not(.ProseMirror-focused) p.is-editor-empty:first-child::before { @apply text-gray-500; } </style>
2302_79757062/insights
frontend/src/notebook/tiptap/TipTap.vue
Vue
agpl-3.0
3,351
<template> <node-view-wrapper class="not-prose text-base"> <Suspense> <ChartBlock :chartName="props.node.attrs.chart_name" @setChartName="props.updateAttributes({ chart_name: $event })" @remove="props.deleteNode()" /> </Suspense> </node-view-wrapper> </template> <script setup> import ChartBlock from '@/notebook/blocks/chart/ChartBlock.vue' import { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3' const props = defineProps(nodeViewProps) </script>
2302_79757062/insights
frontend/src/notebook/tiptap/extensions/Chart.vue
Vue
agpl-3.0
481
<template> <node-view-wrapper class="not-prose text-base"> <Suspense> <QueryBlock :query="props.node.attrs.query" @setQuery="props.updateAttributes({ query: $event })" @remove="props.deleteNode()" /> </Suspense> </node-view-wrapper> </template> <script setup> import QueryBlock from '@/notebook/blocks/query/QueryBlock.vue' import { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3' const props = defineProps(nodeViewProps) </script>
2302_79757062/insights
frontend/src/notebook/tiptap/extensions/Query.vue
Vue
agpl-3.0
463
import { createNodeExtension } from './utils' import Query from './Query.vue' export default createNodeExtension({ name: 'query-editor', tag: 'query-editor', component: Query, attributes: { query: undefined, }, })
2302_79757062/insights
frontend/src/notebook/tiptap/extensions/QueryEditor.js
JavaScript
agpl-3.0
222
import { mergeAttributes, Node } from '@tiptap/core' import { VueNodeViewRenderer } from '@tiptap/vue-3' export function createNodeExtension(options) { const { name, component, tag, ...rest } = options return Node.create({ name, group: rest.group || 'block', atom: rest.atom || true, addAttributes() { return rest.attributes || {} }, parseHTML() { return [{ tag }] }, renderHTML({ HTMLAttributes }) { return [tag, mergeAttributes(HTMLAttributes)] }, addNodeView() { return VueNodeViewRenderer(component) }, }) }
2302_79757062/insights
frontend/src/notebook/tiptap/extensions/utils.js
JavaScript
agpl-3.0
550
<template> <div class="flex w-40 flex-col rounded border bg-white p-1 text-base shadow"> <template v-if="enabledItems.length"> <button class="flex h-8 w-full cursor-pointer items-center rounded px-1 text-base" :class="{ 'bg-gray-100': index === selectedIndex }" v-for="(item, index) in enabledItems" :key="index" @click="selectItem(index)" @mouseenter="selectedIndex = index" > <component :is="item.icon || 'Minus'" class="mr-2 h-4 w-4 text-gray-600" /> {{ item.title }} </button> </template> <div class="item" v-else>No result</div> </div> </template> <script> import { Minus } from 'lucide-vue-next' export default { props: { items: { type: Array, required: true, }, editor: { type: Object, required: true, }, command: { type: Function, required: true, }, }, components: { Minus, }, data() { return { selectedIndex: 0, } }, watch: { items() { this.selectedIndex = 0 }, }, computed: { enabledItems() { return this.items.filter((item) => (item.disabled ? !item.disabled(this.editor) : true)) }, }, methods: { onKeyDown({ event }) { if (event.key === 'ArrowUp') { this.upHandler() return true } if (event.key === 'ArrowDown') { this.downHandler() return true } if (event.key === 'Enter') { this.enterHandler() return true } return false }, upHandler() { this.selectedIndex = (this.selectedIndex + this.enabledItems.length - 1) % this.enabledItems.length }, downHandler() { this.selectedIndex = (this.selectedIndex + 1) % this.enabledItems.length }, enterHandler() { this.selectItem(this.selectedIndex) }, selectItem(index) { const item = this.enabledItems[index] if (item) { this.command(item) } }, }, } </script>
2302_79757062/insights
frontend/src/notebook/tiptap/slash-command/CommandsList.vue
Vue
agpl-3.0
1,834
import { Extension } from '@tiptap/core' import Suggestion from '@tiptap/suggestion' export default Extension.create({ name: 'slash-commands', addOptions() { return { suggestion: { char: '/', command: ({ editor, range, props }) => { props.command({ editor, range }) }, }, } }, addProseMirrorPlugins() { return [ Suggestion({ editor: this.editor, ...this.options.suggestion, }), ] }, })
2302_79757062/insights
frontend/src/notebook/tiptap/slash-command/commands.js
JavaScript
agpl-3.0
439
import { VueRenderer } from '@tiptap/vue-3' import { ChevronRightSquare, Heading1, Heading2, Heading3, LineChart, ParkingSquare, Table, } from 'lucide-vue-next' import tippy from 'tippy.js' import { markRaw } from 'vue' import CommandsList from './CommandsList.vue' export default { items: ({ query }) => { return [ { title: 'Paragraph', icon: ParkingSquare, command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).setNode('paragraph').run() }, disabled: (editor) => editor.isActive('table'), }, { title: 'Heading 1', icon: Heading1, command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).setNode('heading', { level: 2 }).run() }, disabled: (editor) => editor.isActive('table'), }, { title: 'Heading 2', icon: Heading2, command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).setNode('heading', { level: 3 }).run() }, disabled: (editor) => editor.isActive('table'), }, { title: 'Heading 3', icon: Heading3, command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).setNode('heading', { level: 4 }).run() }, disabled: (editor) => editor.isActive('table'), }, { title: 'Table', icon: Table, command: ({ editor, range }) => { editor .chain() .focus() .deleteRange(range) .insertTable({ rows: 3, cols: 3, withHeaderRow: true }) .run() }, disabled: (editor) => editor.isActive('table'), }, { title: 'Add Column', command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).addColumnAfter().run() }, disabled: (editor) => !editor.isActive('table'), }, { title: 'Add Row', command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).addRowAfter().run() }, disabled: (editor) => !editor.isActive('table'), }, { title: 'Delete Column', command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).deleteColumn().run() }, disabled: (editor) => !editor.isActive('table'), }, { title: 'Delete Row', command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).deleteRow().run() }, disabled: (editor) => !editor.isActive('table'), }, { title: 'Delete Table', command: ({ editor, range }) => { editor.chain().focus().deleteRange(range).deleteTable().run() }, disabled: (editor) => !editor.isActive('table'), }, { title: 'Chart', icon: markRaw(LineChart), command: ({ editor, range }) => { const element = '<chart></chart>' editor.chain().focus().deleteRange(range).insertContent(element).run() }, disabled: (editor) => !editor.isActive('paragraph') || editor.isActive('table'), }, { title: 'SQL', icon: markRaw(ChevronRightSquare), command: ({ editor, range }) => { const element = '<query-editor></query-editor>' editor.chain().focus().deleteRange(range).insertContent(element).run() }, disabled: (editor) => !editor.isActive('paragraph') || editor.isActive('table'), }, ].filter((item) => item.title.toLowerCase().includes(query.toLowerCase())) }, render: () => { let component let popup return { onStart: (props) => { component = new VueRenderer(CommandsList, { props, editor: props.editor, }) if (!props.clientRect) { return } popup = tippy('body', { getReferenceClientRect: props.clientRect, appendTo: () => document.body, content: component.element, showOnCreate: true, interactive: true, trigger: 'manual', placement: 'bottom-start', }) }, onUpdate(props) { component.updateProps(props) if (!props.clientRect) { return } popup[0].setProps({ getReferenceClientRect: props.clientRect, }) }, onKeyDown(props) { if (props.event.key === 'Escape') { popup[0].hide() return true } return component.ref?.onKeyDown(props) }, onExit() { popup[0].destroy() component.destroy() }, } }, }
2302_79757062/insights
frontend/src/notebook/tiptap/slash-command/suggestion.js
JavaScript
agpl-3.0
4,196
import dayjs from '@/utils/dayjs' import { call, createDocumentResource } from 'frappe-ui' import { reactive } from 'vue' export default function useNotebook(name) { if (!name) throw new Error('Notebook name is required') const resource = createDocumentResource({ doctype: 'Insights Notebook', name: name, }) const state = reactive({ doc: {}, pages: [], loading: false, }) state.reload = async () => { state.loading = true state.doc = await resource.get.fetch() state.pages = await call('insights.api.notebooks.get_notebook_pages', { notebook: name, }) state.pages = state.pages.map((page) => { page.created_from_now = dayjs(page.creation).fromNow() page.modified_from_now = dayjs(page.modified).fromNow() return page }) state.loading = false } state.reload() state.createPage = async () => { return call('insights.api.notebooks.create_notebook_page', { notebook: name, }) } state.deleteNotebook = async () => { state.deleting = true await resource.delete.submit() state.deleting = false } return state }
2302_79757062/insights
frontend/src/notebook/useNotebook.js
JavaScript
agpl-3.0
1,072
import { safeJSONParse, useAutoSave } from '@/utils' import { createDocumentResource } from 'frappe-ui' import { computed, reactive } from 'vue' export default function useNotebookPage(page_name) { const resource = createDocumentResource({ doctype: 'Insights Notebook Page', name: page_name, transform(data) { data.content = safeJSONParse(data.content) return data }, }) const state = reactive({ doc: {}, loading: false, }) state.reload = async () => { state.loading = true state.doc = await resource.get.fetch() if (isEmpty(state.doc.content)) { state.doc.content = getPlaceholderContent() } state.loading = false } state.reload() state.save = async () => { state.loading = true state.doc.content = appendLastParagraph(state.doc.content) const contentString = JSON.stringify(state.doc.content, null, 2) await resource.setValue.submit({ title: state.doc.title || 'Untitled', content: contentString, }) state.loading = false } const fieldsToWatch = computed(() => { // if doc is not loaded, don't watch if (!state.doc.name) return return { title: state.doc.title, content: state.doc.content, } }) useAutoSave(fieldsToWatch, { saveFn: state.save, interval: 1500, }) state.delete = async () => { state.loading = true await resource.delete.submit() state.loading = false } state.addQuery = async (queryType, queryName) => { const validTypes = ['query-editor'] if (!validTypes.includes(queryType)) { throw new Error(`Invalid query type: ${queryType}`) } state.loading = true const content = safeJSONParse(state.doc.content) content.content.push({ type: queryType, attrs: { query: queryName }, }) state.doc.content = content await state.save() await state.reload() state.loading = false } return state } function appendLastParagraph(content) { if (typeof content == 'string') content = safeJSONParse(content) if (!content.content?.length) return {} const lastBlock = content.content?.at(-1) if (lastBlock?.type != 'paragraph') { content.content.push({ type: 'paragraph', attrs: { textAlign: 'left' }, }) } return content } function isEmpty(content) { if (!content) return true if (typeof content == 'string') content = safeJSONParse(content) if (!content.type) return true if (!content.content?.length) return true } function getPlaceholderContent() { return { type: 'doc', content: [ { type: 'paragraph', attrs: { textAlign: 'left' }, content: [ { type: 'text', text: '❓Don’t know where to start? Start by defining your..' }, ], }, { type: 'paragraph', attrs: { textAlign: 'left' }, content: [ { type: 'text', marks: [{ type: 'bold' }], text: '🎯 Objective' }, { type: 'text', text: ': ' }, { type: 'text', marks: [{ type: 'italic' }], text: 'We have to find out why so and so…', }, ], }, { type: 'paragraph', attrs: { textAlign: 'left' }, content: [{ type: 'text', marks: [{ type: 'bold' }], text: '🔍 Approach:' }], }, { type: 'bulletList', content: [ { type: 'listItem', content: [ { type: 'paragraph', attrs: { textAlign: 'left' }, content: [ { type: 'text', marks: [{ type: 'italic' }], text: 'We start with this data', }, ], }, ], }, { type: 'listItem', content: [ { type: 'paragraph', attrs: { textAlign: 'left' }, content: [ { type: 'text', marks: [{ type: 'italic' }], text: 'Combine with that data', }, ], }, ], }, ], }, { type: 'paragraph', attrs: { textAlign: 'left' }, content: [ { type: 'text', text: '❌ Want to start from scratch? Use the clear button inside the 3-dot menu ', }, ], }, ], } }
2302_79757062/insights
frontend/src/notebook/useNotebookPage.js
JavaScript
agpl-3.0
3,986
import dayjs from '@/utils/dayjs' import { createResource, call } from 'frappe-ui' import { defineStore } from 'pinia' const notebooks = createResource({ url: 'insights.api.notebooks.get_notebooks', initialData: [], cache: 'notebookList', transform(data) { return data.map((notebook) => { notebook.created_from_now = dayjs(notebook.creation).fromNow() notebook.modified_from_now = dayjs(notebook.modified).fromNow() return notebook }) }, }) export default defineStore('notebooks', { state: () => ({ list: [], loading: false, creating: false, deleting: false, }), actions: { async reload() { this.loading = true this.list = await notebooks.fetch() this.loading = false }, async createNotebook(title) { this.creating = true await call('insights.api.notebooks.create_notebook', { title }) this.creating = false this.reload() }, async createPage(notebook_name) { return call('insights.api.notebooks.create_notebook_page', { notebook: notebook_name, }) }, }, })
2302_79757062/insights
frontend/src/notebook/useNotebooks.js
JavaScript
agpl-3.0
1,032
<template> <Dialog :options="{ title: 'Add Team' }" v-model="show"> <template #body-content> <Form v-model="newTeam" :meta="{ fields: [ { name: 'team_name', label: 'Team Name', type: 'text', placeholder: 'Enter team name', }, ], }" /> </template> <template #actions> <Button variant="solid" :disabled="!newTeam.team_name" @click="addTeam"> Add </Button> <Button @click="show = false">Cancel</Button> </template> </Dialog> </template> <script setup> import { reactive, computed } from 'vue' import { createResource } from 'frappe-ui' import { useTeams } from '@/utils/useTeams' import Form from './Form.vue' const emit = defineEmits(['close']) const show = computed({ get: () => true, set: (value) => { if (!value) { emit('close') } }, }) const newTeam = reactive({ team_name: '', }) const teams = useTeams() const addTeamResource = createResource({ url: 'insights.insights.doctype.insights_team.insights_team_client.add_new_team', }) function addTeam() { addTeamResource .submit({ team_name: newTeam.team_name, }) .then(() => { teams.refresh() emit('close') }) } </script>
2302_79757062/insights
frontend/src/pages/AddTeamDialog.vue
Vue
agpl-3.0
1,191
<template> <Dialog :options="{ title: 'Add User' }" v-model="show"> <template #body-content> <Form v-model="newUser" :meta="{ fields: [ { name: 'first_name', label: 'First Name', type: 'text', placeholder: 'Enter first name', }, { name: 'last_name', label: 'Last Name', type: 'text', placeholder: 'Enter last name', }, { name: 'email', label: 'Email', type: 'email', placeholder: 'Enter email', }, { name: 'role', label: 'Role', type: 'select', placeholder: 'Select role', options: ['Admin', 'User'], }, { name: 'team', label: 'Team', type: 'select', placeholder: 'Select team', options: teamOptions, }, ], }" /> </template> <template #actions> <Button variant="solid" :disabled="!newUser.first_name || !newUser.last_name || !newUser.email" @click="addUser" > Add </Button> <Button @click="show = false">Cancel</Button> </template> </Dialog> </template> <script setup> import { reactive, computed } from 'vue' import { useTeams } from '@/utils/useTeams' import { useUsers } from '@/utils/useUsers' import Form from './Form.vue' const emit = defineEmits(['close']) const show = computed({ get: () => true, set: (value) => { if (!value) { emit('close') } }, }) const newUser = reactive({ first_name: '', last_name: '', email: '', team: '', role: 'User', }) const teams = useTeams() const teamOptions = computed(() => [{ label: 'Select Team', value: '' }].concat( teams.list.map((team) => { return { label: team.team_name, value: team.name, } }) ) ) const users = useUsers() function addUser() { users.add(newUser).then(() => { emit('close') }) } </script>
2302_79757062/insights
frontend/src/pages/AddUserDialog.vue
Vue
agpl-3.0
1,877
<template> <div class="flex -space-x-2"> <Avatar class="ring-2 ring-white" v-for="avatar in avatars" :key="avatar.label" :label="avatar.label" :image="avatar.image" /> </div> </template> <script setup> const props = defineProps({ avatars: { type: Array, required: true, }, }) </script>
2302_79757062/insights
frontend/src/pages/Avatars.vue
Vue
agpl-3.0
314
<script setup> import { computed } from 'vue' const props = defineProps({ meta: { type: Object, required: true, }, modelValue: { type: Object, required: true, }, }) const modelValue = computed({ get: () => props.modelValue, set: (value) => { emit('update:modelValue', value) }, }) props.meta.fields.forEach((field) => { if (field.defaultValue) { modelValue.value[field.name] = field.defaultValue } }) </script> <template> <div class="flex flex-col space-y-4"> <div class="relative" v-for="field in meta.fields" :key="field.name"> <Input :type="field.type" :label="field.label" :options="field.options" :placeholder="field.placeholder" v-model="modelValue[field.name]" /> <span v-if="field.required && !modelValue[field.name]" class="absolute right-0 top-1 text-xs text-red-400" > * required </span> </div> </div> </template>
2302_79757062/insights
frontend/src/pages/Form.vue
Vue
agpl-3.0
901
<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 LoginBox from '@/components/LoginBox.vue' import sessionStore from '@/stores/sessionStore' import { onMounted, ref } from '@vue/runtime-core' import { useRoute, useRouter } from 'vue-router' const session = sessionStore() 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/src/pages/Login.vue
Vue
agpl-3.0
1,799
<template> <Dialog :options="{ title: `Manage ${team.doc?.team_name} Team`, size: '3xl' }" v-model="show"> <template #body> <div class="flex h-[70vh] text-base"> <ManageTeamSidebar @change="currentSidebarItem = $event" @delete-team="show = false" ></ManageTeamSidebar> <div class="flex w-3/4 space-y-4 overflow-y-auto p-5"> <ManageTeamMembers v-if="currentSidebarItem == 'Members'" /> <ManageTeamResourceAccess v-if="currentSidebarItem != 'Members'" :key="currentSidebarItem" :resourceType=" { 'Data Sources': 'Insights Data Source', Tables: 'Insights Table', Queries: 'Insights Query', Dashboards: 'Insights Dashboard', }[currentSidebarItem] " /> </div> </div> </template> </Dialog> </template> <script setup> import { ref, computed, provide } from 'vue' import { useTeam } from '@/utils/useTeams.js' import ManageTeamSidebar from './ManageTeamSidebar.vue' import ManageTeamMembers from './ManageTeamMembers.vue' import ManageTeamResourceAccess from './ManageTeamResourceAccess.vue' const emit = defineEmits(['close']) const props = defineProps({ teamname: { type: String, required: true, }, }) const currentSidebarItem = ref('Members') const team = useTeam(props.teamname) provide('team', team) const show = computed({ get: () => Boolean(team.doc?.team_name), set: (value) => { if (!value) { emit('close') } }, }) </script>
2302_79757062/insights
frontend/src/pages/ManageTeamDialog.vue
Vue
agpl-3.0
1,468
<script setup> import { ref, computed, inject } from 'vue' import ListPicker from '@/components/Controls/ListPicker.vue' const team = inject('team') const selectedMembers = ref([]) const memberOptions = computed(() => { return team.memberOptions?.map((member) => { return { label: member.full_name, description: member.email, value: member.name, } }) }) const addingMember = ref(false) function addMembers(members) { addingMember.value = true team.addMembers(members.map((member) => member.value)) .then(() => { addingMember.value = false }) .catch(() => { addingMember.value = false }) selectedMembers.value = [] } </script> <template> <div class="flex w-full flex-col space-y-3 text-base"> <div class="flex flex-shrink-0 flex-col space-y-2"> <div class="text-lg font-medium">Members</div> <ListPicker placeholder="Add a member" v-model="selectedMembers" :options="memberOptions" :loading="team.search_team_members.loading" @inputChange="(query) => team.searchMembers(query)" @apply="(selected) => addMembers(selected)" ></ListPicker> </div> <div class="flex-1 divide-y overflow-y-auto text-gray-800" v-if="team.members && team.members.length" > <div class="flex h-12 justify-between px-1" v-for="member in team.members" :key="member.name" > <div class="flex items-center space-x-2"> <Avatar :label="member.full_name" :image="member.user_image" /> <div> <div>{{ member.full_name }}</div> <div class="text-sm text-gray-600">{{ member.email }}</div> </div> </div> <div class="flex items-center"> <Button icon="x" variant="minimal" @click="team.removeMember(member.name)" ></Button> </div> </div> </div> <div v-else-if="addingMember" class="flex flex-1 items-center justify-center text-gray-500"> <LoadingIndicator class="h-6 w-6" /> </div> <div v-else class="flex flex-1 items-center justify-center rounded border border-dashed p-4 font-light text-gray-500" > This team has no members </div> </div> </template>
2302_79757062/insights
frontend/src/pages/ManageTeamMembers.vue
Vue
agpl-3.0
2,109
<script setup> import { ref, computed, inject } from 'vue' import ListPicker from '@/components/Controls/ListPicker.vue' const props = defineProps({ resourceType: { type: String, required: true, }, }) const resourceTitle = computed(() => props.resourceType.replace('Insights ', '')) const resourceDescription = computed(() => { const description_map = { 'Insights Data Source': 'All the tables from these data source will be accessible to the team.', 'Insights Table': 'Give access to only specific tables of a data source. Tables from accessible data sources will also be accessible to the team.', 'Insights Query': 'Queries that are accessible to this team.', 'Insights Dashboard': 'Dashboards that are accessible to this team.', } return description_map[props.resourceType] }) const team = inject('team') team.searchResources(props.resourceType, '') const accessibleResources = computed(() => { return team.resources?.filter((resource) => resource.type == props.resourceType) }) const selectedResources = ref([]) const resourceOptions = computed(() => { return team.resourceOptions?.map((resource) => { const description_map = { 'Insights Data Source': `${resource.database_type}`, 'Insights Table': `${resource.data_source}`, 'Insights Query': `${resource.data_source}`, 'Insights Dashboard': '', } return { ...resource, value: resource.name, label: resource.title, description: description_map[resource.type], } }) }) function addResources(resources) { team.addResources(resources) selectedResources.value = [] } </script> <template> <div class="flex w-full flex-col space-y-3 text-base"> <div class="flex flex-shrink-0 flex-col"> <div class="text-lg font-medium leading-6">Manage {{ resourceTitle }} Access</div> <div class="mb-4 text-sm text-gray-600"> {{ resourceDescription }} </div> <ListPicker :placeholder="`Add a ${resourceTitle}`" v-model="selectedResources" :options="resourceOptions" :loading="team.search_team_resources.loading" @apply="(resources) => addResources(resources)" @inputChange="(query) => team.searchResources(props.resourceType, query)" ></ListPicker> </div> <div class="flex-1 space-y-3 overflow-y-auto pl-1"> <div class="divide-y" v-if="accessibleResources && accessibleResources.length"> <div class="flex h-10 items-center justify-between" v-for="resource in accessibleResources" :key="resource.name" > <span class="w-[20rem] overflow-hidden text-ellipsis whitespace-nowrap"> {{ resource.title }} </span> <div class="flex items-center space-x-2"> <Button icon="x" variant="minimal" @click="team.removeResource(resource)" ></Button> </div> </div> </div> <div v-else class="flex h-full items-center justify-center rounded border border-dashed p-4 text-sm font-light text-gray-600" > No {{ resourceTitle }} added yet. </div> </div> </div> </template>
2302_79757062/insights
frontend/src/pages/ManageTeamResourceAccess.vue
Vue
agpl-3.0
3,014
<script setup> import { showPrompt } from '@/utils/prompt' import { ref, computed, inject } from 'vue' const sidebarItems = ref([ { label: 'Members', icon: 'users', current: true, }, { label: 'Data Sources', icon: 'database', }, { label: 'Tables', icon: 'table', }, { label: 'Dashboards', icon: 'monitor', }, { label: 'Queries', icon: 'file-text', }, { label: 'Delete Team', icon: 'trash-2', variant: 'solid', theme: 'red', }, ]) const emit = defineEmits(['change', 'delete-team']) const currentSidebarItem = computed({ get: () => sidebarItems.value.find((item) => item.current).label, set: (value) => { sidebarItems.value = sidebarItems.value.map((item) => { item.current = item.label == value return item }) emit('change', value) }, }) const team = inject('team') function handleSidebarItemClick(item) { if (item.variant == 'danger') { showDeletePrompt() } else { currentSidebarItem.value = item.label } } function showDeletePrompt() { showPrompt({ title: 'Delete Team', message: `Are you sure you want to delete this team?`, icon: { name: 'trash', variant: 'solid', theme: 'red' }, primaryAction: { label: 'Delete', variant: 'solid', theme: 'red', action: ({ close }) => { return team .deleteTeam() .then(close) .then(() => emit('delete-team')) }, }, }) } </script> <template> <div class="w-1/4 bg-gray-50 p-3 text-gray-600"> <div class="mb-2 text-lg font-medium text-gray-800">{{ team.doc.team_name }} Team</div> <nav class="flex-1 space-y-1 pb-4 text-base"> <div v-for="item in sidebarItems" :key="item.label" :class="[ item.current ? 'bg-gray-200/70' : 'text-gray-600 ', item.variant == 'danger' ? 'text-red-600 hover:bg-gray-200/70 hover:text-red-600' : 'text-gray-600 hover:bg-gray-200/70 hover:text-gray-800', 'group flex cursor-pointer items-center rounded px-2 py-1.5 font-medium hover:bg-gray-200/70 hover:text-gray-800', ]" @click="handleSidebarItemClick(item)" > <FeatherIcon :name="item.icon" :class="['mr-3 h-4 w-4 flex-shrink-0']" /> {{ item.label }} </div> </nav> </div> </template>
2302_79757062/insights
frontend/src/pages/ManageTeamSidebar.vue
Vue
agpl-3.0
2,186
<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">403</p> <h1 class="mt-1 text-[48px] font-bold tracking-tight text-gray-900"> Permission Denied </h1> <div class="text-xl font-light"> You don't have permission to access this page. Make sure you have the right roles & permissions. </div> <router-link to="/" class="mt-2 text-lg text-blue-600 underline"> Go Back </router-link> </div> </div> </template>
2302_79757062/insights
frontend/src/pages/NoPermission.vue
Vue
agpl-3.0
538
<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/src/pages/NotFound.vue
Vue
agpl-3.0
453
<template> <header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5"> <PageBreadcrumbs class="h-7" :items="[{ label: 'Settings' }]" /> <div class="space-x-2.5"> <Button label="Update" :disabled="updateDisabled" variant="solid" @click="store.update(configurables)" > <template #prefix> <CheckIcon class="w-4" /> </template> </Button> </div> </header> <div class="flex flex-1 space-y-4 overflow-hidden bg-white px-6 py-2"> <div class="-m-1 flex flex-1 flex-col space-y-6 overflow-y-auto p-1"> <div class="rounded bg-white p-6 shadow"> <div class="flex items-baseline"> <div class="text-xl font-medium text-gray-700">General</div> </div> <div class="mt-4 flex flex-col space-y-8"> <Setting label="Max Query Result Limit" description="Maximum number of rows to be returned by a query. This is to prevent long running queries and memory issues." > <Input type="number" min="0" v-model="configurables.query_result_limit" /> <div class="ml-2 text-gray-600">Rows</div> </Setting> <Setting label="Cache Query Results For" description="Number of minutes to cache query results. This is to prevent accidental running of the same query multiple times." > <Input type="number" min="0" v-model="configurables.query_result_expiry" /> <div class="ml-2 text-gray-600">Minutes</div> </Setting> <Setting label="Fiscal Year Start" description="Start of the fiscal year. This is used to calculate fiscal year for date columns." > <DatePicker placeholder="Select Date" :value="configurables.fiscal_year_start" @change="configurables.fiscal_year_start = $event" /> </Setting> <Setting label="Auto Execute Query" description="Automatically execute when tables, columns, or filters are changed." > <Input type="checkbox" v-model="configurables.auto_execute_query" :label="configurables.auto_execute_query ? 'Enabled' : 'Disabled'" /> </Setting> <Setting label="Enable Query Reusability" description="Allow selecting query as a table in another query. Any query selected as a table will be appended as a sub query using CTE (Common Table Expression)." > <Input type="checkbox" v-model="configurables.allow_subquery" :label="configurables.allow_subquery ? 'Enabled' : 'Disabled'" /> </Setting> </div> </div> <div class="rounded bg-white p-6 shadow"> <div class="flex items-baseline"> <div class="text-xl font-medium text-gray-700">Notifications</div> </div> <div class="mt-4 flex flex-col space-y-8"> <Setting label="Telegram Bot Token" description="Telegram bot token to send notifications to Telegram." > <Input type="password" v-model="configurables.telegram_api_token" placeholder="Telegram Bot Token" /> </Setting> </div> </div> </div> </div> </template> <script setup> import DatePicker from '@/components/Controls/DatePicker.vue' import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue' import Setting from '@/components/Setting.vue' import settingsStore from '@/stores/settingsStore' import { CheckIcon } from 'lucide-vue-next' import { computed, ref, watchEffect } from 'vue' const initialValues = { query_result_limit: 1000, query_result_expiry: 60, auto_execute_query: true, allow_subquery: true, fiscal_year_start: null, telegram_api_token: '', } const configurables = ref(initialValues) const store = settingsStore() watchEffect(() => { if (store.settings) { Object.keys(configurables.value).forEach((key) => { configurables.value[key] = store.settings[key] }) } else { configurables.value = initialValues } }) const updateDisabled = computed(() => { const local = configurables.value const remote = store.settings if (!local || !remote) return true return ( // check if any value of local is different from remote Object.keys(local).find((key) => local[key] !== remote[key]) === undefined || store.settings.loading ) }) document.title = 'Settings - Insights' </script>
2302_79757062/insights
frontend/src/pages/Settings.vue
Vue
agpl-3.0
4,255
<template> <BasePage> <template #header> <div class="flex flex-1 justify-between"> <h1 class="text-3xl font-medium text-gray-900">Teams</h1> <div class="space-x-4"> <Button variant="outline" class="shadow" iconLeft="plus" @click="showAddTeamDialog = true" >Add Team</Button > </div> </div> </template> <template #main> <div class="flex flex-1 flex-col overflow-hidden"> <div class="mb-4 flex flex-shrink-0 space-x-4"> <Input type="text" placeholder="Team Name" /> </div> <div class="flex flex-1 flex-col rounded border"> <!-- List Header --> <div class="flex flex-shrink-0 items-center justify-between border-b px-4 py-3 text-sm text-gray-600" > <p class="mr-4"> <Input type="checkbox" class="rounded border-gray-300" /> </p> <p class="flex-1 flex-shrink-0">Team Name</p> <p class="flex-1 flex-shrink-0">Members</p> <p class="hidden flex-1 flex-shrink-0 lg:inline-block">Data Sources</p> <p class="hidden flex-1 flex-shrink-0 lg:inline-block">Tables</p> <p class="hidden flex-1 flex-shrink-0 lg:inline-block">Queries</p> <p class="hidden flex-1 flex-shrink-0 lg:inline-block">Dashboards</p> </div> <ul role="list" v-if="teams.list?.length > 0" class="flex flex-1 flex-col divide-y divide-gray-200 overflow-y-auto" > <li v-for="team in teams.list" :key="team.name" @click="teamToEdit = team.name" > <div class="flex h-11 cursor-pointer items-center rounded px-4 hover:bg-gray-50" > <p class="mr-4"> <Input type="checkbox" class="rounded border-gray-300" /> </p> <p class="flex-1 flex-shrink-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium text-gray-900" > {{ team.team_name }} </p> <p class="flex-1 flex-shrink-0 overflow-hidden whitespace-nowrap text-sm text-gray-600" > <Avatars v-if="team.members.length > 0" :avatars="getAvatars(team.members)" ></Avatars> <span v-else> - </span> </p> <p class="hidden flex-1 flex-shrink-0 overflow-hidden whitespace-nowrap text-sm text-gray-600 lg:inline-block" > {{ team.source_count }} </p> <p class="hidden flex-1 flex-shrink-0 overflow-hidden whitespace-nowrap text-sm text-gray-600 lg:inline-block" > {{ team.table_count }} </p> <p class="hidden flex-1 flex-shrink-0 overflow-hidden whitespace-nowrap text-sm text-gray-600 lg:inline-block" > {{ team.query_count }} </p> <p class="hidden flex-1 flex-shrink-0 overflow-hidden whitespace-nowrap text-sm text-gray-600 lg:inline-block" > {{ team.dashboard_count }} </p> </div> </li> </ul> </div> </div> </template> </BasePage> <AddTeamDialog v-if="showAddTeamDialog" @close="showAddTeamDialog = false"></AddTeamDialog> <ManageTeamDialog v-if="teamToEdit" :teamname="teamToEdit" @close="teamToEdit = null" ></ManageTeamDialog> </template> <script setup> import { ref } from 'vue' import BasePage from '@/components/BasePage.vue' import { useTeams } from '@/utils/useTeams.js' import ManageTeamDialog from './ManageTeamDialog.vue' import AddTeamDialog from './AddTeamDialog.vue' import Avatars from './Avatars.vue' const teams = useTeams() const teamToEdit = ref(null) const showAddTeamDialog = ref(false) function getAvatars(members) { return members .map((member) => ({ label: member.full_name, image: member.user_image, })) .slice(0, 3) .concat(members.length > 3 ? [{ label: `${members.length - 3}` }] : []) } </script>
2302_79757062/insights
frontend/src/pages/Teams.vue
Vue
agpl-3.0
3,852
<script setup></script> <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-500">Your free trial has ended</p> <h1 class="mb-3 mt-1 text-[48px] font-bold tracking-tight text-gray-900"> Hope you enjoyed it! </h1> <div class="mx-auto w-[28rem] text-center text-xl font-light"> Hello again! We hope you enjoyed your free trial of our service. You can continue using our service by upgrading to a paid plan. Click <a href="https://frappe.cloud/marketplace/apps/insights" class="text-blue-500"> here </a> to learn more about our pricing plans. </div> </div> </div> </template>
2302_79757062/insights
frontend/src/pages/TrialExpired.vue
Vue
agpl-3.0
715
<template> <BasePage> <template #header> <div class="flex flex-1 justify-between"> <h1 class="text-3xl font-medium text-gray-900">Users</h1> <div class="space-x-4"> <Button variant="outline" iconLeft="plus" @click="showAddUserDialog = true"> Add User </Button> </div> </div> </template> <template #main> <div class="flex flex-1 flex-col overflow-hidden"> <div class="mb-4 flex flex-shrink-0 space-x-4"> <Input type="text" placeholder="Full Name" v-model="search.full_name" /> </div> <div class="flex flex-1 flex-col overflow-hidden rounded border"> <!-- List Header --> <div class="flex flex-shrink-0 items-center justify-between border-b px-4 py-3 text-sm text-gray-600" > <p class="mr-4"> <Input type="checkbox" class="rounded border-gray-300" /> </p> <p class="flex-1 flex-shrink-0">Full Name</p> <p class="flex-1 flex-shrink-0">Email</p> <p class="flex-1 flex-shrink-0">Teams</p> <p class="flex-1 flex-shrink-0">Last Active</p> </div> <ul role="list" v-if="users.list?.length > 0" class="flex flex-1 flex-col divide-y divide-gray-200 overflow-y-auto" > <li v-for="user in filteredUsers" :key="user.name" @click="userToEdit = user.name" > <div class="group flex h-11 cursor-pointer items-center rounded px-4 hover:bg-gray-50" > <p class="mr-4"> <Input type="checkbox" class="rounded border-gray-300" /> </p> <p class="flex flex-1 flex-shrink-0 items-center justify-between"> <span class="overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium text-gray-900" > {{ user.full_name }} </span> <Badge v-if="user.type == 'Admin'" theme="green" class="mr-6"> {{ user.type }} </Badge> </p> <p class="flex-1 flex-shrink-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm text-gray-600" > {{ user.email }} </p> <p class="hidden flex-1 flex-shrink-0 overflow-hidden whitespace-nowrap text-sm text-gray-600 lg:inline-block" > {{ user.teams.length > 0 ? user.teams.join(', ') : '-' }} </p> <p class="hidden flex-1 flex-shrink-0 overflow-hidden whitespace-nowrap text-sm text-gray-600 lg:inline-block" > {{ fromNow(user.last_active) || '-' }} </p> </div> </li> </ul> </div> </div> </template> </BasePage> <AddUserDialog v-if="showAddUserDialog" @close="showAddUserDialog = false"></AddUserDialog> </template> <script setup> import BasePage from '@/components/BasePage.vue' import { useUsers } from '@/utils/useUsers.js' import { computed, inject, reactive, ref } from 'vue' import AddUserDialog from './AddUserDialog.vue' const users = useUsers() const userToEdit = ref(null) const showAddUserDialog = ref(false) const dayjs = inject('$dayjs') const fromNow = (date) => date && dayjs(date).fromNow() const search = reactive({ full_name: '', }) const filteredUsers = computed(() => { return users.list.filter((user) => { return user.full_name.toLowerCase().includes(search.full_name.toLowerCase()) }) }) </script>
2302_79757062/insights
frontend/src/pages/Users.vue
Vue
agpl-3.0
3,315
<script setup> import PublicShareDialog from '@/components/PublicShareDialog.vue' import useDashboards from '@/dashboard/useDashboards' import { Maximize } from 'lucide-vue-next' import { computed, inject, ref, watch } from 'vue' const emit = defineEmits(['fullscreen']) const query = inject('query') const showShareDialog = ref(false) const showDashboardDialog = ref(false) const dashboards = useDashboards() const toDashboard = ref(null) const addingToDashboard = ref(false) const dashboardOptions = computed(() => { return dashboards.list.map((d) => { return { label: d.title, value: d.name } }) }) const $notify = inject('$notify') function onAddToDashboard() { showDashboardDialog.value = true } const addChartToDashboard = async () => { if (!toDashboard.value) return await query.chart.addToDashboard(toDashboard.value.value) showDashboardDialog.value = false $notify({ variant: 'success', title: 'Success', message: 'Chart added to dashboard', }) } watch(showDashboardDialog, (val) => val && dashboards.reload(), { immediate: true }) const showNewDashboardDialog = ref(false) function onCreateDashboard() { showNewDashboardDialog.value = true showDashboardDialog.value = false } const newDashboardTitle = ref('') const creatingDashboard = ref(false) async function createNewDashboard() { if (!newDashboardTitle.value) return creatingDashboard.value = true await dashboards.create(newDashboardTitle.value) creatingDashboard.value = false showNewDashboardDialog.value = false showDashboardDialog.value = true } </script> <template> <div class="flex gap-2"> <Button variant="outline" @click="emit('fullscreen')"> <template #icon> <Maximize class="h-4 w-4" /> </template> </Button> <Button variant="outline" @click="onAddToDashboard()"> Add to Dashboard </Button> <Button variant="outline" @click="showShareDialog = true"> Share </Button> </div> <PublicShareDialog v-if="query.chart.doc?.doctype && query.chart.doc?.name" v-model:show="showShareDialog" :resource-type="query.chart.doc.doctype" :resource-name="query.chart.doc.name" :allow-public-access="true" :isPublic="Boolean(query.chart.doc.is_public)" @togglePublicAccess="query.chart.togglePublicAccess" /> <Dialog :options="{ title: 'Add to Dashboard', actions: [ { label: 'Add', variant: 'solid', disabled: !toDashboard, onClick: addChartToDashboard, loading: addingToDashboard, }, ], }" v-model="showDashboardDialog" > <template #body-content> <div class="text-base"> <span class="mb-2 block text-sm leading-4 text-gray-700">Dashboard</span> <Autocomplete :options="dashboardOptions" v-model="toDashboard"> <template #footer="{ togglePopover }"> <Button class="w-full" variant="ghost" iconLeft="plus" @click="onCreateDashboard() || togglePopover()" > Create New </Button> </template> </Autocomplete> </div> </template> </Dialog> <Dialog :options="{ title: 'Create New Dashboard', actions: [ { label: 'Create', variant: 'solid', onClick: createNewDashboard, loading: creatingDashboard, }, ], }" v-model="showNewDashboardDialog" > <template #body-content> <div class="text-base"> <span class="mb-2 block text-sm leading-4 text-gray-700">Dashboard Title</span> <FormControl v-model="newDashboardTitle" placeholder="Enter title" class="w-full" autocomplete="off" /> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src/query/ChartActionButtons.vue
Vue
agpl-3.0
3,550
<script setup> import Autocomplete from '@/components/Controls/Autocomplete.vue' import widgets from '@/widgets/widgets' import { inject } from 'vue' const query = inject('query') function resetOptions() { query.chart.doc.options = {} } </script> <template> <div class="flex h-full flex-col space-y-4 overflow-y-auto p-0.5"> <div> <label class="mb-1.5 block text-xs text-gray-600">Chart type</label> <Autocomplete :modelValue="query.chart.doc.chart_type" :options="widgets.getChartOptions()" @update:modelValue=" (option) => { query.chart.doc.chart_type = option.value query.chart.doc.options = {} } " > <template #prefix> <component :is="widgets.getIcon(query.chart.doc.chart_type)" class="mr-1.5 h-4 w-4 text-gray-600" stroke-width="1.5" /> </template> <template #item-prefix="{ option }"> <component :is="widgets.getIcon(option.label)" class="h-4 w-4" stroke-width="1.5" /> </template> </Autocomplete> </div> <component v-if="query.chart.doc.chart_type" :is="widgets.getOptionComponent(query.chart.doc.chart_type)" :key="query.chart.doc.chart_type" v-model="query.chart.doc.options" :columns="query.results.columns" /> <Button variant="subtle" @click="resetOptions"> Reset Options </Button> </div> </template>
2302_79757062/insights
frontend/src/query/ChartOptions.vue
Vue
agpl-3.0
1,367
<script setup> import { downloadImage } from '@/utils' import widgets from '@/widgets/widgets' import { computed, inject, ref } from 'vue' import ChartActionButtons from './ChartActionButtons.vue' import ChartSectionEmptySvg from './ChartSectionEmptySvg.vue' import ChartTypeSelector from './ChartTypeSelector.vue' const query = inject('query') const chartRef = ref(null) const showChart = computed(() => { return ( query.chart.doc?.name && query.results.formattedResults?.length && query.doc.status !== 'Pending Execution' ) }) const emptyMessage = computed(() => { if (query.doc.status == 'Pending Execution') { return 'Execute the query to see the chart' } if (!query.results.formattedResults?.length) { return 'No results found' } return 'Pick a chart type to get started' }) const chart = computed(() => { const chart_type = query.chart.doc.chart_type const guessedChart = query.chart.getGuessedChart(chart_type) if (!guessedChart) return {} const options = Object.assign({}, guessedChart.options, query.chart.doc.options) return { type: guessedChart.chart_type, data: query.chart.data, options: chart_type == 'Auto' ? guessedChart.options : options, component: widgets.getComponent(guessedChart.chart_type), } }) const fullscreenDialog = ref(false) function showInFullscreenDialog() { fullscreenDialog.value = true } const downloading = ref(false) function downloadChartImage() { if (!chartRef.value) { $notify({ variant: 'error', title: 'Chart container reference not found', }) return } downloading.value = true const title = query.chart.doc.options.title || query.doc.title downloadImage(chartRef.value.$el, `${title}.png`).then(() => { downloading.value = false }) } </script> <template> <div v-if="query.chart.doc?.name" class="flex flex-1 flex-col gap-4 overflow-hidden"> <div v-if="!showChart" class="flex flex-1 flex-col items-center justify-center rounded border" > <ChartSectionEmptySvg></ChartSectionEmptySvg> <span class="text-gray-500">{{ emptyMessage }}</span> </div> <template v-else> <div class="flex w-full flex-shrink-0 justify-between"> <ChartTypeSelector></ChartTypeSelector> <ChartActionButtons @fullscreen="showInFullscreenDialog"></ChartActionButtons> </div> <div class="flex w-full flex-1 overflow-hidden rounded border"> <component v-if="chart.type" :is="chart.component" :options="chart.options" :data="chart.data" :key="JSON.stringify(query.chart.doc) + JSON.stringify(query.chart.data)" /> </div> </template> <Dialog v-if="chart.type" v-model="fullscreenDialog" :options="{ size: '7xl', }" > <template #body> <div class="relative flex h-[40rem] w-full p-1"> <component v-if="chart.type" ref="chartRef" :is="chart.component" :options="chart.options" :data="chart.data" :key="JSON.stringify(query.chart.doc)" /> <div class="absolute top-0 right-0 p-2"> <Button variant="outline" @click="downloadChartImage" :loading="downloading" icon="download" > </Button> </div> </div> </template> </Dialog> </div> </template>
2302_79757062/insights
frontend/src/query/ChartSection.vue
Vue
agpl-3.0
3,219
<script setup></script> <template> <svg width="158" height="118" viewBox="0 0 158 118" fill="none" xmlns="http://www.w3.org/2000/svg" > <g filter="url(#filter0_dd_33890_17132)"> <rect x="88.3955" y="53.6816" width="40" height="40" rx="4" transform="rotate(-8.96992 88.3955 53.6816)" fill="white" /> <path d="M104.171 76.1108L108.501 70.4174L112.275 73.1625L117.274 66.0299" stroke="#505A62" stroke-linecap="round" /> <path d="M112.928 66.7168L117.274 66.0308L117.96 70.377" stroke="#505A62" stroke-linecap="round" /> </g> <g filter="url(#filter1_dd_33890_17132)"> <rect x="24" y="53.0078" width="40" height="40" rx="4" fill="white" /> <path d="M44 66.957L44 79.057" stroke="#505A62" stroke-width="1.25" stroke-linecap="round" /> <path d="M39.6 69.6641L39.6 79.0576" stroke="#505A62" stroke-width="1.25" stroke-linecap="round" /> <path d="M48.4 71.957L48.4 79.0571" stroke="#505A62" stroke-width="1.25" stroke-linecap="round" /> </g> <g filter="url(#filter2_dd_33890_17132)"> <rect x="64.6121" y="23" width="40" height="40" rx="4" transform="rotate(16.4816 64.6121 23)" fill="white" /> <g clip-path="url(#clip0_33890_17132)"> <path d="M84.5644 52.0617C83.8393 53.173 82.8392 54.078 81.6613 54.6889C80.4834 55.2999 79.1676 55.5961 77.8416 55.5488C76.5155 55.5015 75.2241 55.1123 74.0927 54.419C72.9613 53.7257 72.0283 52.7517 71.3842 51.5917C70.74 50.4316 70.4066 49.1247 70.4162 47.7978C70.4258 46.4709 70.7782 45.169 71.4391 44.0184C72.1 42.8678 73.0471 41.9075 74.1884 41.2307C75.3297 40.5539 76.6266 40.1834 77.9532 40.1554" stroke="#505A62" stroke-linecap="round" /> <path d="M85.4997 50.0379C85.7866 49.0682 85.8797 48.0516 85.7737 47.046C85.6677 46.0404 85.3646 45.0655 84.8818 44.177C84.3991 43.2885 83.746 42.5038 82.96 41.8677C82.1739 41.2316 81.2703 40.7566 80.3007 40.4697L78.1161 47.8533L85.4997 50.0379Z" stroke="#505A62" /> </g> </g> <defs> <filter id="filter0_dd_33890_17132" x="64.3955" y="24.4453" width="93.7474" height="93.748" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feOffset dy="1" /> <feGaussianBlur stdDeviation="12" /> <feColorMatrix type="matrix" values="0 0 0 0 0.0666667 0 0 0 0 0.16915 0 0 0 0 0.258824 0 0 0 0.03 0" /> <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_33890_17132" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feMorphology radius="2" operator="dilate" in="SourceAlpha" result="effect2_dropShadow_33890_17132" /> <feOffset dy="2" /> <feGaussianBlur stdDeviation="3" /> <feColorMatrix type="matrix" values="0 0 0 0 0.0666667 0 0 0 0 0.168627 0 0 0 0 0.258824 0 0 0 0.12 0" /> <feBlend mode="normal" in2="effect1_dropShadow_33890_17132" result="effect2_dropShadow_33890_17132" /> <feBlend mode="normal" in="SourceGraphic" in2="effect2_dropShadow_33890_17132" result="shape" /> </filter> <filter id="filter1_dd_33890_17132" x="0" y="30.0078" width="88" height="88" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feOffset dy="1" /> <feGaussianBlur stdDeviation="12" /> <feColorMatrix type="matrix" values="0 0 0 0 0.0666667 0 0 0 0 0.16915 0 0 0 0 0.258824 0 0 0 0.03 0" /> <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_33890_17132" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feMorphology radius="2" operator="dilate" in="SourceAlpha" result="effect2_dropShadow_33890_17132" /> <feOffset dy="2" /> <feGaussianBlur stdDeviation="3" /> <feColorMatrix type="matrix" values="0 0 0 0 0.0666667 0 0 0 0 0.168627 0 0 0 0 0.258824 0 0 0 0.12 0" /> <feBlend mode="normal" in2="effect1_dropShadow_33890_17132" result="effect2_dropShadow_33890_17132" /> <feBlend mode="normal" in="SourceGraphic" in2="effect2_dropShadow_33890_17132" result="shape" /> </filter> <filter id="filter2_dd_33890_17132" x="29.2638" y="0" width="97.7047" height="97.7051" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feOffset dy="1" /> <feGaussianBlur stdDeviation="12" /> <feColorMatrix type="matrix" values="0 0 0 0 0.0666667 0 0 0 0 0.16915 0 0 0 0 0.258824 0 0 0 0.03 0" /> <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_33890_17132" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feMorphology radius="2" operator="dilate" in="SourceAlpha" result="effect2_dropShadow_33890_17132" /> <feOffset dy="2" /> <feGaussianBlur stdDeviation="3" /> <feColorMatrix type="matrix" values="0 0 0 0 0.0666667 0 0 0 0 0.168627 0 0 0 0 0.258824 0 0 0 0.12 0" /> <feBlend mode="normal" in2="effect1_dropShadow_33890_17132" result="effect2_dropShadow_33890_17132" /> <feBlend mode="normal" in="SourceGraphic" in2="effect2_dropShadow_33890_17132" result="shape" /> </filter> <clipPath id="clip0_33890_17132"> <rect x="70.6889" y="34.1836" width="22" height="22" rx="4" transform="rotate(16.4816 70.6889 34.1836)" fill="white" /> </clipPath> </defs> </svg> </template>
2302_79757062/insights
frontend/src/query/ChartSectionEmptySvg.vue
Vue
agpl-3.0
6,625
<script setup> import widgets from '@/widgets/widgets' import { CheckIcon, ChevronDownIcon } from 'lucide-vue-next' import { computed, inject } from 'vue' const query = inject('query') if (!query.chart.doc.chart_type) { query.chart.doc.chart_type = 'Auto' } const currentChartType = computed(() => { return query.chart.doc?.chart_type }) const AutoChartType = { label: 'Auto', value: 'Auto' } const chartOptions = computed(() => { return [AutoChartType, ...widgets.getChartOptions()] }) </script> <template> <Autocomplete :options="chartOptions" :modelValue="query.chart.doc.chart_type" @update:modelValue="query.chart.doc.chart_type = $event?.value" > <template #target="{ togglePopover }"> <Button variant="outline" @click="togglePopover"> <div class="flex items-center gap-2"> <component :is="widgets.getIcon(currentChartType)" class="h-4 w-4 text-gray-600" /> <span class="truncate">{{ currentChartType }}</span> <ChevronDownIcon class="h-4 w-4 text-gray-600" /> </div> </Button> </template> <template #item-prefix="{ option }"> <component :is="widgets.getIcon(option.value)" class="h-4 w-4 text-gray-600" /> </template> <template #item-suffix="{ selected }"> <CheckIcon v-if="selected" class="h-4 w-4 text-gray-600" /> </template> </Autocomplete> </template>
2302_79757062/insights
frontend/src/query/ChartTypeSelector.vue
Vue
agpl-3.0
1,343
<template> <Button variant="ghost" @click="show = true" icon="help-circle"> </Button> <Dialog :options="{ title: 'Functions' }" v-model="show" :dismissable="true"> <template #body-content> <input v-model="search" placeholder="Search functions" class="form-input block w-full border-gray-400 placeholder-gray-500" /> <div class="mt-4 flex max-h-[30rem] flex-col space-y-1 divide-y overflow-y-auto text-base" > <div v-for="func in filteredList" :key="func.name" class="flex"> <div class="flex-1 space-y-1 py-2"> <p class="font-mono text-lg font-medium">{{ func.name }}</p> <p class="text-sm text-gray-600">{{ func.description }}</p> </div> <div class="mt-2 flex-1 rounded bg-gray-50 p-2 text-sm leading-5"> <code> <span class="text-gray-600"># Syntax</span> <br /> {{ func.syntax }} <br /> <br /> <span class="text-gray-600"># Example</span> <br /> {{ func.example }} </code> </div> </div> <div v-if="!filteredList.length" class="py-2 text-center text-gray-700"> No functions found </div> </div> </template> </Dialog> </template> <script setup> import { FUNCTIONS } from '@/utils/query' import { computed, ref } from 'vue' const show = ref(false) const search = ref('') const functionsList = Object.keys(FUNCTIONS).map((key) => { return { name: key, ...FUNCTIONS[key], } }) const filteredList = computed(() => { if (!search.value) return functionsList return functionsList.filter((func) => { return ( func.name.toLowerCase().includes(search.value.toLowerCase()) || func.syntax?.toLowerCase().includes(search.value.toLowerCase()) ) }) }) </script>
2302_79757062/insights
frontend/src/query/ExpressionHelpDialog.vue
Vue
agpl-3.0
1,727
<script setup> import { inject, ref, watch, computed } from 'vue' import ResultSection from './ResultSection.vue' import ResultFooter from './visual/ResultFooter.vue' import NativeQueryEditor from './NativeQueryEditor.vue' const query = inject('query') const nativeQuery = ref(query.doc.sql) const executionTime = computed(() => query.doc.execution_time) const queriedRowCount = computed(() => query.doc.results_row_count) const displayedRowCount = computed(() => Math.min(query.MAX_ROWS, queriedRowCount.value)) </script> <template> <div class="flex h-full w-full flex-col pt-2"> <div class="flex-shrink-0 uppercase leading-7 tracking-wide text-gray-600"> Native Query </div> <div class="flex flex-1 flex-shrink-0 overflow-hidden rounded border"> <NativeQueryEditor /> </div> <div class="flex w-full flex-1 flex-shrink-0 overflow-hidden py-4"> <ResultSection> <template #footer> <div class="flex justify-between"> <div v-if="queriedRowCount >= 0" class="flex items-center space-x-1"> <span class="text-gray-600">Showing</span> <span class="font-mono"> {{ displayedRowCount }}</span> <span class="text-gray-600">out of</span> <span class="font-mono">{{ queriedRowCount }}</span> <span class="text-gray-600">rows in</span> <span class="font-mono">{{ executionTime }}</span> <span class="text-gray-600">seconds</span> </div> <Button variant="ghost" class="ml-1" icon="download" @click="query.downloadResults" > </Button> </div> </template> </ResultSection> </div> </div> </template>
2302_79757062/insights
frontend/src/query/NativeQueryBuilder.vue
Vue
agpl-3.0
1,635
<script setup> import Code from '@/components/Controls/Code.vue' import { call } from 'frappe-ui' import { computed, inject, ref, watch } from 'vue' import SchemaExplorerDialog from './SchemaExplorerDialog.vue' const props = defineProps({ showToolbar: { type: Boolean, default: true }, }) const query = inject('query') if (query.doc.data_source) { call('run_doc_method', { method: 'get_schema', dt: 'Insights Data Source', dn: query.doc.data_source, }).then((response) => { query.sourceSchema = response.message }) } const completions = computed(() => { if (!query.sourceSchema) return { schema: {}, tables: [] } const schema = {} Object.entries(query.sourceSchema).forEach(([table, tableData]) => { schema[table] = tableData.columns.map((column) => ({ label: column.column, detail: column.label, })) }) const tables = Object.entries(query.sourceSchema).map(([table, tableData]) => ({ label: table, detail: tableData.label, })) return { schema, tables, } }) const showDataExplorer = ref(false) const nativeQuery = ref(query.doc.sql) watch( () => query.doc.sql, (value) => (nativeQuery.value = value) ) </script> <template> <div class="relative flex flex-1 flex-col overflow-y-auto"> <Code :key="completions.tables.length" language="sql" v-model="nativeQuery" :schema="completions.schema" :tables="completions.tables" placeholder="Type your query here" ></Code> <div v-if="props.showToolbar" class="sticky bottom-0 flex gap-1 border-t bg-white p-1"> <div> <Button variant="outline" iconLeft="book-open" @click="showDataExplorer = !showDataExplorer" label="Tables" > </Button> </div> <div> <Button :variant="query.doc.status !== 'Execution Successful' ? 'solid' : 'outline'" iconLeft="play" @click="query.executeSQL(nativeQuery)" :loading="query.loading" label="Run" > </Button> </div> </div> </div> <SchemaExplorerDialog v-model:show="showDataExplorer" /> </template>
2302_79757062/insights
frontend/src/query/NativeQueryEditor.vue
Vue
agpl-3.0
2,024
<script setup> import widgets from '@/widgets/widgets' import InvalidWidget from '@/widgets/InvalidWidget.vue' import usePublicChart from './usePublicChart' const props = defineProps({ public_key: String }) const chart = usePublicChart(props.public_key) </script> <template> <component v-if="chart.doc.chart_type" ref="widget" :is="widgets.getComponent(chart.doc.chart_type)" :data="chart.data" :options="chart.doc.options" :key="JSON.stringify(chart.doc.options)" /> </template>
2302_79757062/insights
frontend/src/query/PublicChart.vue
Vue
agpl-3.0
495
<script setup> import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue' import Tabs from '@/components/Tabs.vue' import { provide, ref, watchEffect } from 'vue' import ChartOptions from './ChartOptions.vue' import ChartSection from './ChartSection.vue' import NativeQueryBuilder from './NativeQueryBuilder.vue' import QueryHeader from './QueryHeader.vue' import QueryHeaderTitle from './QueryHeaderTitle.vue' import ScriptQueryEditor from './ScriptQueryEditor.vue' import ClassicQueryBuilder from './deprecated/ClassicQueryBuilder.vue' import useQuery from './resources/useQuery' import VisualQueryBuilder from './visual/VisualQueryBuilder.vue' const props = defineProps({ name: String }) const query = useQuery(props.name) await query.reload() provide('query', query) const activeTab = ref(0) const tabs = ref([ { label: 'Query', value: 0 }, { label: 'Visualize', value: 1 }, ]) watchEffect(() => { if (query.doc?.name) { const title = query.doc.title || query.doc.name document.title = `${title} - Frappe Insights` } }) </script> <template> <header class="sticky top-0 z-10 flex w-full items-center justify-between border-b bg-white px-4 py-2.5" > <PageBreadcrumbs class="h-7" :items="[ { label: 'Queries', route: { path: '/query' } }, { component: QueryHeaderTitle }, ]" /> <div class="flex gap-2"> <QueryHeader></QueryHeader> <Tabs v-if="!query.doc.is_assisted_query" v-model="activeTab" :tabs="tabs" /> </div> </header> <div v-if="query.doc?.name" class="flex h-full w-full flex-col space-y-4 overflow-hidden bg-white px-4" > <div v-if="activeTab == 0" class="flex flex-1 flex-shrink-0 overflow-hidden"> <VisualQueryBuilder v-if="query.doc.is_assisted_query"></VisualQueryBuilder> <NativeQueryBuilder v-else-if="query.doc.is_native_query"></NativeQueryBuilder> <ScriptQueryEditor v-else-if="query.doc.is_script_query"></ScriptQueryEditor> <ClassicQueryBuilder v-else-if=" !query.doc.is_assisted_query && !query.doc.is_native_query && !query.doc.is_script_query " /> </div> <div v-if="activeTab == 1 && query.chart.doc?.name" class="flex flex-1 flex-shrink-0 gap-4 overflow-hidden pt-4" > <div class="w-[21rem] flex-shrink-0"> <ChartOptions></ChartOptions> </div> <div class="flex flex-1"> <ChartSection></ChartSection> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/query/Query.vue
Vue
agpl-3.0
2,392
<script setup> import useDataSourceStore from '@/stores/dataSourceStore' import { ChevronDown, Database } from 'lucide-vue-next' import { computed, inject } from 'vue' const $notify = inject('$notify') const query = inject('query') const sources = useDataSourceStore() const currentSource = computed(() => { return sources.list.find((source) => source.name === query.doc.data_source) }) const dataSourceOptions = computed(() => { return sources.list.map((source) => ({ label: source.title, value: source.name, })) }) function changeDataSource(sourceName) { query.changeDataSource(sourceName).then(() => { $notify({ title: 'Data source updated', variant: 'success', }) }) } </script> <template> <Autocomplete :options="dataSourceOptions" :modelValue="query.doc.data_source" @update:modelValue="changeDataSource($event.value)" > <template #target="{ togglePopover }"> <Button variant="outline" @click="togglePopover"> <div class="flex items-center gap-2"> <Database class="h-4 w-4 text-gray-600" /> <span class="truncate"> {{ currentSource?.title || 'Select data source' }} </span> <ChevronDown class="h-4 w-4 text-gray-600" /> </div> </Button> </template> </Autocomplete> </template>
2302_79757062/insights
frontend/src/query/QueryDataSourceSelector.vue
Vue
agpl-3.0
1,260
<script setup lang="jsx"> import { Play } from 'lucide-vue-next' import { inject } from 'vue' import QueryDataSourceSelector from './QueryDataSourceSelector.vue' import QueryMenu from './QueryMenu.vue' const query = inject('query') </script> <template> <div class="flex items-center gap-2"> <QueryMenu></QueryMenu> <QueryDataSourceSelector v-if="!query.doc.is_assisted_query"></QueryDataSourceSelector> <Button v-if="!query.doc.is_script_query && !query.doc.is_native_query" variant="solid" @click="query.execute()" :loading="query.executing" :disabled="!query.doc.data_source || !query.doc.sql" > <template #prefix> <Play class="h-4 w-4"></Play> </template> <span>Execute</span> </Button> </div> </template>
2302_79757062/insights
frontend/src/query/QueryHeader.vue
Vue
agpl-3.0
751
<script setup> import ContentEditable from '@/components/ContentEditable.vue' import { watchDebounced } from '@vueuse/core' import { ComponentIcon } from 'lucide-vue-next' import { inject, ref } from 'vue' const query = inject('query') const title = ref(query.doc.title) watchDebounced(title, query.updateTitle, { debounce: 500 }) </script> <template> <div v-if="query.doc.is_stored" class="mr-1"> <ComponentIcon class="h-4 w-4 text-gray-600" fill="currentColor" /> </div> <ContentEditable v-model="title" placeholder="Untitled Query" class="mr-3 rounded-sm px-1 text-lg font-medium focus:ring-2 focus:ring-gray-700 focus:ring-offset-2" ></ContentEditable> <div v-if="query.loading" class="flex items-center gap-1 text-sm text-gray-600"> <LoadingIndicator class="w-3" /> <span>Saving...</span> </div> </template>
2302_79757062/insights
frontend/src/query/QueryHeaderTitle.vue
Vue
agpl-3.0
833
<script setup lang="jsx"> import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue' import ListFilter from '@/components/ListFilter/ListFilter.vue' import NewDialogWithTypes from '@/components/NewDialogWithTypes.vue' import PageBreadcrumbs from '@/components/PageBreadcrumbs.vue' import useNotebooks from '@/notebook/useNotebooks' import useQueryStore from '@/stores/queryStore' import sessionStore from '@/stores/sessionStore' import { isEmptyObj, updateDocumentTitle } from '@/utils' import { getIcon } from '@/widgets/widgets' import { useStorage } from '@vueuse/core' import { Avatar, ListView } from 'frappe-ui' import { AlignStartVertical, ComponentIcon, FileTerminal, GanttChartSquare, PlusIcon, SearchIcon, Square, } from 'lucide-vue-next' import { computed, ref } from 'vue' import { useRoute, useRouter } from 'vue-router' const queryStore = useQueryStore() const router = useRouter() const route = useRoute() const new_dialog = ref(false) if (route.hash == '#new') { new_dialog.value = true } const pageMeta = ref({ title: 'Queries' }) updateDocumentTitle(pageMeta) const notebooks = useNotebooks() async function openQueryEditor(type) { if (type === 'notebook') { await notebooks.reload() const uncategorized = notebooks.list.find((notebook) => notebook.title === 'Uncategorized') const page_name = await notebooks.createPage(uncategorized.name) return router.push({ name: 'NotebookPage', params: { notebook: uncategorized.name, name: page_name, }, }) } const new_query = {} if (type === 'visual') new_query.is_assisted_query = 1 if (type === 'sql') new_query.is_native_query = 1 if (type === 'script') new_query.is_script_query = 1 const query = await queryStore.create(new_query) router.push({ name: 'Query', params: { name: query.name }, }) } const queryBuilderTypes = ref([ { label: 'Visual', description: 'Create a query using the visual interface', icon: 'bar-chart-2', onClick: () => openQueryEditor('visual'), }, { label: 'SQL', description: 'Create a query by writing native query', icon: 'code', onClick: () => openQueryEditor('sql'), }, { label: 'Notebook', description: 'Create a query using the notebook interface', icon: 'book', tag: 'beta', onClick: () => openQueryEditor('notebook'), }, { label: 'Script', description: 'Create a query by writing a python script', icon: 'code', tag: 'beta', onClick: () => openQueryEditor('script'), }, ]) const email = sessionStore().user.email const filters = useStorage('insights:query-list-filters', { owner: ['=', email], }) const queries = computed(() => { if (isEmptyObj(filters.value)) { return queryStore.list } return queryStore.list.filter((query) => { for (const [fieldname, [operator, value]] of Object.entries(filters.value)) { if (!fieldname || !operator || !value) continue const field_value = query[fieldname] if (operator === '=') return field_value === value if (operator === '!=') return field_value !== value if (operator === '<') return field_value < value if (operator === '>') return field_value > value if (operator === '<=') return field_value <= value if (operator === '>=') return field_value >= value if (operator.includes('like')) { return field_value.toLowerCase().includes(value.toLowerCase()) } } return true }) }) function getQueryTypeIcon(query) { if (query.is_assisted_query) return AlignStartVertical if (query.is_native_query) return GanttChartSquare if (query.is_script_query) return FileTerminal return Square } const queryListColumns = [ { label: 'Title', key: 'title', width: 2, prefix: ({ row }) => { if (!row.is_stored) return null return <ComponentIcon class="h-4 w-4 text-gray-600" fill="currentColor" /> }, }, { label: 'Execution Status', key: 'status', width: 1, getLabel: ({ row }) => row.status.replace('Execution', ''), prefix: ({ row }) => { let color = 'text-gray-500' if (row.status === 'Pending Execution') color = 'text-yellow-500' if (row.status === 'Execution Successful') color = 'text-green-500' if (row.status === 'Execution Failed') color = 'text-red-500' return <IndicatorIcon class={color} /> }, }, { label: 'Chart Type', key: 'chart_type', width: 1, prefix: ({ row }) => { if (!row.chart_type) return null const Icon = getIcon(row.chart_type) return <Icon class="h-4 w-4 text-gray-700" /> }, }, { label: 'Data Source', key: 'data_source', width: 1, getLabel: ({ row }) => row.data_source_title || row.data_source, }, { label: 'ID', key: 'name', width: 1, }, { label: 'Created By', key: 'owner_name', width: 1, prefix: ({ row }) => { return <Avatar image={row.owner_image} label={row.owner_name} size="md" /> }, }, { label: 'Created', key: 'created_from_now', width: 1, align: 'right', }, ] </script> <template> <header class="sticky top-0 z-10 flex items-center justify-between bg-white px-5 py-2.5"> <PageBreadcrumbs class="h-7" :items="[{ label: 'Queries' }]" /> <div> <Button label="New Query" variant="solid" @click="new_dialog = true"> <template #prefix> <PlusIcon class="w-4" /> </template> </Button> </div> </header> <div class="mb-4 flex h-full flex-col gap-2 overflow-auto px-4"> <div class="flex gap-2 overflow-visible py-1"> <FormControl placeholder="Search by Title" :modelValue="filters.title?.[1]" @update:modelValue="filters.title = ['like', $event]" :debounce="300" > <template #prefix> <SearchIcon class="h-4 w-4 text-gray-500" /> </template> </FormControl> <ListFilter v-model="filters" :docfields="queryStore.getFilterableFields()" /> </div> <ListView :columns="queryListColumns" :rows="queries" :row-key="'name'" :options="{ showTooltip: false, getRowRoute: (query) => ({ name: 'Query', params: { name: query.name } }), emptyState: { title: 'No Query Created.', description: 'Create a new query to get started.', button: { label: 'New Query', variant: 'solid', onClick: () => (new_dialog = true), }, }, }" > </ListView> </div> <NewDialogWithTypes v-model:show="new_dialog" title="Select Interface Type" :types="queryBuilderTypes" /> </template>
2302_79757062/insights
frontend/src/query/QueryList.vue
Vue
agpl-3.0
6,321
<template> <div class="flex flex-shrink-0 space-x-2"> <Dropdown placement="right" :button="{ icon: 'more-horizontal', variant: 'outline' }" :options="[ !query.doc.is_stored ? { label: 'Store Query', icon: 'bookmark', onClick: storeQuery, } : { label: 'Unstore Query', icon: BookmarkMinus, onClick: unstoreQuery, }, { label: 'Execute (⌘+E)', icon: 'play', onClick: query.execute, }, settings.enable_permissions && query.isOwner ? { label: 'Share', icon: 'share-2', onClick: () => (show_share_dialog = true), } : null, { label: 'Set Alert', icon: 'bell', onClick: () => (show_alert_dialog = true), }, !query.doc.is_native_query ? { label: 'View SQL', icon: 'help-circle', onClick: () => (show_sql_dialog = true), } : null, { label: 'Duplicate', icon: 'copy', onClick: duplicateQuery, }, { label: 'Download CSV', icon: 'download', onClick: query.downloadResults, }, { label: query.doc.is_assisted_query ? 'Switch to Classic Query Builder' : 'Switch to Visual Query Builder', icon: 'toggle-left', onClick: () => (show_switch_dialog = true), }, { label: 'Delete', icon: 'trash-2', onClick: () => (show_delete_dialog = true), }, ]" /> <Dialog v-model="show_delete_dialog" :dismissable="true" :options="{ title: 'Delete Query', message: 'Are you sure you want to delete this query?', icon: { name: 'trash', appearance: 'danger' }, actions: [ { label: 'Delete', variant: 'solid', theme: 'red', onClick: () => { useQueryStore() .delete(query.doc.name) .then(() => { $router.push('/query') show_delete_dialog = false }) }, }, ], }" > </Dialog> <Dialog v-model="show_switch_dialog" :dismissable="true" :options="{ title: query.doc.is_assisted_query ? 'Switch to Classic Query Builder' : 'Switch to Visual Query Builder', message: query.doc.is_assisted_query ? 'All the changes you have made in the query will be preserved. However, if you make any changes in the Classic Query Builder, they will be lost when you switch back to the Visual Query Builder. Are you sure you want to continue?' : 'All the changes you have made in the Classic Query Builder will be converted to the Visual Query Builder. Are you sure you want to continue?', icon: { name: 'toggle-left', appearance: 'warning' }, actions: [ { label: 'Switch', variant: 'solid', onClick: () => query.switchQueryBuilder().then(() => (show_switch_dialog = false)), }, ], }" /> <Dialog :options="{ title: 'Generated SQL', size: '3xl' }" v-model="show_sql_dialog" :dismissable="true" > <template #body-content> <div class="relative"> <div class="max-h-[50vh] overflow-y-auto rounded border text-base"> <Code language="sql" :model-value="query.doc.sql" :read-only="true" :hide-line-numbers="true" /> </div> <Button icon="copy" variant="outline" class="absolute bottom-2 right-2" @click="copyToClipboard(query.doc.sql)" ></Button> </div> </template> </Dialog> </div> <ShareDialog v-if="settings.enable_permissions" v-model:show="show_share_dialog" :resource-type="query.doc.doctype" :resource-name="query.doc.name" /> <AlertDialog v-if="query.doc.name" v-model:show="show_alert_dialog" :queryName="query.doc.name" /> </template> <script setup> import AlertDialog from '@/components/AlertDialog.vue' import ShareDialog from '@/components/ShareDialog.vue' import useQueryStore from '@/stores/queryStore' import settingsStore from '@/stores/settingsStore' import { copyToClipboard } from '@/utils' import { useMagicKeys } from '@vueuse/core' import { Dialog, Dropdown } from 'frappe-ui' import { BookmarkMinus } from 'lucide-vue-next' import { computed, inject, nextTick, ref, watch } from 'vue' import { useRouter } from 'vue-router' import Code from '@/components/Controls/Code.vue' const settings = settingsStore().settings const props = defineProps(['query']) const query = props.query || inject('query') const show_delete_dialog = ref(false) const show_sql_dialog = ref(false) const show_share_dialog = ref(false) const show_alert_dialog = ref(false) const show_switch_dialog = ref(false) const keys = useMagicKeys() const cmdE = keys['Meta+E'] watch(cmdE, (value) => value && query.execute()) const formattedSQL = computed(() => { return query.doc.sql.replaceAll('\n', '<br>').replaceAll(' ', '&ensp;&ensp;&ensp;&ensp;') }) const router = useRouter() const $notify = inject('$notify') function duplicateQuery() { query.duplicate().then(async (query_name) => { await nextTick() router.push(`/query/build/${query_name}`) $notify({ variant: 'success', title: 'Query Duplicated', }) }) } function storeQuery() { query.store().then((res) => { $notify({ variant: 'success', title: 'Query Stored', }) }) } function unstoreQuery() { query.unstore().then((res) => { $notify({ variant: 'success', title: 'Query Unstored', }) }) } </script>
2302_79757062/insights
frontend/src/query/QueryMenu.vue
Vue
agpl-3.0
5,407
<script setup> import TanstackTable from '@/components/Table/TanstackTable.vue' import { FIELDTYPES, formatNumber } from '@/utils' import { convertResultToObjects } from '@/widgets/useChartData' import { computed, inject } from 'vue' const query = inject('query') const needsExecution = computed(() => query.doc.status == 'Pending Execution') const hasResults = computed(() => query.results?.formattedResults?.length > 0) const data = computed(() => convertResultToObjects(query.results.formattedResults)) const tanstackColumns = computed(() => { if (!query.results.columns?.length) return [] const indexColumn = { id: '__index', header: '#', accessorKey: '__index', cell: (props) => props.row.index + 1, } const cols = query.results.columns.map((column) => { const isNumber = FIELDTYPES.NUMBER.includes(column.type) return { id: column.label, header: column.label, accessorKey: column.label, enableSorting: false, isNumber: isNumber, cell: (props) => { const value = props.getValue() return isNumber ? formatNumber(value) : value }, } }) return [indexColumn, ...cols] }) </script> <template> <div class="relative flex h-full w-full flex-col overflow-hidden rounded border"> <div v-if="needsExecution || query.executing" class="absolute top-8 z-10 flex h-[calc(100%-2rem)] w-full items-center justify-center rounded bg-gray-50/30 backdrop-blur-sm" > <div class="flex flex-1 flex-col items-center justify-center gap-2"> <Button class="shadow-2xl" variant="solid" @click="query.execute()" :loading="query.executing" > Execute Query </Button> </div> </div> <TanstackTable :class="needsExecution ? 'pointer-events-none' : ''" :data="data" :columns="tanstackColumns" :showPagination="false" > <template v-if="$slots.columnActions" #columnActions="{ column: tanstackColumn }"> <slot name="columnActions" v-if="tanstackColumn.id != 'index'" :column="{ label: tanstackColumn.id }" ></slot> </template> </TanstackTable> <div v-if="$slots.footer && hasResults" class="border-t p-1"> <slot name="footer"></slot> </div> </div> </template>
2302_79757062/insights
frontend/src/query/ResultSection.vue
Vue
agpl-3.0
2,191
<script setup> import useDataSource from '@/datasource/useDataSource' import useDataSourceTable from '@/datasource/useDataSourceTable' import useDataSourceStore from '@/stores/dataSourceStore' import { computed, inject, ref, watch } from 'vue' const emit = defineEmits(['update:show']) const props = defineProps({ show: Boolean }) const show = computed({ get: () => props.show, set: (value) => emit('update:show', value), }) const dataSources = computed(() => useDataSourceStore().list.map((d) => { return { title: d.title, name: d.name, } }) ) const currentTables = ref([]) const currentColumns = ref([]) const query = inject('query') const currentDataSource = ref(null) watch( () => query?.doc?.data_source, (value) => { if (!value) return currentDataSource.value = { name: value } }, { immediate: true } ) const currentTable = ref(null) watch( currentDataSource, () => { if (!currentDataSource.value) return currentTables.value = [] currentColumns.value = [] const dataSource = useDataSource(currentDataSource.value.name) dataSource.fetchTables().then((tables) => { currentTables.value = tables.map((t) => { return { label: t.label, table: t.table, name: t.name, } }) }) }, { immediate: true } ) const fetchingColumns = ref(false) watch( currentTable, async () => { if (!currentTable.value) return currentColumns.value = [] fetchingColumns.value = true const table = await useDataSourceTable({ name: currentTable.value.name }) fetchingColumns.value = false currentColumns.value = table.columns.map((c) => { return { label: c.label, column: c.column, type: c.type, } }) }, { immediate: true } ) function toggleDataSource(dataSource) { if (currentDataSource.value?.name == dataSource.name) { currentDataSource.value = null } else { currentDataSource.value = dataSource } } function toggleTable(table) { if (currentTable.value?.name == table.name) { currentTable.value = null } else { currentTable.value = table } } </script> <template> <Dialog v-model="show" :options="{ title: 'Browse Data Sources' }"> <template #body-content> <div class="-ml-2 h-[32rem] w-full overflow-y-auto overflow-x-hidden overflow-y-hidden pl-2" > <div class="flex flex-col gap-1"> <div v-for="dataSource in dataSources" :key="dataSource.name" class="flex cursor-pointer flex-col space-x-4" > <div class="-ml-1 flex flex-1 cursor-pointer items-center gap-2 rounded py-1 pl-1 transition-colors hover:bg-gray-100" :class=" currentDataSource?.name == dataSource.name && !currentTable ? 'bg-gray-100' : '' " @click="toggleDataSource(dataSource)" > <FeatherIcon :name=" currentDataSource?.name == dataSource.name ? 'minus' : 'plus' " class="h-4 w-4" /> <div class="flex items-center gap-2"> <FeatherIcon name="database" class="h-4 w-4 text-gray-600" /> <p class="font-medium leading-6 text-gray-900"> {{ dataSource.title }} </p> </div> </div> <div v-if="currentDataSource?.name == dataSource.name" class="mt-1 flex flex-col gap-1" > <div v-for="table in currentTables" :key="table.name" class="pl-2"> <div class="-ml-1 flex flex-1 cursor-pointer items-center gap-2 rounded py-1 pl-1 transition-colors hover:bg-gray-100" :class="currentTable?.name == table.name ? 'bg-gray-100' : ''" @click="toggleTable(table)" > <FeatherIcon :name="currentTable?.name == table.name ? 'minus' : 'plus'" class="h-4 w-4" /> <div class="flex items-center gap-2"> <FeatherIcon name="folder" class="h-4 w-4 text-gray-600" /> <p class="font-medium leading-6 text-gray-900"> {{ table.label }} </p> </div> </div> <div v-if="currentTable?.name == table.name" class="mt-1 ml-4 mb-1 flex items-center justify-center" > <LoadingIndicator v-if="fetchingColumns" class="w-6 text-gray-600" /> <div v-else class="w-full space-y-2"> <div v-for="column in currentColumns" :key="column.column"> <div class="flex items-center space-x-2 pl-2"> <FeatherIcon name="type" class="h-4 w-4 text-gray-600" /> <p class="font-medium leading-6 text-gray-900"> {{ column.label }} </p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src/query/SchemaExplorerDialog.vue
Vue
agpl-3.0
4,776
<script setup> import Code from '@/components/Controls/Code.vue' import { useStorage } from '@vueuse/core' import { Braces, Bug } from 'lucide-vue-next' import { computed, inject, ref, watch } from 'vue' import VariablesDialog from './VariablesDialog.vue' import ResultSection from './ResultSection.vue' const query = inject('query') const script = ref(query.doc.script) watch( () => query.doc.script, (value) => (script.value = value) ) const executing = ref(false) async function onExecuteQuery() { if (executing.value) return executing.value = true try { await query.updateScript(script.value) await query.execute() } finally { executing.value = false } } const showVariablesDialog = ref(false) function handleSaveVariables(variables) { query.updateScriptVariables(variables) showVariablesDialog.value = false } const showLogs = useStorage(`insights:query-${query.doc.name}-show-logs`, false) const scriptLogs = computed(() => query.doc.script_log?.split('\n')?.slice(1)) const showHelp = ref(false) const exampleCode = `def fetch_data_from_url(): # URL of the CSV file csv_url = "https://example.com/data.csv" try: # Read data from the CSV file into a Pandas DataFrame df = pandas.read_csv(csv_url) # use the log function to log messages to the script log log(df) # return the DataFrame return df except Exception as e: log("An error occurred:", str(e)) return None # Call the function to execute the script and # then convert the data into a Pandas DataFrame or a List of lists with first row as column names results = fetch_data_from_url()` </script> <template> <div class="flex h-full w-full flex-col pt-2"> <div class="flex-shrink-0 uppercase leading-7 tracking-wide text-gray-600"> Script Query </div> <div class="flex flex-1 flex-shrink-0 overflow-hidden rounded border"> <div class="relative flex flex-1 flex-col overflow-y-auto"> <Code language="python" v-model="script" placeholder="Enter your script here..."> </Code> <div class="sticky bottom-0 flex justify-between border-t bg-white p-2"> <div class="flex gap-2"> <Button variant="outline" icon="help-circle" @click="showHelp = true" /> <Button variant="outline" @click="showVariablesDialog = !showVariablesDialog" > <template #icon> <Braces class="h-4 w-4" /> </template> </Button> <Button variant="outline" @click="showLogs = !showLogs"> <template #icon> <Bug class="h-4 w-4" /> </template> </Button> <Button variant="solid" icon="play" @click="onExecuteQuery" :loading="executing" > </Button> </div> </div> </div> <transition tag="div" name="slide" enter-active-class="transition ease-out duration-200" enter-from-class="transform translate-x-full opacity-0" enter-to-class="transform translate-x-0 opacity-100" leave-active-class="transition ease-in duration-200" leave-from-class="transform translate-x-0" leave-to-class="transform translate-x-full" > <div v-if="showLogs" class="flex h-full w-[30rem] flex-col overflow-hidden bg-gray-50 p-3" > <div class="text-sm uppercase tracking-wide text-gray-600">Logs</div> <div class="mt-2 flex w-full flex-col gap-2 overflow-y-auto font-mono"> <div v-for="(log, index) in scriptLogs" :key="index" class="flex gap-2"> <div class="text-gray-400">[{{ index + 1 }}]</div> <div class="text-gray-500">{{ log }}</div> </div> </div> </div> </transition> </div> <div class="flex w-full flex-1 flex-shrink-0 overflow-hidden py-4"> <ResultSection></ResultSection> </div> </div> <VariablesDialog v-model:show="showVariablesDialog" v-model:variables="query.doc.variables" @save="handleSaveVariables" /> <Dialog v-model="showHelp" :options="{ title: 'Help', size: '3xl', }" > <template #body-content> <div class="flex w-full flex-col gap-2 text-base leading-5"> <div class=""> In the Script Query interface, you can write custom Python scripts to query the database and retrieve data as a Pandas DataFrame. You can also fetch data from external sources using Pandas functions </div> <div> For detailed information about these functions and how to use them, please refer to <a class="text-blue-500 underline" href="https://frappeframework.com/docs/user/en/desk/scripting/script-api" > Frappe Framework's Script API </a> </div> <div class=""> Example script to read data from a CSV file hosted on a URL and create a Pandas DataFrame: </div> <div class="rounded bg-gray-50 text-sm"> <Code :readOnly="true" language="python" :model-value="exampleCode"> </Code> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src/query/ScriptQueryEditor.vue
Vue
agpl-3.0
4,905
<script setup> import { computed } from 'vue' const emit = defineEmits(['update:show', 'update:variables', 'save']) const props = defineProps({ show: Boolean, variables: Array }) const show = computed({ get: () => props.show, set: (value) => emit('update:show', value), }) const variables = computed({ get: () => props.variables, set: (value) => emit('update:variables', value), }) </script> <template> <Dialog v-model="show" :options="{ title: 'Variables' }"> <template #body-content> <p class="-mt-4 mb-5 text-base text-gray-600"> Variables are used to store sensitive information such as API keys and credentials. They can be referenced in your script just like any other variable. For eg.: <code class="text-sm text-gray-800">print(api_key)</code> </p> <div class="flex flex-col overflow-hidden"> <div class="relative flex max-h-[10rem] flex-col overflow-y-auto"> <div class="sticky top-0 flex gap-x-2 border-b py-2 text-sm uppercase text-gray-600" > <div class="flex flex-1 flex-shrink-0 px-2">Name</div> <div class="flex flex-1 flex-shrink-0 px-2">Value</div> <div class="flex w-10"></div> </div> <div class="flex gap-x-2" v-for="(variable, index) in variables" :key="index"> <div class="flex flex-1 flex-shrink-0"> <input class="w-full rounded-sm border-none bg-transparent px-2 py-2 text-base focus:bg-gray-100 focus:outline-none focus:ring-0" type="text" v-model="variable.variable_name" placeholder="eg. api_key" /> </div> <div class="flex flex-1 flex-shrink-0"> <input type="password" class="w-full rounded-sm border-none bg-transparent px-2 py-2 text-base focus:bg-gray-100 focus:outline-none focus:ring-0" v-model="variable.variable_value" placeholder="**********************" /> </div> <div class="flex w-10 justify-end"> <Button variant="ghost" icon="x" @click="variables.splice(index, 1)" /> </div> </div> <div v-if="variables?.length === 0" class="flex justify-center py-4"> <span class="text-sm text-gray-400">No variables</span> </div> </div> <div class="mt-4 flex justify-between"> <Button variant="subtle" @click=" variables.push({ variable_name: '', variable_type: 'text', variable_value: '', }) " > <span class="text-sm">Add Variable</span> </Button> <Button variant="solid" label="Save" @click="$emit('save', variables)" /> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src/query/VariablesDialog.vue
Vue
agpl-3.0
2,632
<template> <div v-if="query.doc?.name" class="flex h-full w-full flex-col pt-4"> <div class="flex flex-1 flex-shrink-0 gap-4 overflow-y-scroll"> <TablePanel /> <ColumnPanel /> <FilterPanel /> </div> <div class="flex w-full flex-1 flex-shrink-0 overflow-hidden rounded py-4"> <ResultSection> <template #footer> <LimitsAndOrder /> </template> </ResultSection> </div> </div> </template> <script setup> import ResultSection from '@/query/ResultSection.vue' import { updateDocumentTitle } from '@/utils' import { computed, inject } from 'vue' import ColumnPanel from './Column/ColumnPanel.vue' import FilterPanel from './Filter/FilterPanel.vue' import LimitsAndOrder from './LimitsAndOrder.vue' import TablePanel from './Table/TablePanel.vue' const query = inject('query') const pageMeta = computed(() => ({ title: query.doc?.title, subtitle: query.doc?.name, })) updateDocumentTitle(pageMeta) </script>
2302_79757062/insights
frontend/src/query/deprecated/ClassicQueryBuilder.vue
Vue
agpl-3.0
933
<template> <div class="flex w-full flex-shrink-0 items-center bg-white pb-2"> <Button icon="chevron-left" class="mr-2" @click="$emit('close')"> </Button> <div class="text-sm uppercase tracking-wide text-gray-700">Edit Column</div> </div> <div class="flex flex-1 flex-col overflow-y-scroll"> <ColumnExpressionPicker v-if="props.column.is_expression" :column="props.column" @close="$emit('close')" /> <SimpleColumnPicker v-else :column="props.column" @close="$emit('close')" /> </div> </template> <script setup> import SimpleColumnPicker from './SimpleColumnPicker.vue' import ColumnExpressionPicker from './ColumnExpressionPicker.vue' const emit = defineEmits(['close']) const props = defineProps({ column: { type: Object, default: {}, required: true, }, }) </script>
2302_79757062/insights
frontend/src/query/deprecated/Column/ColumnEditor.vue
Vue
agpl-3.0
800
<template> <div class="relative flex flex-col"> <!-- Expression Code Field --> <div class="flex justify-between"> <div class="mb-1 text-sm">Expression</div> <Tooltip v-if="expression.error" :text="expression.error"> <div class="!mt-1 flex cursor-pointer items-center text-xs text-red-500"> <FeatherIcon name="alert-circle" class="h-4 w-4" /> </div> </Tooltip> </div> <Popover class="h-36 w-full text-sm" placement="left-start"> <template #target="{ open }"> <div class="relative h-full w-full rounded border p-1"> <Code v-model="input.value" :completions="getCompletions" @inputChange="open" @viewUpdate="codeViewUpdate" ></Code> <div class="absolute bottom-1 left-1"> <ExpressionHelpDialog /> </div> </div> </template> <template #body> <div class="w-full pr-3 text-base"> <transition enter-active-class="transition duration-100 ease-out" enter-from-class="transform scale-95 opacity-0" enter-to-class="transform scale-100 opacity-100" leave-active-class="transition duration-75 ease-in" leave-from-class="transform opacity-100" leave-to-class="transform opacity-0" > <ExpressionHelp v-show="expression.help" :info="expression.help" /> </transition> </div> </template> </Popover> <!-- Label Field --> <div class="mt-2 text-sm text-gray-700"> <div class="mb-1">Label</div> <Input type="text" v-model="expression.label" class="placeholder:text-sm" placeholder="Enter a label..." /> </div> <!-- Type Field --> <div class="mt-2 text-sm text-gray-700"> <div class="mb-1">Type</div> <Input type="select" v-model="expression.valueType" class="placeholder:text-sm" placeholder="Select a type..." :options="columnTypes" /> </div> <div v-if="showDateFormatOptions" class="mt-2 text-sm text-gray-700"> <div class="mb-1">Date Format</div> <Autocomplete v-model="expression.dateFormat" :options="dateFormats" placeholder="Select a date format..." /> </div> <div class="mt-2 space-y-1 text-sm text-gray-700"> <div class="">Sort</div> <Input type="select" v-model="expression.order_by" :options="[ { label: '', value: '', }, { label: 'Ascending', value: 'asc', }, { label: 'Descending', value: 'desc', }, ]" class="placeholder:text-sm" placeholder="Enter a label..." /> </div> <div class="mt-4 text-sm text-gray-700"> <Input v-if="expression.valueType == 'String'" type="checkbox" label="Group By" v-model="expression.groupBy" /> </div> <!-- Action Buttons --> <div class="sticky bottom-0 mt-3 flex justify-end space-x-2 bg-white pt-1"> <Button v-if="editing" class="text-red-500" variant="outline" @click="removeExpressionColumn" > Remove </Button> <Button variant="solid" @click="addOrEditColumn" :disabled="addDisabled"> {{ editing ? 'Update' : 'Add ' }} </Button> </div> </div> </template> <script setup> import Code from '@/components/Controls/Code.vue' import ExpressionHelpDialog from '@/query/ExpressionHelpDialog.vue' import Tooltip from '@/components/Tooltip.vue' import { debounce } from 'frappe-ui' import ExpressionHelp from '@/components/ExpressionHelp.vue' import { dateFormats } from '@/utils/format' import { FUNCTIONS } from '@/utils/query' import { parse } from '@/utils/expressions' import { ref, inject, watchEffect, reactive, computed } from 'vue' const query = inject('query') const emit = defineEmits(['close']) const props = defineProps({ column: { type: Object, default: {}, validate: (value) => { if (value.is_expression != 1) { return 'Column must be an expression' } }, }, }) const column = { ...props.column, expression: props.column.expression || {}, } const editing = ref(Boolean(column.name)) const input = reactive({ value: column.expression.raw || '', caretPosition: column.expression.raw?.length || 0, }) const columnTypes = ['String', 'Integer', 'Decimal', 'Text', 'Datetime', 'Date', 'Time'] // parse the expression when input changes const expression = reactive({ raw: input.value, label: column.label, order_by: column.order_by, groupBy: column.aggregation == 'Group By', valueType: column.type || 'String', ast: null, error: null, tokens: [], help: null, dateFormat: ['Date', 'Datetime'].includes(props.column.type) ? dateFormats.find((format) => format.value === props.column.format_option?.date_format) : {}, }) watchEffect(() => { expression.raw = input.value const { ast, tokens, errorMessage } = parse(input.value) expression.ast = ast expression.tokens = tokens expression.error = errorMessage }) const showDateFormatOptions = computed(() => ['Date', 'Datetime'].includes(expression.valueType)) watchEffect(() => { if (showDateFormatOptions.value || expression.valueType !== 'String') { // Currently group by date field is not supported on expressions due to. // pymysql.err.OperationalError: (1056, "Can't group on '{AGGREGATE} of {DATE_FIELD}'") expression.groupBy = false } }) const codeViewUpdate = debounce(function ({ cursorPos }) { expression.help = null const { tokens } = expression const token = tokens .filter((t) => t.start <= cursorPos - 1 && t.end >= cursorPos && t.type == 'FUNCTION') .at(-1) if (token) { const { value } = token if (FUNCTIONS[value]) { expression.help = FUNCTIONS[value] } } }, 300) const getCompletions = (context, syntaxTree) => { let word = context.matchBefore(/\w*/) let nodeBefore = syntaxTree.resolveInner(context.pos, -1) if (nodeBefore.name === 'TemplateString') { return { from: word.from, options: query.columns.options.map((c) => { return { label: `${c.table}.${c.column}` } }), } } if (nodeBefore.name === 'VariableName') { return { from: word.from, options: Object.keys(FUNCTIONS).map((label) => ({ label })), } } } const addDisabled = computed(() => { return Boolean( expression.error || !expression.raw || !expression.label || !expression.valueType ) }) const addOrEditColumn = () => { const newColumn = { name: props.column.name, is_expression: 1, expression: { raw: expression.raw, ast: expression.ast, }, type: expression.valueType, label: expression.label, order_by: expression.order_by, column: expression.label.replace(/\s/g, '_'), aggregation: expression.groupBy ? 'Group By' : '', } if (showDateFormatOptions.value) { newColumn.format_option = { date_format: expression.dateFormat.value, } } if (props.column.name) { query.updateColumn.submit({ column: newColumn }) } else { query.addColumn.submit({ column: newColumn }) } emit('close') } const removeExpressionColumn = () => { query.removeColumn.submit({ column: props.column }) emit('close') } </script>
2302_79757062/insights
frontend/src/query/deprecated/Column/ColumnExpressionPicker.vue
Vue
agpl-3.0
6,945
<template> <div v-if="columns.length == 0" class="flex h-full w-full items-center justify-center rounded border-2 border-dashed border-gray-200 text-sm text-gray-500" > <p>No columns selected</p> </div> <div v-else-if="columns.length > 0" class="flex h-full w-full flex-col overflow-y-scroll"> <Draggable class="w-full" v-model="columns" group="columns" item-key="name" handle=".handle" @sort="updateColumnOrder" > <template #item="{ element: column }"> <div class="flex h-10 w-full cursor-pointer items-center border-b text-sm last:border-0 hover:bg-gray-50" @click.prevent.stop=" () => { $emit('edit-column', column) newColumnType = column.aggregation == 'Group By' ? 'Dimension' : 'Metric' } " > <DragHandleIcon class="handle -ml-1 mr-1 h-4 w-4 rotate-90 cursor-grab self-center text-gray-500" /> <span class="overflow-hidden text-ellipsis whitespace-nowrap text-base font-medium" > {{ column.label }} </span> <span class="ml-auto mr-1 overflow-hidden text-ellipsis whitespace-nowrap text-gray-700" > {{ column.is_expression ? 'Expression' : ellipsis(column.table_label, 12) }} </span> <div class="flex items-center px-1 py-0.5 text-gray-700 hover:text-gray-700" @click.prevent.stop="query.removeColumn.submit({ column })" > <FeatherIcon name="x" class="h-3 w-3" /> </div> </div> </template> </Draggable> </div> </template> <script setup> import Draggable from 'vuedraggable' import DragHandleIcon from '@/components/Icons/DragHandleIcon.vue' import { inject, unref, ref, watch } from 'vue' import { ellipsis } from '@/utils' const query = inject('query') defineEmits(['edit-column']) const columns = ref(unref(query.columns.data)) watch( () => query.columns.data, (newColumns) => { columns.value = newColumns } ) function updateColumnOrder(e) { if (e.oldIndex != e.newIndex) { query.moveColumn.submit({ from_index: e.oldIndex, to_index: e.newIndex, }) } } </script>
2302_79757062/insights
frontend/src/query/deprecated/Column/ColumnList.vue
Vue
agpl-3.0
2,097
<template> <div class="flex flex-1 flex-shrink-0 flex-col overflow-hidden text-gray-900"> <template v-if="!addingColumn && !editingColumn"> <div class="flex w-full flex-shrink-0 items-center justify-between bg-white pb-2"> <div class="text-sm tracking-wide text-gray-700">COLUMNS</div> <Button icon="plus" @click="addingColumn = true"></Button> </div> <div class="w-full flex-1 overflow-hidden"> <ColumnList @edit-column="(column) => ([editColumn, editingColumn] = [column, true])" ></ColumnList> </div> </template> <ColumnPicker v-if="addingColumn" @close="addingColumn = false" /> <ColumnEditor v-if="editingColumn" @close="editingColumn = false" :column="editColumn" /> </div> </template> <script setup> import ColumnEditor from './ColumnEditor.vue' import ColumnList from './ColumnList.vue' import ColumnPicker from './ColumnPicker.vue' import { ref } from 'vue' const addingColumn = ref(false) const editColumn = ref({}) const editingColumn = ref(false) </script>
2302_79757062/insights
frontend/src/query/deprecated/Column/ColumnPanel.vue
Vue
agpl-3.0
1,015
<template> <div class="flex w-full flex-shrink-0 items-center bg-white pb-2"> <Button icon="chevron-left" class="mr-2" @click="$emit('close')"> </Button> <div class="text-sm uppercase tracking-wide text-gray-700">Add Column</div> </div> <div class="flex flex-1 flex-col space-y-3 overflow-y-scroll"> <div class="flex h-9 flex-shrink-0 cursor-pointer items-center space-x-2 rounded bg-gray-100 p-1 text-sm" > <div v-for="tab in ['Simple', 'Expression']" class="flex h-full flex-1 items-center justify-center rounded" :class="{ ' bg-white font-normal shadow': newColumnType == tab, }" @click.prevent.stop="newColumnType = tab" > {{ tab }} </div> </div> <SimpleColumnPicker v-if="newColumnType == 'Simple'" @close="$emit('close')" /> <ColumnExpressionPicker v-if="newColumnType == 'Expression'" @close="$emit('close')" /> </div> </template> <script setup> import SimpleColumnPicker from './SimpleColumnPicker.vue' import ColumnExpressionPicker from './ColumnExpressionPicker.vue' import { ref } from 'vue' defineEmits(['close']) const newColumnType = ref('Simple') </script>
2302_79757062/insights
frontend/src/query/deprecated/Column/ColumnPicker.vue
Vue
agpl-3.0
1,133
<template> <div class="relative flex flex-col space-y-3"> <div class="space-y-1 text-sm"> <div class="text-gray-700">Aggregation Type</div> <Autocomplete v-model="simpleColumn.aggType" :options="aggregations" placeholder="Select aggregation type" @update:modelValue="onTypeSelect" /> </div> <div v-if="columnNeeded" class="space-y-1 text-sm"> <div class="text-gray-700">Column</div> <Autocomplete v-model="simpleColumn.column" :options="filteredColumns" placeholder="Select a column..." :emptyText="requiresNumberColumn ? 'No number columns' : 'No columns'" @update:modelValue="onColumnSelect" /> </div> <div class="space-y-1 text-sm"> <div class="text-gray-700">Label</div> <Input type="text" v-model="simpleColumn.label" class="placeholder:text-sm" placeholder="Enter a label..." /> </div> <div v-if="showDateFormatOptions" class="space-y-1 text-sm"> <div class="text-gray-700">Date Format</div> <Autocomplete v-model="simpleColumn.dateFormat" :options="dateFormats.map((f) => ({ ...f, description: f.value }))" placeholder="Select a date format..." @update:modelValue="selectDateFormat" /> </div> <div class="space-y-1 text-sm"> <div class="text-gray-700">Sort</div> <Input type="select" v-model="simpleColumn.order_by" :options="[ { label: '', value: '', }, { label: 'Ascending', value: 'asc', }, { label: 'Descending', value: 'desc', }, ]" class="placeholder:text-sm" placeholder="Enter a label..." /> </div> <div class="sticky bottom-0 mt-3 flex justify-end space-x-2 bg-white pt-1"> <Button v-if="props.column.name" class="text-red-500" variant="outline" @click="removeMetric" > Remove </Button> <Button @click="addOrEditColumn" variant="solid" :disabled="applyDisabled"> {{ props.column.name ? 'Update' : 'Add ' }} </Button> </div> </div> </template> <script setup> import { FIELDTYPES, isEmptyObj } from '@/utils' import { dateFormats } from '@/utils/format' import { computed, inject, reactive, ref } from 'vue' const query = inject('query') const emit = defineEmits(['column-select', 'close']) const props = defineProps({ column: { type: Object, default: {}, }, }) const aggregations = ref([ { label: 'No Aggregation', value: '', }, { label: 'Group by', value: 'Group By', }, { label: 'Count of Records', value: 'Count', }, { label: 'Sum of', value: 'Sum', }, { label: 'Avg of', value: 'Avg', }, { label: 'Min of', value: 'Min', }, { label: 'Max of', value: 'Max', }, { label: 'Cumulative Count of Records', value: 'Cumulative Count', }, { label: 'Cumulative Sum of', value: 'Cumulative Sum', }, ]) const simpleColumn = reactive({ // since props.column comes from doc.columns, it doesn't have value property // value is needed to show the selected column in the autocomplete column: { ...props.column, value: props.column.column }, label: props.column.label, order_by: props.column.order_by, aggType: aggregations.value.find((t) => { return t.value == props.column.aggregation }), dateFormat: dateFormats.find((t) => { return t.value == props.column.format_option?.date_format }) || {}, }) if (!simpleColumn.aggType) simpleColumn.aggType = { label: 'No Aggregation', value: '' } const columnNeeded = computed(() => { return simpleColumn.aggType.label && !simpleColumn.aggType.label?.includes('Count') }) const applyDisabled = computed(() => { return ( !simpleColumn.label || (columnNeeded.value && isEmptyObj(simpleColumn.column)) || (showDateFormatOptions.value && isEmptyObj(simpleColumn.dateFormat)) ) }) const columnOptions = query.columns.options const requiresNumberColumn = computed( () => simpleColumn.aggType.value === 'Sum' || simpleColumn.aggType.value === 'Avg' || simpleColumn.aggType.value === 'Min' || simpleColumn.aggType.value === 'Max' || simpleColumn.aggType.value === 'Cumulative Sum' ) const filteredColumns = computed(() => requiresNumberColumn.value ? columnOptions?.filter((c) => FIELDTYPES.NUMBER.includes(c.type)) : columnOptions ) const showDateFormatOptions = computed(() => ['Date', 'Datetime'].includes(simpleColumn.column.type) ) function selectDateFormat(option) { simpleColumn.column.format_option = { date_format: typeof option === 'string' ? option : option.value, } } function onTypeSelect(option) { simpleColumn.aggType = option ? option : {} simpleColumn.label = simpleColumn.aggType.label } function onColumnSelect(option) { simpleColumn.column = option ? option : {} simpleColumn.column.name = props.column.name if (simpleColumn.aggType.value) { simpleColumn.label = simpleColumn.aggType.label + ' ' + simpleColumn.column.label } else { simpleColumn.label = simpleColumn.column.label } } function addOrEditColumn() { if (applyDisabled.value) return const editing = props.column?.name const column = { ...simpleColumn.column, aggregation: simpleColumn.aggType.value, label: simpleColumn.label, order_by: simpleColumn.order_by, format_option: showDateFormatOptions.value ? simpleColumn.column.format_option : null, } if (!columnNeeded.value) { column.column = 'count' column.type = 'Integer' column.table = query.tables.data[0].table column.table_label = query.tables.data[0].table_label } if (editing) { query.updateColumn.submit({ column }) } else { query.addColumn.submit({ column }) } emit('close') } function removeMetric() { query.removeColumn.submit({ column: simpleColumn.column }) emit('close') } </script>
2302_79757062/insights
frontend/src/query/deprecated/Column/SimpleColumnPicker.vue
Vue
agpl-3.0
5,702
<template> <div class="inline-flex w-full flex-wrap items-baseline"> <ExpressionTerm :term="props.expression.left" /> <span class="w-2"></span> <p class="whitespace-nowrap text-sm font-medium text-green-600"> {{ props.expression.operator }} </p> <span class="w-2"></span> <ExpressionTerm :term="props.expression.right" /> </div> </template> <script setup> import ExpressionTerm from './ExpressionTerm.vue' const props = defineProps({ expression: { type: Object, required: true, }, }) </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/BinaryExpression.vue
Vue
agpl-3.0
519
<template> <div class="inline-flex w-full flex-wrap"> <div class="whitespace-nowrap font-mono font-medium text-purple-700"> {{ props.expression.function }} </div> <div class="font-mono text-purple-700">(</div> <div v-for="(arg, idx) in props.expression.arguments" class="flex items-center"> <ExpressionTerm :term="arg" /> <div v-if="idx < props.expression.arguments.length - 1">,&nbsp;</div> </div> <div class="font-mono text-purple-700">)</div> </div> </template> <script setup> import ExpressionTerm from './ExpressionTerm.vue' const props = defineProps({ expression: { type: Object, required: true, }, }) </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/CallExpression.vue
Vue
agpl-3.0
649
<template> <div class="group relative flex w-full max-w-fit cursor-pointer items-center rounded border p-2 pr-6 hover:border-gray-300" @click.prevent.stop="$emit('edit')" > <BinaryExpression v-if="expression.type == 'BinaryExpression'" :expression="expression" /> <CallExpression v-else-if="expression.type == 'CallExpression'" :expression="expression" /> <FeatherIcon name="x" class="absolute right-1.5 h-3 w-3 self-center text-gray-600 hover:text-gray-700" @click.prevent.stop="$emit('remove')" /> </div> </template> <script setup> import BinaryExpression from './BinaryExpression.vue' import CallExpression from './CallExpression.vue' import { inject, reactive, unref } from 'vue' defineEmits(['edit', 'remove']) const props = defineProps({ expression: { type: Object, required: true, validate: (value) => value.type === 'BinaryExpression' || value.type === 'CallExpression', }, }) let expression = reactive(unref(props.expression)) const isStringOrNumber = (arg) => arg.type == 'String' || arg.type == 'Number' const isSimpleFilter = (expression.type == 'BinaryExpression' && expression.left.type == 'Column' && isStringOrNumber(expression.right)) || (expression.type == 'CallExpression' && expression.arguments[0].type == 'Column' && expression.arguments.slice(1).every(isStringOrNumber)) const query = inject('query') if (isSimpleFilter) { const simpleFilter = query.filters.convertIntoSimpleFilter(expression) if (simpleFilter) { expression = reactive({ type: 'BinaryExpression', left: { type: 'Column', value: { table: simpleFilter.column?.table_label, column: simpleFilter.column?.label, }, }, operator: simpleFilter.operator.label, // TODO: store proper label right: { type: 'String', value: simpleFilter.value.label, }, }) } } </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/Expression.vue
Vue
agpl-3.0
1,850
<template> <BinaryExpression v-if="type == 'BinaryExpression'" :expression="props.term" /> <CallExpression v-else-if="type == 'CallExpression'" :expression="props.term" /> <!-- Column --> <p class="w-fit" v-else-if="type == 'Column'"> <Tooltip :text="value.table"> <span>{{ value.column }}</span> </Tooltip> </p> <!-- Number or String --> <p class="w-fit" v-else-if="type == 'String'">{{ value }}</p> <p class="w-fit" v-else-if="type == 'Number'"> {{ value }} </p> </template> <script setup> import BinaryExpression from './BinaryExpression.vue' import CallExpression from './CallExpression.vue' const props = defineProps({ term: { type: Object, required: true, }, }) const type = props.term.type const value = props.term.value </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/ExpressionTerm.vue
Vue
agpl-3.0
764
<template> <div class="flex flex-col"> <!-- Expression Code Field --> <div class="flex justify-between"> <div class="mb-1 text-sm">Expression</div> <Tooltip v-if="expression.error" :text="expression.error"> <div class="!mt-1 flex cursor-pointer items-center text-xs text-red-500"> <FeatherIcon name="alert-circle" class="h-4 w-4" /> </div> </Tooltip> </div> <Popover class="h-36 w-full text-sm" placement="left-start"> <template #target="{ open }"> <div class="relative h-full w-full rounded border p-1"> <Code v-model="input" :completions="getCompletions" @inputChange="open" @viewUpdate="codeViewUpdate" ></Code> <div class="absolute bottom-1 left-1"> <ExpressionHelpDialog /> </div> </div> </template> <template #body> <div class="w-full pr-3 text-base"> <transition enter-active-class="transition duration-100 ease-out" enter-from-class="transform scale-95 opacity-0" enter-to-class="transform scale-100 opacity-100" leave-active-class="transition duration-75 ease-in" leave-from-class="transform scale-100 opacity-100" leave-to-class="transform scale-95 opacity-0" > <ExpressionHelp v-show="expression.help" :info="expression.help" /> </transition> </div> </template> </Popover> <!-- Action Buttons --> <div class="mt-3 flex justify-end space-x-2"> <Button variant="solid" @click="addExpressionFilter" :disabled="Boolean(expression.error)" > {{ editing ? 'Update' : 'Add ' }} </Button> </div> </div> </template> <script setup> import Code from '@/components/Controls/Code.vue' import ExpressionHelp from '@/components/ExpressionHelp.vue' import Tooltip from '@/components/Tooltip.vue' import { parse } from '@/utils/expressions' import { FUNCTIONS } from '@/utils/query' import { debounce } from 'frappe-ui' import { computed, inject, reactive, ref, watchEffect } from 'vue' import ExpressionHelpDialog from '@/query/ExpressionHelpDialog.vue' const query = inject('query') const emit = defineEmits(['filter-select', 'close']) const props = defineProps({ filter: { type: Object, default: {}, }, }) const editing = computed(() => query.filters.editFilterAt.idx !== -1) const input = ref(props.filter?.raw || '') // parse the expression when input changes const expression = reactive({ raw: input.value, ast: null, error: null, tokens: [], help: null, }) watchEffect(() => { expression.raw = input.value const { ast, tokens, errorMessage } = parse(expression.raw) expression.ast = ast expression.tokens = tokens expression.error = errorMessage }) const getCompletions = (context, syntaxTree) => { let word = context.matchBefore(/\w*/) let nodeBefore = syntaxTree.resolveInner(context.pos, -1) if (nodeBefore.name === 'TemplateString') { return { from: word.from, options: query.columns.options.map((c) => { return { label: `${c.table}.${c.column}` } }), } } if (nodeBefore.name === 'VariableName') { return { from: word.from, options: Object.keys(FUNCTIONS).map((label) => ({ label })), } } } const codeViewUpdate = debounce(function ({ cursorPos }) { expression.help = null const { tokens } = expression const token = tokens .filter((t) => t.start <= cursorPos - 1 && t.end >= cursorPos && t.type == 'FUNCTION') .at(-1) if (token) { const { value } = token if (FUNCTIONS[value]) { expression.help = FUNCTIONS[value] } } }, 300) const addExpressionFilter = () => { emit('filter-select', { ...expression.ast, raw: expression.raw, is_expression: true, }) } </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/FilterExpressionPicker.vue
Vue
agpl-3.0
3,652
<template> <div class="flex flex-1 flex-shrink-0 flex-col overflow-hidden"> <div v-if="!pickingFilter" class="flex w-full flex-shrink-0 items-center justify-between bg-white pb-2" > <div class="text-sm tracking-wide text-gray-700">FILTERS</div> <Button icon="plus" @click="pickingFilter = true"></Button> </div> <div v-if="!pickingFilter && (!filters.conditions || filters.conditions.length == 0)" class="flex h-full w-full items-center justify-center rounded border-2 border-dashed border-gray-200 text-sm text-gray-600" > <p>No filters added</p> </div> <div v-else-if="!pickingFilter && filters.conditions?.length > 0" class="h-full w-full overflow-scroll" > <LogicalExpression :key="JSON.stringify(filters)" :expression="filters" @add-filter="showFilterPicker" @edit-filter="showFilterPicker" @remove-filter="removeFilter" @toggle-operator="toggleOperator" /> </div> <FilterPicker v-else-if="pickingFilter" @close="pickingFilter = false" @filter-select="onFilterSelect" :filter="editFilter" /> </div> </template> <script setup> import LogicalExpression from './LogicalExpression.vue' import FilterPicker from './FilterPicker.vue' import { ref, inject, computed } from 'vue' const pickingFilter = ref(false) const query = inject('query') const filters = computed(() => query.filters.data || {}) const editFilter = ref(null) const showFilterPicker = ({ condition, level, position, idx }) => { pickingFilter.value = true if (condition) { editFilter.value = condition query.filters.editFilterAt.level = level query.filters.editFilterAt.position = position query.filters.editFilterAt.idx = idx } else { editFilter.value = null query.filters.addNextFilterAt.level = level query.filters.addNextFilterAt.position = position } } function onFilterSelect(filter) { if (editFilter.value) { query.filters.edit(filter) } else { query.filters.add(filter) } editFilter.value = null pickingFilter.value = false } function removeFilter({ level, position, idx }) { query.filters.remove(level, position, idx) } function toggleOperator({ level, position }) { query.filters.toggleOperator(level, position) } </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/FilterPanel.vue
Vue
agpl-3.0
2,228
<template> <div class="flex w-full flex-shrink-0 items-center bg-white pb-2"> <Button icon="chevron-left" class="mr-2" @click="$emit('close')"> </Button> <div class="text-sm tracking-wide text-gray-700">{{ editing ? 'EDIT' : 'ADD' }} FILTER</div> </div> <div class="flex flex-1 flex-col space-y-3 overflow-y-scroll"> <div class="flex h-9 flex-shrink-0 items-center space-x-2 rounded bg-gray-100 p-1 text-sm"> <div class="flex h-full flex-1 items-center justify-center rounded" :class="{ 'bg-white font-normal shadow': filterType == 'simple', }" @click.prevent.stop="filterType = 'simple'" > Simple </div> <div class="flex h-full flex-1 items-center justify-center rounded" :class="{ ' bg-white font-normal shadow': filterType == 'expression', }" @click.prevent.stop="filterType = 'expression'" > Expression </div> </div> <SimpleFilterPicker v-if="filterType == 'simple'" :filter="props.filter" @filter-select="(args) => $emit('filter-select', args)" /> <FilterExpressionPicker v-if="filterType == 'expression'" :filter="props.filter" @filter-select="(args) => $emit('filter-select', args)" /> </div> </template> <script setup> import FilterExpressionPicker from './FilterExpressionPicker.vue' import SimpleFilterPicker from './SimpleFilterPicker.vue' import { ref } from 'vue' const props = defineProps(['filter']) defineEmits(['filter-select', 'close']) const editing = ref(Boolean(props.filter)) const filterType = ref(props.filter?.is_expression ? 'expression' : 'simple') </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/FilterPicker.vue
Vue
agpl-3.0
1,595
<template> <div class="relative flex w-full"> <div class="z-[5] flex w-full items-center"> <div ref="operatorRef" class="z-[5] mr-2 flex h-6 w-6 flex-shrink-0 cursor-pointer items-center justify-center rounded-full border border-gray-300 bg-white hover:border-blue-300 hover:font-normal hover:text-blue-500" @click.prevent.stop="$emit('toggle-operator', { level, position })" > {{ operator == '&&' ? '&' : 'or' }} </div> <div class="flex flex-1 flex-col space-y-2"> <div :key="idx" ref="conditionRefs" v-for="(condition, idx) in conditions"> <LogicalExpression v-if="condition.type == 'LogicalExpression'" :expression="condition" @add-filter="$emit('add-filter', $event)" @edit-filter="$emit('edit-filter', $event)" @remove-filter="$emit('remove-filter', $event)" @toggle-operator="$emit('toggle-operator', $event)" /> <Expression v-else :expression="condition" @edit=" $emit('edit-filter', { condition, level, position, idx, }) " @remove="$emit('remove-filter', { level, position, idx })" /> </div> <div ref="addConditionRef" class="!-mt-0.5 !-mb-2 flex h-9 cursor-pointer items-center text-sm text-gray-600 hover:text-gray-700" @click.prevent.stop="$emit('add-filter', { level, position })" > + {{ operator == '&&' ? 'and' : 'or' }} condition </div> </div> </div> <div class="absolute top-0 left-0 z-0 h-full w-full"> <svg width="100%" height="100%" class="text-gray-400"> <g ref="connectorsRef" fill="none"></g> </svg> </div> </div> </template> <script setup> import { computed, nextTick, watch, ref, onMounted } from 'vue' import Expression from './Expression.vue' defineEmits(['add-filter', 'edit-filter', 'remove-filter', 'toggle-operator']) const props = defineProps({ expression: { type: Object, required: true, validate: (value) => value.type === 'LogicalExpression', }, }) const level = computed(() => props.expression.level) const position = computed(() => props.expression.position) const operator = computed(() => props.expression.operator) const conditions = computed(() => props.expression.conditions) onMounted(() => { watch( () => props.expression, () => nextTick(() => draw_connectors()), { immediate: true, deep: true, } ) }) const operatorRef = ref(null) const addConditionRef = ref(null) const connectorsRef = ref(null) const conditionRefs = ref([]) function draw_connectors() { if ( !connectorsRef.value || !addConditionRef.value || !operatorRef.value || !conditionRefs.value?.length ) { return } connectorsRef.value.innerHTML = '' conditionRefs.value.forEach((condition) => { add_connector(operatorRef.value, condition) }) add_connector(operatorRef.value, addConditionRef.value, true) } function add_connector(parent_node, child_node, dotted = false) { let path = document.createElementNS('http://www.w3.org/2000/svg', 'path') // we need to connect right side of the parent to the left side of the child node const pos_parent_center = { x: parent_node.offsetLeft + parent_node.offsetWidth / 2, y: parent_node.offsetTop + parent_node.offsetHeight / 2, } const pos_child_left = { x: child_node.offsetLeft, y: child_node.offsetTop + child_node.offsetHeight / 2, } const connector = get_connector(pos_parent_center, pos_child_left) path.setAttribute('d', connector) path.setAttribute('stroke', 'currentColor') if (dotted) { path.setAttribute('stroke-dasharray', '3,3') } connectorsRef.value.appendChild(path) } function get_connector(pos_parent_center, pos_child_left) { if (Math.abs(pos_parent_center.y - pos_child_left.y) < 3) { // don't add arcs if it's a straight line return `M${pos_parent_center.x},${pos_parent_center.y} L${pos_child_left.x},${pos_child_left.y}` } else { let arc_1 = '' let offset = 0 if (pos_parent_center.y > pos_child_left.y) { // if child is above parent on Y axis 1st arc is anticlocwise // second arc is clockwise arc_1 = 'a5,5 0 0 1 5,-5 ' offset = 5 } else { // if child is below parent on Y axis 1st arc is clockwise // second arc is anticlockwise arc_1 = 'a5,5 1 0 0 5,5 ' offset = -5 } return ( `M${pos_parent_center.x},${pos_parent_center.y} ` + `L${pos_parent_center.x},${pos_child_left.y + offset} ` + `${arc_1}` + `L${pos_child_left.x},${pos_child_left.y}` ) } } </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/LogicalExpression.vue
Vue
agpl-3.0
4,488
<template> <div class="flex flex-col space-y-3"> <div class="space-y-1 text-sm text-gray-700"> <div class="">Column</div> <Autocomplete v-model="filter.column" :options="columnOptions" placeholder="Select a column..." /> </div> <div class="space-y-1 text-sm text-gray-700"> <div class="">Operator</div> <Autocomplete v-model="filter.operator" :options="operatorOptions" placeholder="Select operator..." /> </div> <div class="space-y-1 text-sm text-gray-700"> <div class="">Value</div> <Autocomplete v-if="showValueOptions" v-model="filter.value" :options="valueOptions" :placeholder="valuePlaceholder" @update:query="checkAndFetchColumnValues" :loading="query.fetchColumnValues.loading" /> <TimespanPicker v-else-if="showTimespanPicker" id="value" v-model="filter.value" :placeholder="valuePlaceholder" /> <ListPicker v-else-if="showListPicker" :value="filter.value.value" @change=" (event) => { if (!filter.value.value) { filter.value = { value: null, label: null, } } filter.value.value = event } " :options="valueOptions" :placeholder="valuePlaceholder" @inputChange="checkAndFetchColumnValues" :loading="query.fetchColumnValues.loading" /> <DateRangePicker v-else-if="showDatePicker && filter.operator.value === 'between'" id="value" :value="filter.value.value" :placeholder="valuePlaceholder" :formatter="formatDate" @change=" (date) => { filter.value = { value: date, label: formatDate(date), } } " /> <DatePicker v-else-if="showDatePicker" id="value" :value="filter.value.value" :placeholder="valuePlaceholder" :formatter="formatDate" @change=" (date) => { filter.value = { value: date, label: formatDate(date), } } " /> <Input v-else type="text" v-model="filter.value.value" :placeholder="valuePlaceholder" /> </div> <div class="flex justify-end"> <Button @click="apply" variant="solid" :disabled="applyDisabled"> Apply </Button> </div> </div> </template> <script setup> import DatePicker from '@/components/Controls/DatePicker.vue' import DateRangePicker from '@/components/Controls/DateRangePicker.vue' import ListPicker from '@/components/Controls/ListPicker.vue' import TimespanPicker from '@/components/Controls/TimespanPicker.vue' import { formatDate, isEmptyObj } from '@/utils' import { debounce } from 'frappe-ui' import { getOperatorOptions } from '@/utils' import { computed, inject, reactive, watch } from 'vue' const query = inject('query') const props = defineProps({ filter: { type: Object, default: { column: {}, operator: {}, value: {}, }, }, }) const emit = defineEmits(['filter-select']) const initalData = { column: {}, operator: {}, value: {}, } let filter = reactive(initalData) if (props.filter && props.filter.type) { const simpleFilter = query.filters.convertIntoSimpleFilter(props.filter) filter = reactive(simpleFilter) } const columnOptions = query.columns.options const operatorOptions = computed(() => getOperatorOptions(filter.column?.type)) const showDatePicker = computed(() => { return ( ['Date', 'Datetime'].includes(filter.column?.type) && ['=', '!=', '>', '>=', '<', '<=', 'between'].includes(filter.operator?.value) ) }) const showTimespanPicker = computed( () => ['Date', 'Datetime'].includes(filter.column?.type) && filter.operator?.value === 'timespan' ) const showListPicker = computed( () => ['in', 'not_in'].includes(filter.operator?.value) && filter.column?.type == 'String' ) const showValueOptions = computed( () => ['=', '!=', 'is'].includes(filter.operator?.value) && filter.column?.type == 'String' ) const valueOptions = computed(() => { if (filter.operator?.value == 'is') { return [ { label: 'Set', value: 'set' }, { label: 'Not Set', value: 'not set' }, ] } return query.fetchColumnValues.data?.message }) const valuePlaceholder = computed(() => { if (showDatePicker.value) { return 'Select a date...' } if (isEmptyObj(filter.operator)) { return 'Type a value...' } if (filter.operator?.value == 'between') { return 'Type two comma separated values...' } if (filter.operator?.value == 'in' || filter.operator?.value == 'not_in') { return 'Select one or more values...' } return 'Type a value...' }) const applyDisabled = computed(() => isEmptyObj(filter.column, filter.operator, filter.value)) watch( () => filter.column, (newColumn) => { filter.column = newColumn filter.operator = {} filter.value = {} } ) watch( () => filter.operator, (newOperator) => { filter.operator = newOperator filter.value = {} } ) function processListPickerOption(options) { if (!Array.isArray(options)) { return { value: [], label: '', } } return { value: options.map((option) => (option.hasOwnProperty('value') ? option.value : option)), label: options.length > 1 ? options.length + ' values' : options.length > 0 ? options[0].value || options[0] : '', } } function apply() { if (applyDisabled.value) { return } if (showListPicker.value) { filter.value = processListPickerOption(filter.value.value) } else if (showDatePicker.value) { filter.value = { value: filter.value.value, label: formatDate(filter.value.value), } } emit('filter-select', query.filters.convertIntoExpression(filter)) Object.assign(filter, initalData) } const checkAndFetchColumnValues = debounce(function (search_text = '') { if ( isEmptyObj(filter.column) || !['=', '!=', 'in', 'not_in'].includes(filter.operator?.value) ) { return } if (filter.column?.type == 'String') { query.fetchColumnValues.submit({ column: filter.column, search_text, }) } }, 300) watch( () => ({ shouldFetch: showListPicker.value || showValueOptions.value, columnChanged: filter.column?.value, }), ({ shouldFetch, columnChanged }) => { const oldValues = query.fetchColumnValues.data?.message if (columnChanged && oldValues?.length) { query.fetchColumnValues.data.message = [] } shouldFetch && columnChanged && !valueOptions.value?.length && checkAndFetchColumnValues() }, { immediate: true } ) </script>
2302_79757062/insights
frontend/src/query/deprecated/Filter/SimpleFilterPicker.vue
Vue
agpl-3.0
6,364
<template> <div class="flex h-full flex-1 items-center justify-between rounded-b-md px-1 text-base text-gray-600" > <div v-if="queriedRowCount >= 0" class="flex items-center space-x-1 text-gray-900"> <span class="text-gray-600">Showing</span> <span class="font-mono"> {{ displayedRowCount }}</span> <span class="text-gray-600">out of</span> <span class="font-mono">{{ queriedRowCount }}</span> <span class="text-gray-600">rows in</span> <span class="font-mono">{{ executionTime }}</span> <span class="text-gray-600">seconds</span> </div> <div class="ml-auto space-x-1"> <span>Limit to</span> <input type="text" ref="limitInput" v-model.number="limit" :size="String(limit).length" class="form-input border-gray-400 pr-1 placeholder-gray-500" @keydown.enter.stop=" () => { query.setLimit.submit({ limit: parseInt(limit) }) $refs.limitInput.blur() } " @keydown.esc.stop="$refs.limitInput.blur()" /> <span>rows</span> </div> </div> </template> <script setup> import { computed, inject, ref } from 'vue' const query = inject('query') const executionTime = computed(() => query.doc.execution_time) const queriedRowCount = computed(() => query.doc.results_row_count) const displayedRowCount = computed(() => Math.min(query.MAX_ROWS, queriedRowCount.value)) const limit = ref(query.doc.limit) const sortedByColumns = computed(() => { return query.doc.columns .filter((c) => c.order_by) .map((c) => ({ column: c.label, order: c.order_by, })) }) </script>
2302_79757062/insights
frontend/src/query/deprecated/LimitsAndOrder.vue
Vue
agpl-3.0
1,563
<template> <div class="flex w-full flex-col overflow-hidden"> <div class="flex flex-shrink-0 items-center bg-white pb-3 pt-1"> <Button icon="chevron-left" class="mr-2" @click="$emit('close')"> </Button> <div class="text-sm tracking-wide text-gray-700">JOIN</div> </div> <div class="flex flex-1 flex-col space-y-3 overflow-y-scroll"> <div class="flex flex-col space-y-3"> <div class="space-y-1 text-sm"> <div class="text-gray-700">Left Table</div> <LinkIcon :link="getQueryLink(editTable.table)" :show="editTable.label"> <Input v-model="editTable.label" disabled class="cursor-not-allowed" /> </LinkIcon> </div> <div class="space-y-1 text-sm"> <div class="text-gray-700">Join Type</div> <Autocomplete v-model="join.type" :options="joinTypeOptions" placeholder="Select a type..." /> </div> <div class="space-y-1 text-sm"> <div class="text-gray-700">Right Table</div> <LinkIcon :link="getQueryLink(join.with?.value)" :show="join.with?.label"> <Autocomplete v-model="join.with" :options="query.tables.joinOptions" placeholder="Select a table..." /> </LinkIcon> </div> <div class="text-sm"> <div class="flex items-end space-x-1"> <div class="flex-1"> <div class="mb-1 text-gray-700">Left Column</div> <Autocomplete :key="join.condition.left" v-model="join.condition.left" :options="leftColumnOptions" placeholder="Select a Column" /> </div> <span class="flex items-center px-1 text-lg"> = </span> <div class="flex-1"> <div class="mb-1 text-gray-700">Right Column</div> <Autocomplete :key="join.condition.right" v-model="join.condition.right" :options="rightColumnOptions" placeholder="Select a Column" /> </div> </div> </div> </div> <div class="flex justify-end space-x-2"> <Button :disabled="!editTable.join" @click="clear_join"> Clear </Button> <Button variant="solid" :disabled="!join.with || !join.condition || !join.type" @click="applyJoin" > Apply </Button> </div> </div> </div> </template> <script setup> import { inject, ref, watch } from 'vue' import LinkIcon from '@/components/Controls/LinkIcon.vue' import { getQueryLink } from '@/utils' const emits = defineEmits(['close']) const props = defineProps({ table: { type: Object, required: true, }, }) const query = inject('query') const join = ref({ type: { label: 'Left', value: 'left' }, with: {}, condition: { left: {}, right: {}, }, }) const editTable = ref({ ...props.table }) // table that is being edited if (editTable.value.join) { join.value = editTable.value.join } const joinTypeOptions = ref([ { label: 'Inner Join', value: 'inner' }, { label: 'Left Join', value: 'left' }, { label: 'Full Outer Join', value: 'full' }, ]) watch( () => join.value.with, (newVal) => newVal && setJoinCondition() ) const leftColumnOptions = ref([]) const rightColumnOptions = ref([]) function setJoinCondition() { const leftTable = editTable.value.table const rightTable = join.value.with.value if (!leftTable || !rightTable) return query.fetchJoinOptions .submit({ left_table: leftTable, right_table: rightTable, }) .then(({ message }) => { setJoinConditionOptions(message) if (message.saved_links.length) { setSavedJoinCondition(message.saved_links[0]) } }) } function setJoinConditionOptions({ left_columns, right_columns }) { leftColumnOptions.value = left_columns.map((c) => ({ label: c.label, value: c.column, })) rightColumnOptions.value = right_columns.map((c) => ({ label: c.label, value: c.column, })) } function setSavedJoinCondition({ left, right }) { join.value.condition = { left: leftColumnOptions.value.find((col) => col.value === left), right: rightColumnOptions.value.find((col) => col.value === right), } } function applyJoin() { editTable.value.join = join.value query.updateTable.submit({ table: editTable.value }) emits('close') } function clear_join() { editTable.value.join = '' query.updateTable.submit({ table: editTable.value }) emits('close') } </script>
2302_79757062/insights
frontend/src/query/deprecated/Table/TableJoiner.vue
Vue
agpl-3.0
4,257
<template> <div class="flex flex-1 flex-shrink-0 flex-col overflow-hidden text-gray-900"> <template v-if="!selectedTable"> <div v-if="!addingTable" class="flex flex-shrink-0 items-center justify-between bg-white pb-2" > <div class="text-sm tracking-wide text-gray-700">TABLES</div> <Button icon="plus" @click="addingTable = true"></Button> </div> <div v-if="addingTable" class="flex w-full flex-shrink-0 space-x-2 pb-3 pt-1"> <div class="flex-1"> <Autocomplete ref="tableSearch" v-model="newTable" :options="query.tables.newTableOptions" placeholder="Select a table..." @update:modelValue="addNewTable" /> </div> <Button icon="x" @click="addingTable = false"></Button> </div> <div v-if="query.tables.data?.length == 0" class="flex flex-1 items-center justify-center rounded border-2 border-dashed border-gray-200 text-sm text-gray-700" > <p>No tables selected</p> </div> <div v-else class="flex w-full flex-1 select-none flex-col divide-y overflow-y-scroll"> <div v-for="(table, idx) in query.tables.data" :key="idx" class="flex h-10 w-full cursor-pointer items-center border-b text-sm last:border-0 hover:bg-gray-50" @click.prevent.stop="selectedTable = table" > <FeatherIcon name="layout" class="mr-2 h-[14px] w-[14px]" /> <span class="overflow-hidden text-ellipsis whitespace-nowrap text-base font-medium" > {{ table.label }} </span> <span v-if="table.join" class="ml-2 text-gray-700"> <JoinLeftIcon v-if="table.join.type.value == 'left'" /> <JoinRightIcon v-if="table.join.type.value == 'right'" /> <JoinInnerIcon v-if="table.join.type.value == 'inner'" /> <JoinFullIcon v-if="table.join.type.value == 'full'" /> </span> <span v-if="table.join" class="ml-2 overflow-hidden text-ellipsis whitespace-nowrap text-base font-medium" > {{ table.join.with.label }} </span> <span class="ml-auto mr-1 overflow-hidden text-ellipsis whitespace-nowrap text-gray-700" > {{ query.doc.data_source }} </span> <div class="flex items-center px-1 py-0.5 text-gray-700 hover:text-gray-700" @click.prevent.stop="removeTable(table)" > <FeatherIcon name="x" class="h-3 w-3" /> </div> </div> </div> </template> <!-- Editor --> <TableJoiner v-else :table="selectedTable" @close="selectedTable = null"></TableJoiner> </div> </template> <script setup> import JoinLeftIcon from '@/components/Icons/JoinLeftIcon.vue' import JoinRightIcon from '@/components/Icons/JoinRightIcon.vue' import JoinInnerIcon from '@/components/Icons/JoinInnerIcon.vue' import JoinFullIcon from '@/components/Icons/JoinFullIcon.vue' import TableJoiner from './TableJoiner.vue' import { inject, ref, watch } from 'vue' const query = inject('query') const newTable = ref({}) const selectedTable = ref(null) const addingTable = ref(false) const tableSearch = ref(null) watch(addingTable, (newValue) => { newTable.value = {} if (newValue) { query.fetchTables.submit().then(() => { tableSearch.value.input.el.focus() }) } }) const $notify = inject('$notify') function addNewTable(table) { addingTable.value = false if (table?.value) { query.addTable.submit({ table: { table: table.value, label: table.label, }, }) } } function removeTable(table) { const validationError = query.tables.validateRemoveTable(table) if (validationError) { return $notify(validationError) } query.removeTable.submit({ table }) } </script>
2302_79757062/insights
frontend/src/query/deprecated/Table/TablePanel.vue
Vue
agpl-3.0
3,618
import { useQueryResource } from '@/query/useQueryResource' import sessionStore from '@/stores/sessionStore' import settingsStore from '@/stores/settingsStore' import { areDeeplyEqual, createTaskRunner } from '@/utils' import { useQueryColumns } from '@/utils/query/columns' import { useQueryFilters } from '@/utils/query/filters' import { useQueryTables } from '@/utils/query/tables' import { createToast } from '@/utils/toasts' import { whenever } from '@vueuse/core' import { debounce } from 'frappe-ui' import { computed, reactive } from 'vue' import useQueryChart from './useQueryChart' import useQueryResults from './useQueryResults' const session = sessionStore() export default function useQuery(name) { const resource = useQueryResource(name) const state = reactive({ loading: true, executing: false, doc: {}, chart: {}, results: {}, sourceSchema: {}, }) const queue = createTaskRunner() state.doc = computed(() => resource.doc) const setLoading = (value) => (state.loading = value) // Results state.MAX_ROWS = 100 state.isOwner = computed(() => resource.doc?.owner === session.user.email) state.reload = () => { setLoading(true) return resource.get .fetch() .then(() => initChartAndResults()) .finally(() => setLoading(false)) } async function initChartAndResults() { if (state.doc.result_name) { state.results = useQueryResults(state.doc.result_name) } if (state.doc.chart) { state.chart = useQueryChart(state.doc.chart, state.doc.title, state.results) } } state.updateTitle = (title) => { setLoading(true) return queue(() => resource.setValue.submit({ title }).finally(() => setLoading(false))) } state.changeDataSource = (data_source) => { setLoading(true) return queue(() => resource.setValue.submit({ data_source }).then(() => setLoading(false))) } const autoExecuteEnabled = settingsStore().settings.auto_execute_query state.updateQuery = async (newQuery) => { if (areDeeplyEqual(newQuery, resource.originalDoc.json)) return Promise.resolve({ query_updated: false }) setLoading(true) return new Promise((resolve) => queue(() => resource.setValue .submit({ json: JSON.stringify(newQuery, null, 2) }) .then(() => autoExecuteEnabled && state.execute()) .then(() => resolve({ query_updated: true })) .finally(() => setLoading(false)) ) ) } state.execute = debounce(async () => { if (!state.doc?.data_source) return setLoading(true) state.executing = true await queue(() => resource.run.submit().catch(() => {})) await state.results.reload() state.executing = false setLoading(false) }, 500) state.updateTransforms = debounce(async (transforms) => { if (!transforms) return setLoading(true) const updateTransform = () => resource.setValue.submit({ transforms }) const updateStatus = () => resource.set_status.submit({ status: 'Pending Execution' }) const autoExecute = () => autoExecuteEnabled && state.execute() return queue(() => updateTransform() .then(updateStatus) .then(autoExecute) .finally(() => setLoading(false)) ) }, 500) state.duplicate = async () => { state.duplicating = true await queue(() => resource.duplicate.submit()) state.duplicating = false return resource.duplicate.data } state.delete = async () => { state.deleting = true await queue(() => resource.delete.submit()) state.deleting = false } state.store = () => { setLoading(true) return queue(() => resource.store.submit().finally(() => setLoading(false))) } state.unstore = () => { setLoading(true) return queue(() => resource.unstore.submit().finally(() => setLoading(false))) } state.switchQueryBuilder = () => { return queue(() => { return resource.switch_query_type.submit().then(() => { window.location.reload() }) }) } // classic query const isClassicQuery = computed(() => { if (!resource.doc) return false return ( !resource.doc?.is_assisted_query && !resource.doc?.is_native_query && !resource.doc?.is_script_query ) }) whenever(isClassicQuery, () => { if (state.classicQueryInitialized || !isClassicQuery.value) return state.addTable = resource.addTable state.fetchTables = resource.fetchTables state.updateTable = resource.updateTable state.removeTable = resource.removeTable state.fetchJoinOptions = resource.fetchJoinOptions state.tables = useQueryTables(state) state.addColumn = resource.addColumn state.moveColumn = resource.moveColumn state.removeColumn = resource.removeColumn state.updateColumn = resource.updateColumn state.fetchColumns = resource.fetchColumns state.columns = useQueryColumns(state) state.updateFilters = resource.updateFilters state.fetchColumnValues = resource.fetchColumnValues state.filters = useQueryFilters(state) state.classicQueryInitialized = true }) state.convertToNative = async () => { if (state.doc.is_native_query) return setLoading(true) return queue(() => { return resource.setValue .submit({ is_native_query: 1, is_assisted_query: 0, is_script_query: 0 }) .finally(() => setLoading(false)) }) } // native query state.executeSQL = debounce((sql) => { if (!sql || sql === state.doc.sql) return state.execute() setLoading(true) return queue(() => resource.setValue .submit({ sql }) .then(() => state.execute()) .finally(() => setLoading(false)) ) }, 500) // script query state.updateScript = debounce((script) => { if (script === state.doc.script) return setLoading(true) return queue(() => resource.setValue.submit({ script }).finally(() => setLoading(false))) }, 500) state.updateScriptVariables = debounce((variables) => { setLoading(true) return queue(() => resource.setValue.submit({ variables }).finally(() => { createToast({ title: 'Secret Variables Updated', }) setLoading(false) }) ) }, 500) state.downloadResults = () => { const results = state.results?.data if (!results || results.length === 0) return let data = [...results] if (data.length === 0) return data[0] = data[0].map((d) => d.label) const csvString = data.map((row) => row.join(',')).join('\n') const blob = new Blob([csvString], { type: 'text/csv' }) const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('hidden', '') a.setAttribute('href', url) a.setAttribute('download', `${state.doc.title || 'data'}.csv`) document.body.appendChild(a) a.click() document.body.removeChild(a) } return state }
2302_79757062/insights
frontend/src/query/resources/useQuery.js
JavaScript
agpl-3.0
6,549
import { areDeeplyEqual, createTaskRunner, safeJSONParse } from '@/utils' import { convertResultToObjects, guessChart } from '@/widgets/useChartData' import { watchDebounced } from '@vueuse/core' import { call, createDocumentResource } from 'frappe-ui' import { computed, reactive } from 'vue' export default function useQueryChart(chartName, queryTitle, queryResults) { const resource = getChartResource(chartName) resource.get.fetch() const chart = reactive({ doc: computed(() => resource.doc || {}), data: computed(() => convertResultToObjects(queryResults.formattedResults)), togglePublicAccess, addToDashboard, getGuessedChart, resetOptions, delete: deleteChart, }) const run = createTaskRunner() watchDebounced( () => ({ chart_type: chart.doc.chart_type, options: chart.doc.options, }), _updateDoc, { deep: true, debounce: 1000 } ) async function _updateDoc(newDoc) { const ogDoc = resource.originalDoc const chartTypeChanged = newDoc.chart_type != ogDoc.chart_type const optionsChanged = !areDeeplyEqual(newDoc.options, ogDoc.options) if (!chartTypeChanged && !optionsChanged) return let newOptions = { ...newDoc.options } if (!newOptions.query) { newOptions.query = chart.doc.query } if (chartTypeChanged && newDoc.chart_type != 'Auto') { const guessedChart = getGuessedChart(newDoc.chart_type) newOptions = { ...guessedChart.options, ...newOptions } newOptions.title = queryTitle } _save({ chart_type: newDoc.chart_type, options: newOptions }) } function _save(chartDoc) { chartDoc.options.query = chart.doc.query return run(() => resource.setValue.submit({ title: chartDoc.options.title || queryTitle, chart_type: chartDoc.chart_type, options: chartDoc.options, }) ) } function getGuessedChart(chart_type) { if (!queryResults.formattedResults.length) return chart_type = chart_type || chart.doc.chart_type const recommendedChart = guessChart(queryResults.formattedResults, chart_type) return { chart_type: recommendedChart?.type, options: { ...recommendedChart?.options, title: recommendedChart?.options?.title || queryTitle, }, } } function togglePublicAccess(isPublic) { if (resource.doc.is_public === isPublic) return resource.setValue.submit({ is_public: isPublic }).then(() => { $notify({ title: 'Chart access updated', variant: 'success', }) resource.doc.is_public = isPublic }) } async function addToDashboard(dashboardName) { if (!dashboardName || !resource.doc.name || resource.addingToDashboard) return resource.addingToDashboard = true if (chart.doc.chart_type == 'Auto') { const guessedChart = getGuessedChart() await _save({ chart_type: guessedChart.chart_type, options: guessedChart.options, }) } await call('insights.api.dashboards.add_chart_to_dashboard', { dashboard: dashboardName, chart: resource.doc.name, }) resource.addingToDashboard = false } function resetOptions() { state.doc.chart_type = undefined state.doc.options = {} } async function deleteChart() { state.deleting = true return run(() => resource.delete.submit().then(() => (state.deleting = false))) } return chart } export function getChartResource(chartName) { return createDocumentResource({ doctype: 'Insights Chart', name: chartName, auto: false, transform: (doc) => { doc.chart_type = doc.chart_type doc.options = safeJSONParse(doc.options) return doc }, }) }
2302_79757062/insights
frontend/src/query/resources/useQueryChart.js
JavaScript
agpl-3.0
3,494
import { safeJSONParse } from '@/utils' import { createDocumentResource } from 'frappe-ui' import { computed, reactive } from 'vue' import { getFormattedResult } from '@/utils/query/results' export default function useQueryResults(result_name) { const resource = getResultResource(result_name) resource.get.fetch() return reactive({ reload: () => resource.get.fetch(), loading: computed(() => resource.loading), data: computed(() => resource.doc?.results || []), columns: computed(() => resource.doc?.results?.[0] || []), formattedResults: computed(() => getFormattedResult(resource.doc?.results)), }) } export function getResultResource(resultName) { return createDocumentResource({ doctype: 'Insights Query Result', name: resultName, auto: false, transform: (doc) => { doc.results = safeJSONParse(doc.results, []) return doc }, }) }
2302_79757062/insights
frontend/src/query/resources/useQueryResults.js
JavaScript
agpl-3.0
869
import { useQueryResource } from '@/query/useQueryResource' import { safeJSONParse, whenHasValue } from '@/utils' import { getFormattedResult } from '@/utils/query/results' import { convertResultToObjects, guessChart } from '@/widgets/useChartData' import { watchDebounced, watchOnce } from '@vueuse/core' import { call, createDocumentResource, debounce } from 'frappe-ui' import { reactive } from 'vue' import useQuery from './resources/useQuery' const charts = {} export async function createChart() { return call('insights.api.queries.create_chart') } export default function useChartOld(name) { if (!charts[name]) { charts[name] = getChart(name) } return charts[name] } function getChart(chartName) { const chartDocResource = getChartResource(chartName) const state = reactive({ query: null, data: [], columns: [], loading: false, error: null, options: {}, autosave: false, doc: { doctype: 'Insights Chart', name: undefined, chart_type: undefined, options: {}, is_public: false, }, }) async function load() { state.loading = true await chartDocResource.get.fetch() state.doc = chartDocResource.doc if (!state.doc.query) { state.loading = false return } state.doc.query = chartDocResource.doc.query updateChartData() } load() function updateChartData() { state.loading = true const _query = useQuery(state.doc.query) _query.reload() watchOnce( () => _query.results.doc, () => { if (!_query.doc) return state.columns = _query.results.columns const formattedResults = _query.results.formattedResults state.data = convertResultToObjects(formattedResults) if (!state.doc.chart_type) { const recommendedChart = guessChart(formattedResults) state.doc.chart_type = recommendedChart?.type state.doc.options = recommendedChart?.options state.doc.options.title = _query.doc.title } state.doc.options.query = state.doc.query state.loading = false } ) } function save() { chartDocResource.setValue.submit({ chart_type: state.doc.chart_type, options: state.doc.options, }) } function togglePublicAccess(isPublic) { if (state.doc.is_public === isPublic) return chartDocResource.setValue.submit({ is_public: isPublic }).then(() => { $notify({ title: 'Chart access updated', variant: 'success', }) state.doc.is_public = isPublic }) } function updateQuery(query) { if (!query) return if (state.doc.query === query) return state.doc.query = query chartDocResource.setValue.submit({ query }).then(() => { updateChartData() }) } updateQuery = debounce(updateQuery, 500) let autosaveWatcher = undefined function enableAutoSave() { state.autosave = true autosaveWatcher = watchDebounced(() => state.doc, save, { deep: true, debounce: 500, }) } function disableAutoSave() { state.autosave = false if (autosaveWatcher) { autosaveWatcher() autosaveWatcher = undefined } } async function deleteChart() { state.deleting = true await chartDocResource.delete.submit() state.deleting = false } async function addToDashboard(dashboardName) { if (!dashboardName || !state.doc.name || state.addingToDashboard) return state.addingToDashboard = true await call('insights.api.dashboards.add_chart_to_dashboard', { dashboard: dashboardName, chart: state.doc.name, }) state.addingToDashboard = false } function resetOptions() { state.doc.chart_type = undefined state.doc.options = {} } return Object.assign(state, { load, save, togglePublicAccess, updateQuery, enableAutoSave, disableAutoSave, addToDashboard, resetOptions, delete: deleteChart, }) } export function getChartResource(chartName) { return createDocumentResource({ doctype: 'Insights Chart', name: chartName, transform: (doc) => { doc.chart_type = doc.chart_type doc.options = safeJSONParse(doc.options) doc.options.query = doc.query return doc }, }) }
2302_79757062/insights
frontend/src/query/useChart.js
JavaScript
agpl-3.0
3,990
import { safeJSONParse } from '@/utils' import { getFormattedResult } from '@/utils/query/results' import { convertResultToObjects } from '@/widgets/useChartData' import { createResource } from 'frappe-ui' import { reactive } from 'vue' export default function usePublicChart(publicKey) { const resource = getPublicChart(publicKey) const state = reactive({ query: null, data: [], loading: false, error: null, doc: { doctype: 'Insights Chart', name: undefined, chart_type: undefined, options: {}, is_public: false, }, }) async function load() { state.loading = true state.doc = await resource.fetch() const results = getFormattedResult(state.doc.data) state.data = convertResultToObjects(results) state.loading = false } load() return Object.assign(state, { load, }) } function getPublicChart(public_key) { return createResource({ url: 'insights.api.public.get_public_chart', params: { public_key }, transform(doc) { doc.options = safeJSONParse(doc.options) doc.data = safeJSONParse(doc.data) return doc }, }) }
2302_79757062/insights
frontend/src/query/usePublicChart.js
JavaScript
agpl-3.0
1,081
import { safeJSONParse } from '@/utils' import { createDocumentResource } from 'frappe-ui' export const API_METHODS = { run: 'run', store: 'store', unstore: 'unstore', convert: 'convert', setLimit: 'set_limit', set_status: 'set_status', duplicate: 'duplicate', reset: 'reset_and_save', fetchTables: 'fetch_tables', fetchColumns: 'fetch_columns', fetchColumnValues: 'fetch_column_values', fetch_related_tables: 'fetch_related_tables', // table methods addTable: 'add_table', removeTable: 'remove_table', updateTable: 'update_table', fetchJoinOptions: 'fetch_join_options', // column methods addColumn: 'add_column', moveColumn: 'move_column', updateColumn: 'update_column', removeColumn: 'remove_column', // filter methods updateFilters: 'update_filters', addTransform: 'add_transform', resetTransforms: 'reset_transforms', run: 'run', convert_to_native: 'convert_to_native', convert_to_assisted: 'convert_to_assisted', get_tables_columns: 'get_tables_columns', save_as_table: 'save_as_table', delete_linked_table: 'delete_linked_table', switch_query_type: 'switch_query_type', } export function useQueryResource(name) { if (!name) return const resource = createDocumentResource({ doctype: 'Insights Query', name: name, auto: false, whitelistedMethods: API_METHODS, transform(doc) { doc.columns = doc.columns.map((c) => { c.format_option = safeJSONParse(c.format_option, {}) return c }) doc.json = safeJSONParse(doc.json, defaultQueryJSON) doc.transforms = doc.transforms.map((t) => { t.options = safeJSONParse(t.options, {}) return t }) return doc }, }) return resource } const defaultQueryJSON = { table: {}, joins: [], filters: [], columns: [], calculations: [], measures: [], dimensions: [], orders: [], limit: null, }
2302_79757062/insights
frontend/src/query/useQueryResource.js
JavaScript
agpl-3.0
1,822
<script setup> import { COLUMN_TYPES, FIELDTYPES, GRANULARITIES } from '@/utils' import { parse } from '@/utils/expressions' import { computed, defineProps, inject, reactive } from 'vue' import ExpressionBuilder from './ExpressionBuilder.vue' import { NEW_COLUMN } from './constants' import { getSelectedTables } from './useAssistedQuery' const emptyExpressionColumn = { ...NEW_COLUMN, expression: { raw: '', ast: {}, }, } const assistedQuery = inject('assistedQuery') const emit = defineEmits(['save', 'remove']) const props = defineProps({ column: Object }) const propsColumn = props.column || emptyExpressionColumn const column = reactive({ ...NEW_COLUMN, ...propsColumn, }) if (!column.expression) { column.expression = { ...emptyExpressionColumn.expression } } const isValid = computed(() => { if (!column.label || !column.type) return false if (!column.expression.raw) return false return true }) const columnOptions = computed(() => { const selectedTables = getSelectedTables(assistedQuery) return assistedQuery.columnOptions.filter((c) => selectedTables.includes(c.table)) || [] }) function onSave() { if (!isValid.value) return emit('save', { ...column, label: column.label.trim(), type: column.type.trim(), expression: { raw: column.expression.raw, ast: parse(column.expression.raw).ast, }, }) } </script> <template> <div class="space-y-3 text-base"> <ExpressionBuilder v-model="column.expression" :columnOptions="columnOptions" /> <div class="grid grid-cols-2 gap-4"> <FormControl type="text" label="Label" class="col-span-1" v-model="column.label" placeholder="Label" autocomplete="off" /> <FormControl label="Type" type="select" class="col-span-1" v-model="column.type" :options="COLUMN_TYPES" /> <div v-if="FIELDTYPES.DATE.includes(column.type)" class="col-span-1 space-y-1"> <span class="mb-2 block text-sm leading-4 text-gray-700">Date Format</span> <Autocomplete :modelValue="column.granularity" placeholder="Date Format" :options="GRANULARITIES" @update:modelValue="(op) => (column.granularity = op.value)" /> </div> </div> <div class="flex flex-col justify-end gap-2 lg:flex-row"> <Button variant="outline" theme="red" @click="emit('remove')">Remove</Button> <Button variant="solid" :disabled="!isValid" @click="onSave"> Save </Button> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/ColumnExpressionEditor.vue
Vue
agpl-3.0
2,436
<script setup> import { fieldtypesToIcon } from '@/utils' import { X } from 'lucide-vue-next' defineProps(['column', 'isActive']) defineEmits(['edit-column', 'remove-column']) function isValidColumn(column) { const isExpression = column.expression?.raw return column.label && column.type && (isExpression || (column.table && column.column)) } const aggregationToAbbr = { min: 'MIN', max: 'MAX', sum: 'SUM', avg: 'AVG', count: 'CNT', distinct: 'UDST', distinct_count: 'DCNT', 'group by': 'UNQ', 'cumulative count': 'CCNT', 'cumulative sum': 'CSUM', } function getAbbreviation(column) { if (column.expression?.raw) return 'EXPR' return aggregationToAbbr[column.aggregation] || 'UNQ' } </script> <template> <div class="group relative flex h-8 flex-1 cursor-pointer items-center justify-between overflow-hidden rounded border border-gray-300 bg-white px-2 pl-2.5 hover:shadow" :class="isActive ? 'border-gray-500 bg-white shadow-sm ring-1 ring-gray-400' : ''" @click.prevent.stop="$emit('edit-column', column)" > <div class="absolute left-0 h-full w-1 flex-shrink-0 bg-blue-500"></div> <div class="flex w-full items-center overflow-hidden"> <div class="flex w-full items-center space-x-1.5 truncate" v-if="isValidColumn(column)"> <!-- <div class="rounded border border-violet-400 py-0.5 px-1 font-mono text-xs tracking-wider text-violet-700" > {{ getAbbreviation(column) }} </div> --> <component :is="fieldtypesToIcon[column.type]" class="h-4 w-4 text-gray-600" /> <div>{{ column.label }}</div> </div> <div v-else class="text-gray-600">Select a column</div> </div> <div class="flex items-center space-x-2"> <X class="invisible h-4 w-4 text-gray-600 transition-all hover:text-gray-800 group-hover:visible" @click.prevent.stop="$emit('remove-column', column)" /> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/ColumnListItem.vue
Vue
agpl-3.0
1,873
<script setup> import DraggableList from '@/components/DraggableList.vue' import { Combine } from 'lucide-vue-next' import { computed, inject, nextTick, ref } from 'vue' import ColumnExpressionEditor from './ColumnExpressionEditor.vue' import ColumnListItem from './ColumnListItem.vue' import SectionHeader from './SectionHeader.vue' import SimpleColumnEditor from './SimpleColumnEditor.vue' import { NEW_COLUMN } from './constants' const query = inject('query') const assistedQuery = inject('assistedQuery') !assistedQuery.columnOptions.length && assistedQuery.fetchColumnOptions() const columns = computed({ get: () => assistedQuery.columns, set: (value) => (assistedQuery.columns = value), }) const columnRefs = ref(null) const activeColumnIdx = ref(null) const showExpressionEditor = computed(() => { if (activeColumnIdx.value === null) return false const activeColumn = columns.value[activeColumnIdx.value] return isExpressionColumn(activeColumn) }) const showSimpleColumnEditor = computed(() => { if (activeColumnIdx.value === null) return false return !showExpressionEditor.value }) function isExpressionColumn(column) { return column.expression.hasOwnProperty('raw') || column.expression.hasOwnProperty('ast') } function onColumnSelect(column) { if (!column) return const columnAlreadyExists = columns.value.find( (c) => c.table === column.table && c.column === column.column && c.label === column.label ) if (columnAlreadyExists) { return } assistedQuery.addColumns([column]) } function onRemoveColumn() { assistedQuery.removeColumnAt(activeColumnIdx.value) activeColumnIdx.value = null } function onSaveColumn(column) { assistedQuery.updateColumnAt(activeColumnIdx.value, column) activeColumnIdx.value = null } function onAddColumnExpression() { assistedQuery.addColumns([ { ...NEW_COLUMN, expression: { raw: '', ast: {}, }, }, ]) nextTick(() => { activeColumnIdx.value = columns.value.length - 1 }) } function onColumnSort(e) { if (e.oldIndex != e.newIndex) { assistedQuery.moveColumn(e.oldIndex, e.newIndex) } } </script> <template> <div class="space-y-2"> <SectionHeader title="Columns" :icon="Combine" info="Select the columns you want to see in the results." > <Autocomplete :modelValue="columns" bodyClasses="w-[18rem]" @update:modelValue="onColumnSelect" :options="assistedQuery.groupedColumnOptions" @update:query="assistedQuery.fetchColumnOptions" > <template #target="{ togglePopover }"> <Button variant="outline" icon="plus" @click="togglePopover"></Button> </template> <template #footer="{ togglePopover }"> <Button class="w-full" variant="ghost" iconLeft="plus" @click="onAddColumnExpression() || togglePopover()" > Custom Expression </Button> </template> </Autocomplete> </SectionHeader> <DraggableList v-if="columns.length" v-model:items="columns" group="columns" item-key="label" :showEmptyState="true" :showHandle="false" > <template #item="{ item: column, index: idx }"> <ColumnListItem v-if="isExpressionColumn(column)" :column="column" :isActive="activeColumnIdx === idx" @edit-column="activeColumnIdx = idx" @remove-column="assistedQuery.removeColumnAt(idx)" /> <Popover v-else :show="showSimpleColumnEditor && activeColumnIdx === idx" @close="activeColumnIdx === idx ? (activeColumnIdx = null) : null" placement="right-start" > <template #target="{ togglePopover }"> <ColumnListItem :column="column" :isActive="activeColumnIdx === idx" @edit-column="activeColumnIdx = idx" @remove-column="assistedQuery.removeColumnAt(idx)" /> </template> <template #body> <div v-if="showSimpleColumnEditor && activeColumnIdx === idx" class="ml-2 w-[20rem] rounded-lg border border-gray-100 bg-white text-base shadow-xl" > <SimpleColumnEditor :column="column" @remove="onRemoveColumn" @save="onSaveColumn" @discard="activeColumnIdx = null" /> </div> </template> </Popover> </template> </DraggableList> </div> <Dialog :modelValue="showExpressionEditor" :options="{ size: '3xl' }"> <template #body> <div class="bg-white px-4 pb-6 pt-5 sm:px-6"> <div class="flex items-center justify-between pb-4"> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> Column Expression </h3> <Button variant="ghost" @click="activeColumnIdx = null" icon="x"> </Button> </div> <ColumnExpressionEditor :column="columns[activeColumnIdx]" @remove="onRemoveColumn" @save="onSaveColumn" /> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src/query/visual/ColumnSection.vue
Vue
agpl-3.0
4,796
<script setup> import { FIELDTYPES } from '@/utils' import { computed, inject } from 'vue' const emit = defineEmits(['update:transformOptions']) const props = defineProps({ transformOptions: Object }) const query = inject('query') const options = computed({ get: () => props.transformOptions, set: (value) => emit('update:transformOptions', value), }) const valueOptions = computed(() => { if (!query.results.columns) return [] return query.results.columns .filter((c) => FIELDTYPES.NUMBER.includes(c.type)) .map((c) => ({ label: c.label, value: c.label, description: c.type })) }) </script> <template> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Number Column</span> <Autocomplete placeholder="Number Column" :options="valueOptions" :modelValue="options.column" @update:modelValue="options.column = $event?.value" /> </div> </template>
2302_79757062/insights
frontend/src/query/visual/CumulativeSumTransformFields.vue
Vue
agpl-3.0
897
<script setup> import Code from '@/components/Controls/Code.vue' import { fieldtypesToIcon, returnTypesToIcon } from '@/utils' import { parse } from '@/utils/expressions' import { FUNCTIONS } from '@/utils/query' import { computed, nextTick, reactive, ref, watch } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ modelValue: Object, columnOptions: Array, }) const rawExpression = computed({ get: () => props.modelValue?.raw || '', set: (value) => emit('update:modelValue', { raw: value, ast: parse(value).ast, }), }) const focused = ref(false) const codeEditor = ref(null) const functionHelp = ref(null) const suggestionContext = reactive({ from: null, to: null, text: null, }) watch(rawExpression, (val) => { if (!val.length) { suggestionContext.from = null suggestionContext.to = null suggestionContext.text = null } }) const codeViewUpdate = function ({ cursorPos: _cursorPos }) { functionHelp.value = null if (!rawExpression.value) { suggestionContext.from = null suggestionContext.to = null suggestionContext.text = null return } const tokens = parse(rawExpression.value).tokens const token = tokens .filter((t) => t.type == 'FUNCTION' && t.start < _cursorPos && t.end >= _cursorPos) .at(-1) if (token) { const { value } = token if (FUNCTIONS[value]) { functionHelp.value = FUNCTIONS[value] } } } function onSuggestionSelect(item) { const raw = rawExpression.value || '' const start = isNaN(suggestionContext.from) ? codeEditor.value.cursorPos : suggestionContext.from const end = isNaN(suggestionContext.to) ? codeEditor.value.cursorPos : suggestionContext.to if (item.suggestionType === 'function') { const textBeforeToken = raw.slice(0, start) const textAfterToken = raw.slice(end) let newText = `${item.label}` if (!textAfterToken.trim().startsWith('(')) newText += '()' rawExpression.value = `${textBeforeToken}${newText}${textAfterToken}` const newCursorPos = start + newText.length - 1 nextTick(() => { codeEditor.value.focus() codeEditor.value.setCursorPos(newCursorPos) }) } if (item.suggestionType === 'column') { // insert `table.column` const textBefore = raw.slice(0, start) const textAfter = raw.slice(end) let newText = `${item.table}.${item.column}` if (!textBefore.trim().endsWith('`')) newText = '`' + newText if (!textAfter.trim().startsWith('`')) newText += '`' rawExpression.value = `${textBefore}${newText}${textAfter}` const newCursorPos = start + newText.length nextTick(() => { codeEditor.value.focus() codeEditor.value.setCursorPos(newCursorPos) }) } } const allFunctionOptions = Object.keys(FUNCTIONS).map((f) => { return { label: f, ...FUNCTIONS[f], } }) const allOptions = computed(() => { return [ ...props.columnOptions.map((c) => ({ ...c, icon: fieldtypesToIcon[c.type], label: c.label || c.column, value: `${c.table}.${c.column}`, description: c.table_label, suggestionType: 'column', })), ...allFunctionOptions.map((f) => ({ icon: returnTypesToIcon[f.returnType], label: f.label, value: f.label, description: f.returnType, suggestionType: 'function', })), ] }) const filteredOptions = computed(() => { if (!suggestionContext.text) return allOptions.value const _searchTxt = suggestionContext.text.toLowerCase() return allOptions.value.filter( (o) => o.label.toLowerCase().includes(_searchTxt) || o.value.toLowerCase().includes(_searchTxt) || o.description?.toLowerCase().includes(_searchTxt) ) }) const filteredGroupedOptions = computed(() => { return [ { groupLabel: 'Columns', items: filteredOptions.value.filter((o) => o.suggestionType === 'column'), }, { groupLabel: 'Functions', items: filteredOptions.value.filter((o) => o.suggestionType === 'function'), }, ] }) const onGetCodeCompletion = (context) => { const _context = context.matchBefore(/\w*/) if (!_context) return suggestionContext.from = _context.from suggestionContext.to = _context.to suggestionContext.text = _context.text } </script> <template> <div class="min-w-[32rem]"> <span class="mb-2 block text-sm leading-4 text-gray-700">Expression</span> <div class="h-fit min-h-[2.5rem] rounded rounded-b-none border border-transparent bg-gray-100 p-0 px-1 transition-all" :class=" focused ? ' border border-b-0 !border-gray-300 bg-white hover:bg-transparent' : '' " > <Code ref="codeEditor" v-model="rawExpression" :completions="onGetCodeCompletion" placeholder="Write an expression" @focus="focused = true" @blur="focused = false" @viewUpdate="codeViewUpdate" ></Code> </div> <div class="-mt-1 flex h-[14rem] divide-x divide-gray-300 rounded rounded-t-none border border-t border-gray-300" > <div class="relative flex flex-1 flex-col overflow-hidden overflow-y-auto" v-auto-animate > <template v-for="group in filteredGroupedOptions"> <div class="sticky top-0 flex-shrink-0 truncate bg-gray-50 px-2.5 py-1.5 text-sm font-medium text-gray-600" > {{ group.groupLabel }} </div> <div v-for="item in group.items.slice(0, 25)" :key="item.value" class="exp-editor-suggestion flex cursor-pointer items-center rounded py-1.5 px-2 hover:bg-gray-100" @click.prevent.stop="onSuggestionSelect(item)" > <component :is="item.icon" class="mr-1 h-4 w-4 flex-shrink-0 text-gray-600" /> <div class="flex flex-1 items-center justify-between overflow-hidden"> <span class="flex-1 truncate text-sm text-gray-700"> {{ item.label }} </span> <span v-if="item.description" class="flex-shrink-0 text-xs text-gray-500" > {{ item.description }} </span> </div> </div> <div v-if="group.items.length == 0" class="flex h-10 items-center justify-center text-sm text-gray-500" > No {{ group.groupLabel.toLowerCase() }} found </div> </template> </div> <div class="flex flex-1 flex-col overflow-hidden pb-2" v-auto-animate> <div class="flex-shrink-0 truncate bg-gray-50 px-2.5 py-1.5 text-sm font-medium text-gray-600" > Info </div> <div v-if="functionHelp" class="flex flex-col px-3 py-2 text-sm"> <p>{{ functionHelp.description }}</p> <div class="mt-2 rounded bg-gray-50 p-2 text-xs leading-5"> <code> <span class="text-gray-600"># Syntax</span> <br /> {{ functionHelp.syntax }} <br /> <br /> <span class="text-gray-600"># Example</span> <br /> {{ functionHelp.example }} </code> </div> </div> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/ExpressionBuilder.vue
Vue
agpl-3.0
6,769
<script setup> import { FIELDTYPES, getOperatorOptions } from '@/utils' import { computed, defineProps, inject, reactive, ref, watch } from 'vue' import ExpressionBuilder from './ExpressionBuilder.vue' import FilterValueSelector from './FilterValueSelector.vue' import { NEW_FILTER } from './constants' import { getSelectedTables } from './useAssistedQuery' const emit = defineEmits(['save', 'discard', 'remove']) const props = defineProps({ filter: Object }) const assistedQuery = inject('assistedQuery') const activeTab = ref('Simple') const filter = reactive({ ...NEW_FILTER, ...props.filter, }) if (filter.expression?.raw) { activeTab.value = 'Expression' } if (filter.column && filter.column.column && filter.column.table && !filter.column.value) { filter.column.value = `${filter.column.table}.${filter.column.column}` } if (filter.operator?.value == 'is' && filter.value?.value?.toLowerCase().includes('set')) { filter.operator.value = filter.value.value === 'Set' ? 'is_set' : 'is_not_set' } const filterColumnOptions = computed(() => { return assistedQuery.groupedColumnOptions.map((group) => { return { group: group.group, items: group.items.filter((c) => c.column !== 'count'), } }) }) const isValidFilter = computed(() => { if (filter.expression?.raw && filter.expression?.ast) return true if (filter.column?.value && filter.operator?.value && filter.value?.value) return true if (filter.operator?.value?.includes('is_') && filter.column?.column) return true return false }) const operatorOptions = computed(() => { const options = getOperatorOptions(filter.column?.type) return options .filter((option) => option.value !== 'is') .concat([ { label: 'is set', value: 'is_set' }, { label: 'is not set', value: 'is_not_set' }, ]) }) if (!filter.operator?.value) { filter.operator = operatorOptions.value[0] } // prettier-ignore watch(() => filter.operator.value, (newVal, oldVal) => { if (newVal !== oldVal) { filter.value = {} } }) function isValidExpression(c) { if (!c) return false return c.expression?.raw && c.expression?.ast } const expressionColumnOptions = computed(() => { const selectedTables = getSelectedTables(assistedQuery) return assistedQuery.columnOptions.filter((c) => selectedTables.includes(c.table)) || [] }) </script> <template> <div class="flex flex-col gap-4 p-4"> <div class="flex h-8 w-full cursor-pointer select-none items-center rounded bg-gray-100 p-1" > <div v-for="(tab, idx) in ['Simple', 'Expression']" class="flex h-full flex-1 items-center justify-center px-4 text-sm transition-all" :class="activeTab === tab ? 'rounded bg-white shadow' : ''" @click.prevent.stop="activeTab = tab" > {{ tab }} </div> </div> <template v-if="activeTab == 'Expression'"> <ExpressionBuilder v-model="filter.expression" :columnOptions="expressionColumnOptions" /> </template> <template v-if="activeTab == 'Simple'"> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Column</span> <Autocomplete v-if="!isValidExpression(filter.column)" :modelValue="filter.column" placeholder="Column" :options="filterColumnOptions" @update:modelValue="filter.column = $event || {}" @update:query="assistedQuery.fetchColumnOptions" /> <FormControl v-else type="textarea" class="w-full" :modelValue="filter.column?.expression.raw" disabled /> <span v-if="isValidExpression(filter.column)" class="text-xs text-orange-500"> Editing a filter with a <i>column expression</i> is not supported yet. Remove this filter and add an expression filter instead. </span> </div> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Operator</span> <Autocomplete :modelValue="filter.operator" placeholder="Operator" :options="operatorOptions" @update:modelValue="filter.operator = $event" /> </div> <div> <FilterValueSelector :column="filter.column" :operator="filter.operator" :modelValue="filter.value" :data-source="assistedQuery.data_source" @update:modelValue="filter.value = $event" /> </div> </template> <div class="flex justify-between"> <Button variant="outline" @click="emit(isValidFilter ? 'discard' : 'remove')"> Discard </Button> <div class="flex gap-2"> <Button variant="outline" theme="red" @click="emit('remove')">Remove</Button> <Button variant="solid" :disabled="!isValidFilter" @click="emit('save', filter)"> Save </Button> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/FilterEditor.vue
Vue
agpl-3.0
4,635
<script setup> import { fieldtypesToIcon } from '@/utils' import { Sigma, X } from 'lucide-vue-next' defineProps(['filter', 'isActive']) defineEmits(['edit', 'remove']) function isValidExpression(expression) { return expression?.raw && expression?.ast } function isValidFilter(filter) { if (isValidExpression(filter.expression)) return true const is_valid_column = filter.column.column || isValidExpression(filter.column.expression) return ( is_valid_column && filter.operator.value && (filter.value.value || filter.operator.value.includes('is_')) ) } </script> <template> <div class="group relative flex h-8 w-full cursor-pointer items-center justify-between overflow-hidden rounded border border-gray-300 bg-white px-2 pl-2.5 hover:shadow" :class="isActive ? 'border-gray-500 bg-white shadow-sm ring-1 ring-gray-400' : ''" @click.prevent.stop="$emit('edit')" > <div class="absolute left-0 h-full w-1 flex-shrink-0 bg-green-600"></div> <div class="flex w-full items-center overflow-hidden"> <div class="flex w-full space-x-2" v-if="isValidFilter(filter)"> <template v-if="filter.expression?.raw"> <component :is="Sigma" class="h-4 w-4 flex-shrink-0 text-gray-600" /> <span class="truncate font-mono">{{ filter.expression.raw }}</span> </template> <template v-else> <div class="flex max-w-[60%] flex-shrink-0 gap-1 truncate"> <component :is="fieldtypesToIcon[filter.column.type]" class="h-4 w-4 flex-shrink-0 text-gray-600" /> {{ filter.column.label || filter.column.column }} </div> <span class="flex-shrink-0 font-medium text-green-600"> {{ filter.operator.value }} </span> <span v-if="!filter.operator.value.includes('is_')" class="flex-1 flex-shrink-0 truncate" > {{ filter.value.label || filter.value.value }} </span> </template> </div> <div v-else class="text-gray-600">Select a filter</div> </div> <div class="flex items-center"> <X class="invisible h-4 w-4 text-gray-600 transition-all hover:text-gray-800 group-hover:visible" @click.prevent.stop="$emit('remove')" /> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/FilterListItem.vue
Vue
agpl-3.0
2,176
<script setup> import { ListFilter } from 'lucide-vue-next' import { computed, inject, nextTick, ref } from 'vue' import FilterEditor from './FilterEditor.vue' import FilterListItem from './FilterListItem.vue' import SectionHeader from './SectionHeader.vue' const query = inject('query') const assistedQuery = inject('assistedQuery') const filters = computed(() => assistedQuery.filters) const activeFilterIdx = ref(null) const showExpressionEditor = computed(() => { if (activeFilterIdx.value === null) return false const activeFilter = filters.value[activeFilterIdx.value] if (!activeFilter) return false return ( activeFilter.expression.hasOwnProperty('raw') || activeFilter.expression.hasOwnProperty('ast') ) }) function onAddFilter() { assistedQuery.addFilter() nextTick(() => { activeFilterIdx.value = filters.value.length - 1 }) } function onRemoveFilter() { assistedQuery.removeFilterAt(activeFilterIdx.value) activeFilterIdx.value = null } function onSaveFilter(filter) { assistedQuery.updateFilterAt(activeFilterIdx.value, filter) activeFilterIdx.value = null } </script> <template> <div class="space-y-2"> <SectionHeader title="Filters" :icon="ListFilter" info="Apply filters to narrow down the results." > <Button variant="outline" icon="plus" @click.prevent.stop="onAddFilter"></Button> </SectionHeader> <div class="space-y-2" v-if="filters.length"> <template v-for="(filter, idx) in filters" :key="idx"> <Popover :show="activeFilterIdx === idx" @close="activeFilterIdx === idx ? (activeFilterIdx = null) : null" placement="right-start" > <template #target="{ togglePopover }"> <FilterListItem :filter="filter" :isActive="activeFilterIdx === idx" @edit="activeFilterIdx = idx" @remove="assistedQuery.removeFilterAt(idx)" /> </template> <template #body> <div v-if="activeFilterIdx === idx" class="ml-2 min-w-[20rem] rounded-lg border border-gray-100 bg-white text-base shadow-xl transition-all" > <FilterEditor :filter="filters[activeFilterIdx]" @discard="activeFilterIdx = null" @remove="onRemoveFilter" @save="onSaveFilter" /> </div> </template> </Popover> </template> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/FilterSection.vue
Vue
agpl-3.0
2,327
<script setup> import DatePicker from '@/components/Controls/DatePicker.vue' import DateRangePicker from '@/components/Controls/DateRangePicker.vue' import TimespanPicker from '@/components/Controls/TimespanPicker.vue' import { FIELDTYPES, formatDate } from '@/utils' import { FormControl, call, debounce } from 'frappe-ui' import { computed, defineProps, ref, watch } from 'vue' const props = defineProps({ label: { type: String, required: false, default: 'Value' }, column: { type: Object, required: true }, operator: { type: Object, required: true }, dataSource: { type: String, required: true }, }) const filterValue = defineModel() const operator = computed(() => props.operator?.value) const isExpression = computed(() => props.column?.expression?.raw) const isString = computed(() => props.column?.type === 'String') const isDate = computed(() => FIELDTYPES.DATE.includes(props.column?.type)) const isEqualityCheck = computed(() => ['=', '!=', 'in', 'not_in'].includes(operator.value)) const isNullCheck = computed(() => ['is_set', 'is_not_set'].includes(operator.value)) const selectorType = computed(() => { if (isNullCheck.value) return 'none' if (isDate.value && operator.value === 'between') return 'datepickerrange' if (isDate.value && operator.value === 'timespan') return 'timespanpicker' if (isDate.value) return 'datepicker' if (!isExpression.value && isString.value && isEqualityCheck.value) return 'combobox' return 'text' }) function onDateRangeChange(dates) { filterValue.value = { value: dates, label: dates .split(',') .map((date) => formatDate(date)) .join(' to '), } } function onDateChange(date) { filterValue.value = { value: date, label: formatDate(date), } } const isMultiValue = computed(() => ['in', 'not_in'].includes(operator.value)) const columnValues = ref([]) const fetchingColumnValues = ref(false) const checkAndFetchColumnValues = debounce(async function (search_text = '') { if (!props.column || !operator.value) return if (!['=', '!=', 'in', 'not_in'].includes(operator.value)) return if (!props.column.table || !props.column.column || !props.dataSource) return if (props.column?.type == 'String' && props.dataSource) { const URL = 'insights.api.data_sources.fetch_column_values' fetchingColumnValues.value = true const values = await call(URL, { data_source: props.dataSource, table: props.column.table, column: props.column.column, search_text, }) columnValues.value = values.map((value) => ({ label: value, value })) // prepend the selected value to the list if (Array.isArray(filterValue.value?.value)) { // filterValue.value = {label: '2 selected', value: [{ label: '', value: ''}, ...]} filterValue.value.forEach((selectedOption) => { if (!columnValues.value.find((v) => v.value === selectedOption.value)) { columnValues.value.unshift(selectedOption) } }) } fetchingColumnValues.value = false } }, 300) watch( () => { return { column: `${props.column.table}.${props.column.column}`, operator: operator.value, } }, (newVal, oldVal) => { if (!newVal.column || !newVal.operator) return if (newVal.column === oldVal?.column && newVal.operator === oldVal?.operator) return if (selectorType.value !== 'combobox') return checkAndFetchColumnValues() }, { deep: true, immediate: true } ) function onOptionSelect(value) { filterValue.value = !isMultiValue.value ? value : { label: `${value.length} values`, value: value, } } </script> <template> <div v-if="selectorType != 'none'" class="space-y-1"> <span class="mb-2 block text-sm leading-4 text-gray-700"> {{ props.label }} </span> <Autocomplete v-if="selectorType === 'combobox'" :key="isMultiValue" placeholder="Value" :multiple="isMultiValue" :modelValue="filterValue?.value" :options="columnValues" @update:query="checkAndFetchColumnValues" @update:modelValue="onOptionSelect" /> <TimespanPicker v-if="selectorType === 'timespanpicker'" v-model="filterValue" placeholder="Value" /> <DateRangePicker v-if="selectorType === 'datepickerrange'" :value="filterValue?.value" :formatter="formatDate" @change="onDateRangeChange($event)" /> <DatePicker v-if="selectorType === 'datepicker'" :value="filterValue?.value" :formatter="formatDate" @change="onDateChange($event)" /> <FormControl v-if="selectorType === 'text'" type="text" autocomplete="off" placeholder="Value" :modelValue="filterValue?.value" @update:modelValue=" filterValue = { value: $event, label: $event, } " /> </div> </template>
2302_79757062/insights
frontend/src/query/visual/FilterValueSelector.vue
Vue
agpl-3.0
4,639
<script setup> import { watchDebounced } from '@vueuse/core' import { Infinity } from 'lucide-vue-next' import { inject, ref, watch } from 'vue' import SectionHeader from './SectionHeader.vue' const assistedQuery = inject('assistedQuery') const limit = ref(assistedQuery.limit) watchDebounced(limit, assistedQuery.setLimit, { debounce: 300 }) watch( () => assistedQuery.limit, (val) => (limit.value = val) ) </script> <template> <div> <SectionHeader :icon="Infinity" title="Row Limit" info="Limit the number of rows returned by the query" > <input type="text" ref="limitInput" v-model.number="limit" :size="String(limit).length" class="tnum form-input rounded border border-gray-300 bg-white pr-1.5 text-gray-800 placeholder-gray-500 transition-colors hover:border-gray-400 hover:bg-white" /> </SectionHeader> </div> </template>
2302_79757062/insights
frontend/src/query/visual/LimitSection.vue
Vue
agpl-3.0
876
<script setup> import { FIELDTYPES } from '@/utils' import { computed, inject } from 'vue' const emit = defineEmits(['update:transformOptions']) const props = defineProps({ transformOptions: Object }) const query = inject('query') const options = computed({ get: () => props.transformOptions, set: (value) => emit('update:transformOptions', value), }) const valueOptions = computed(() => { if (!query.results.columns) return [] return query.results.columns .filter((c) => FIELDTYPES.NUMBER.includes(c.type)) .map((c) => ({ label: c.label, value: c.label, description: c.type })) }) const allOptions = computed(() => { if (!query.results.columns) return [] return query.results.columns.map((c) => ({ label: c.label, value: c.label, description: c.type, })) }) const errors = computed(() => { return { column: options.value.column && [options.value.index, options.value.value].includes(options.value.column) ? 'Column cannot be same as Row or Value' : '', index: options.value.index && [options.value.column, options.value.value].includes(options.value.index) ? 'Row cannot be same as Column or Value' : '', value: options.value.value && [options.value.column, options.value.index].includes(options.value.value) ? 'Value cannot be same as Column or Row' : '', } }) </script> <template> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Column</span> <Autocomplete placeholder="Column" :options="allOptions" :modelValue="options.column" @update:modelValue="options.column = $event?.value" /> <span v-if="errors.column" class="text-xs text-red-500"> {{ errors.column }} </span> </div> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Row</span> <Autocomplete placeholder="Row" :options="allOptions" :modelValue="options.index" @update:modelValue="options.index = $event?.value" /> <span v-if="errors.index" class="text-xs text-red-500"> {{ errors.index }} </span> </div> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Value</span> <Autocomplete placeholder="Value" :options="valueOptions" :modelValue="options.value" @update:modelValue="options.value = $event?.value" /> <span v-if="errors.value" class="text-xs text-red-500"> {{ errors.value }} </span> </div> </template>
2302_79757062/insights
frontend/src/query/visual/PivotTransformFields.vue
Vue
agpl-3.0
2,377
<script setup> import { ArrowDown, ArrowDownUp, ArrowUp } from 'lucide-vue-next' import { inject } from 'vue' const props = defineProps({ column: Object }) const assistedQuery = inject('assistedQuery') function getOrder(columnLabel) { return assistedQuery.columns.find((c) => c.label == columnLabel)?.order } const sortOptions = [ { label: 'Sort Ascending', onClick: () => assistedQuery.setOrderBy(props.column.label, 'asc'), }, { label: 'Sort Descending', onClick: () => assistedQuery.setOrderBy(props.column.label, 'desc'), }, { label: 'Remove Sort', onClick: () => assistedQuery.setOrderBy(props.column.label, ''), }, ] const sortOrderToIcon = { asc: ArrowUp, desc: ArrowDown, } </script> <template> <div class="flex items-center space-x-1"> <Dropdown :options="sortOptions"> <component :is="sortOrderToIcon[getOrder(column.label)] || ArrowDownUp" class="h-4 w-4 cursor-pointer text-gray-500 hover:text-gray-700" /> </Dropdown> </div> </template>
2302_79757062/insights
frontend/src/query/visual/ResultColumnActions.vue
Vue
agpl-3.0
992
<template> <div class="flex items-center justify-between rounded-b-md px-1 text-base"> <div v-if="queriedRowCount >= 0" class="flex items-center space-x-1"> <span class="text-gray-600">Showing</span> <span class="tnum"> {{ displayedRowCount }}</span> <span class="text-gray-600">out of</span> <span class="tnum">{{ queriedRowCount }}</span> <span class="text-gray-600">rows in</span> <span class="tnum">{{ executionTime }}</span> <span class="text-gray-600">seconds</span> </div> <div class="ml-auto flex items-center gap-1"> <Button variant="ghost" icon="download" @click="query.downloadResults"> </Button> </div> </div> </template> <script setup> import { computed, inject } from 'vue' const query = inject('query') const executionTime = computed(() => query.doc.execution_time) const queriedRowCount = computed(() => query.doc.results_row_count) const displayedRowCount = computed(() => Math.min(query.MAX_ROWS, queriedRowCount.value)) </script>
2302_79757062/insights
frontend/src/query/visual/ResultFooter.vue
Vue
agpl-3.0
985
<template> <div class="flex items-center justify-between"> <div class="flex items-center space-x-1.5"> <component :is="icon" class="h-4 w-4 text-gray-600" /> <Tooltip v-if="info" :text="info" bodyClasses="!max-w-[8rem] !text-left ml-1" placement="right" > <div class="flex items-baseline"> <p class="cursor-pointer font-medium">{{ title }}</p> <span class="ml-1.5 font-mono text-xs text-gray-600"> i </span> </div> </Tooltip> <p v-else class="font-medium">{{ title }}</p> </div> <slot></slot> </div> </template> <script setup> import Tooltip from '@/components/Tooltip.vue' defineProps(['title', 'info', 'icon']) </script>
2302_79757062/insights
frontend/src/query/visual/SectionHeader.vue
Vue
agpl-3.0
682
<script setup> import { AGGREGATIONS, FIELDTYPES, GRANULARITIES } from '@/utils' import { computed, defineProps, inject, reactive } from 'vue' import { NEW_COLUMN } from './constants' const emit = defineEmits(['save', 'discard', 'remove']) const props = defineProps({ column: Object }) const assistedQuery = inject('assistedQuery') const query = inject('query') const column = reactive({ ...NEW_COLUMN, ...props.column, }) if (column.table && column.column && !column.value) { column.value = `${column.table}.${column.column}` } if (!column.aggregation) { column.aggregation = 'group by' } function onColumnChange(option) { const selectedOption = { ...option } column.table = selectedOption.table column.table_label = selectedOption.table_label column.column = selectedOption.column column.label = selectedOption.label column.alias = selectedOption.label column.type = selectedOption.type column.value = selectedOption.value } const isValidColumn = computed(() => { if (!column.label || !column.type) return false if (column.table && column.column) return true return false }) function onAggregationChange(aggregation) { column.aggregation = aggregation.value const number_agg = [ 'count', 'sum', 'avg', 'cumulative sum', 'cumulative count', 'distinct', 'distinct_count', 'min', 'max', ] if (number_agg.includes(aggregation.value)) { column.type = 'Decimal' } } </script> <template> <div class="flex flex-col gap-4 p-4"> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Aggregation</span> <Autocomplete :modelValue="column.aggregation.toLowerCase()" placeholder="Aggregation" :options="AGGREGATIONS" @update:modelValue="onAggregationChange" /> </div> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Column</span> <Autocomplete :modelValue="column" bodyClasses="w-[18rem]" placeholder="Column" @update:modelValue="onColumnChange" :options="assistedQuery.groupedColumnOptions" @update:query="assistedQuery.fetchColumnOptions" /> </div> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Label</span> <FormControl type="text" class="w-full" v-model="column.label" placeholder="Label" @update:modelValue="(val) => (column.alias = val)" /> </div> <div v-if="FIELDTYPES.DATE.includes(column.type)" class="space-y-1"> <span class="text-sm font-medium text-gray-700">Date Format</span> <Autocomplete :modelValue="column.granularity" placeholder="Date Format" :options="GRANULARITIES" @update:modelValue="(op) => (column.granularity = op.value)" /> </div> <div class="flex justify-between"> <Button variant="outline" @click="emit('discard')"> Discard </Button> <div class="flex gap-2"> <Button variant="outline" theme="red" @click="emit('remove')">Remove</Button> <Button variant="solid" :disabled="!isValidColumn" @click="emit('save', column)"> Save </Button> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/SimpleColumnEditor.vue
Vue
agpl-3.0
3,060
<script setup> import { DatabaseIcon } from 'lucide-vue-next' import QueryDataSourceSelector from '../QueryDataSourceSelector.vue' import SectionHeader from './SectionHeader.vue' </script> <template> <SectionHeader :icon="DatabaseIcon" title="Data Source" info="Select the data source you want to query." > <QueryDataSourceSelector></QueryDataSourceSelector> </SectionHeader> </template>
2302_79757062/insights
frontend/src/query/visual/SourceSection.vue
Vue
agpl-3.0
400
<script setup> import useDataSource from '@/datasource/useDataSource' import useDataSourceTable from '@/datasource/useDataSourceTable' import { computed, defineProps, inject, reactive, ref, watch } from 'vue' const emit = defineEmits(['save', 'remove', 'discard']) const props = defineProps({ join: Object }) const assistedQuery = inject('assistedQuery') const dataSource = useDataSource(assistedQuery.data_source) !dataSource.tableList.length && dataSource.fetchTables() const activeJoin = reactive({ left_table: {}, left_column: {}, join_type: {}, right_table: {}, right_column: {}, ...props.join, }) const setOptionValue = (option, value) => (option.value = value) setOptionValue(activeJoin.left_table, activeJoin.left_table.table) setOptionValue(activeJoin.left_column, activeJoin.left_column.column) setOptionValue(activeJoin.right_table, activeJoin.right_table.table) setOptionValue(activeJoin.right_column, activeJoin.right_column.column) const joinTypeOptions = computed(() => [ { label: 'Inner Join', value: 'inner' }, { label: 'Left Join', value: 'left' }, ]) const leftTableOptions = computed(() => { const options = [assistedQuery.table] assistedQuery.joins.forEach((join) => { // exclude the current joined table if (join.right_table.table === activeJoin.right_table.table) return // exclude the already added tables if (options.find((o) => o.table === join.right_table.table)) return options.push(join.right_table) }) return options.map((o) => ({ ...o, value: o.table })) }) const rightTableOptions = computed(() => dataSource?.groupedTableOptions || []) const leftColumnOptions = ref(null) const rightColumnOptions = ref(null) watch( () => activeJoin.left_table?.table, async (newLeft, oldLeft) => { if (!newLeft) return if (newLeft === oldLeft) return const leftTable = await useDataSourceTable({ data_source: assistedQuery.data_source, table: newLeft, }) leftColumnOptions.value = leftTable.columns.map((c) => ({ column: c.column, table: c.table, label: c.label, value: c.column, })) if (activeJoin.left_column?.table !== newLeft) { activeJoin.left_column = {} } }, { immediate: true } ) watch( () => activeJoin.right_table?.table, async (newRight, oldRight) => { if (!newRight) return if (newRight === oldRight) return const rightTable = await useDataSourceTable({ data_source: assistedQuery.data_source, table: newRight, }) rightColumnOptions.value = rightTable.columns.map((c) => ({ column: c.column, table: c.table, label: c.label, value: c.column, })) if (activeJoin.right_column?.table !== newRight) { activeJoin.right_column = {} } }, { immediate: true } ) </script> <template> <div class="flex flex-col gap-1 p-4"> <span class="text-sm font-medium text-gray-700">Join</span> <div class="mb-2 flex gap-2"> <div class="flex-1"> <Autocomplete v-model="activeJoin.left_table" :hideSearch="true" :options="leftTableOptions" placeholder="Left Table" /> </div> <div class="flex-shrink-0"> <Autocomplete v-model="activeJoin.join_type" :hide-search="true" :options="joinTypeOptions" placeholder="Join Type" /> </div> <div class="flex-1"> <Autocomplete v-model="activeJoin.right_table" :options="rightTableOptions" placeholder="Right Table" /> </div> </div> <span class="text-sm font-medium text-gray-700">Condition</span> <div class="mb-2 flex gap-2"> <div class="flex-1"> <Autocomplete v-model="activeJoin.left_column" :options="leftColumnOptions" placeholder="Left Column" /> </div> <div class="flex flex-shrink-0 items-center font-mono">=</div> <div class="flex-1"> <Autocomplete v-model="activeJoin.right_column" :options="rightColumnOptions" placeholder="Right Column" /> </div> </div> <div class="flex justify-between"> <Button variant="outline" @click="emit('discard')">Discard</Button> <div class="flex gap-2"> <Button variant="outline" theme="red" @click="emit('remove')">Remove</Button> <Button variant="solid" @click="emit('save', activeJoin)">Save</Button> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/TableJoinEditor.vue
Vue
agpl-3.0
4,223
<script setup> import Autocomplete from '@/components/Controls/Autocomplete.vue' import JoinFullIcon from '@/components/Icons/JoinFullIcon.vue' import JoinInnerIcon from '@/components/Icons/JoinInnerIcon.vue' import JoinLeftIcon from '@/components/Icons/JoinLeftIcon.vue' import JoinRightIcon from '@/components/Icons/JoinRightIcon.vue' import UsePopover from '@/components/UsePopover.vue' import useDataSource from '@/datasource/useDataSource' import { whenever } from '@vueuse/core' import { ExternalLink, GanttChartSquare, Sheet, Table2, X } from 'lucide-vue-next' import { computed, inject, reactive, ref } from 'vue' import { useRouter } from 'vue-router' import SectionHeader from './SectionHeader.vue' import TableJoinEditor from './TableJoinEditor.vue' const assistedQuery = inject('assistedQuery') let dataSource = reactive({}) whenever( () => assistedQuery.data_source, (newVal, oldVal) => { if (!newVal) return if (newVal == oldVal) return dataSource = useDataSource(assistedQuery.data_source) dataSource.fetchTables() }, { immediate: true } ) const joins = computed(() => assistedQuery.joins) const joinRefs = ref([]) const activeJoinIdx = ref(null) function onSaveJoin(newJoin) { assistedQuery.updateJoinAt(activeJoinIdx.value, newJoin) activeJoinIdx.value = null } function onRemoveJoin() { assistedQuery.removeJoinAt(activeJoinIdx.value) activeJoinIdx.value = null } const router = useRouter() function onTableLinkClick(table) { const route = table.startsWith('QRY-') ? router.resolve({ name: 'Query', params: { name: table } }) : router.resolve({ name: 'DataSource', params: { name: assistedQuery.data_source } }) window.open(route.href, '_blank') } </script> <template> <div :key="assistedQuery.data_source" class="space-y-2"> <SectionHeader :icon="Sheet" title="Tables" info="Select the tables you want to extract data from." > <Autocomplete bodyClasses="w-[18rem]" :options="dataSource.groupedTableOptions" @update:modelValue="$event && assistedQuery.addTable($event)" > <template #target="{ togglePopover }"> <Button variant="outline" icon="plus" @click="togglePopover"></Button> </template> </Autocomplete> </SectionHeader> <div class="space-y-2"> <div v-if="assistedQuery.table.table" class="group relative flex h-8 cursor-pointer items-center justify-between overflow-hidden rounded border border-gray-300 bg-white px-2 pl-2.5 hover:shadow" > <div class="absolute left-0 h-full w-1 flex-shrink-0 bg-orange-500"></div> <div class="flex flex-1 items-center gap-1 overflow-hidden"> <component :is=" assistedQuery.table.table.startsWith('QRY-') ? GanttChartSquare : Table2 " class="h-4 w-4 flex-shrink-0 text-gray-600" /> <div class="flex flex-1 items-center gap-1 overflow-hidden"> <span class="truncate">{{ assistedQuery.table.label }}</span> <ExternalLink class="h-3 w-3 text-gray-600 opacity-0 transition-all hover:text-gray-800 group-hover:opacity-100" @click.prevent.stop="onTableLinkClick(assistedQuery.table.table)" /> </div> </div> <div class="ml-2 flex items-center space-x-2"> <X class="invisible h-4 w-4 text-gray-600 transition-all hover:text-gray-800 group-hover:visible" @click="assistedQuery.resetMainTable()" /> </div> </div> <div ref="joinRefs" v-for="(join, idx) in joins" :key="join.right_table.table" class="group relative flex h-8 cursor-pointer items-center justify-between overflow-hidden rounded border border-gray-300 bg-white px-2 pl-2.5 hover:shadow" :class=" idx === activeJoinIdx ? 'border-gray-500 bg-white shadow-sm ring-1 ring-gray-400' : '' " @click="activeJoinIdx = idx" > <div class="absolute left-0 h-full w-1 flex-shrink-0 bg-orange-500"></div> <div class="flex flex-1 items-center gap-1"> <component :is="join.right_table.table.startsWith('QRY-') ? GanttChartSquare : Table2" class="h-4 w-4 text-gray-600" /> <span class="truncate">{{ join.right_table.label }}</span> <ExternalLink class="h-3 w-3 text-gray-600 opacity-0 transition-all hover:text-gray-800 group-hover:opacity-100" @click.prevent.stop="onTableLinkClick(join.right_table.table)" /> </div> <JoinLeftIcon v-if="join.join_type.value == 'left'" class="text-gray-600" /> <JoinRightIcon v-if="join.join_type.value == 'right'" class="text-gray-600" /> <JoinInnerIcon v-if="join.join_type.value == 'inner'" class="text-gray-600" /> <JoinFullIcon v-if="join.join_type.value == 'full'" class="text-gray-600" /> </div> </div> </div> <UsePopover v-if="joinRefs?.[activeJoinIdx]" :key="activeJoinIdx" :show="activeJoinIdx !== null" @update:show="activeJoinIdx = null" :target-element="joinRefs[activeJoinIdx]" placement="right-start" > <div class="min-w-[24rem] rounded bg-white text-base shadow-2xl"> <TableJoinEditor :join="joins[activeJoinIdx]" @save="onSaveJoin($event)" @discard="activeJoinIdx = null" @remove="onRemoveJoin" /> </div> </UsePopover> </template>
2302_79757062/insights
frontend/src/query/visual/TableSection.vue
Vue
agpl-3.0
5,168
<script setup> import { isEmptyObj } from '@/utils' import { computed, defineProps, inject, reactive } from 'vue' import CumulativeSumTransformFields from './CumulativeSumTransformFields.vue' import PivotTransformFields from './PivotTransformFields.vue' import { NEW_TRANSFORM } from './constants' const emit = defineEmits(['save', 'discard', 'remove']) const props = defineProps({ transform: Object }) const assistedQuery = inject('assistedQuery') const query = inject('query') const activeTransform = reactive({ ...NEW_TRANSFORM, ...props.transform, }) if (!activeTransform.type) activeTransform.type = 'Pivot' if (!activeTransform.options) activeTransform.options = {} const transformTypes = [ { label: 'Select Transform Type', value: '', disabled: true }, { label: 'Pivot', value: 'Pivot' }, // { label: 'Unpivot', value: 'Unpivot' }, // { label: 'Transpose', value: 'Transpose' }, { label: 'Cumulative Sum', value: 'CumulativeSum' }, ] const isValidTransform = computed( () => activeTransform?.type && !isEmptyObj(activeTransform.options) ) </script> <template> <div class="flex flex-col gap-4 p-4"> <div class="space-y-1"> <span class="text-sm font-medium text-gray-700">Type</span> <FormControl type="select" v-model="activeTransform.type" placeholder="Select Transform Type" :options="transformTypes" @update:modelValue="activeTransform.options = {}" /> </div> <PivotTransformFields v-if="activeTransform.type == 'Pivot'" v-model:transformOptions="activeTransform.options" ></PivotTransformFields> <CumulativeSumTransformFields v-else-if="activeTransform.type == 'CumulativeSum'" v-model:transformOptions="activeTransform.options" ></CumulativeSumTransformFields> <div class="flex justify-between"> <Button variant="outline" @click="emit(isValidTransform ? 'discard' : 'remove')"> Discard </Button> <div class="flex gap-2"> <Button variant="outline" theme="red" @click="emit('remove')">Remove</Button> <Button variant="solid" :disabled="!isValidTransform" @click="emit('save', activeTransform)" > Save </Button> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/TransformEditor.vue
Vue
agpl-3.0
2,178
<script setup> import { isEmptyObj } from '@/utils' import { CornerLeftDown, CornerRightUp, Crop, Sigma, X } from 'lucide-vue-next' defineEmits(['edit', 'remove']) defineProps(['transform', 'isActive']) const transformTypeToIcon = { Pivot: CornerRightUp, Unpivot: CornerLeftDown, Transpose: Crop, CumulativeSum: Sigma, } const transformTypeToLabel = { Pivot: 'Convert Row to Column', Unpivot: 'Convert Column to Row', Transpose: 'Transpose', CumulativeSum: 'Cumulative Sum', } function isValidTransform(transform) { return transform?.type && !isEmptyObj(transform.options) } </script> <template> <div class="group flex h-8 w-full cursor-pointer items-center justify-between rounded border border-gray-300 bg-white px-2 hover:shadow" :class="isActive ? 'border-gray-500 bg-white shadow-sm ring-1 ring-gray-400' : ''" @click.prevent.stop="$emit('edit')" > <div class="flex w-full items-center overflow-hidden"> <div class="flex w-full space-x-2 truncate" v-if="isValidTransform(transform)"> <component :is="transformTypeToIcon[transform.type]" class="h-4 w-4 text-gray-600" /> <span class="truncate">{{ transformTypeToLabel[transform.type] }}</span> </div> <div v-else class="text-gray-600">Select a transform</div> </div> <div class="flex items-center space-x-2"> <X class="invisible h-4 w-4 text-gray-600 transition-all hover:text-gray-800 group-hover:visible" @click.prevent.stop="$emit('remove')" /> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/TransformListItem.vue
Vue
agpl-3.0
1,503
<script setup> import { Option } from 'lucide-vue-next' import { inject, ref } from 'vue' import SectionHeader from './SectionHeader.vue' import TransformEditor from './TransformEditor.vue' import TransformListItem from './TransformListItem.vue' const query = inject('query') const assistedQuery = inject('assistedQuery') const activeTransformIdx = ref(null) async function onAddTransform() { assistedQuery.addTransform() setTimeout(() => { activeTransformIdx.value = assistedQuery.transforms.length - 1 }, 500) } function onRemoveTransform() { assistedQuery.removeTransformAt(activeTransformIdx.value) activeTransformIdx.value = null } function onSaveTransform(transform) { assistedQuery.updateTransformAt(activeTransformIdx.value, transform) activeTransformIdx.value = null } </script> <template> <div class="space-y-2"> <SectionHeader title="Transform" :icon="Option" info="Apply transforms to the results."> <Button variant="outline" icon="plus" @click.prevent.stop="onAddTransform"></Button> </SectionHeader> <div class="space-y-2" v-if="assistedQuery.transforms.length"> <template v-for="(transform, idx) in assistedQuery.transforms" :key="idx"> <Popover :show="activeTransformIdx === idx" @close="activeTransformIdx === idx ? (activeTransformIdx = null) : null" placement="right-start" > <template #target="{ togglePopover }"> <TransformListItem :transform="transform" :isActive="activeTransformIdx === idx" @edit="activeTransformIdx = idx" @remove="onRemoveTransform" /> </template> <template #body> <div v-if="activeTransformIdx === idx" class="ml-2 min-w-[20rem] rounded-lg border border-gray-100 bg-white text-base shadow-xl transition-all" > <TransformEditor :transform="assistedQuery.transforms[activeTransformIdx]" @discard="activeTransformIdx = null" @remove="onRemoveTransform" @save="onSaveTransform" /> </div> </template> </Popover> </template> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/TransformSection.vue
Vue
agpl-3.0
2,086
<script setup> import Tabs from '@/components/Tabs.vue' import { inject, provide, ref } from 'vue' import ChartOptions from '../ChartOptions.vue' import ChartSection from '../ChartSection.vue' import ResultSection from '../ResultSection.vue' import ColumnSection from './ColumnSection.vue' import FilterSection from './FilterSection.vue' import LimitSection from './LimitSection.vue' import ResultColumnActions from './ResultColumnActions.vue' import ResultFooter from './ResultFooter.vue' import SourceSection from './SourceSection.vue' import TableSection from './TableSection.vue' import TransformSection from './TransformSection.vue' import useAssistedQuery from './useAssistedQuery' const activeTab = ref('Build') const tabs = ['Build', 'Visualize'] const query = inject('query') const assistedQuery = useAssistedQuery(query) provide('assistedQuery', assistedQuery) const hideChart = ref(false) </script> <template> <div class="relative flex h-full w-full flex-row-reverse overflow-hidden"> <div class="flex h-full w-full flex-col overflow-hidden p-4 pt-0 pr-0" v-auto-animate> <div v-if="!hideChart" class="flex h-[60%] !max-h-[60%] flex-shrink-0 flex-col overflow-hidden pt-4" > <ChartSection></ChartSection> </div> <div class="my-1.5 mx-auto w-2 rounded-full bg-gray-200 pt-1 transition-all hover:bg-gray-400" :class="hideChart ? 'cursor-s-resize' : 'cursor-n-resize'" @click="hideChart = !hideChart" ></div> <div class="flex flex-1 flex-shrink-0 flex-col overflow-hidden"> <ResultSection> <template #columnActions="{ column }"> <ResultColumnActions :column="column" /> </template> <template #footer> <ResultFooter></ResultFooter> </template> </ResultSection> </div> </div> <div class="relative flex w-[22rem] flex-shrink-0 flex-col overflow-y-auto bg-white px-0.5"> <div class="sticky top-0 z-10 w-full flex-shrink-0 bg-white py-4"> <Tabs v-model="activeTab" class="w-full" :tabs="tabs" /> </div> <div class="flex flex-1 flex-col gap-4 pb-4"> <template v-if="activeTab === 'Build'"> <SourceSection></SourceSection> <hr class="border-gray-200" /> <TableSection></TableSection> <hr class="border-gray-200" /> <FilterSection></FilterSection> <hr class="border-gray-200" /> <ColumnSection></ColumnSection> <hr class="border-gray-200" /> <LimitSection></LimitSection> <hr class="border-gray-200" /> <TransformSection></TransformSection> </template> <template v-if="activeTab === 'Visualize'"> <ChartOptions></ChartOptions> </template> </div> </div> </div> </template>
2302_79757062/insights
frontend/src/query/visual/VisualQueryBuilder.vue
Vue
agpl-3.0
2,664
export const NEW_COLUMN = { table: '', column: '', label: '', type: '', alias: '', order: '', granularity: '', aggregation: '', format: {}, expression: {}, } export const NEW_FILTER = { column: { ...NEW_COLUMN }, operator: {}, value: {}, expression: {}, } export const NEW_JOIN = { join_type: { label: 'Inner Join', value: 'inner' }, left_table: {}, left_column: {}, right_table: {}, right_column: {}, } export const NEW_TRANSFORM = { type: '', options: {}, }
2302_79757062/insights
frontend/src/query/visual/constants.js
JavaScript
agpl-3.0
484
export const WARN_UNABLE_TO_INFER_JOIN = (table1, table2) => ({ variant: 'warning', title: 'Unable to find a relationship', message: `Please add a relationship between ${table1} and ${table2} manually`, }) export const ERROR_CANNOT_ADD_SELF_AS_TABLE = () => ({ variant: 'error', title: 'Cannot add self as table', message: `Please select a different table`, }) export const ERROR_UNABLE_TO_RESET_MAIN_TABLE = () => ({ variant: 'error', title: 'Unable to reset main table', message: 'Please remove all columns and joins before resetting the main table', })
2302_79757062/insights
frontend/src/query/visual/messages.js
JavaScript
agpl-3.0
565
import { areDeeplyEqual, makeColumnOption, run_doc_method } from '@/utils' import { createToast } from '@/utils/toasts' import { watchDebounced } from '@vueuse/core' import { debounce } from 'frappe-ui' import { computed, onMounted, reactive } from 'vue' import { NEW_COLUMN, NEW_FILTER, NEW_JOIN } from './constants' import { ERROR_CANNOT_ADD_SELF_AS_TABLE, ERROR_UNABLE_TO_RESET_MAIN_TABLE, WARN_UNABLE_TO_INFER_JOIN, } from './messages' import { inferJoinForTable, inferJoinsFromColumns, isTableAlreadyAdded, makeNewColumn, sanitizeQueryJSON, } from './utils' export default function useAssistedQuery(query) { const state = reactive({ data_source: computed(() => query.doc.data_source), table: {}, joins: [], columns: [], filters: [], calculations: [], dimensions: [], measures: [], orders: [], limit: 100, transforms: computed(() => [...query.doc.transforms]), joinAssistEnabled: true, columnOptions: [], groupedColumnOptions: [], setDataSource, addTable, resetMainTable, removeJoinAt, updateJoinAt, addColumns, removeColumnAt, updateColumnAt, moveColumn, addFilter, removeFilterAt, updateFilterAt, setOrderBy, setLimit, addTransform, removeTransformAt, updateTransformAt, fetchColumnOptions: debounce(fetchColumnOptions, 500), }) onMounted(() => { const queryJSON = sanitizeQueryJSON(query.doc.json) state.table = queryJSON.table state.joins = queryJSON.joins state.columns = queryJSON.columns state.filters = queryJSON.filters state.calculations = queryJSON.calculations state.dimensions = queryJSON.dimensions state.measures = queryJSON.measures state.orders = queryJSON.orders state.limit = queryJSON.limit }) watchDebounced( () => { return { table: state.table, joins: state.joins, columns: state.columns, filters: state.filters, calculations: state.calculations, dimensions: state.dimensions, measures: state.measures, orders: state.orders, limit: state.limit, } }, (newQuery, oldQuery) => { const tablesChanged = hasTablesChanged(newQuery, oldQuery) query.updateQuery(newQuery).then(({ query_updated }) => { query_updated && tablesChanged && fetchColumnOptions() }) }, { deep: true, debounce: 500 } ) async function fetchColumnOptions(search_txt = '') { if (!state.data_source) return const search_txt_lower = search_txt.toLowerCase() const res = await run_doc_method('fetch_related_tables_columns', query.doc, { search_txt: search_txt_lower, }) state.columnOptions = res.message.map(makeColumnOption) state.groupedColumnOptions = makeGroupedColumnOptions(res.message) } async function setDataSource(dataSource) { if (!dataSource || query.doc.data_source) return return query.changeDataSource(dataSource) } async function addTable(newTable) { if (!newTable?.table) return if (newTable.table === query.doc.name) { return createToast(ERROR_CANNOT_ADD_SELF_AS_TABLE()) } const mainTable = state.table if (!mainTable?.table) { state.table = { table: newTable.table, label: newTable.label } return } if (isTableAlreadyAdded(state, newTable)) return const join = await inferJoinForTable(newTable, state) if (join) { return state.joins.push(join) } createToast(WARN_UNABLE_TO_INFER_JOIN(mainTable.label, newTable.label)) state.joins.push({ ...NEW_JOIN, left_table: { table: mainTable.table, label: mainTable.label }, right_table: { table: newTable.table, label: newTable.label }, }) } function resetMainTable() { if (state.joins.length || state.columns.length) { createToast(ERROR_UNABLE_TO_RESET_MAIN_TABLE()) return } state.table = {} } function removeJoinAt(joinIdx) { state.joins.splice(joinIdx, 1) } function updateJoinAt(joinIdx, newJoin) { state.joins.splice(joinIdx, 1, newJoin) } function addColumns(addedColumns) { const newColumns = addedColumns.map(makeNewColumn) state.columns.push(...newColumns) state.joinAssistEnabled && inferJoins() } function removeColumnAt(removedColumnIdx) { state.columns.splice(removedColumnIdx, 1) } function updateColumnAt(updatedColumnIdx, newColumn) { state.columns.splice(updatedColumnIdx, 1, newColumn) state.joinAssistEnabled && inferJoins() } function moveColumn(oldIndex, newIndex) { state.columns.splice(newIndex, 0, state.columns.splice(oldIndex, 1)[0]) } function addFilter() { state.filters.push({ ...NEW_FILTER }) } function removeFilterAt(removedFilterIdx) { state.filters.splice(removedFilterIdx, 1) } function updateFilterAt(updatedFilterIdx, newFilter) { state.filters.splice(updatedFilterIdx, 1, newFilter) state.joinAssistEnabled && inferJoins() } function setOrderBy(column, order) { state.columns.some((c) => { if (c.label === column) { c.order = order return true } }) } function setLimit(limit) { if (limit === state.limit) return state.limit = limit } function addTransform() { state.transforms.push({ type: '', options: {} }) query.updateTransforms(state.transforms) } function removeTransformAt(removedTransformIdx) { state.transforms.splice(removedTransformIdx, 1) query.updateTransforms(state.transforms) } function updateTransformAt(updatedTransformIdx, newTransform) { state.transforms.splice(updatedTransformIdx, 1, newTransform) query.updateTransforms(state.transforms) } async function inferJoins() { const joins = await inferJoinsFromColumns(state) const newJoins = joins.filter((join) => { return !state.joins.some( (j) => j.left_table.table === join.left_table.table && j.right_table.table === join.right_table.table ) }) state.joins.push(...newJoins) } return state } function makeGroupedColumnOptions(options) { const columnsByTable = options.reduce((acc, column) => { if (!acc[column.table_label]) acc[column.table_label] = [] acc[column.table_label].push(column) return acc }, {}) return Object.entries(columnsByTable).map(([table_label, columns]) => { if (!columns.length) return { group: table_label, items: [] } columns.splice(0, 0, { ...NEW_COLUMN, table: columns[0].table, column: 'count', type: 'Integer', label: 'Count of Rows', alias: 'Count of Rows', aggregation: 'count', }) return { group: table_label, items: columns.map(makeColumnOption), } }) } export function hasTablesChanged(newJson, oldJson) { if (!oldJson) return true const newTables = getSelectedTables(newJson) const oldTables = getSelectedTables(oldJson) return !areDeeplyEqual(newTables, oldTables) } export function getSelectedTables(queryJson) { if (!queryJson) return [] const tables = [queryJson.table.table, ...queryJson.joins.map((join) => join.right_table.table)] return tables.filter((table) => table) }
2302_79757062/insights
frontend/src/query/visual/useAssistedQuery.js
JavaScript
agpl-3.0
6,815
import { FIELDTYPES } from '@/utils' import { call } from 'frappe-ui' import { NEW_COLUMN, NEW_JOIN } from './constants' export function makeNewColumn(newColumn) { const isDate = FIELDTYPES.DATE.includes(newColumn.type) const isNumber = FIELDTYPES.NUMBER.includes(newColumn.type) return { ...NEW_COLUMN, ...newColumn, granularity: newColumn.granularity || (isDate ? 'Month' : ''), aggregation: newColumn.aggregation || (isNumber ? 'sum' : ''), } } export async function inferJoinsFromColumns(assistedQuery) { const newJoins = [] const data_source = assistedQuery.data_source const mainTable = assistedQuery.table if (!mainTable.table) return newJoins const columns = [ ...assistedQuery.columns.filter((c) => c.table && c.column), ...assistedQuery.filters.map((f) => f.column).filter((c) => c.table && c.column), ] const columnByTable = columns.reduce((acc, column) => { acc[column.table] = column return acc }, {}) for (const column of Object.values(columnByTable)) { if (column.table == mainTable.table) continue // check if the column has a relation with main table, if so add the join const relation = await getRelation(mainTable.table, column.table, data_source) if (relation) { newJoins.push(makeJoinFromRelation(relation)) continue } // check if the column has a relation with any other table, if so add the join for (const table of Object.keys(columnByTable)) { if (table === column.table) continue if (table === mainTable.table) continue const relation = await getRelation(table, column.table, data_source) if (relation) { newJoins.push(makeJoinFromRelation(relation)) break } } } return newJoins } function makeJoinFromRelation(relation) { return { ...NEW_JOIN, left_table: { table: relation.primary_table, label: relation.primary_table_label, }, left_column: { table: relation.primary_table, column: relation.primary_column, }, right_table: { table: relation.foreign_table, label: relation.foreign_table_label, }, right_column: { table: relation.foreign_table, column: relation.foreign_column, }, } } const relations_cache = {} async function getRelation(tableOne, tableTwo, data_source) { const cache_key = `${data_source}-${tableOne}-${tableTwo}` if (relations_cache[cache_key]) { return relations_cache[cache_key] } relations_cache[cache_key] = await call('insights.api.data_sources.get_relation', { data_source: data_source, table_one: tableOne, table_two: tableTwo, }) return relations_cache[cache_key] } export async function inferJoinForTable(newTable, assistedQuery) { const mainTable = assistedQuery.table const data_source = assistedQuery.data_source if (!mainTable.table) return null const relation = await getRelation(mainTable.table, newTable.table, data_source) if (relation) return makeJoinFromRelation(relation) // find a relation with any other joined table let relationWithJoinedTable = null for (const join of assistedQuery.joins) { const relation = await getRelation(join.right_table.table, newTable.table, data_source) if (relation) { return makeJoinFromRelation(relation) } } return null } export function isTableAlreadyAdded(assistedQuery, newTable) { const table = assistedQuery.table if (table.table === newTable.table) return true return assistedQuery.joins.some((join) => join.right_table.table === newTable.table) } export function sanitizeQueryJSON(queryJson) { // backward compatibility with old json if (queryJson.measures.length || queryJson.dimensions.length) { // copy measures and dimensions to columns queryJson.measures.forEach((m) => { if (!queryJson.columns.find((col) => col.label === m.label)) { queryJson.columns.push(m) } }) queryJson.dimensions.forEach((d) => { if (!queryJson.columns.find((col) => col.label === d.label)) { queryJson.columns.push(d) } }) } if (queryJson.orders.length) { // set `order` property on columns queryJson.columns.forEach((c) => { const order = queryJson.orders.find((o) => o.label === c.label) if (order) c.order = order.order }) } if (queryJson.filters.length) { // TODO: // some filters have column set as expression // we need to convert that into column expression object } if (!queryJson.limit) queryJson.limit = 100 return { ...queryJson } }
2302_79757062/insights
frontend/src/query/visual/utils.js
JavaScript
agpl-3.0
4,361