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 lang="ts"> import { FIELDTYPES } from '../../helpers/constants' import { computed } from 'vue' import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' import { NumberChartConfig } from '../../types/chart.types' import { DimensionOption, MeasureOption } from './ChartConfigForm.vue' const props = defineProps<{ dimensions: DimensionOption[] measures: MeasureOption[] }>() const config = defineModel<NumberChartConfig>({ required: true, default: () => ({ number_columns: [], comparison: false, sparkline: false, }), }) const date_dimensions = computed(() => props.dimensions.filter((d) => FIELDTYPES.DATE.includes(d.data_type)) ) </script> <template> <InlineFormControlLabel label="Number"> <Autocomplete :multiple="true" :showFooter="true" :options="props.measures" :modelValue="config.number_columns?.map((c) => c.measure_name)" @update:modelValue="config.number_columns = $event" /> </InlineFormControlLabel> <InlineFormControlLabel label="Date"> <Autocomplete :showFooter="true" :options="date_dimensions" :modelValue="config.date_column?.column_name" @update:modelValue="config.date_column = $event" /> </InlineFormControlLabel> <InlineFormControlLabel label="Prefix"> <FormControl v-model="config.prefix" /> </InlineFormControlLabel> <InlineFormControlLabel label="Suffix"> <FormControl v-model="config.suffix" /> </InlineFormControlLabel> <InlineFormControlLabel label="Decimal"> <FormControl v-model="config.decimal" type="number" /> </InlineFormControlLabel> <InlineFormControlLabel label="Show short numbers" class="!w-1/2"> <Switch v-model="config.shorten_numbers" :tabs="[ { label: 'Yes', value: true, default: true }, { label: 'No', value: false }, ]" /> </InlineFormControlLabel> <InlineFormControlLabel v-if="config.date_column" label="Show comparison" class="!w-1/2"> <Switch v-model="config.comparison" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> <InlineFormControlLabel v-if="config.comparison" label="Negative is better" class="!w-1/2"> <Switch v-model="config.negative_is_better" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> <InlineFormControlLabel v-if="config.date_column" label="Show sparkline" class="!w-1/2"> <Switch v-model="config.sparkline" :tabs="[ { label: 'Yes', value: true }, { label: 'No', value: false, default: true }, ]" /> </InlineFormControlLabel> </template>
2302_79757062/insights
frontend/src2/charts/components/NumberChartConfigForm.vue
Vue
agpl-3.0
2,647
<script setup lang="ts"> import { graphic } from 'echarts/core' import { getColors } from '../colors' import BaseChart from './BaseChart.vue' const props = defineProps<{ dates: string[]; values: number[] }>() const color = getColors()[0] const gradient = new graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: color }, { offset: 1, color: '#fff' }, ]) </script> <template> <BaseChart :options="{ animation: true, animationDuration: 700, grid: { top: '20%', left: 0, right: 0, bottom: 0, }, xAxis: { show: false, type: 'category', data: props.dates, boundaryGap: false, splitLine: false, axisLabel: false, }, yAxis: { show: false, type: 'value', splitLine: false, axisLabel: false, }, series: [ { data: props.values, type: 'line', showSymbol: false, color: color, areaStyle: { color: gradient, opacity: 0.3, }, }, ], }" /> </template>
2302_79757062/insights
frontend/src2/charts/components/Sparkline.vue
Vue
agpl-3.0
987
<script setup lang="ts"> import { computed } from 'vue' import { TableChartConfig } from '../../types/chart.types' import { Chart } from '../chart' import DataTable from '../../components/DataTable.vue' import ChartBuilderTableColumn from './ChartBuilderTableColumn.vue' import ChartTitle from './ChartTitle.vue' const props = defineProps<{ chart: Chart }>() const title = computed(() => props.chart.doc.title) const config = computed(() => props.chart.doc.config as TableChartConfig) </script> <template> <div class="flex h-full w-full flex-col overflow-hidden rounded bg-white shadow"> <ChartTitle v-if="title" :title="title" /> <DataTable v-if="chart.doc.chart_type == 'Table'" class="w-full flex-1 overflow-hidden border-t" :columns="chart.dataQuery.result.columns" :rows="chart.dataQuery.result.formattedRows" > <template #column-header="{ column }"> <ChartBuilderTableColumn :chart="chart" :column="column" /> </template> </DataTable> </div> </template>
2302_79757062/insights
frontend/src2/charts/components/TableChart.vue
Vue
agpl-3.0
995
<script setup lang="ts"> import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' import { TableChartConfig } from '../../types/chart.types' import { DimensionOption, MeasureOption } from './ChartConfigForm.vue' const props = defineProps<{ dimensions: DimensionOption[] measures: MeasureOption[] }>() const config = defineModel<TableChartConfig>({ required: true, default: () => ({ rows: [], columns: [], values: [], }), }) </script> <template> <InlineFormControlLabel label="Rows"> <Autocomplete :multiple="true" :options="props.dimensions" :modelValue="config.rows" @update:modelValue="config.rows = $event" /> </InlineFormControlLabel> <InlineFormControlLabel label="Columns"> <Autocomplete :multiple="true" :options="props.dimensions" :modelValue="config.columns" @update:modelValue="config.columns = $event" /> </InlineFormControlLabel> <InlineFormControlLabel label="Values"> <Autocomplete :multiple="true" :options="props.measures" :modelValue="config.values" @update:modelValue="config.values = $event" /> </InlineFormControlLabel> </template>
2302_79757062/insights
frontend/src2/charts/components/TableChartConfigForm.vue
Vue
agpl-3.0
1,144
import { graphic } from 'echarts/core' import { formatNumber, getShortNumber } from '../helpers' import { FIELDTYPES } from '../helpers/constants' import { BarChartConfig, LineChartConfig } from '../types/chart.types' import { ColumnDataType, QueryResultColumn, QueryResultRow } from '../types/query.types' import { Chart } from './chart' import { getColors } from './colors' // eslint-disable-next-line no-unused-vars export function guessChart(columns: QueryResultColumn[], rows: QueryResultRow[]) { // categorize the columns into dimensions and measures and then into discrete and continuous const dimensions = columns.filter((c) => FIELDTYPES.DIMENSION.includes(c.type)) const discreteDimensions = dimensions.filter((c) => FIELDTYPES.DISCRETE.includes(c.type)) const continuousDimensions = dimensions.filter((c) => FIELDTYPES.CONTINUOUS.includes(c.type)) const measures = columns.filter((c) => FIELDTYPES.MEASURE.includes(c.type)) const discreteMeasures = measures.filter((c) => FIELDTYPES.DISCRETE.includes(c.type)) const continuousMeasures = measures.filter((c) => FIELDTYPES.CONTINUOUS.includes(c.type)) if (measures.length === 1 && dimensions.length === 0) return 'number' if (discreteDimensions.length === 1 && measures.length) return 'bar' if (continuousDimensions.length === 1 && measures.length) return 'line' if (discreteDimensions.length > 1 && measures.length) return 'table' } export function getLineChartOptions(chart: Chart) { const _config = chart.doc.config as LineChartConfig const _columns = chart.dataQuery.result.columns const _rows = chart.dataQuery.result.rows const measures = _columns.filter((c) => FIELDTYPES.MEASURE.includes(c.type)) const show_legend = measures.length > 1 const xAxis = getXAxis({ column_type: _config.x_axis.data_type }) const leftYAxis = getYAxis() const rightYAxis = getYAxis({ is_secondary: true }) const yAxis = !_config.y2_axis ? [leftYAxis] : [leftYAxis, rightYAxis] const sortedRows = FIELDTYPES.DATE.includes(_config.x_axis.data_type) ? _rows.sort((a, b) => { const a_date = new Date(a[_config.x_axis.column_name]) const b_date = new Date(b[_config.x_axis.column_name]) return a_date.getTime() - b_date.getTime() }) : _rows const getSeriesData = (column: string) => sortedRows.map((r) => { const x_value = r[_config.x_axis.column_name] const y_value = r[column] return [x_value, y_value] }) const colors = getColors() return { animation: true, animationDuration: 700, grid: getGrid({ show_legend }), colors, xAxis, yAxis, series: measures.map((c, idx) => { const is_right_axis = _config.y2_axis?.some((y) => c.name.includes(y.measure_name)) const type = is_right_axis ? _config.y2_axis_type : 'line' return { type, name: c.name, data: getSeriesData(c.name), emphasis: { focus: 'series' }, yAxisIndex: is_right_axis ? 1 : 0, smooth: _config.smooth ? 0.4 : false, smoothMonotone: 'x', showSymbol: _config.show_data_points || _config.show_data_labels, label: { fontSize: 11, show: _config.show_data_labels, position: idx === measures.length - 1 ? 'top' : 'inside', formatter: (params: any) => { return getShortNumber(params.value?.[1], 1) }, }, labelLayout: { hideOverlap: true }, areaStyle: _config.show_area ? { color: new graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: colors[idx] }, { offset: 1, color: '#fff' }, ]), opacity: 0.2, } : undefined, } }), tooltip: getTooltip(), legend: getLegend(show_legend), } } export function getBarChartOptions(chart: Chart) { const _config = chart.doc.config as BarChartConfig const _columns = chart.dataQuery.result.columns const _rows = chart.dataQuery.result.rows const measures = _columns.filter((c) => FIELDTYPES.MEASURE.includes(c.type)) const total_per_x_value = _rows.reduce((acc, row) => { const x_value = row[_config.x_axis.column_name] if (!acc[x_value]) acc[x_value] = 0 measures.forEach((m) => (acc[x_value] += row[m.name])) return acc }, {} as Record<string, number>) const show_legend = measures.length > 1 const xAxisValues = _rows.map((r) => r[_config.x_axis.column_name]) const xAxis = getXAxis({ values: _config.swap_axes ? xAxisValues.reverse() : xAxisValues, column_type: _config.x_axis.data_type, }) const leftYAxis = getYAxis({ normalized: _config.normalize }) const rightYAxis = getYAxis({ is_secondary: true }) const yAxis = !_config.y2_axis ? [leftYAxis] : [leftYAxis, rightYAxis] const getSeriesData = (column: string) => _rows.map((r) => { const x_value = r[_config.x_axis.column_name] const y_value = r[column] if (!_config.normalize) { return _config.swap_axes ? [y_value, x_value] : [x_value, y_value] } const total = total_per_x_value[x_value] const normalized_value = total ? (y_value / total) * 100 : 0 return _config.swap_axes ? [normalized_value, x_value] : [x_value, normalized_value] }) const colors = getColors() return { animation: true, animationDuration: 700, colors: colors, grid: getGrid({ show_legend }), xAxis: _config.swap_axes ? yAxis : xAxis, yAxis: _config.swap_axes ? xAxis : yAxis, series: measures.map((c, idx) => { const is_right_axis = _config.y2_axis?.some((y) => c.name.includes(y.measure_name)) const type = is_right_axis ? _config.y2_axis_type : 'bar' return getSeries({ type, name: c.name, data: getSeriesData(c.name), stack: type === 'bar' && _config.stack, axis_swaped: _config.swap_axes, on_right_axis: is_right_axis, show_data_label: _config.show_data_labels, data_label_position: idx === measures.length - 1 ? 'top' : 'inside', }) }), tooltip: getTooltip(), legend: getLegend(show_legend), } } type XAxisCustomizeOptions = { values?: string[] column_type?: ColumnDataType } function getXAxis(options: XAxisCustomizeOptions = {}) { const xAxisIsDate = options.column_type && FIELDTYPES.DATE.includes(options.column_type) return { type: xAxisIsDate ? 'time' : 'category', data: options.values, z: 2, scale: true, boundaryGap: ['1%', '2%'], splitLine: { show: false }, axisLine: { show: true }, axisTick: { show: false }, } } type YAxisCustomizeOptions = { is_secondary?: boolean normalized?: boolean } function getYAxis(options: YAxisCustomizeOptions = {}) { return { show: true, type: 'value', z: 2, scale: false, alignTicks: true, boundaryGap: ['0%', '1%'], splitLine: { show: true }, axisTick: { show: false }, axisLine: { show: false, onZero: false }, axisLabel: { show: true, hideOverlap: true, margin: 4, formatter: (value: number) => getShortNumber(value, 1), }, min: options.normalized ? 0 : undefined, max: options.normalized ? 100 : undefined, } } type SeriesCustomizationOptions = { type?: 'bar' | 'line' data?: any[] name?: string stack?: boolean axis_swaped?: boolean show_data_label?: boolean data_label_position?: 'inside' | 'top' on_right_axis?: boolean } function getSeries(options: SeriesCustomizationOptions = {}) { return { type: options.type || 'bar', stack: options.stack, name: options.name, data: options.data, label: { show: options.show_data_label, position: options.axis_swaped ? 'right' : options.data_label_position, formatter: (params: any) => { const valueIndex = options.axis_swaped ? 0 : 1 return getShortNumber(params.value?.[valueIndex], 1) }, fontSize: 11, }, labelLayout: { hideOverlap: true }, emphasis: { focus: 'series' }, barMaxWidth: 60, yAxisIndex: options.on_right_axis ? 1 : 0, } } export function getDonutChartOptions(columns: QueryResultColumn[], rows: QueryResultRow[]) { const MAX_SLICES = 10 const data = getDonutChartData(columns, rows, MAX_SLICES) const colors = getColors() return { animation: true, animationDuration: 700, colors: colors, dataset: { source: data }, series: [ { type: 'pie', center: ['50%', '45%'], radius: ['40%', '70%'], labelLine: { show: false }, label: { show: false }, emphasis: { scaleSize: 5, }, }, ], legend: getLegend(), tooltip: { ...getTooltip(), trigger: 'item', }, } } function getDonutChartData( columns: QueryResultColumn[], rows: QueryResultRow[], maxSlices: number ) { // reduce the number of slices to 10 const measureColumn = columns.find((c) => FIELDTYPES.MEASURE.includes(c.type)) if (!measureColumn) { throw new Error('No measure column found') } const labelColumn = columns.find((c) => FIELDTYPES.DIMENSION.includes(c.type)) if (!labelColumn) { throw new Error('No label column found') } const valueByLabel = rows.reduce((acc, row) => { const label = row[labelColumn.name] const value = row[measureColumn.name] if (!acc[label]) acc[label] = 0 acc[label] = acc[label] + value return acc }, {} as Record<string, number>) const sortedLabels = Object.keys(valueByLabel).sort((a, b) => valueByLabel[b] - valueByLabel[a]) const topLabels = sortedLabels.slice(0, maxSlices) const others = sortedLabels.slice(maxSlices) const topData = topLabels.map((label) => [label, valueByLabel[label]]) const othersTotal = others.reduce((acc, label) => acc + valueByLabel[label], 0) if (othersTotal) { topData.push(['Others', othersTotal]) } return topData } function getGrid(options: any = {}) { return { top: 18, left: 30, right: 30, bottom: options.show_legend ? 36 : 22, containLabel: true, } } function getTooltip() { return { trigger: 'axis', confine: true, appendToBody: false, valueFormatter: (value: any) => (isNaN(value) ? value : formatNumber(value)), } } function getLegend(show_legend = true) { return { show: show_legend, icon: 'circle', type: 'scroll', orient: 'horizontal', bottom: 'bottom', itemGap: 16, padding: [10, 30], textStyle: { padding: [0, 0, 0, -4] }, pageIconSize: 10, pageIconColor: '#64748B', pageIconInactiveColor: '#C0CCDA', pageFormatter: '{current}', pageButtonItemGap: 2, } }
2302_79757062/insights
frontend/src2/charts/helpers.ts
TypeScript
agpl-3.0
10,101
<template> <div class="flex h-full flex-col justify-between transition-all duration-300 ease-in-out" :class="isSidebarCollapsed ? 'w-12' : 'w-56'" > <div class="flex flex-col overflow-hidden"> <UserDropdown class="p-2" :isCollapsed="isSidebarCollapsed" /> <div class="flex flex-col overflow-y-auto"> <SidebarLink v-for="link in links" :icon="link.icon" :label="link.label" :to="link.to" :isCollapsed="isSidebarCollapsed" class="mx-2 my-0.5" /> </div> </div> <SidebarLink :label="isSidebarCollapsed ? 'Expand' : 'Collapse'" :isCollapsed="isSidebarCollapsed" @click="isSidebarCollapsed = !isSidebarCollapsed" class="m-2" > <template #icon> <span class="grid h-5 w-6 flex-shrink-0 place-items-center"> <PanelRightOpen class="h-4.5 w-4.5 text-gray-700 duration-300 ease-in-out" :class="{ '[transform:rotateY(180deg)]': isSidebarCollapsed }" stroke-width="1.5" /> </span> </template> </SidebarLink> </div> </template> <script setup lang="ts"> import { Book, Database, PanelRightOpen, ShieldHalf, Users } from 'lucide-vue-next' import { ref } from 'vue' import SidebarLink from './SidebarLink.vue' import UserDropdown from './UserDropdown.vue' const isSidebarCollapsed = ref(false) const links = [ // { // label: 'Dashboards', // icon: LayoutGrid, // to: 'DashboardList', // }, { label: 'Workbooks', icon: Book, to: 'WorkbookList', }, { label: 'Data Sources', icon: Database, to: 'DataSourceList', }, { label: 'Users', icon: Users, to: 'UserList', }, { label: 'Teams', icon: ShieldHalf, to: 'TeamList', }, ] </script>
2302_79757062/insights
frontend/src2/components/AppSidebar.vue
Vue
agpl-3.0
1,672
<template> <Combobox v-model="selectedValue" :multiple="multiple" nullable v-slot="{ open: isComboboxOpen }" > <Popover class="w-full" v-model:show="showOptions" :placement="placement"> <template #target="{ open: openPopover, togglePopover, close: closePopover }"> <slot name="target" v-bind="{ open: openPopover, close: closePopover, togglePopover, isOpen: isComboboxOpen, }" > <div class="w-full space-y-1.5"> <label v-if="$props.label" class="block text-xs text-gray-600"> {{ $props.label }} </label> <button class="flex h-7 w-full items-center justify-between gap-2 rounded bg-gray-100 py-1 px-2 transition-colors hover:bg-gray-200 focus:ring-2 focus:ring-gray-400" :class="[isComboboxOpen ? 'bg-gray-200' : '', $props.buttonClasses]" @click="() => togglePopover()" > <div class="flex flex-1 items-center gap-2 overflow-hidden"> <slot name="prefix" /> <span v-if="selectedValue" class="flex-1 truncate text-left text-base leading-5" > {{ displayValue(selectedValue) }} </span> <span v-else class="text-base leading-5 text-gray-600"> {{ placeholder || '' }} </span> <slot name="suffix" /> </div> <FeatherIcon v-show="!$props.loading" name="chevron-down" class="h-4 w-4 text-gray-600" aria-hidden="true" /> <LoadingIndicator class="h-4 w-4 text-gray-600" v-show="$props.loading" /> </button> </div> </slot> </template> <template #body="{ isOpen, togglePopover }"> <div v-show="isOpen"> <div class="relative mt-1 overflow-hidden rounded-lg bg-white text-base shadow-2xl" :class="bodyClasses" > <ComboboxOptions class="flex max-h-[15rem] flex-col overflow-hidden p-1.5" static > <div v-if="!hideSearch" class="relative mb-1 w-full flex-shrink-0"> <ComboboxInput ref="searchInput" class="form-input w-full" type="text" :value="query" @change="query = $event.target.value" autocomplete="off" placeholder="Search" /> <button class="absolute right-0 inline-flex h-7 w-7 items-center justify-center" @click="selectedValue = null" > <FeatherIcon name="x" class="w-4" /> </button> </div> <div class="w-full flex-1 overflow-y-auto"> <div v-for="group in groups" :key="group.key" v-show="group.items.length > 0" > <div v-if="group.group && !group.hideLabel" class="sticky top-0 truncate bg-white px-2.5 py-1.5 text-sm font-medium text-gray-600" > {{ group.group }} </div> <ComboboxOption as="template" v-for="(option, idx) in group.items.slice(0, 50)" :key="option?.value || idx" :value="option" v-slot="{ active, selected }" > <li :class="[ 'flex h-7 cursor-pointer items-center justify-between rounded px-2.5 text-base', { 'bg-gray-100': active }, ]" > <div class="flex flex-1 items-center gap-2 overflow-hidden" > <div v-if="$slots['item-prefix'] || $props.multiple" class="flex-shrink-0" > <slot name="item-prefix" v-bind="{ active, selected, option }" > <Square v-show="!isOptionSelected(option)" class="h-4 w-4 text-gray-700" /> <CheckSquare v-show="isOptionSelected(option)" class="h-4 w-4 text-gray-700" /> </slot> </div> <span class="flex-1 truncate"> {{ getLabel(option) }} </span> </div> <div v-if="$slots['item-suffix'] || option?.description" class="ml-2 flex-shrink-0" > <slot name="item-suffix" v-bind="{ active, selected, option }" > <div v-if="option?.description" class="text-sm text-gray-600" > {{ option.description }} </div> </slot> </div> </li> </ComboboxOption> </div> </div> <li v-if="groups.length == 0" class="rounded-md px-2.5 py-1.5 text-base text-gray-600" > No results found </li> </ComboboxOptions> <div v-if="$slots.footer || showFooter || multiple" class="border-t p-1"> <slot name="footer" v-bind="{ togglePopover }"> <div v-if="multiple" class="flex items-center justify-end"> <Button v-if="!areAllOptionsSelected" label="Select All" @click.stop="selectAll" /> <Button v-if="areAllOptionsSelected" label="Clear All" @click.stop="clearAll" /> </div> <div v-else class="flex items-center justify-end"> <Button label="Clear" @click.stop="selectedValue = null" /> </div> </slot> </div> </div> </div> </template> </Popover> </Combobox> </template> <script> import { Combobox, ComboboxButton, ComboboxInput, ComboboxOption, ComboboxOptions, } from '@headlessui/vue' import { LoadingIndicator } from 'frappe-ui' import { CheckSquare, Square } from 'lucide-vue-next' import { nextTick } from 'vue' import { fuzzySearch } from '../helpers' import Popover from './Popover.vue' export default { name: 'Autocomplete', props: [ 'label', 'modelValue', 'options', 'placeholder', 'bodyClasses', 'multiple', 'loading', 'hideSearch', 'autoFocus', 'placement', 'showFooter', 'buttonClasses', ], emits: ['update:modelValue', 'update:query', 'change'], components: { Popover, Combobox, ComboboxInput, ComboboxOptions, ComboboxOption, ComboboxButton, CheckSquare, Square, }, expose: ['togglePopover'], data() { return { query: '', showOptions: false, } }, computed: { selectedValue: { get() { let _selectedOptions if (!this.multiple) { _selectedOptions = this.findOption(this.modelValue) if (this.modelValue && !_selectedOptions) { _selectedOptions = this.sanitizeOption(this.modelValue) } return _selectedOptions } _selectedOptions = this.modelValue?.map((v) => { const option = this.findOption(v) if (option) return option return this.sanitizeOption(v) }) if (this.modelValue && !_selectedOptions.length) { _selectedOptions = this.sanitizeOptions(this.modelValue) } return _selectedOptions }, set(val) { this.query = '' if (val && !this.multiple) this.showOptions = false this.$emit('update:modelValue', val) }, }, groups() { if (!this.options || this.options.length == 0) return [] let groups = this.options[0]?.group ? this.options : [{ group: '', items: this.sanitizeOptions(this.options) }] return groups .map((group, i) => { return { key: i, group: group.group, hideLabel: group.hideLabel || false, items: this.filterOptions(this.sanitizeOptions(group.items)), } }) .filter((group) => group.items.length > 0) }, allOptions() { return this.groups.flatMap((group) => group.items) }, areAllOptionsSelected() { if (!this.multiple) return false return this.allOptions.length === this.selectedValue?.length }, }, watch: { query(q) { this.$emit('update:query', q) }, showOptions(val) { if (val) nextTick(() => this.$refs.searchInput?.$el?.focus()) }, }, methods: { togglePopover(val) { this.showOptions = val ?? !this.showOptions }, findOption(option) { if (!option) return option return this.allOptions.find((o) => o.value === (option.value || option)) }, filterOptions(options) { if (!this.query) return options return fuzzySearch(options, { term: this.query, keys: ['label', 'value'], }) }, displayValue(option) { if (!option) return '' if (!this.multiple) { if (typeof option === 'object') { return this.getLabel(option) } let selectedOption = this.allOptions.find((o) => o.value === option) return this.getLabel(selectedOption) } if (!Array.isArray(option)) return '' if (option.length === 0) return '' if (option.length === 1) return this.getLabel(option[0]) return `${option.length} selected` // in case of `multiple`, option is an array of values // so the display value should be comma separated labels // return option // .map((v) => { // if (typeof v === 'object') { // return this.getLabel(v) // } // let selectedOption = this.allOptions.find((o) => o.value === v) // return this.getLabel(selectedOption) // }) // .join(', ') }, getLabel(option) { if (typeof option !== 'object') return option return option?.label || option?.value || 'No label' }, sanitizeOptions(options) { if (!options) return [] // in case the options are just strings, convert them to objects return options.map((option) => this.sanitizeOption(option)) }, sanitizeOption(option) { return typeof option === 'string' ? { label: option, value: option } : option }, isOptionSelected(option) { if (!this.multiple) { return this.selectedValue?.value === option.value } return this.selectedValue?.find((v) => v && v.value === option.value) }, selectAll() { this.selectedValue = this.allOptions }, clearAll() { this.selectedValue = [] }, }, } </script>
2302_79757062/insights
frontend/src2/components/Autocomplete.vue
Vue
agpl-3.0
9,958
<template> <SwitchGroup v-bind="$attrs"> <div class="flex items-center justify-between text-sm"> <SwitchLabel class="mr-4 select-none text-base font-medium text-gray-800"> {{ $props.label }} </SwitchLabel> <Switch v-model="enabled" class="relative inline-flex items-center rounded-full transition-colors" :class="[ enabled ? 'bg-gray-900' : 'bg-gray-300', props.size === 'sm' ? 'h-4 w-6' : 'h-4.5 w-8', ]" > <span :class="[ enabled ? props.size == 'sm' ? 'translate-x-2.5' : 'translate-x-4' : 'translate-x-1', props.size == 'sm' ? 'h-2.5 w-2.5' : ' h-3 w-3 ', ]" class="inline-block transform rounded-full bg-white transition-transform" /> </Switch> </div> </SwitchGroup> </template> <script setup> import { Switch, SwitchGroup, SwitchLabel } from '@headlessui/vue' const props = defineProps(['label', 'size']) const enabled = defineModel({ type: Boolean }) </script>
2302_79757062/insights
frontend/src2/components/Checkbox.vue
Vue
agpl-3.0
986
<template> <codemirror :tab-size="2" :disabled="readOnly" v-model="code" class="font-[400]" :autofocus="autofocus" :indent-with-tab="true" :extensions="extensions" :placeholder="placeholder" @update="onUpdate" @focus="emit('focus')" @blur="emit('blur')" @ready="codeMirror = $event" /> </template> <script setup> import { autocompletion, closeBrackets } from '@codemirror/autocomplete' import { javascript } from '@codemirror/lang-javascript' import { python } from '@codemirror/lang-python' import { MySQL, sql } from '@codemirror/lang-sql' import { HighlightStyle, syntaxHighlighting, syntaxTree } from '@codemirror/language' import { EditorView } from '@codemirror/view' import { tags } from '@lezer/highlight' import { onMounted, ref, watch } from 'vue' import { Codemirror } from 'vue-codemirror' const props = defineProps({ modelValue: String, readOnly: { type: Boolean, default: false, }, autofocus: { type: Boolean, default: true, }, placeholder: { type: String, default: 'Enter an expression...', }, completions: { type: Function, default: null, }, language: { type: String, default: 'javascript', }, tables: { type: Array, default: () => [], }, schema: { type: Object, default: () => ({}), }, hideLineNumbers: { type: Boolean, default: false, }, disableAutocompletions: { type: Boolean, default: false, }, }) const emit = defineEmits(['inputChange', 'viewUpdate', 'focus', 'blur']) onMounted(() => { if (props.hideLineNumbers) { document.querySelectorAll('.cm-gutters').forEach((gutter) => { gutter.style.display = 'none' }) } }) const onUpdate = (viewUpdate) => { emit('viewUpdate', { cursorPos: viewUpdate.state.selection.ranges[0].to, syntaxTree: syntaxTree(viewUpdate.state), state: viewUpdate.state, }) } const codeMirror = ref(null) const code = defineModel() watch(code, (value, oldValue) => { if (value !== oldValue) { emit('inputChange', value) } }) const language = props.language === 'javascript' ? javascript() : props.language === 'python' ? python() : sql({ dialect: MySQL, upperCaseKeywords: true, schema: props.schema, tables: props.tables, }) const extensions = [language, closeBrackets(), EditorView.lineWrapping] const autocompletionOptions = { activateOnTyping: true, closeOnBlur: false, maxRenderedOptions: 10, icons: false, optionClass: () => 'flex h-7 !px-2 items-center rounded !text-gray-600', } if (props.completions) { autocompletionOptions.override = [ (context) => { return props.completions(context, syntaxTree(context.state)) }, ] } extensions.push(autocompletion(autocompletionOptions)) const chalky = '#e5a05b', coral = '#b04a54', cyan = '#45a5b1', invalid = '#ffffff', ivory = '#6a6a6a', stone = '#7d8799', // Brightened compared to original to increase contrast malibu = '#61afef', sage = '#76c457', whiskey = '#d19a66', violet = '#c678dd' const getHighlighterStyle = () => HighlightStyle.define([ { tag: tags.keyword, color: violet }, { tag: [tags.name, tags.deleted, tags.character, tags.propertyName, tags.macroName], color: coral, }, { tag: [tags.function(tags.variableName), tags.labelName], color: malibu, }, { tag: [tags.color, tags.constant(tags.name), tags.standard(tags.name)], color: whiskey, }, { tag: [tags.definition(tags.name), tags.separator], color: ivory }, { tag: [ tags.typeName, tags.className, tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace, ], color: chalky, }, { tag: [ tags.operator, tags.operatorKeyword, tags.url, tags.escape, tags.regexp, tags.link, tags.special(tags.string), ], color: cyan, }, { tag: [tags.meta, tags.comment], color: stone }, { tag: tags.strong, fontWeight: 'bold' }, { tag: tags.emphasis, fontStyle: 'italic' }, { tag: tags.strikethrough, textDecoration: 'line-through' }, { tag: tags.link, color: stone, textDecoration: 'underline' }, { tag: tags.heading, fontWeight: 'bold', color: coral }, { tag: [tags.atom, tags.bool, tags.special(tags.variableName)], color: whiskey, }, { tag: [tags.processingInstruction, tags.string, tags.inserted], color: sage, }, { tag: tags.invalid, color: invalid }, ]) extensions.push(syntaxHighlighting(getHighlighterStyle())) defineExpose({ get cursorPos() { return codeMirror.value.view.state.selection.ranges[0].to }, focus: () => codeMirror.value.view.focus(), setCursorPos: (pos) => { const _pos = Math.min(pos, code.value.length) codeMirror.value.view.dispatch({ selection: { anchor: _pos, head: _pos } }) }, }) </script>
2302_79757062/insights
frontend/src2/components/Code.vue
Vue
agpl-3.0
4,723
<template> <Dialog v-model="show" :options="{ title: title }"> <template #body-content> <p class="text-p-base text-gray-700" v-if="message"> {{ message }} </p> <div class="space-y-4"> <FormControl v-for="field in fields" v-bind="field" v-model="values[field.fieldname]" :key="field.fieldname" /> </div> <ErrorMessage class="mt-2" :message="error" /> </template> <template #actions> <div class="flex items-center justify-end space-x-2"> <Button @click="show = false">Cancel</Button> <Button variant="solid" :theme="$props.theme" @click="onConfirm" :loading="isLoading" > Confirm </Button> </div> </template> </Dialog> </template> <script> import { ErrorMessage, FormControl } from 'frappe-ui' export default { name: 'ConfirmDialog', props: ['title', 'message', 'theme', 'fields', 'onSuccess'], data() { return { show: true, error: null, isLoading: false, values: {}, } }, components: { FormControl, ErrorMessage }, methods: { onConfirm() { this.error = null this.isLoading = true try { let result = this.onSuccess({ hide: this.hide, values: this.values }) if (result?.then) { result .then(() => (this.isLoading = false)) .catch((error) => (this.error = error)) } } catch (error) { this.error = error } finally { this.isLoading = false this.hide() } }, hide() { this.show = false }, }, } </script>
2302_79757062/insights
frontend/src2/components/ConfirmDialog.vue
Vue
agpl-3.0
1,494
<template> <component :is="tag" class="contenteditable align-middle outline-none transition-all before:text-gray-500" :contenteditable="disabled ? false : contenteditable" :placeholder="placeholder" @input="update" @blur="update('blur')" @paste="onPaste" @keypress="onKeypress" ref="element" spellcheck="false" > </component> </template> <script setup> import { onMounted, ref, watch } from 'vue' function replaceAll(str, search, replacement) { return str.split(search).join(replacement) } const emit = defineEmits(['returned', 'update:modelValue', 'change', 'blur']) const props = defineProps({ tag: { type: String, default: 'div', }, contenteditable: { type: [Boolean, String], default: true, }, disabled: { type: Boolean, default: false, }, modelValue: String | Number, value: String | Number, placeholder: String, noHtml: { type: Boolean, default: true, }, noNl: { type: Boolean, default: true, }, }) const element = ref() function currentContent() { return props.noHtml ? element.value?.innerText : element.value?.innerHTML } function updateContent(newcontent) { if (props.noHtml) { element.value.innerText = newcontent } else { element.value.innerHTML = newcontent } } function valuePropPresent() { return props.value != undefined } function update(event) { if (event == 'blur') emit('blur', currentContent()) if (valuePropPresent()) { emit('change', currentContent()) } else { emit('update:modelValue', currentContent()) } } function onPaste(event) { event.preventDefault() let text = (event.originalEvent || event).clipboardData.getData('text/plain') if (props.noNl) { text = replaceAll(text, '\r\n', ' ') text = replaceAll(text, '\n', ' ') text = replaceAll(text, '\r', ' ') } window.document.execCommand('insertText', false, text) } function onKeypress(event) { if (event.key == 'Enter' && props.noNl) { event.preventDefault() emit('returned', currentContent()) } } onMounted(() => { updateContent(valuePropPresent() ? props.value : props.modelValue ?? '') }) watch( () => props.modelValue ?? props.value, (newval, oldval) => { if (newval != currentContent()) { updateContent(newval ?? '') } } ) watch( () => props.noHtml, (newval, oldval) => { updateContent(props.modelValue ?? '') } ) watch( () => props.tag, (newval, oldval) => { updateContent(props.modelValue ?? '') }, { flush: 'post' } ) </script> <style lang="scss"> .contenteditable:empty:before { content: attr(placeholder); pointer-events: none; display: block; /* For Firefox */ } </style>
2302_79757062/insights
frontend/src2/components/ContentEditable.vue
Vue
agpl-3.0
2,591
<script setup lang="ts"> import { Table2Icon } from 'lucide-vue-next' import { formatNumber } from '../helpers' import { FIELDTYPES } from '../helpers/constants' import { QueryResultColumn, QueryResultRow } from '../types/query.types' const props = defineProps<{ columns: QueryResultColumn[] | undefined rows: QueryResultRow[] | undefined }>() const isNumberColumn = (col: QueryResultColumn) => FIELDTYPES.NUMBER.includes(col.type) </script> <template> <div v-if="columns?.length || rows?.length" class="flex h-full w-full flex-col overflow-hidden font-mono text-sm" > <div class="w-full flex-1 overflow-y-auto"> <table class="h-full w-full border-separate border-spacing-0"> <thead class="sticky top-0 bg-white"> <tr> <td class="whitespace-nowrap border-b border-r" width="1%"></td> <td v-for="(column, idx) in props.columns" :key="idx" class="border-b border-r" :class="isNumberColumn(column) ? 'text-right' : 'text-left'" > <slot name="column-header" :column="column"> <div class="truncate py-2 px-3"> {{ column.name }} </div> </slot> </td> </tr> </thead> <tbody> <tr v-for="(row, idx) in props.rows?.slice(0, 100)" :key="idx"> <td class="whitespace-nowrap border-b border-r px-3" width="1%" height="30px" > {{ idx + 1 }} </td> <td v-for="col in props.columns" class="max-w-[24rem] truncate border-b border-r py-2 px-3 text-gray-800" :class="isNumberColumn(col) ? 'text-right' : 'text-left'" height="30px" > {{ isNumberColumn(col) ? formatNumber(row[col.name]) : row[col.name] }} </td> </tr> <tr height="99%" class="border-b"></tr> </tbody> </table> </div> <slot name="footer"></slot> </div> <div v-else class="flex h-full w-full items-center justify-center"> <div class="flex flex-col items-center gap-2"> <Table2Icon class="h-16 w-16 text-gray-300" stroke-width="1.5" /> <p class="text-center text-gray-500">No data to display.</p> </div> </div> </template>
2302_79757062/insights
frontend/src2/components/DataTable.vue
Vue
agpl-3.0
2,130
<script setup> import { GripVertical, X } from 'lucide-vue-next' import Draggable from 'vuedraggable' const emit = defineEmits(['sort']) const items = defineModel('items') const props = defineProps({ items: { type: Array, required: true }, group: { type: String, required: true }, itemKey: { type: String, default: 'value' }, emptyText: { type: String, default: 'No items' }, showEmptyState: { type: Boolean, default: true }, showHandle: { type: Boolean, default: true }, }) function onChange(e) { if (e.moved) { emit('sort', e.moved.oldIndex, e.moved.newIndex) items.value.splice(e.moved.newIndex, 0, items.value.splice(e.moved.oldIndex, 1)[0]) } if (e.added) { items.value.splice(e.added.newIndex, 0, e.added.element) } if (e.removed) { items.value.splice(e.removed.oldIndex, 1) } } </script> <template> <Draggable class="w-full" :model-value="items" :group="props.group" :item-key="itemKey" @change="onChange" > <template #item="{ element: item, index: idx }"> <div class="mb-2 flex items-center gap-1 last:mb-0"> <GripVertical v-if="props.showHandle" class="h-4 w-4 flex-shrink-0 cursor-grab text-gray-500" /> <div class="flex flex-1 flex-col justify-center overflow-hidden"> <slot name="item" :item="item" :index="idx"> <div class="group form-input flex h-7 flex-1 cursor-pointer items-center justify-between px-2" > <div class="flex items-center space-x-2"> <div>{{ typeof item === 'object' ? item[itemKey] : item }}</div> </div> <div class="flex items-center space-x-2"> <X @click.prevent.stop="items.splice(idx, 1)" class="invisible h-4 w-4 text-gray-600 transition-all hover:text-gray-800 group-hover:visible" /> </div> </div> </slot> </div> <slot name="item-suffix" :item="item" :index="idx" /> </div> </template> </Draggable> <template v-if="showEmptyState && !items?.length"> <div class="flex h-12 flex-col items-center justify-center rounded border border-dashed border-gray-300 py-2" > <div class="text-xs text-gray-500">{{ props.emptyText }}</div> </div> </template> </template>
2302_79757062/insights
frontend/src2/components/DraggableList.vue
Vue
agpl-3.0
2,189
<script setup lang="ts"> import { computed } from 'vue' const props = defineProps<{ fields: { name: string label: string type: string options?: string[] placeholder?: string required?: boolean defaultValue?: any }[] actions?: { label: string disabled?: boolean loading?: boolean onClick: () => void }[] }>() type Form = Record<string, any> const form = defineModel<Form>({ required: true, }) props.fields.forEach((field) => { if (field.defaultValue) { form.value[field.name] = field.defaultValue } }) defineExpose({ hasRequiredFields: computed(() => { return props.fields.every((field) => !field.required || form.value[field.name]) }), }) </script> <template> <div class="flex w-full flex-col gap-2"> <div class="flex flex-col gap-4"> <div class="relative" v-for="field in fields" :key="field.name"> <FormControl :type="field.type" :label="field.label" :options="field.options" :placeholder="field.placeholder" v-model="form[field.name]" /> <span v-if="field.required && !form[field.name]" class="absolute right-0 top-0 text-xs text-red-400" > * required </span> </div> </div> <div class="flex w-full justify-end gap-2 pt-2"> <Button v-for="action in actions" :key="action.label" v-bind="action" /> </div> </div> </template>
2302_79757062/insights
frontend/src2/components/Form.vue
Vue
agpl-3.0
1,344
<script setup lang="ts"> import { FormControl } from 'frappe-ui' </script> <template> <FormControl v-bind="$attrs" autocomplete="off"> <slot></slot> </FormControl> </template>
2302_79757062/insights
frontend/src2/components/FormControl.vue
Vue
agpl-3.0
181
<script setup lang="ts"></script> <template> <svg xmlns="http://www.w3.org/2000/svg" height="64" viewBox="0 0 56 64" width="56"> <path clip-rule="evenodd" d="m5.106 0c-2.802 0-5.073 2.272-5.073 5.074v53.841c0 2.803 2.271 5.074 5.073 5.074h45.774c2.801 0 5.074-2.271 5.074-5.074v-38.605l-18.903-20.31h-31.945z" fill="#45b058" fill-rule="evenodd" /> <path d="m20.306 43.197c.126.144.198.324.198.522 0 .378-.306.72-.703.72-.18 0-.378-.072-.504-.234-.702-.846-1.891-1.387-3.007-1.387-2.629 0-4.627 2.017-4.627 4.88 0 2.845 1.999 4.879 4.627 4.879 1.134 0 2.25-.486 3.007-1.369.125-.144.324-.233.504-.233.415 0 .703.359.703.738 0 .18-.072.36-.198.504-.937.972-2.215 1.693-4.015 1.693-3.457 0-6.176-2.521-6.176-6.212s2.719-6.212 6.176-6.212c1.8.001 3.096.721 4.015 1.711zm6.802 10.714c-1.782 0-3.187-.594-4.213-1.495-.162-.144-.234-.342-.234-.54 0-.361.27-.757.702-.757.144 0 .306.036.432.144.828.739 1.98 1.314 3.367 1.314 2.143 0 2.827-1.152 2.827-2.071 0-3.097-7.112-1.386-7.112-5.672 0-1.98 1.764-3.331 4.123-3.331 1.548 0 2.881.467 3.853 1.278.162.144.252.342.252.54 0 .36-.306.72-.703.72-.144 0-.306-.054-.432-.162-.882-.72-1.98-1.044-3.079-1.044-1.44 0-2.467.774-2.467 1.909 0 2.701 7.112 1.152 7.112 5.636.001 1.748-1.187 3.531-4.428 3.531zm16.994-11.254-4.159 10.335c-.198.486-.685.81-1.188.81h-.036c-.522 0-1.008-.324-1.207-.81l-4.142-10.335c-.036-.09-.054-.18-.054-.288 0-.36.323-.793.81-.793.306 0 .594.18.72.486l3.889 9.992 3.889-9.992c.108-.288.396-.486.72-.486.468 0 .81.378.81.793.001.09-.017.198-.052.288z" fill="#fff" /> <g clip-rule="evenodd" fill-rule="evenodd"> <path d="m56.001 20.357v1h-12.8s-6.312-1.26-6.128-6.707c0 0 .208 5.707 6.003 5.707z" fill="#349c42" /> <path d="m37.098.006v14.561c0 1.656 1.104 5.791 6.104 5.791h12.8l-18.904-20.352z" fill="#fff" opacity=".5" /> </g> </svg> </template>
2302_79757062/insights
frontend/src2/components/Icons/CSVIcon.vue
Vue
agpl-3.0
1,879
<template> <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M10.875 9.06223L3 9.06232" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" /> <path d="M6.74537 5.31699L3 9.06236L6.74527 12.8076" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" /> <path d="M14.1423 4L14.1423 14.125" stroke="currentColor" stroke-linecap="round" /> </svg> </template>
2302_79757062/insights
frontend/src2/components/Icons/CollapseSidebar.vue
Vue
agpl-3.0
479
<script setup lang="ts"></script> <template> <img src="../../assets/duckdb-logo.webp" alt="DuckDB" v-bind="$attrs" /> </template>
2302_79757062/insights
frontend/src2/components/Icons/DuckDBIcon.vue
Vue
agpl-3.0
132
<template> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none"> <rect width="16" height="16" rx="4.5" class="currentColor fill-current" /> <circle cx="8" cy="8" r="3" fill="white" /> </svg> </template>
2302_79757062/insights
frontend/src2/components/Icons/IndicatorIcon.vue
Vue
agpl-3.0
251
<template> <svg xmlns="http://www.w3.org/2000/svg" height="20" width="20"> <path strokeWidth="1" fill="currentColor" d="M13.333 15.833Q12.812 15.833 12.406 15.75Q12 15.667 11.667 15.5Q12.667 14.708 13.229 13.25Q13.792 11.792 13.792 10Q13.792 8.208 13.229 6.75Q12.667 5.292 11.667 4.5Q12 4.333 12.406 4.25Q12.812 4.167 13.333 4.167Q15.771 4.167 17.469 5.865Q19.167 7.562 19.167 10Q19.167 12.438 17.469 14.135Q15.771 15.833 13.333 15.833ZM10 14.792Q8.958 14.792 8.25 13.406Q7.542 12.021 7.542 10Q7.542 7.979 8.25 6.594Q8.958 5.208 10 5.208Q11.042 5.208 11.75 6.594Q12.458 7.979 12.458 10Q12.458 12.021 11.75 13.406Q11.042 14.792 10 14.792ZM6.667 15.833Q4.229 15.833 2.531 14.135Q0.833 12.438 0.833 10Q0.833 7.562 2.531 5.865Q4.229 4.167 6.667 4.167Q7.188 4.167 7.594 4.25Q8 4.333 8.333 4.5Q7.333 5.292 6.771 6.75Q6.208 8.208 6.208 10Q6.208 11.792 6.771 13.25Q7.333 14.708 8.333 15.5Q8 15.667 7.594 15.75Q7.188 15.833 6.667 15.833Z" /> </svg> </template>
2302_79757062/insights
frontend/src2/components/Icons/JoinFullIcon.vue
Vue
agpl-3.0
967
<script setup lang="ts"></script> <template> <svg xmlns="http://www.w3.org/2000/svg" height="64" viewBox="0 0 25.6 25.6" width="64"> <g fill="none" stroke="#fff"> <path d="M18.983 18.636c.163-1.357.114-1.555 1.124-1.336l.257.023c.777.035 1.793-.125 2.4-.402 1.285-.596 2.047-1.592.78-1.33-2.89.596-3.1-.383-3.1-.383 3.053-4.53 4.33-10.28 3.227-11.687-3.004-3.84-8.205-2.024-8.292-1.976l-.028.005c-.57-.12-1.2-.19-1.93-.2-1.308-.02-2.3.343-3.054.914 0 0-9.277-3.822-8.846 4.807.092 1.836 2.63 13.9 5.66 10.25C8.29 15.987 9.36 14.86 9.36 14.86c.53.353 1.167.533 1.834.468l.052-.044a2.01 2.01 0 0 0 .021.518c-.78.872-.55 1.025-2.11 1.346-1.578.325-.65.904-.046 1.056.734.184 2.432.444 3.58-1.162l-.046.183c.306.245.285 1.76.33 2.842s.116 2.093.337 2.688.48 2.13 2.53 1.7c1.713-.367 3.023-.896 3.143-5.81" fill="#000" stroke="#000" stroke-linecap="butt" stroke-width="2.149" class="D" /> <path d="M23.535 15.6c-2.89.596-3.1-.383-3.1-.383 3.053-4.53 4.33-10.28 3.228-11.687-3.004-3.84-8.205-2.023-8.292-1.976l-.028.005a10.31 10.31 0 0 0-1.929-.201c-1.308-.02-2.3.343-3.054.914 0 0-9.278-3.822-8.846 4.807.092 1.836 2.63 13.9 5.66 10.25C8.29 15.987 9.36 14.86 9.36 14.86c.53.353 1.167.533 1.834.468l.052-.044a2.02 2.02 0 0 0 .021.518c-.78.872-.55 1.025-2.11 1.346-1.578.325-.65.904-.046 1.056.734.184 2.432.444 3.58-1.162l-.046.183c.306.245.52 1.593.484 2.815s-.06 2.06.18 2.716.48 2.13 2.53 1.7c1.713-.367 2.6-1.32 2.725-2.906.088-1.128.286-.962.3-1.97l.16-.478c.183-1.53.03-2.023 1.085-1.793l.257.023c.777.035 1.794-.125 2.39-.402 1.285-.596 2.047-1.592.78-1.33z" fill="#336791" stroke="none" /> <g class="E"> <g class="B"> <path d="M12.814 16.467c-.08 2.846.02 5.712.298 6.4s.875 2.05 2.926 1.612c1.713-.367 2.337-1.078 2.607-2.647l.633-5.017M10.356 2.2S1.072-1.596 1.504 7.033c.092 1.836 2.63 13.9 5.66 10.25C8.27 15.95 9.27 14.907 9.27 14.907m6.1-13.4c-.32.1 5.164-2.005 8.282 1.978 1.1 1.407-.175 7.157-3.228 11.687" class="C" /> <path d="M20.425 15.17s.2.98 3.1.382c1.267-.262.504.734-.78 1.33-1.054.49-3.418.615-3.457-.06-.1-1.745 1.244-1.215 1.147-1.652-.088-.394-.69-.78-1.086-1.744-.347-.84-4.76-7.29 1.224-6.333.22-.045-1.56-5.7-7.16-5.782S7.99 8.196 7.99 8.196" stroke-linejoin="bevel" /> </g> <g class="C"> <path d="M11.247 15.768c-.78.872-.55 1.025-2.11 1.346-1.578.325-.65.904-.046 1.056.734.184 2.432.444 3.58-1.163.35-.49-.002-1.27-.482-1.468-.232-.096-.542-.216-.94.23z" /> <path d="M11.196 15.753c-.08-.513.168-1.122.433-1.836.398-1.07 1.316-2.14.582-5.537-.547-2.53-4.22-.527-4.22-.184s.166 1.74-.06 3.365c-.297 2.122 1.35 3.916 3.246 3.733" class="B" /> </g> </g> <g fill="#fff" class="D"> <path d="M10.322 8.145c-.017.117.215.43.516.472s.558-.202.575-.32-.215-.246-.516-.288-.56.02-.575.136z" stroke-width=".239" /> <path d="M19.486 7.906c.016.117-.215.43-.516.472s-.56-.202-.575-.32.215-.246.516-.288.56.02.575.136z" stroke-width=".119" /> </g> <path d="M20.562 7.095c.05.92-.198 1.545-.23 2.524-.046 1.422.678 3.05-.413 4.68" class="B C E" /> </g> </svg> </template>
2302_79757062/insights
frontend/src2/components/Icons/PostgreSQLIcon.vue
Vue
agpl-3.0
3,201
<script setup lang="ts"> defineOptions({ inheritAttrs: false }) const props = defineProps<{ label: string }>() </script> <template> <div class="flex items-start justify-between gap-1"> <span class="inline-flex w-1/3 flex-shrink-0 text-xs leading-7 text-gray-700" :class="$attrs.class" > {{ props.label }} </span> <div class="h-full flex-1 overflow-hidden p-[0.5px]"> <slot /> </div> </div> </template>
2302_79757062/insights
frontend/src2/components/InlineFormControlLabel.vue
Vue
agpl-3.0
427
<script setup lang="ts"></script> <template> <div class="absolute top-0 left-0 z-10 flex h-full w-full items-center justify-center rounded bg-gray-50/30 backdrop-blur-sm" > <LoadingIndicator class="h-8 w-8 text-gray-700" /> </div> </template>
2302_79757062/insights
frontend/src2/components/LoadingOverlay.vue
Vue
agpl-3.0
251
<script setup lang="ts"></script> <template> <div class="sticky top-0 z-10 flex w-full flex-shrink-0 items-center gap-3 bg-white px-3 py-2 shadow-sm" > <div class="flex flex-1 items-center justify-between"> <div> <slot name="left"> <router-link :to="{ path: '/' }"> <img src="../assets/insights-logo-new.svg" alt="logo" class="h-8" /> </router-link> </slot> </div> <div> <slot name="center"></slot> </div> <div> <slot name="right"></slot> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/components/Navbar.vue
Vue
agpl-3.0
532
<template> <div ref="reference"> <div ref="target" :class="['flex', $attrs.class]" @click="updatePosition" @focusin="updatePosition" @keydown="updatePosition" @mouseover="onMouseover" @mouseleave="onMouseleave" > <slot name="target" v-bind="{ togglePopover, updatePosition, open, close, isOpen }" /> </div> <teleport to="#frappeui-popper-root"> <div ref="popover" class="relative z-[100]" :class="[popoverContainerClass, popoverClass]" :style="{ minWidth: targetWidth ? targetWidth + 'px' : null }" @mouseover="pointerOverTargetOrPopup = true" @mouseleave="onMouseleave" > <transition v-bind="popupTransition"> <div v-show="isOpen"> <slot name="body" v-bind="{ togglePopover, updatePosition, open, close, isOpen }" > <div class="rounded-lg border border-gray-100 bg-white shadow-xl" :class="bodyClass" > <slot name="body-main" v-bind="{ togglePopover, updatePosition, open, close, isOpen, }" /> </div> </slot> </div> </transition> </div> </teleport> </div> </template> <script> import { createPopper } from '@popperjs/core' export default { name: 'Popover', inheritAttrs: false, props: { show: { default: undefined, }, trigger: { type: String, default: 'click', // click, hover }, hoverDelay: { type: Number, default: 0, }, leaveDelay: { type: Number, default: 0, }, placement: { type: String, default: 'bottom-start', }, popoverClass: [String, Object, Array], bodyClass: [String, Object, Array], transition: { default: null, }, hideOnBlur: { default: true, }, }, emits: ['open', 'close', 'update:show'], expose: ['open', 'close'], data() { return { popoverContainerClass: 'body-container', showPopup: false, targetWidth: null, pointerOverTargetOrPopup: false, } }, watch: { show(val) { if (val) { this.open() } else { this.close() } }, }, created() { if (typeof window === 'undefined') return if (!document.getElementById('frappeui-popper-root')) { const root = document.createElement('div') root.id = 'frappeui-popper-root' document.body.appendChild(root) } }, mounted() { this.listener = (e) => { if (!this.isOpen) return const clickedElement = e.target const reference = this.$refs.reference const popoverBody = this.$refs.popover const insideClick = clickedElement === reference || clickedElement === popoverBody || reference?.contains(clickedElement) || popoverBody?.contains(clickedElement) if (insideClick) { return } const root = document.getElementById('frappeui-popper-root') const insidePopoverRoot = root.contains(clickedElement) if (!insidePopoverRoot) { return this.close() } const bodyClass = `.${this.popoverContainerClass}` const clickedElementBody = clickedElement?.closest(bodyClass) const currentPopoverBody = reference?.closest(bodyClass) const isSiblingClicked = clickedElementBody && currentPopoverBody && clickedElementBody === currentPopoverBody if (isSiblingClicked) { this.close() } } if (this.hideOnBlur) { document.addEventListener('click', this.listener) // https://github.com/tailwindlabs/headlessui/issues/834#issuecomment-1030907894 document.addEventListener('mousedown', this.listener) } this.$nextTick(() => { this.targetWidth = this.$refs['target'].clientWidth }) }, beforeDestroy() { this.popper && this.popper.destroy() document.removeEventListener('click', this.listener) document.removeEventListener('mousedown', this.listener) }, computed: { showPropPassed() { return this.show != null }, isOpen: { get() { if (this.showPropPassed) { return this.show } return this.showPopup }, set(val) { val = Boolean(val) if (this.showPropPassed) { this.$emit('update:show', val) } else { this.showPopup = val } if (val === false) { this.$emit('close') } else if (val === true) { this.$emit('open') } }, }, popupTransition() { let templates = { default: { enterActiveClass: 'transition duration-150 ease-out', enterFromClass: 'translate-y-1 opacity-0', enterToClass: 'translate-y-0 opacity-100', leaveActiveClass: 'transition duration-150 ease-in', leaveFromClass: 'translate-y-0 opacity-100', leaveToClass: 'translate-y-1 opacity-0', }, } if (typeof this.transition === 'string') { return templates[this.transition] } return this.transition }, }, methods: { setupPopper() { if (!this.popper) { this.popper = createPopper(this.$refs.reference, this.$refs.popover, { placement: this.placement, }) } else { this.updatePosition() } }, updatePosition() { this.popper && this.popper.update() }, togglePopover(flag) { if (flag instanceof Event) { flag = null } if (flag == null) { flag = !this.isOpen } flag = Boolean(flag) if (flag) { this.open() } else { this.close() } }, open() { this.isOpen = true this.$nextTick(() => this.setupPopper()) }, close() { this.isOpen = false }, onMouseover() { this.pointerOverTargetOrPopup = true if (this.leaveTimer) { clearTimeout(this.leaveTimer) this.leaveTimer = null } if (this.trigger === 'hover') { if (this.hoverDelay) { this.hoverTimer = setTimeout(() => { if (this.pointerOverTargetOrPopup) { this.open() } }, Number(this.hoverDelay) * 1000) } else { this.open() } } }, onMouseleave(e) { this.pointerOverTargetOrPopup = false if (this.hoverTimer) { clearTimeout(this.hoverTimer) this.hoverTimer = null } if (this.trigger === 'hover') { if (this.leaveTimer) { clearTimeout(this.leaveTimer) } if (this.leaveDelay) { this.leaveTimer = setTimeout(() => { if (!this.pointerOverTargetOrPopup) { this.close() } }, Number(this.leaveDelay) * 1000) } else { if (!this.pointerOverTargetOrPopup) { this.close() } } } }, }, } </script>
2302_79757062/insights
frontend/src2/components/Popover.vue
Vue
agpl-3.0
6,322
<script setup lang="ts"> import { computed } from 'vue' const props = defineProps<{ title: string types: { icon: any label: string description: string tag?: string onClick?: () => void }[] }>() const show = defineModel() </script> <template> <Dialog v-model="show"> <template #body> <div class="bg-white px-4 py-5 text-base sm:p-6"> <h3 class="text-lg font-medium leading-6 text-gray-900"> {{ props.title }} </h3> <div class="mt-4 grid grid-cols-1 gap-6"> <div v-for="(type, index) in props.types" :key="index" class="group flex cursor-pointer items-center space-x-4" @click="type.onClick?.()" > <div class="rounded border p-4 text-gray-500 shadow-sm transition-all group-hover:scale-105" > <component :is="type.icon" /> </div> <div> <div class="flex items-center space-x-2"> <p class="text-lg font-medium leading-6 text-gray-900 transition-colors group-hover:text-blue-500" > {{ type.label }} </p> <Badge v-if="type.tag" theme="green"> {{ type.tag }} </Badge> </div> <p class="text-sm leading-5 text-gray-600"> {{ type.description }} </p> </div> </div> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/components/SelectTypeDialog.vue
Vue
agpl-3.0
1,336
<template> <button class="flex h-7 cursor-pointer items-center rounded text-gray-800 duration-300 ease-in-out focus:outline-none focus:transition-none focus-visible:rounded focus-visible:ring-2 focus-visible:ring-gray-400" :class="isActive ? 'bg-white shadow-sm' : 'hover:bg-gray-100'" @click="handleClick" > <div class="flex items-center duration-300 ease-in-out" :class="isCollapsed ? 'p-1' : 'px-2 py-1'" > <Tooltip :text="label" placement="right"> <slot name="icon"> <span class="grid h-5 w-6 flex-shrink-0 place-items-center"> <component :is="icon" class="h-4.5 w-4.5 text-gray-700" stroke-width="1.5" /> </span> </slot> </Tooltip> <span class="flex-shrink-0 text-base duration-300 ease-in-out" :class=" isCollapsed ? 'ml-0 w-0 overflow-hidden opacity-0' : 'ml-2 w-auto opacity-100' " > {{ label }} </span> </div> </button> </template> <script setup lang="ts"> import { computed } from 'vue' import { useRouter } from 'vue-router' const router = useRouter() const props = defineProps<{ icon?: any label: string to?: string isCollapsed?: boolean }>() function handleClick() { router.push({ name: props.to }) } let isActive = computed(() => { return router.currentRoute.value.name === props.to }) </script>
2302_79757062/insights
frontend/src2/components/SidebarLink.vue
Vue
agpl-3.0
1,328
<template> <div class="flex h-7 w-full cursor-pointer select-none items-center rounded border bg-gray-100"> <div v-for="tab in tabs" class="flex h-full flex-1 items-center justify-center truncate px-4 transition-all" :class="{ 'rounded bg-white shadow': tab.active || currentTab === tab.value || (currentTab === undefined && tab.default), 'cursor-not-allowed': tab.disabled, }" @click="handleClick(tab)" > {{ tab.label }} </div> </div> </template> <script setup> import { computed } from 'vue' const currentTab = defineModel() const emit = defineEmits(['switch']) const props = defineProps({ tabs: { type: Array, required: true } }) const tabs = computed(() => { if (typeof props.tabs?.[0] == 'string') { return props.tabs.map((label) => ({ label, value: label })) } return props.tabs }) function handleClick(tab) { if (tab.disabled) return currentTab.value = tab.value emit('switch', tab) } </script>
2302_79757062/insights
frontend/src2/components/Switch.vue
Vue
agpl-3.0
962
<template> <div class="m-2 flex transition duration-200 ease-out"> <div :class="['w-[22rem] rounded bg-white p-3 shadow-md', variantClasses]"> <div class="flex items-start"> <div v-if="icon || variantIcon" class="mr-2 pt-1"> <FeatherIcon :name="icon || variantIcon" :class="['h-4 w-4 rounded-full', variantIconClasses, iconClasses]" /> </div> <div> <slot> <p class="text-base font-medium leading-5 text-gray-900"> {{ title }} </p> <p v-if="message" class="text-base text-gray-600"> <span v-if="containsHTML" v-html="message"></span> <span v-else>{{ message }}</span> </p> </slot> </div> <div class="ml-auto pl-2"> <slot name="actions"> <!-- <button class="grid h-5 w-5 place-items-center rounded hover:bg-gray-100"> <FeatherIcon name="x" class="h-4 w-4 text-gray-700" /> </button> --> </slot> </div> </div> </div> </div> </template> <script setup lang="ts"> import { computed } from 'vue' import { ToastVariant } from '../helpers/toasts' const props = defineProps<{ title: string message?: string variant: ToastVariant icon?: string iconClasses?: string }>() const containsHTML = computed(() => props.message?.includes('<')) const variantClasses = computed(() => { if (props.variant === 'success') { return 'bg-green-50' } if (props.variant === 'info') { return 'bg-blue-50' } if (props.variant === 'warning') { return 'bg-orange-50' } if (props.variant === 'error') { return 'bg-red-50' } }) const variantIcon = computed(() => { if (props.variant === 'success') { return 'check' } if (props.variant === 'info') { return 'info' } if (props.variant === 'warning') { return 'alert-circle' } if (props.variant === 'error') { return 'x' } }) const variantIconClasses = computed(() => { if (props.variant === 'success') { return 'text-white bg-green-600 p-0.5' } if (props.variant === 'info') { return 'text-white bg-blue-600' } if (props.variant === 'warning') { return 'text-white bg-orange-600' } if (props.variant === 'error') { return 'text-white bg-red-600 p-0.5' } }) </script>
2302_79757062/insights
frontend/src2/components/Toast.vue
Vue
agpl-3.0
2,181
<template> <div> <Dropdown :options="userDropdownOptions"> <template v-slot="{ open }"> <button class="flex h-12 items-center rounded-md py-2 duration-300 ease-in-out" :class=" props.isCollapsed ? 'w-auto px-0' : open ? 'w-52 bg-white px-2 shadow-sm' : 'w-52 px-2 hover:bg-gray-200' " > <img src="../assets/insights-logo-new.svg" alt="logo" class="h-8 w-8 flex-shrink-0 rounded" /> <div class="flex flex-1 flex-col text-left duration-300 ease-in-out" :class=" props.isCollapsed ? 'ml-0 w-0 overflow-hidden opacity-0' : 'ml-2 w-auto opacity-100' " > <div class="text-base font-medium leading-none text-gray-900">Insights</div> <div class="mt-1 text-sm leading-none text-gray-700"> {{ session.user.full_name }} </div> </div> <div class="duration-300 ease-in-out" :class=" props.isCollapsed ? 'ml-0 w-0 overflow-hidden opacity-0' : 'ml-2 w-auto opacity-100' " > <ChevronDown class="h-4 w-4 text-gray-600" aria-hidden="true" /> </div> </button> </template> </Dropdown> <Dialog v-model="showSwitchToV2Dialog" :options="{ title: 'Switch to Insights v2', actions: [ { label: 'Continue', variant: 'solid', onClick: openInsightsV2, }, ], }" > <template #body-content> <div class="prose prose-sm mb-4"> <p>Switch to the old version of Insights?</p> </div> <FormControl type="checkbox" label="Set Insights v2 as default" :modelValue="session.user.default_version === 'v2'" @update:modelValue="session.user.default_version = $event ? 'v2' : ''" /> </template> </Dialog> </div> </template> <script setup lang="ts"> import { Dropdown } from 'frappe-ui' import { ChevronDown } from 'lucide-vue-next' import { ref } from 'vue' import { confirmDialog } from '../helpers/confirm_dialog' import session from '../session' const props = defineProps<{ isCollapsed: boolean }>() const showSwitchToV2Dialog = ref(false) const userDropdownOptions = [ { label: 'Documentation', icon: 'help-circle', onClick: () => window.open('https://docs.frappeinsights.com', '_blank'), }, { label: 'Join Telegram Group', icon: 'message-circle', onClick: () => window.open('https://t.me/frappeinsights', '_blank'), }, { label: 'Switch to Insights v2', icon: 'grid', onClick: () => (showSwitchToV2Dialog.value = true), }, { icon: 'log-out', label: 'Log out', onClick: () => confirmDialog({ title: 'Log out', message: 'Are you sure you want to log out?', onSuccess: session.logout, }), }, ] function openInsightsV2() { session.updateDefaultVersion(session.user.default_version).then(() => { window.location.href = '/insights_v2' }) } </script>
2302_79757062/insights
frontend/src2/components/UserDropdown.vue
Vue
agpl-3.0
2,907
<script setup lang="ts"> import { computed, ref, watchEffect } from 'vue' import useUserStore, { User } from '../users/users' const props = defineProps<{ placeholder?: string hideUsers?: string[] }>() const selectedUserEmail = defineModel<string>() const userStore = useUserStore() const searchTxt = ref('') watchEffect(() => { searchTxt.value = selectedUserEmail.value || '' }) const filteredUsers = computed(() => { return userStore.users .filter((user) => { if (!searchTxt.value) return true return ( user.full_name.toLowerCase().includes(searchTxt.value.toLowerCase()) || user.email.toLowerCase().includes(searchTxt.value.toLowerCase()) ) }) .filter((user) => { return !props.hideUsers?.includes(user.email) }) .map((user) => { return { ...user, label: user.full_name, value: user.email, description: user.email, } }) }) </script> <template> <Autocomplete :hide-search="true" :autofocus="false" :modelValue="selectedUserEmail" @update:modelValue="selectedUserEmail = $event?.value" :options="filteredUsers" > <template #target="{ open }"> <FormControl class="w-full" type="text" :placeholder="props.placeholder || 'Search user...'" autocomplete="off" v-model="searchTxt" @update:modelValue="open" @focus="open" /> </template> <template #item-prefix="{ option }"> <Avatar size="sm" :label="option.label" :image="option.user_image" /> </template> </Autocomplete> </template>
2302_79757062/insights
frontend/src2/components/UserSelector.vue
Vue
agpl-3.0
1,497
<script setup lang="ts"> import { CheckSquare, SearchIcon, SquareIcon } from 'lucide-vue-next' import { computed, ref } from 'vue' import ChartIcon from '../charts/components/ChartIcon.vue' import { copy } from '../helpers' import { WorkbookChart } from '../types/workbook.types' const showDialog = defineModel() const props = defineProps<{ selectedCharts: WorkbookChart[] chartOptions: WorkbookChart[] }>() const emit = defineEmits({ select: (charts: WorkbookChart[]) => true, }) const searchQuery = ref('') const filteredCharts = computed(() => { if (!props.chartOptions.length) return [] if (!searchQuery.value) return props.chartOptions return props.chartOptions.filter((chart) => { return chart.name.toLowerCase().includes(searchQuery.value.toLowerCase()) }) }) const selectedCharts = ref<WorkbookChart[]>(copy(props.selectedCharts)) function isSelected(chart: WorkbookChart) { return selectedCharts.value.find((c) => c.name === chart.name) } function toggleChart(chart: WorkbookChart) { const index = selectedCharts.value.findIndex((c) => c.name === chart.name) if (index === -1) { selectedCharts.value.push(chart) } else { selectedCharts.value.splice(index, 1) } } function toggleSelectAll() { if (areAllSelected.value) { selectedCharts.value = [] } else { selectedCharts.value = [...props.chartOptions] } } const areAllSelected = computed(() => selectedCharts.value.length === props.chartOptions.length) const areNoneSelected = computed(() => selectedCharts.value.length === 0) function confirmSelection() { emit('select', selectedCharts.value) selectedCharts.value = [] showDialog.value = false } </script> <template> <Dialog v-model="showDialog" :options="{ size: 'sm', title: 'Select Charts', actions: [ { label: 'Add', variant: 'solid', disabled: areNoneSelected, onClick: confirmSelection, }, { label: 'Cancel', onClick: () => (showDialog = false), }, ], }" > <template #body-content> <div class="-mb-5 flex flex-col gap-2 p-0.5"> <div class="flex gap-2"> <FormControl class="flex-1" autocomplete="off" placeholder="Search by name" v-model="searchQuery" > <template #prefix> <SearchIcon class="h-4 w-4 text-gray-500" /> </template> </FormControl> <Button @click="toggleSelectAll"> {{ areAllSelected ? `Deselect All (${selectedCharts.length})` : `Select All (${selectedCharts.length})` }} </Button> </div> <div class="flex h-[15rem] flex-col overflow-y-scroll rounded border p-0.5 text-base" > <template v-for="chart in filteredCharts"> <div class="flex h-7 flex-shrink-0 cursor-pointer items-center justify-between rounded px-2 hover:bg-gray-100" @click="toggleChart(chart)" > <div class="flex items-center gap-1.5"> <ChartIcon :chartType="chart.chart_type" /> <span>{{ chart.title || chart.name }}</span> </div> <component class="h-4 w-4" stroke-width="1.5" :is="isSelected(chart) ? CheckSquare : SquareIcon" :class="isSelected(chart) ? 'text-gray-900' : 'text-gray-600'" /> </div> </template> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/dashboard/ChartSelectorDialog.vue
Vue
agpl-3.0
3,311
<script setup lang="ts"> import { Edit3, RefreshCcw } from 'lucide-vue-next' import { computed, provide, ref } from 'vue' import { safeJSONParse } from '../helpers' import { createToast } from '../helpers/toasts' import { WorkbookChart, WorkbookDashboard, WorkbookQuery } from '../types/workbook.types' import ChartSelectorDialog from './ChartSelectorDialog.vue' import useDashboard from './dashboard' import DashboardFilterSelector from './DashboardFilterSelector.vue' import DashboardItem from './DashboardItem.vue' import DashboardItemActions from './DashboardItemActions.vue' import VueGridLayout from './VueGridLayout.vue' import ContentEditable from '../components/ContentEditable.vue' const props = defineProps<{ dashboard: WorkbookDashboard charts: WorkbookChart[] queries: WorkbookQuery[] }>() const dashboard = useDashboard(props.dashboard) provide('dashboard', dashboard) dashboard.refresh() const selectedCharts = computed(() => { return dashboard.doc.items.filter((item) => item.type == 'chart') }) const showChartSelectorDialog = ref(false) const showTextWidgetCreationDialog = ref(false) function onDragOver(event: DragEvent) { if (!event.dataTransfer) return event.preventDefault() event.dataTransfer.dropEffect = 'copy' } function onDrop(event: DragEvent) { if (!event.dataTransfer) return event.preventDefault() if (!dashboard.editing && dashboard.doc.items.length > 0) { return createToast({ title: 'Info', message: 'You can only add charts to the dashboard in edit mode', variant: 'info', }) } if (!dashboard.editing) { dashboard.editing = true } const data = safeJSONParse(event.dataTransfer.getData('text/plain')) const chartName = data.item.name const chart = props.charts.find((c) => c.name === chartName) if (!chart) return dashboard.addChart([chart]) } </script> <template> <div class="relative flex h-full w-full divide-x overflow-hidden"> <div class="relative flex h-full w-full flex-col overflow-hidden"> <div class="flex items-center justify-between border-x bg-white py-3 px-4 shadow-sm"> <ContentEditable class="rounded-sm text-lg font-medium !text-gray-800 focus:ring-2 focus:ring-gray-700 focus:ring-offset-4" :class="[dashboard.editing ? '' : 'cursor-default']" v-model="dashboard.doc.title" :disabled="!dashboard.editing" placeholder="Untitled Dashboard" ></ContentEditable> <div class="flex gap-2"> <DashboardFilterSelector v-if="!dashboard.editing" :dashboard="dashboard" :queries="props.queries" :charts="props.charts" /> <Button v-if="!dashboard.editing" variant="outline" @click="() => dashboard.refresh()" label="Refresh" > <template #prefix> <RefreshCcw class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> <Button v-if="!dashboard.editing" variant="outline" @click="dashboard.editing = true" label="Edit" > <template #prefix> <Edit3 class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> <Button v-if="dashboard.editing" variant="outline" icon-left="plus" @click="showChartSelectorDialog = true" > Chart </Button> <Button v-if="dashboard.editing" variant="solid" icon-left="check" @click="dashboard.editing = false" > Done </Button> </div> </div> <div class="flex-1 overflow-y-auto p-2" @dragover="onDragOver" @drop="onDrop"> <VueGridLayout v-if="dashboard.doc.items.length > 0" class="h-fit w-full" :class="[dashboard.editing ? 'mb-[20rem] ' : '']" :cols="20" :disabled="!dashboard.editing" :modelValue="dashboard.doc.items.map((item) => item.layout)" @update:modelValue=" (newLayout) => { dashboard.doc.items.forEach((item, idx) => { item.layout = newLayout[idx] }) } " > <template #item="{ index }"> <div class="relative h-full w-full p-2 [&>div:first-child]:h-full"> <Popover class="h-full" :show="dashboard.editing && dashboard.isActiveItem(index)" placement="top-start" > <template #target> <DashboardItem :index="index" :item="dashboard.doc.items[index]" /> </template> <template #body> <DashboardItemActions :dashboard="dashboard" :item-index="index" :item="dashboard.doc.items[index]" /> </template> </Popover> </div> </template> </VueGridLayout> </div> </div> </div> <ChartSelectorDialog v-model="showChartSelectorDialog" :chartOptions="props.charts" :selected-charts=" selectedCharts.map( (c) => props.charts.find((chart) => chart.name === c.chart) as WorkbookChart, ) " @select="dashboard.addChart($event)" /> </template>
2302_79757062/insights
frontend/src2/dashboard/DashboardBuilder.vue
Vue
agpl-3.0
4,950
<script setup lang="ts"> import { ListFilter } from 'lucide-vue-next' import { computed, reactive, ref } from 'vue' import { copy } from '../helpers' import FiltersSelectorDialog from '../query/components/FiltersSelectorDialog.vue' import { getCachedQuery } from '../query/query' import { FilterArgs, FilterGroupArgs } from '../types/query.types' import { WorkbookChart, WorkbookQuery } from '../types/workbook.types' import { Dashboard } from './dashboard' const props = defineProps<{ dashboard: Dashboard charts: WorkbookChart[] queries: WorkbookQuery[] }>() const showDialog = ref(false) const columnOptions = computed(() => { return props.queries .map((q) => { const query = getCachedQuery(q.name) if (!query) return [] return query.result.columns.map((c) => ({ query: q.name, label: c.name, data_type: c.type, description: c.type, value: `'${q.name}'.'${c.name}'`, })) }) .flat() }) const filterGroup = reactive<FilterGroupArgs>({ logical_operator: 'And', filters: [], }) setInitialFilters() function setInitialFilters() { const dashboardFilters = copy(props.dashboard.filters) filterGroup.filters = Object.entries(dashboardFilters) .map(([queryName, filters]) => { return filters.map((filter) => { if ('column' in filter) { filter.column.column_name = `'${queryName}'.'${filter.column.column_name}'` } return filter }) }) .flat() } function applyFilters(args: FilterGroupArgs) { const filtersByQuery = {} as Record<string, FilterArgs[]> args.filters.forEach((filter) => { if ('column' in filter) { const [queryName, columnName] = filter.column.column_name .split("'.'") .map((s) => s.replace(/'/g, '')) filter.column.column_name = columnName filtersByQuery[queryName] = filtersByQuery[queryName] || [] filtersByQuery[queryName].push(filter) } }) props.dashboard.filters = filtersByQuery props.dashboard.refresh() setInitialFilters() } </script> <template> <Button label="Filter" variant="outline" @click="showDialog = true"> <template #prefix> <ListFilter class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> Filter <template v-if="filterGroup.filters?.length" #suffix> <div class="flex h-5 w-5 items-center justify-center rounded bg-gray-900 pt-[1px] text-2xs font-medium text-white" > {{ filterGroup.filters.length }} </div> </template> </Button> <FiltersSelectorDialog v-if="showDialog" v-model="showDialog" :filter-group="filterGroup" :column-options="columnOptions" @select="applyFilters($event)" /> </template>
2302_79757062/insights
frontend/src2/dashboard/DashboardFilterSelector.vue
Vue
agpl-3.0
2,592
<script setup lang="ts"> import { computed, inject } from 'vue' import { Chart, getCachedChart } from '../charts/chart' import ChartRenderer from '../charts/components/ChartRenderer.vue' import ColumnFilter from '../query/components/ColumnFilter.vue' import DataTypeIcon from '../query/components/DataTypeIcon.vue' import { column } from '../query/helpers' import { Query, getCachedQuery } from '../query/query' import { FilterOperator, FilterValue } from '../types/query.types' import { WorkbookDashboardChart, WorkbookDashboardFilter, WorkbookDashboardItem, } from '../types/workbook.types' import { Dashboard } from './dashboard' const props = defineProps<{ index: number item: WorkbookDashboardItem }>() const dashboard = inject('dashboard') as Dashboard const chart = computed(() => { if (props.item.type != 'chart') return null const item = props.item as WorkbookDashboardChart return getCachedChart(item.chart) as Chart }) const filter = computed(() => { if (props.item.type != 'filter') return null return props.item as WorkbookDashboardFilter }) function getDistinctColumnValues(searchTxt: string) { if (!filter.value) return const query = getCachedQuery(filter.value.column.query) as Query return query.getDistinctColumnValues(filter.value.column.name, searchTxt) } function handleApplyFilter(operator: FilterOperator, value: FilterValue) { if (!filter.value) return dashboard.applyFilter(filter.value.column.query, { column: column(filter.value.column.name), operator, value, }) } </script> <template> <div class="flex h-full w-full items-center rounded" :class="[ dashboard.editing && dashboard.isActiveItem(index) ? 'outline outline-gray-700' : '', ]" @click="dashboard.setActiveItem(index)" > <div class="h-full w-full" :class="dashboard.editing ? 'pointer-events-none' : ''"> <ChartRenderer v-if="chart" :chart="chart" /> </div> </div> </template>
2302_79757062/insights
frontend/src2/dashboard/DashboardItem.vue
Vue
agpl-3.0
1,910
<script setup lang="ts"> import { computed, inject } from 'vue' import { useRouter } from 'vue-router' import { WorkbookDashboardChart, WorkbookDashboardItem } from '../types/workbook.types' import { Workbook, workbookKey } from '../workbook/workbook' import { Dashboard } from './dashboard' const props = defineProps<{ dashboard: Dashboard itemIndex: number item: WorkbookDashboardItem }>() const workbook = inject(workbookKey) as Workbook const router = useRouter() const chartIndex = computed(() => { if (props.item.type !== 'chart') return const chartItem = props.item as WorkbookDashboardChart return workbook.doc.charts.findIndex((c) => c.name === chartItem.chart) }) const actions = [ { icon: 'trash', label: 'Delete', onClick: () => props.dashboard.removeItem(props.itemIndex), }, ] if (props.item.type === 'chart') { actions.splice(0, 0, { icon: 'edit', label: 'Edit', onClick: () => router.push(`/workbook/${workbook.doc.name}/chart/${chartIndex.value}`), }) } </script> <template> <div class="flex w-fit cursor-pointer rounded bg-gray-800 p-1 shadow-sm"> <div v-for="action in actions" :key="action.label" class="px-1 py-0.5" @click="action.onClick()" > <FeatherIcon :name="action.icon" class="h-3.5 w-3.5 text-white" /> </div> </div> </template>
2302_79757062/insights
frontend/src2/dashboard/DashboardItemActions.vue
Vue
agpl-3.0
1,307
<script setup lang="ts"></script> <template></template>
2302_79757062/insights
frontend/src2/dashboard/DashboardList.vue
Vue
agpl-3.0
57
<template> <grid-layout v-model:layout="layouts" v-bind="options"> <template #default="{ gridItemProps }"> <grid-item v-for="(layout, index) in layouts" v-bind="gridItemProps" :key="layout.i" :i="layout.i" :x="layout.x" :y="layout.y" :w="layout.w" :h="layout.h" > <slot name="item" :index="index" :i="layout.i" :x="layout.x" :y="layout.y" :w="layout.w" :h="layout.h" > <pre class="h-full w-full rounded bg-white p-4 shadow"> {{ { i: layout.i, x: layout.x, y: layout.y, w: layout.w, h: layout.h } }} </pre > </slot> </grid-item> </template> </grid-layout> </template> <script setup lang="ts"> import { computed, reactive } from 'vue' type Layout = { i: string x: number y: number w: number h: number } const layouts = defineModel<Layout[]>() const props = defineProps<{ cols?: number disabled?: Boolean }>() const options = reactive({ colNum: props.cols || 12, margin: [0, 0], rowHeight: 52, isDraggable: computed(() => !props.disabled), isResizable: computed(() => !props.disabled), responsive: true, verticalCompact: false, preventCollision: true, useCssTransforms: true, cols: { lg: props.cols || 12, md: props.cols || 12, sm: props.cols || 12, xs: 1, xxs: 1, }, }) </script> <style lang="scss"> .vgl-layout { --vgl-placeholder-bg: #b1b1b1; --vgl-placeholder-opacity: 15%; --vgl-placeholder-z-index: 2; --vgl-item-resizing-z-index: 3; --vgl-item-resizing-opacity: 100%; --vgl-item-dragging-z-index: 3; --vgl-item-dragging-opacity: 100%; --vgl-resizer-size: 10px; --vgl-resizer-border-color: #444; --vgl-resizer-border-width: 2px; } .vgl-item--placeholder { z-index: var(--vgl-placeholder-z-index, 2); user-select: none; background-color: var(--vgl-placeholder-bg); opacity: var(--vgl-placeholder-opacity); transition-duration: 100ms; border-radius: 0.5rem; } .vgl-item__resizer { position: absolute; right: 12px; bottom: 12px; box-sizing: border-box; width: var(--vgl-resizer-size); height: var(--vgl-resizer-size); cursor: se-resize; } .vgl-item__resizer:before { position: absolute; inset: 0 3px 3px 0; content: ''; border: 0 solid var(--vgl-resizer-border-color); border-right-width: var(--vgl-resizer-border-width); border-bottom-width: var(--vgl-resizer-border-width); } </style>
2302_79757062/insights
frontend/src2/dashboard/VueGridLayout.vue
Vue
agpl-3.0
2,367
import { reactive } from 'vue' import { getCachedChart } from '../charts/chart' import { getUniqueId, store } from '../helpers' import { FilterArgs } from '../types/query.types' import { DashboardFilterColumn, WorkbookChart, WorkbookDashboard, WorkbookDashboardChart, } from '../types/workbook.types' const dashboards = new Map<string, Dashboard>() export default function useDashboard(workbookDashboard: WorkbookDashboard) { const existingDashboard = dashboards.get(workbookDashboard.name) if (existingDashboard) return existingDashboard const dashboard = makeDashboard(workbookDashboard) dashboards.set(workbookDashboard.name, dashboard) return dashboard } function makeDashboard(workbookDashboard: WorkbookDashboard) { const dashboard = reactive({ doc: workbookDashboard, editing: false, filters: {} as Record<string, FilterArgs[]>, activeItemIdx: null as number | null, setActiveItem(index: number) { dashboard.activeItemIdx = index }, isActiveItem(index: number) { return dashboard.activeItemIdx == index }, addChart(charts: WorkbookChart[]) { charts.forEach((chart) => { if ( !dashboard.doc.items.some((item) => item.type === 'chart' && item.chart === chart.name) ) { dashboard.doc.items.push({ type: 'chart', chart: chart.name, layout: { i: getUniqueId(), x: 0, y: 0, w: chart.chart_type === 'Number' ? 20 : 10, h: chart.chart_type === 'Number' ? 3 : 8, }, }) } }) }, addFilter(column: DashboardFilterColumn) { dashboard.doc.items.push({ type: 'filter', column: column, layout: { i: getUniqueId(), x: 0, y: 0, w: 4, h: 1, }, }) }, removeItem(index: number) { dashboard.doc.items.splice(index, 1) }, applyFilter(query: string, args: FilterArgs) { if (!dashboard.filters[query]) dashboard.filters[query] = [] dashboard.filters[query].push(args) }, refresh() { dashboard.doc.items .filter((item): item is WorkbookDashboardChart => item.type === 'chart') .forEach((chartItem) => { const chart = getCachedChart(chartItem.chart) if (!chart || !chart.doc.query) return const filters = dashboard.filters[chart.doc.query] chart.refresh(filters, true) }) }, }) const key = `insights:dashboard-filters-${workbookDashboard.name}` dashboard.filters = store(key, () => dashboard.filters) return dashboard } export type Dashboard = ReturnType<typeof makeDashboard>
2302_79757062/insights
frontend/src2/dashboard/dashboard.ts
TypeScript
agpl-3.0
2,510
<script setup lang="ts"> import { computed, ref } from 'vue' import Form from '../components/Form.vue' import useDataSourceStore from './data_source' import { MariaDBDataSource } from './data_source.types' const show = defineModel({ default: false, }) const database = ref<MariaDBDataSource>({ database_type: 'MariaDB', title: '', host: 'localhost', port: 3306, database_name: '', username: '', password: '', use_ssl: false, }) const form = ref() const fields = [ { name: 'title', label: 'Title', type: 'text', placeholder: 'My Database', required: true, }, { label: 'Host', name: 'host', type: 'text', placeholder: 'localhost', required: true, defaultValue: 'localhost', }, { label: 'Port', name: 'port', type: 'number', placeholder: '3306', required: true, defaultValue: 3306, }, { label: 'Database Name', name: 'database_name', type: 'text', placeholder: 'DB_1267891', required: true, }, { label: 'Username', name: 'username', type: 'text', placeholder: 'read_only_user', required: true, }, { label: 'Password', name: 'password', type: 'password', placeholder: '**********', required: true, }, { label: 'Use secure connection (SSL)?', name: 'use_ssl', type: 'checkbox' }, ] const sources = useDataSourceStore() const connected = ref<boolean | null>(null) const connectButton = computed(() => { const _button = { label: 'Connect', disabled: form.value?.hasRequiredFields === false, loading: sources.testing, variant: 'subtle', theme: 'gray', onClick() { sources.testConnection(database.value).then((result: boolean) => { connected.value = Boolean(result) }) }, } if (sources.testing) { _button.label = 'Connecting...' } else if (connected.value) { _button.label = 'Connected' _button.variant = 'outline' _button.theme = 'green' } else if (connected.value === false) { _button.label = 'Failed, Retry?' _button.variant = 'outline' _button.theme = 'red' } return _button }) const submitButton = computed(() => { return { label: 'Add Data Source', disabled: form.value?.hasRequiredFields === false || !connected.value || sources.creating, loading: sources.creating, variant: connected.value ? 'solid' : 'subtle', onClick() { sources.createDataSource(database.value).then(() => { show.value = false }) }, } }) </script> <template> <Dialog v-model="show" :options="{ title: 'Connect to MariaDB' }"> <template #body-content> <Form ref="form" class="flex-1" v-model="database" :fields="fields" :actions="[connectButton, submitButton]" > </Form> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/data_source/ConnectMariaDBDialog.vue
Vue
agpl-3.0
2,672
<script setup lang="ts"> import { computed, ref } from 'vue' import Form from '../components/Form.vue' import useDataSourceStore from './data_source' import { PostgreSQLDataSource } from './data_source.types' const show = defineModel({ default: false, }) const database = ref<PostgreSQLDataSource>({ database_type: 'PostgreSQL', title: '', host: 'localhost', port: 5432, database_name: '', username: '', password: '', use_ssl: false, }) const form = ref() const fields = [ { name: 'title', label: 'Title', type: 'text', placeholder: 'My Database', required: true, }, { label: 'Host', name: 'host', type: 'text', placeholder: 'localhost', required: true, defaultValue: 'localhost', }, { label: 'Port', name: 'port', type: 'number', placeholder: '5432', required: true, defaultValue: 5432, }, { label: 'Database Name', name: 'database_name', type: 'text', placeholder: 'DB_1267891', required: true, }, { label: 'Username', name: 'username', type: 'text', placeholder: 'read_only_user', required: true, }, { label: 'Password', name: 'password', type: 'password', placeholder: '**********', required: true, }, { label: 'Use secure connection (SSL)?', name: 'use_ssl', type: 'checkbox' }, ] const sources = useDataSourceStore() const connected = ref<boolean | null>(null) const connectButton = computed(() => { const _button = { label: 'Connect', disabled: form.value?.hasRequiredFields === false, loading: sources.testing, variant: 'subtle', theme: 'gray', onClick() { sources.testConnection(database.value).then((result: boolean) => { connected.value = Boolean(result) }) }, } if (sources.testing) { _button.label = 'Connecting...' } else if (connected.value) { _button.label = 'Connected' _button.variant = 'outline' _button.theme = 'green' } else if (connected.value === false) { _button.label = 'Failed, Retry?' _button.variant = 'outline' _button.theme = 'red' } return _button }) const submitButton = computed(() => { return { label: 'Add Data Source', disabled: form.value?.hasRequiredFields === false || !connected.value || sources.creating, loading: sources.creating, variant: connected.value ? 'solid' : 'subtle', onClick() { sources.createDataSource(database.value).then(() => { show.value = false }) }, } }) </script> <template> <Dialog v-model="show" :options="{ title: 'Connect to PostgreSQL' }"> <template #body-content> <Form ref="form" class="flex-1" v-model="database" :fields="fields" :actions="[connectButton, submitButton]" > </Form> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/data_source/ConnectPostgreSQLDialog.vue
Vue
agpl-3.0
2,684
<script setup lang="tsx"> import { Avatar, Breadcrumbs, ListView } from 'frappe-ui' import { PlusIcon, SearchIcon } from 'lucide-vue-next' import { computed, ref } from 'vue' import CSVIcon from '../components/Icons/CSVIcon.vue' import DuckDBIcon from '../components/Icons/DuckDBIcon.vue' import IndicatorIcon from '../components/Icons/IndicatorIcon.vue' import MariaDBIcon from '../components/Icons/MariaDBIcon.vue' import PostgreSQLIcon from '../components/Icons/PostgreSQLIcon.vue' import SQLiteIcon from '../components/Icons/SQLiteIcon.vue' import SelectTypeDialog from '../components/SelectTypeDialog.vue' import useUserStore from '../users/users' import ConnectMariaDBDialog from './ConnectMariaDBDialog.vue' import ConnectPostgreSQLDialog from './ConnectPostgreSQLDialog.vue' import useDataSourceStore from './data_source' import { DataSourceListItem } from './data_source.types' import UploadCSVFileDialog from './UploadCSVFileDialog.vue' const dataSourceStore = useDataSourceStore() dataSourceStore.getSources() const searchQuery = ref('') const filteredDataSources = computed(() => { if (!searchQuery.value) { return dataSourceStore.sources } return dataSourceStore.sources.filter((data_source) => data_source.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ) }) const showNewSourceDialog = ref(false) const showNewMariaDBDialog = ref(false) const showNewPostgreSQLDialog = ref(false) const showCSVFileUploadDialog = ref(false) const sourceTypes = [ { label: 'MariaDB', icon: <MariaDBIcon class="h-8 w-8" />, description: 'Connect to MariaDB database', onClick: () => { showNewSourceDialog.value = false showNewMariaDBDialog.value = true }, }, { label: 'PostgreSQL', icon: <PostgreSQLIcon class="h-8 w-8" />, description: 'Connect to PostgreSQL database', onClick: () => { showNewSourceDialog.value = false showNewPostgreSQLDialog.value = true }, }, { label: 'Upload CSV', icon: <CSVIcon class="h-8 w-8" />, description: 'Upload a CSV file', onClick: () => { showNewSourceDialog.value = false showCSVFileUploadDialog.value = true }, }, ] const userStore = useUserStore() const listOptions = ref({ columns: [ { label: 'Title', key: 'title', prefix: (props: any) => { const data_source = props.row as DataSourceListItem if (data_source.database_type === 'MariaDB') { return <MariaDBIcon class="h-5 w-5" /> } if (data_source.database_type === 'PostgreSQL') { return <PostgreSQLIcon class="h-5 w-5" /> } if (data_source.database_type === 'SQLite') { return <SQLiteIcon class="h-5 w-5" /> } if (data_source.database_type === 'DuckDB') { return <DuckDBIcon class="h-5 w-5" /> } }, }, { label: 'Status', key: 'status', prefix: (props: any) => { const color = props.row.status == 'Inactive' ? 'text-gray-500' : 'text-green-500' return <IndicatorIcon class={color} /> }, }, { label: 'Owner', key: 'owner', prefix: (props: any) => { const data_source = props.row as DataSourceListItem const imageUrl = userStore.getUser(data_source.owner)?.user_image return <Avatar size="md" label={data_source.owner} image={imageUrl} /> }, }, { label: 'Created', key: 'created_from_now' }, { label: 'Modified', key: 'modified_from_now' }, ], rows: filteredDataSources, rowKey: 'name', options: { showTooltip: false, getRowRoute: (data_source: DataSourceListItem) => ({ path: `/data-source/${data_source.name}`, }), emptyState: { title: 'No data sources.', description: 'No data sources to display.', button: { label: 'New Data Source', variant: 'solid', onClick: () => (showNewSourceDialog.value = true), }, }, }, }) document.title = 'Data Sources | Insights' </script> <template> <header class="mb-2 flex h-12 items-center justify-between border-b py-2.5 pl-5 pr-2"> <Breadcrumbs :items="[{ label: 'Data Sources', route: '/data-source' }]" /> <div class="flex items-center gap-2"> <Button label="New Data Source" variant="solid" @click="showNewSourceDialog = 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" v-model="searchQuery" :debounce="300"> <template #prefix> <SearchIcon class="h-4 w-4 text-gray-500" /> </template> </FormControl> </div> <ListView class="h-full" v-bind="listOptions"> </ListView> </div> <SelectTypeDialog v-model="showNewSourceDialog" :types="sourceTypes" title="Select a data source" /> <ConnectMariaDBDialog v-model="showNewMariaDBDialog" /> <ConnectPostgreSQLDialog v-model="showNewPostgreSQLDialog" /> <UploadCSVFileDialog v-model="showCSVFileUploadDialog" /> </template>
2302_79757062/insights
frontend/src2/data_source/DataSourceList.vue
Vue
agpl-3.0
4,904
<script setup lang="tsx"> import { watchDebounced } from '@vueuse/core' import { Breadcrumbs, ListView } from 'frappe-ui' import { MoreHorizontal, RefreshCcw, SearchIcon } from 'lucide-vue-next' import { h, ref } from 'vue' import useTableStore, { DataSourceTable } from './tables' const props = defineProps<{ name: string }>() const tableStore = useTableStore() const searchQuery = ref('') const filteredTables = ref<DataSourceTable[]>() watchDebounced(searchQuery, () => updateTablesList(), { debounce: 300, immediate: true }) function updateTablesList() { tableStore.getTables(props.name, searchQuery.value).then((tables) => { filteredTables.value = tables }) } const listOptions = ref({ columns: [ { label: 'Table Name', key: 'table_name', }, ], rows: filteredTables, rowKey: 'table_name', options: { showTooltip: false, emptyState: { title: 'No Tables Found', description: 'No tables found for the selected data source.', button: { label: 'Refresh', iconLeft: 'refresh-ccw', variant: 'outline', loading: tableStore.updatingDataSourceTables, onClick: () => tableStore.updateDataSourceTables(props.name).then(() => updateTablesList()), }, }, }, }) document.title = `Tables | ${props.name}` </script> <template> <header class="mb-2 flex h-12 items-center justify-between border-b py-2.5 pl-5 pr-2"> <Breadcrumbs :items="[ { label: 'Data Sources', route: '/data-source' }, { label: props.name, route: `/data-source/${props.name}` }, ]" /> <div class="flex items-center gap-2"></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" v-model="searchQuery" :debounce="300"> <template #prefix> <SearchIcon class="h-4 w-4 text-gray-500" /> </template> </FormControl> <Dropdown :options="[ { label: 'Update Tables', onClick: () => tableStore .updateDataSourceTables(props.name) .then(() => updateTablesList()), icon: () => h(RefreshCcw, { class: 'h-4 w-4 text-gray-700', 'stroke-width': '1.5', }), }, ]" > <Button> <template #icon> <MoreHorizontal class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> </Dropdown> </div> <ListView class="h-full" v-bind="listOptions"> </ListView> </div> </template>
2302_79757062/insights
frontend/src2/data_source/DataSourceTableList.vue
Vue
agpl-3.0
2,472
<script setup lang="ts"> import { FileUploader, call } from 'frappe-ui' import { FileUp } from 'lucide-vue-next' import { computed, reactive, ref } from 'vue' import DataTable from '../components/DataTable.vue' import { QueryResultColumn, QueryResultRow } from '../types/query.types' import { createToast } from '../helpers/toasts' const show = defineModel() const fileUploaded = ref(false) const csvData = reactive({ loading: false, file: null as File | null, tablename: '', columns: [] as QueryResultColumn[], rows: [] as QueryResultRow[], totalRowCount: 0, }) function uploadFileAndFetchData(file: File) { fileUploaded.value = true csvData.loading = true csvData.file = file return call('insights.api.get_csv_data', { filename: file.name, }) .then((data: any) => { csvData.tablename = data.tablename csvData.columns = data.columns csvData.rows = data.rows csvData.totalRowCount = data.total_rows }) .finally(() => { csvData.loading = false }) } const importing = ref(false) const importDisabled = computed(() => { return !csvData.file || !csvData.tablename || !csvData.columns.length || importing.value }) function importCSVData() { if (importDisabled.value) return if (!csvData.file) return importing.value = true return call('insights.api.import_csv_data', { filename: csvData.file.name, }) .then(() => { show.value = false createToast({ title: 'Table Imported', message: `Table '${csvData.tablename}' imported successfully`, variant: 'success', }) }) .finally(() => { importing.value = false }) } </script> <template> <Dialog v-model="show" :options="{ title: csvData.tablename ? `Import '${csvData.tablename}' Table` : 'Upload CSV File', size: fileUploaded ? '4xl' : '', }" > <template #body-content> <FileUploader v-if="!fileUploaded" :file-types="['.csv']" @success="uploadFileAndFetchData" > <template #default="{ progress, uploading, openFileSelector }"> <div class="flex cursor-pointer flex-col items-center justify-center gap-3 rounded border border-dashed border-gray-400 p-12 text-base" @click="openFileSelector" > <FileUp v-if="!uploading" class="h-6 w-6 text-gray-600" stroke-width="1.2" /> <div class="text-center"> <p v-if="!uploading" class="text-sm font-medium text-gray-800"> Select a CSV file to upload </p> <p v-if="!uploading" class="mt-1 text-xs text-gray-600"> or drag and drop it here </p> <div v-else class="flex w-[15rem] flex-col gap-2"> <div class="h-2 w-full rounded-full bg-gray-200"> <div class="h-2 rounded-full bg-blue-500 transition-all" :style="{ width: `${progress}%` }" ></div> </div> <p class="text-xs">Uploading...</p> </div> </div> </div> </template> </FileUploader> <div v-else class="relative flex h-[30rem] w-full flex-1 flex-col overflow-hidden rounded border bg-white" > <div v-if="csvData.loading" class="absolute top-10 z-10 flex h-[calc(100%-2rem)] w-full items-center justify-center rounded bg-gray-50/30 backdrop-blur-sm" > <LoadingIndicator class="h-8 w-8 text-gray-700" /> </div> <DataTable v-else :columns="csvData.columns" :rows="csvData.rows"> <template #footer> <div class="flex flex-shrink-0 items-center gap-3 border-t p-2"> <p class="tnum text-sm text-gray-600"> Showing {{ csvData.rows.length }} of {{ csvData.totalRowCount }} rows </p> </div> </template> </DataTable> </div> <div class="mt-4 flex justify-between pt-2"> <div class="ml-auto flex items-center space-x-2"> <Button variant="solid" :disabled="importDisabled" :loading="importing" @click="importCSVData" > Import </Button> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/data_source/UploadCSVFileDialog.vue
Vue
agpl-3.0
3,984
import { call } from 'frappe-ui' import { reactive, ref } from 'vue' import { useTimeAgo } from '@vueuse/core' import { DataSource, DataSourceListItem } from './data_source.types' import { showErrorToast } from '../helpers' const sources = ref<DataSourceListItem[]>([]) const loading = ref(false) async function getSources() { loading.value = true sources.value = await call('insights.api.data_sources.get_all_data_sources') sources.value = sources.value.map((source: any) => ({ ...source, created_from_now: useTimeAgo(source.creation), modified_from_now: useTimeAgo(source.modified), title: source.is_site_db && source.title == 'Site DB' ? window.location.hostname : source.title, })) loading.value = false return sources.value } const testing = ref(false) function testConnection(data_source: DataSource) { testing.value = true return call('insights.api.data_sources.test_connection', { data_source }) .catch((error: Error) => { showErrorToast(error, false) }) .finally(() => { testing.value = false }) } const creating = ref(false) function createDataSource(data_source: DataSource) { creating.value = true return call('insights.api.data_sources.create_data_source', { data_source }) .catch((error: Error) => { showErrorToast(error) }) .finally(() => { creating.value = false }) } export default function useDataSourceStore() { if (!sources.value.length) { getSources() } return reactive({ sources, loading, getSources, testing, testConnection, creating, createDataSource, }) }
2302_79757062/insights
frontend/src2/data_source/data_source.ts
TypeScript
agpl-3.0
1,556
export type DataSourceListItem = { title: string name: string owner: string status: 'Active' | 'Inactive' database_type: 'MariaDB' | 'PostgreSQL' | 'SQLite' | 'DuckDB' creation: string modified: string created_from_now: string modified_from_now: string } type BaseDataSource = { title: string database_type: 'MariaDB' | 'PostgreSQL' | 'SQLite' | 'DuckDB' status?: 'Active' | 'Inactive' } export type MariaDBDataSource = BaseDataSource & { database_type: 'MariaDB' host: string port: number database_name: string username: string password: string use_ssl: boolean } export type PostgreSQLDataSource = BaseDataSource & { database_type: 'PostgreSQL' host: string port: number database_name: string username: string password: string use_ssl: boolean } export type DataSource = MariaDBDataSource | PostgreSQLDataSource
2302_79757062/insights
frontend/src2/data_source/data_source.types.ts
TypeScript
agpl-3.0
845
import { call } from 'frappe-ui' import { reactive, ref } from 'vue' import { showErrorToast } from '../helpers' import { createToast } from '../helpers/toasts' import { QueryResultColumn } from '../types/query.types' export type DataSourceTable = { table_name: string; data_source: string } const tables = ref<DataSourceTable[]>([]) const loading = ref(false) async function getTables(data_source?: string, search_term?: string) { loading.value = true tables.value = await call('insights.api.data_sources.get_data_source_tables', { data_source, search_term, }) loading.value = false return tables.value } async function getTableColumns(data_source: string, table_name: string) { return call('insights.api.data_sources.get_data_source_table_columns', { data_source, table_name, }).then((columns: any[]) => { return columns.map((c) => ({ name: c.column, type: c.type, })) as QueryResultColumn[] }) } const updatingDataSourceTables = ref(false) async function updateDataSourceTables(data_source: string) { updatingDataSourceTables.value = true createToast({ message: `Updating tables for ${data_source}`, variant: 'info', }) return call('insights.api.data_sources.update_data_source_tables', { data_source }) .then(() => { getTables(data_source) createToast({ message: `Tables updated for ${data_source}`, variant: 'success', }) }) .catch((e: Error) => { showErrorToast(e) }) .finally(() => { updatingDataSourceTables.value = false }) } type TableLink = { left_table: string right_table: string left_column: string right_column: string } async function getTableLinks( data_source: string, left_table: string, right_table: string ): Promise<TableLink[]> { return call('insights.api.data_sources.get_table_links', { data_source, left_table, right_table, }) } export default function useTableStore() { return reactive({ tables, loading, getTables, getTableColumns, updatingDataSourceTables, updateDataSourceTables, getTableLinks, }) }
2302_79757062/insights
frontend/src2/data_source/tables.ts
TypeScript
agpl-3.0
2,036
import Autocomplete from './components/Autocomplete.vue' import Checkbox from './components/Checkbox.vue' import Popover from './components/Popover.vue' import Switch from './components/Switch.vue' import { Avatar, Badge, Button, Dialog, Dropdown, ErrorMessage, FeatherIcon, Input, LoadingIndicator, Tooltip, FormControl } from 'frappe-ui' import { App } from 'vue' import dayjs from './helpers/dayjs.ts' import { createToast } from './helpers/toasts' import { initSocket } from './socket.ts' export function registerGlobalComponents(app: App) { app.component('Input', Input) app.component('Badge', Badge) app.component('Button', Button) app.component('Dialog', Dialog) app.component('Avatar', Avatar) app.component('Switch', Switch) app.component('Popover', Popover) app.component('Tooltip', Tooltip) app.component('Checkbox', Checkbox) app.component('Dropdown', Dropdown) app.component('FormControl', FormControl) app.component('LoadingIndicator', LoadingIndicator) app.component('Autocomplete', Autocomplete) app.component('ErrorMessage', ErrorMessage) app.component('FeatherIcon', FeatherIcon) } export function registerControllers(app: App) { app.provide('$dayjs', dayjs) app.provide('$notify', createToast) app.provide('$socket', initSocket()) }
2302_79757062/insights
frontend/src2/globals.ts
TypeScript
agpl-3.0
1,284
import ConfirmDialog from '../components/ConfirmDialog.vue' import { VNode, h, ref } from 'vue' export const dialogs = ref<VNode[]>([]) export function confirmDialog({ title = 'Untitled', message = '', theme = 'gray', fields = [], onSuccess = () => {}, }) { const component = h(ConfirmDialog, { title, message, theme, fields, onSuccess, }) dialogs.value.push(component) }
2302_79757062/insights
frontend/src2/helpers/confirm_dialog.ts
TypeScript
agpl-3.0
392
import { defineAsyncComponent } from 'vue' const NumberTypes = ['Integer', 'Decimal'] const TextTypes = ['Text', 'String'] const DateTypes = ['Date', 'Datetime', 'Time'] export const FIELDTYPES = { NUMBER: NumberTypes, TEXT: TextTypes, DATE: DateTypes, MEASURE: NumberTypes, DIMENSION: TextTypes.concat(DateTypes), DISCRETE: TextTypes, CONTINUOUS: NumberTypes.concat(DateTypes), } export const COLUMN_TYPES = [ { label: 'String', value: 'String' }, { label: 'Text', value: 'Text' }, { label: 'Integer', value: 'Integer' }, { label: 'Decimal', value: 'Decimal' }, { label: 'Date', value: 'Date' }, { label: 'Time', value: 'Time' }, { label: 'Datetime', value: 'Datetime' }, ] export const joinTypes = [ { label: 'Inner', icon: defineAsyncComponent(() => import('../components/Icons/JoinInnerIcon.vue')), value: 'inner', description: 'Keep only rows that have matching values in both tables', }, { label: 'Left', icon: defineAsyncComponent(() => import('../components/Icons/JoinLeftIcon.vue')), value: 'left', description: 'Keep all existing rows and include matching rows from the new table', }, { label: 'Right', icon: defineAsyncComponent(() => import('../components/Icons/JoinRightIcon.vue')), value: 'right', description: 'Keep all rows from the new table and include matching rows from the existing table', }, { label: 'Full', icon: defineAsyncComponent(() => import('../components/Icons/JoinFullIcon.vue')), value: 'full', description: 'Keep all rows from both tables', }, ] as const
2302_79757062/insights
frontend/src2/helpers/constants.ts
TypeScript
agpl-3.0
1,550
import dayjs from 'dayjs' import relativeTime from 'dayjs/esm/plugin/relativeTime' import quarterOfYear from 'dayjs/esm/plugin/quarterOfYear' import advancedFormat from 'dayjs/esm/plugin/advancedFormat' import customParseFormat from 'dayjs/esm/plugin/customParseFormat' dayjs.extend(relativeTime) dayjs.extend(quarterOfYear) dayjs.extend(advancedFormat) dayjs.extend(customParseFormat) export default dayjs
2302_79757062/insights
frontend/src2/helpers/dayjs.ts
TypeScript
agpl-3.0
409
import { watchDebounced } from '@vueuse/core' import domtoimage from 'dom-to-image' import { ComputedRef, Ref, watch } from 'vue' import session from '../session' import { createToast } from './toasts' export function getUniqueId(length = 8) { return (+new Date() * Math.random()).toString(36).substring(0, length) } export function titleCase(str: string) { return str .toLowerCase() .split(' ') .map(function (word) { return word.charAt(0).toUpperCase() + word.slice(1) }) .join(' ') } export function copy<T>(obj: T) { return JSON.parse(JSON.stringify(obj)) as T } export function wheneverChanges( getter: Ref | ComputedRef | Function, callback: Function, options: any = {} ) { let prevValue: any function onChange(value: any) { if (areDeeplyEqual(value, prevValue)) return prevValue = value callback(value) } return watchDebounced(getter, onChange, options) } export function areDeeplyEqual(obj1: any, obj2: any): boolean { if (obj1 === obj2) return true if (Array.isArray(obj1) && Array.isArray(obj2)) { if (obj1.length !== obj2.length) return false return obj1.every((elem, index) => { return areDeeplyEqual(elem, obj2[index]) }) } if (typeof obj1 === 'object' && typeof obj2 === 'object' && obj1 !== null && obj2 !== null) { if (Array.isArray(obj1) || Array.isArray(obj2)) return false const keys1 = Object.keys(obj1) const keys2 = Object.keys(obj2) if (keys1.length !== keys2.length || !keys1.every((key) => keys2.includes(key))) return false for (let key in obj1) { let isEqual = areDeeplyEqual(obj1[key], obj2[key]) if (!isEqual) { return false } } return true } return false } export function waitUntil(fn: () => boolean) { return new Promise<void>((resolve) => { if (fn()) { resolve() return } const stop = watch(fn, (value) => { if (value) { stop() resolve() } }) }) } export function store<T>(key: string, value: () => T) { const stored = localStorage.getItem(key) watchDebounced(value, (val) => localStorage.setItem(key, JSON.stringify(val)), { debounce: 500, deep: true, }) return stored ? JSON.parse(stored) : value() } export function getErrorMessage(err: any) { return err.exc?.split('\n').filter(Boolean).at(-1) } export function showErrorToast(err: Error, raise = true) { createToast({ variant: 'error', title: 'Error', message: getErrorMessage(err), }) if (raise) throw err } export function downloadImage(element: HTMLElement, filename: string, scale = 1, options = {}) { return domtoimage .toPng(element, { height: element.offsetHeight * scale, width: element.offsetWidth * scale, style: { transform: 'scale(' + scale + ')', transformOrigin: 'top left', width: element.offsetWidth + 'px', height: element.offsetHeight + 'px', }, bgColor: 'white', ...options, }) .then(function (dataUrl: string) { const img = new Image() img.src = dataUrl img.onload = async () => { const link = document.createElement('a') link.download = filename link.href = img.src link.click() } }) } export function formatNumber(number: number, precision = 2) { if (isNaN(number)) return number precision = precision || guessPrecision(number) const locale = session.user?.country == 'India' ? 'en-IN' : session.user?.locale return new Intl.NumberFormat(locale || 'en-US', { maximumFractionDigits: precision, }).format(number) } export function guessPrecision(number: number) { // eg. 1.0 precision = 1, 1.00 precision = 2 const str = number.toString() const decimalIndex = str.indexOf('.') if (decimalIndex === -1) return 0 return Math.min(str.length - decimalIndex - 1, 2) } export function getShortNumber(number: number, precision = 0) { const locale = session.user?.country == 'India' ? 'en-IN' : session.user?.locale let formatted = new Intl.NumberFormat(locale || 'en-US', { notation: 'compact', maximumFractionDigits: precision, }).format(number) if (locale == 'en-IN') { formatted = formatted.replace('T', 'K') } return formatted } export function fuzzySearch(arr: any[], { term, keys }: { term: string; keys: string[] }) { // search for term in all keys of arr items and sort by relevance const lowerCaseTerm = term.toLowerCase() type Result = { item: any; score: number } const results: Result[] = arr.reduce((acc, item) => { const score = keys.reduce((acc, key) => { const value = item[key] if (value) { const match = value.toLowerCase().indexOf(lowerCaseTerm) if (match !== -1) { return acc + match + 1 } } return acc }, 0) if (score) { acc.push({ item, score }) } return acc }, []) return results.sort((a, b) => a.score - b.score).map((item) => item.item) } export function safeJSONParse(str: string, defaultValue = null) { if (str === null || str === undefined) { return defaultValue } if (typeof str !== 'string') { return str } try { return JSON.parse(str) } catch (e) { console.groupCollapsed('Error parsing JSON') console.log(str) console.error(e) console.groupEnd() createToast({ message: 'Error parsing JSON', variant: 'error', }) return defaultValue } } export function copyToClipboard(text: string) { if (navigator.clipboard) { navigator.clipboard.writeText(text) createToast({ variant: 'success', title: 'Copied to clipboard', }) } else { // try to use execCommand const textArea = document.createElement('textarea') textArea.value = text textArea.style.position = 'fixed' document.body.appendChild(textArea) textArea.focus() textArea.select() try { document.execCommand('copy') createToast({ variant: 'success', title: 'Copied to clipboard', }) } catch (err) { createToast({ variant: 'error', title: 'Copy to clipboard not supported', }) } finally { document.body.removeChild(textArea) } } }
2302_79757062/insights
frontend/src2/helpers/index.ts
TypeScript
agpl-3.0
5,903
import { useStorage, watchDebounced } from '@vueuse/core' import { call } from 'frappe-ui' import { computed, reactive, watchEffect } from 'vue' import { confirmDialog } from '../helpers/confirm_dialog' import { copy, showErrorToast, waitUntil } from './index' import { createToast } from './toasts' type DocumentResourceOptions<T> = { initialDoc: T transform?: (doc: T) => T } export default function useDocumentResource<T extends object>( doctype: string, name: string, options: DocumentResourceOptions<T> ) { const tranformFn = options.transform || ((doc: T) => doc) const afterLoadFns = new Set<Function>() const beforeInsertFns = new Set<Function>() const afterInsertFns = new Set<Function>() const beforeSaveFns = new Set<Function>() const afterSaveFns = new Set<Function>() const resource = reactive({ doctype, name, doc: options.initialDoc, originalDoc: copy(options.initialDoc), isdirty: computed(() => false), islocal: name && name.startsWith('new-'), loading: name && !name.startsWith('new-'), saving: false, deleting: false, onBeforeInsert: (fn: Function) => beforeInsertFns.add(fn), async insert() { if (!this.islocal) return await Promise.all(Array.from(beforeInsertFns).map((fn) => fn())) const doc = await call('frappe.client.insert', { doc: { doctype, ...removeMetaFields(this.doc), }, }).catch(showErrorToast) this.doc = tranformFn({ ...doc }) this.originalDoc = copy(this.doc) this.name = doc.name this.islocal = false await Promise.all(Array.from(afterInsertFns).map((fn) => fn())) return doc }, onAfterInsert: (fn: Function) => afterInsertFns.add(fn), onBeforeSave: (fn: Function) => beforeSaveFns.add(fn), async save() { if (this.saving) { console.log('Already saving', this.doctype, this.name) await waitUntil(() => !this.saving) return this.doc } if (!this.isdirty && !this.islocal) { createToast({ title: 'No changes to save', variant: 'info', }) return this.doc } this.saving = true await Promise.all(Array.from(beforeSaveFns).map((fn) => fn())) if (this.islocal) { await this.insert() } else { const doc = await call('frappe.client.set_value', { doctype: this.doctype, name: this.name, fieldname: removeMetaFields(this.doc), }).catch(showErrorToast) if (doc) { this.doc = tranformFn({ ...doc }) this.originalDoc = copy(this.doc) } } this.saving = false await Promise.all(Array.from(afterSaveFns).map((fn) => fn())) return this.doc }, onAfterSave: (fn: Function) => afterSaveFns.add(fn), discard() { confirmDialog({ title: 'Discard Changes', message: 'Are you sure you want to discard changes?', onSuccess: () => this.load(), }) }, async load() { if (this.islocal) return this.loading = true const doc = await call('frappe.client.get', { doctype: this.doctype, name: this.name, }).catch(showErrorToast) if (!doc) return this.doc = tranformFn({ ...doc }) this.originalDoc = copy(this.doc) await Promise.all(Array.from(afterLoadFns).map((fn) => fn(this.doc))) this.loading = false }, onAfterLoad: (fn: Function) => afterLoadFns.add(fn), async call(method: string, args = {}) { this.loading = true const response = await call('run_doc_method', { method, docs: { ...this.doc, __islocal: this.islocal, }, args, }) .catch(showErrorToast) .finally(() => (this.loading = false)) return response.message }, async delete() { this.deleting = true await call('frappe.client.delete', { doctype: this.doctype, name: this.name, }) .catch(showErrorToast) .finally(() => (this.deleting = false)) }, }) // @ts-ignore resource.isdirty = computed( () => JSON.stringify(resource.doc) !== JSON.stringify(resource.originalDoc) ) resource.load().then(setupLocalStorage) function setupLocalStorage() { const storageKey = `insights:resource:${resource.doctype}:${resource.name}` const storage = useStorage(storageKey, { doc: null as any, originalDoc: null as any, }) // on creation, restore the doc from local storage, if exists if (storage.value && storage.value.doc) { resource.doc = storage.value.doc resource.originalDoc = storage.value.originalDoc } // watch for changes in doc and save it to local storage watchDebounced( () => resource.isdirty, () => { storage.value = resource.isdirty ? { doc: resource.doc, originalDoc: resource.originalDoc, } : null }, { debounce: 500, immediate: true } ) } return resource } export type DocumentResource<T extends object> = ReturnType<typeof useDocumentResource<T>> const metaFields = [ 'doctype', 'name', 'owner', 'creation', 'modified', 'modified_by', 'docstatus', 'parent', 'parentfield', 'parenttype', ] function removeMetaFields(doc: any) { const newDoc = { ...doc } metaFields.forEach((field) => delete newDoc[field]) return newDoc }
2302_79757062/insights
frontend/src2/helpers/resource.ts
TypeScript
agpl-3.0
5,057
import { useStorage, watchDebounced } from '@vueuse/core' type Props<T> = { key: keyof T namespace: string serializeFn: () => T defaultValue: T } export default function storeLocally<T>(props: Props<T>) { const serialized = props.serializeFn() const keyValue = serialized[props.key] const localData = useStorage<T>(`${props.namespace}:${keyValue}`, props.defaultValue) watchDebounced(props.serializeFn, (data) => (localData.value = data), { deep: true, debounce: 1000, }) return localData }
2302_79757062/insights
frontend/src2/helpers/store_locally.ts
TypeScript
agpl-3.0
506
import { h, markRaw } from 'vue' import { toast } from 'vue-sonner' import Toast from '../components/Toast.vue' import { titleCase } from './index' export type ToastVariant = 'success' | 'error' | 'warning' | 'info' type ToastOptions = { title?: string message?: string variant: ToastVariant } export function createToast(toastOptions: ToastOptions) { const options = { ...toastOptions } if (!toastOptions.title && toastOptions.message) { options.title = titleCase(toastOptions.variant) options.message = toastOptions.message } const component = h(Toast, { title: options.title || '', message: options.message, variant: toastOptions.variant, }) toast.custom(markRaw(component)) }
2302_79757062/insights
frontend/src2/helpers/toasts.ts
TypeScript
agpl-3.0
700
<script setup lang="ts"> import { inject } from 'vue' import session from '../session' import HomeQuickActions from './HomeQuickActions.vue' import HomeWorkbookList from './HomeWorkbookList.vue' const $dayjs = inject('$dayjs') // @ts-ignore const today = $dayjs().format('dddd, D MMMM') </script> <template> <div class="flex flex-1 flex-col space-y-8 overflow-hidden bg-white p-6"> <div class="space-y-2"> <div class="text-3xl font-bold text-gray-900"> Hello, {{ session.user.first_name }} 👋 </div> <div class="text-lg text-gray-600">{{ today }}</div> </div> <HomeQuickActions></HomeQuickActions> <HomeWorkbookList></HomeWorkbookList> </div> </template>
2302_79757062/insights
frontend/src2/home/Home.vue
Vue
agpl-3.0
682
<script setup lang="ts"> import { ArrowUpRight, Plus } from 'lucide-vue-next' import { useRouter } from 'vue-router' import { getUniqueId } from '../helpers' const router = useRouter() function openNewWorkbook() { const unique_id = getUniqueId() const name = `new-workbook-${unique_id}` router.push(`/workbook/${name}`) } </script> <template> <div> <div class="flex items-center space-x-2"> <div class="rounded bg-gray-100 p-1"> <ArrowUpRight class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </div> <div class="text-lg">Quick Actions</div> </div> <div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4"> <div class="col-span-1 flex cursor-pointer items-center justify-between rounded border border-transparent bg-white p-4 shadow transition-all hover:border-gray-400" @click="openNewWorkbook" > <div class="text-lg font-medium text-gray-900">New Workbook</div> <div class="rounded bg-gray-100 p-1"> <Plus class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </div> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/home/HomeQuickActions.vue
Vue
agpl-3.0
1,077
<script setup lang="ts"> import { Avatar, createListResource } from 'frappe-ui' import { ArrowUpRight, Book } from 'lucide-vue-next' import { ref, watch } from 'vue' import { useRouter } from 'vue-router' import dayjs from '../helpers/dayjs' const router = useRouter() const workbooks = createListResource({ cache: 'insights_workbooks', doctype: 'Insights Workbook', fields: ['name', 'title', 'owner', 'creation'], pageLength: 20, auto: true, }) const searchQuery = ref('') watch(searchQuery, (query) => { workbooks.filters = query ? { title: ['like', `%${query}%`], } : {} workbooks.reload() }) </script> <template> <div class="flex h-full flex-col overflow-hidden"> <div class="flex items-center space-x-2"> <div class="rounded bg-gray-100 p-1"> <Book class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </div> <div class="text-lg">Workbooks</div> </div> <div class="mt-3 flex-1 overflow-hidden p-1"> <!-- list of recent records --> <ul v-if="workbooks.list.data?.length > 0" class="relative flex flex-1 flex-col overflow-y-auto" > <li class="border-b"></li> <li v-for="(row, idx) in workbooks.list.data" :key="idx" class="flex h-10 cursor-pointer items-center gap-4 border-b transition-colors hover:bg-gray-50" @click="router.push(`/workbook/${row.name}`)" > <ArrowUpRight class="h-4 w-4 text-gray-700" stroke-width="1.5" /> <div class="w-[50%] truncate">{{ row.title }}</div> <div class="flex-1 text-sm text-gray-500"> <Avatar :label="row.owner" /> <span class="ml-1.5">{{ row.owner }}</span> </div> <div class="flex-1 text-sm text-gray-500"> {{ (dayjs(row.creation) as any).fromNow() }} </div> </li> </ul> <!-- empty state --> <div v-else class="flex h-full w-full items-center justify-center"> <div class="flex flex-col items-center space-y-2"> <div class="text-lg text-gray-600">No workbooks created</div> <div class="text-sm text-gray-600"> Your workbooks will appear here. Create a new workbook to get started. </div> </div> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/home/HomeWorkbookList.vue
Vue
agpl-3.0
2,156
@import 'frappe-ui/src/fonts/Inter/inter.css'; @import 'frappe-ui/src/style.css'; @import './styles/codemirror.css'; .tnum { font-feature-settings: 'tnum'; } @layer components { /* Works on Firefox */ * { scrollbar-width: thin; scrollbar-color: #c0c6cc #ebeef0; } html { scrollbar-width: auto; } /* Works on Chrome, Edge, and Safari */ *::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 6px; } *::-webkit-scrollbar-track, *::-webkit-scrollbar-corner { background: #f8fafc; } *::-webkit-scrollbar { width: 0px; height: 6px; } body::-webkit-scrollbar { width: 0px; height: 12px; } } .fade-enter-active, .fade-leave-active { transition: opacity 0.1s ease; } .fade-enter-from, .fade-leave-to { opacity: 0; }
2302_79757062/insights
frontend/src2/index.css
CSS
agpl-3.0
765
import { frappeRequest, setConfig } from 'frappe-ui' import { GridItem, GridLayout } from 'grid-layout-plus' import { createPinia } from 'pinia' import { createApp } from 'vue' import App from './App.vue' import { registerControllers, registerGlobalComponents } from './globals.ts' import './index.css' import router from './router.ts' import './telemetry.ts' setConfig('resourceFetcher', frappeRequest) const app = createApp(App) const pinia = createPinia() app.use(pinia) app.use(router) app.component('grid-layout', GridLayout) app.component('grid-item', GridItem) app.config.errorHandler = (err, vm, info) => { console.groupCollapsed('Unhandled Error in: ', info) console.error('Context:', vm) console.error('Error:', err) console.groupEnd() return false } registerGlobalComponents(app) registerControllers(app) app.mount('#app')
2302_79757062/insights
frontend/src2/main.ts
TypeScript
agpl-3.0
845
<script setup lang="ts"> import { provide } from 'vue' import { WorkbookQuery } from '../types/workbook.types' import QueryBuilderSourceSelector from './components/QueryBuilderSourceSelector.vue' import QueryBuilderTable from './components/QueryBuilderTable.vue' import QueryBuilderToolbar from './components/QueryBuilderToolbar.vue' import QueryInfo from './components/QueryInfo.vue' import QueryOperations from './components/QueryOperations.vue' import useQuery from './query' import { useMagicKeys, whenever } from '@vueuse/core' import { onBeforeUnmount } from 'vue-demi' const props = defineProps<{ query: WorkbookQuery }>() const query = useQuery(props.query) provide('query', query) window.query = query query.execute() const keys = useMagicKeys() const cmdZ = keys['Meta+Z'] const cmdShiftZ = keys['Meta+Shift+Z'] const stopUndoWatcher = whenever(cmdZ, () => query.history.undo()) const stopRedoWatcher = whenever(cmdShiftZ, () => query.history.redo()) onBeforeUnmount(() => { stopUndoWatcher() stopRedoWatcher() }) </script> <template> <div class="flex flex-1 overflow-hidden"> <QueryBuilderSourceSelector v-if="!query.doc.operations.length" /> <div v-else class="relative flex h-full w-full flex-col gap-4 overflow-hidden border-l p-4"> <QueryBuilderToolbar></QueryBuilderToolbar> <div class="flex flex-1 overflow-hidden rounded shadow"> <QueryBuilderTable></QueryBuilderTable> </div> </div> <div class="relative flex h-full w-[17rem] flex-shrink-0 flex-col gap-1 divide-y overflow-y-auto bg-white shadow-sm" > <QueryInfo /> <QueryOperations /> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/QueryBuilder.vue
Vue
agpl-3.0
1,623
<script setup lang="ts"> import { ChevronRight, ListFilter } from 'lucide-vue-next' import { FilterOperator, FilterValue, QueryResultColumn } from '../../types/query.types' import ColumnFilterBody from './ColumnFilterBody.vue' const emit = defineEmits({ filter: (operator: FilterOperator, value: FilterValue) => true, }) const props = defineProps<{ column: QueryResultColumn valuesProvider: (search: string) => Promise<string[]> placement?: string }>() </script> <template> <Popover :placement="props.placement || 'right-start'"> <template #target="{ togglePopover, isOpen }"> <slot name="target" :togglePopover="togglePopover" :isOpen="isOpen"> <Button variant="ghost" @click="togglePopover" class="w-full !justify-start" :class="{ ' !bg-gray-100': isOpen }" > <template #icon> <div class="flex h-7 w-full items-center gap-2 pl-2 pr-1.5 text-base"> <ListFilter class="h-4 w-4 flex-shrink-0" stroke-width="1.5" /> <div class="flex flex-1 items-center justify-between"> <span class="truncate">Filter</span> <ChevronRight class="h-4 w-4" stroke-width="1.5" /> </div> </div> </template> </Button> </slot> </template> <template #body-main="{ togglePopover, isOpen }"> <ColumnFilterBody v-if="isOpen" :column="props.column" :valuesProvider="props.valuesProvider" @filter="(op, val) => emit('filter', op, val)" @close="togglePopover" /> </template> </Popover> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnFilter.vue
Vue
agpl-3.0
1,505
<script setup lang="ts"> import { FIELDTYPES } from '../../helpers/constants' import { computed, reactive } from 'vue' import { FilterOperator, FilterValue, QueryResultColumn } from '../../types/query.types' import ColumnFilterTypeDate from './ColumnFilterTypeDate.vue' import ColumnFilterTypeNumber from './ColumnFilterTypeNumber.vue' import ColumnFilterTypeText from './ColumnFilterTypeText.vue' const emit = defineEmits({ filter: (operator: FilterOperator, value: FilterValue) => true, close: () => true, }) const props = defineProps<{ column: QueryResultColumn valuesProvider: (search: string) => Promise<string[]> placement?: string }>() const isText = computed(() => FIELDTYPES.TEXT.includes(props.column.type)) const isNumber = computed(() => FIELDTYPES.NUMBER.includes(props.column.type)) const isDate = computed(() => FIELDTYPES.DATE.includes(props.column.type)) const initialFilter = { operator: '=' as FilterOperator, value: [] as FilterValue, } const newFilter = reactive({ ...initialFilter }) const isValidFilter = computed(() => { if (!newFilter.operator) return false if (isText.value && newFilter.operator.includes('set')) return true if (!newFilter.value) return false if (isText.value && newFilter.operator.includes('contains')) return newFilter.value const value = newFilter.value as any[] // number & date value is always an array if (isNumber.value) return value[0] || value[1] if (isDate.value) return value[0] || value[1] if (isText.value && newFilter.operator.includes('=')) return value.length return false }) function processFilter(operator: FilterOperator, value: FilterValue) { if (isNumber.value && Array.isArray(value)) { // convert to string so that 0 is not considered as falsy value = value.map((v) => (!isNaN(v) ? String(v) : v)) if (operator === '=' && value[0] === value[1]) return ['=', Number(value[0])] if (operator === '>=' && value[0] && !value[1]) return ['>=', Number(value[0])] if (operator === '<=' && !value[0] && value[1]) return ['<=', Number(value[1])] if (operator === 'between' && value[0] && value[1]) { return ['between', [Number(value[0]), Number(value[1])]] } } if (isText.value) { if (operator.includes('set')) return [operator, value] if (operator.includes('contains')) return [operator, value] if (operator.includes('=')) { return [operator === '!=' ? 'not_in' : 'in', value] } } if (isDate.value && Array.isArray(value)) { if (operator === '=' && value[0] === value[1]) return ['=', value[0]] if (operator === '>=' && value[0] && !value[1]) return ['>=', value[0]] if (operator === '<=' && !value[0] && value[1]) return ['<=', value[1]] if (operator === 'within') return ['within', value.join(' ')] if (operator === 'between' && value[0] && value[1]) return ['between', [value[0], value[1]]] } } function confirmFilter() { const filter = processFilter(newFilter.operator, newFilter.value) if (!filter) { console.error(newFilter.operator, newFilter.value) throw new Error('Invalid filter') } emit('filter', filter[0], filter[1]) Object.assign(newFilter, { ...initialFilter }) emit('close') } </script> <template> <div class="flex flex-col gap-2 px-2.5 py-2"> <ColumnFilterTypeNumber v-if="isNumber" class="w-[15rem]" :column="props.column" :model-value="newFilter" @update:model-value="Object.assign(newFilter, $event)" /> <ColumnFilterTypeText v-else-if="isText" class="w-[15rem]" :column="props.column" :model-value="newFilter" @update:model-value="Object.assign(newFilter, $event)" :valuesProvider="props.valuesProvider" /> <ColumnFilterTypeDate v-else-if="isDate" :column="props.column" :model-value="newFilter" @update:model-value="Object.assign(newFilter, $event)" /> <div class="flex justify-end gap-1"> <Button @click="emit('close')" icon="x"></Button> <Button variant="solid" icon="check" :disabled="!isValidFilter" @click="confirmFilter()" > </Button> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnFilterBody.vue
Vue
agpl-3.0
4,020
<script setup lang="ts"> import { wheneverChanges } from '../../helpers' import dayjs from '../../helpers/dayjs' import { ChevronDown, ChevronRight } from 'lucide-vue-next' import { ref } from 'vue' import useSettings from '../../settings/settings' import { FilterOperator, FilterValue, QueryResultColumn } from '../../types/query.types' import DatePicker from './DatePicker.vue' const props = defineProps<{ column: QueryResultColumn }>() const filter = defineModel<{ operator: FilterOperator; value: FilterValue }>({ type: Object, default: () => ({ operator: '=', value: [] }), }) const currentSection = ref<'presets' | 'relative' | 'specific' | ''>('presets') wheneverChanges(currentSection, () => { if (currentSection.value === 'presets') { filter.value = { operator: '=', value: [] } } else if (currentSection.value === 'relative') { filter.value = { operator: 'within', value: ['Last', 1, 'Day'] } } else if (currentSection.value === 'specific') { filter.value = { operator: '=', value: [] } } else { filter.value = { operator: '=', value: [] } } }) const getValue = (date: Date) => date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', }) const todayValue = getValue(new Date()) const [weekStart, weekEnd] = [dayjs().startOf('week').toDate(), dayjs().endOf('week').toDate()] const [monthStart, monthEnd] = [dayjs().startOf('month').toDate(), dayjs().endOf('month').toDate()] const [qtrStart, qtrEnd] = [dayjs().startOf('quarter').toDate(), dayjs().endOf('quarter').toDate()] const [yearStart, yearEnd] = [dayjs().startOf('year').toDate(), dayjs().endOf('year').toDate()] const fiscal_year_start = useSettings().doc.fiscal_year_start || '04-01-1999' const [fiscalYearStart, fiscalYearEnd] = [ dayjs(fiscal_year_start).toDate(), dayjs(fiscal_year_start).add(1, 'year').subtract(1, 'day').toDate(), ] const thisWeekValue = `${getValue(weekStart)} - ${getValue(weekEnd)}` const thisMonthValue = `${getValue(monthStart)} - ${getValue(monthEnd)}` const thisQuarterValue = `${getValue(qtrStart)} - ${getValue(qtrEnd)}` const thisYearValue = `${getValue(yearStart)} - ${getValue(yearEnd)}` const thisFYValue = `${getValue(fiscalYearStart)} - ${getValue(fiscalYearEnd)}` const predefinedRanges = [ { label: 'Today', value: 'Day', description: todayValue }, { label: 'This Week', value: 'Week', description: thisWeekValue }, { label: 'This Month', value: 'Month', description: thisMonthValue }, { label: 'This Quarter', value: 'Quarter', description: thisQuarterValue }, { label: 'This Year', value: 'Year', description: thisYearValue }, { label: 'This FY', value: 'Fiscal Year', description: thisFYValue }, // last 7 days // last 30 days // last 90 days // last 3 months // last 6 months // last 12 months // last month // last year // month to date // year to date // all time ] function onPredefinedRangeInput(rangeValue: string) { filter.value = { operator: 'within', value: ['Current', rangeValue] } } function isRangeSelected(rangeValue: string) { if (!filter.value || !filter.value.value) return false const value = filter.value.value as string[] return filter.value.operator === 'within' && value[1] === rangeValue } function onDatePickerInput(value: string[]) { // if both dates are same, set operator to '=' // if only first date is present, set operator to '>' // if only second date is present, set operator to '<' // if both dates are present, set operator to 'between' filter.value.value = value if (value[0] === value[1]) { filter.value.operator = '=' } else if (value[0] && !value[1]) { filter.value.operator = '>=' } else if (!value[0] && value[1]) { filter.value.operator = '<=' } else if (value[0] && value[1]) { filter.value.operator = 'between' } else { filter.value.operator = '=' } } </script> <template> <div class="flex w-[210px] flex-col divide-y text-base"> <div class="flex flex-col gap-1 pb-2"> <div class="flex cursor-pointer items-center justify-between text-sm text-gray-600 hover:underline" @click="currentSection = currentSection == 'presets' ? '' : 'presets'" > <span> Presets </span> <component :is="currentSection == 'presets' ? ChevronDown : ChevronRight" class="h-4 w-4" stroke-width="1.5" /> </div> <div v-if="currentSection == 'presets'"> <div v-for="range in predefinedRanges" :key="range.value" class="-mx-1 flex cursor-pointer items-center justify-between gap-8 rounded px-1 py-1" @click="onPredefinedRangeInput(range.value)" :class=" isRangeSelected(range.value) ? 'outline outline-gray-500' : 'hover:bg-gray-100' " > <span>{{ range.label }}</span> <span class="text-sm text-gray-600">{{ range.description }}</span> </div> </div> </div> <div> <div class="flex flex-col gap-1 py-2"> <div class="flex cursor-pointer items-center justify-between text-sm text-gray-600 hover:underline" @click="currentSection = currentSection == 'relative' ? '' : 'relative'" > <span> Relative Dates </span> <component :is="currentSection == 'relative' ? ChevronDown : ChevronRight" class="h-4 w-4" stroke-width="1.5" /> </div> <div v-if="currentSection == 'relative' && Array.isArray(filter.value)" class="flex flex-col gap-1 py-2" > <span>In Last...</span> <div class="flex gap-2"> <div class="flex-1"> <FormControl type="number" autocomplete="off" :min="1" :max="100" :modelValue="filter.value[1]" @update:modelValue="filter.value[1] = $event" /> </div> <div class="flex-[2]"> <FormControl type="select" autocomplete="off" :options="['Day', 'Week', 'Month', 'Quarter', 'Year']" :modelValue="filter.value[2]" @update:modelValue="filter.value[2] = $event" /> </div> </div> </div> </div> </div> <div class=""> <div class="flex flex-col gap-2 pt-2"> <div class="flex cursor-pointer items-center justify-between text-sm text-gray-600 hover:underline" @click="currentSection = currentSection == 'specific' ? '' : 'specific'" > <span> Specific Dates </span> <component :is="currentSection == 'specific' ? ChevronDown : ChevronRight" class="h-4 w-4" stroke-width="1.5" /> </div> <DatePicker v-if="currentSection == 'specific' && Array.isArray(filter.value)" :modelValue="filter.value" @update:modelValue="onDatePickerInput" /> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnFilterTypeDate.vue
Vue
agpl-3.0
6,622
<script setup lang="ts"> import { computed, watch } from 'vue' import { FilterOperator, QueryResultColumn } from '../../types/query.types' const props = defineProps<{ column: QueryResultColumn }>() const filter = defineModel<{ operator: FilterOperator; value: any }>({ type: Object, default: () => ({ operator: '=', value: [0, 0] }), }) // const query = inject('query') as Query // onMounted(() => { // if (!filter.value.value?.[0] && !filter.value.value?.[1]) { // query.getMinAndMax(props.column.name).then((minMax: number[]) => { // console.log(minMax) // if (typeof minMax[0] === 'number' && typeof minMax[1] === 'number') { // filter.value.value = minMax // } // }) // } // }) watch( () => filter.value.value, () => { // set operator based on value if (filter.value.value[0] === filter.value.value[1]) { filter.value.operator = '=' } else if (filter.value.value[0] && !filter.value.value[1]) { filter.value.operator = '>=' } else if (!filter.value.value[0] && filter.value.value[1]) { filter.value.operator = '<=' } else if (filter.value.value[0] && filter.value.value[1]) { filter.value.operator = 'between' } }, { deep: true } ) const numberFilterDescription = computed(() => { if (!filter.value.value[0] && !filter.value.value[1]) { return '' } if (filter.value.value[0] === filter.value.value[1]) { return `${props.column.name} is ${filter.value.value[0]}` } if (filter.value.value[0] && !filter.value.value[1]) { return `${props.column.name} is ${filter.value.value[0]} or greater` } if (!filter.value.value[0] && filter.value.value[1]) { return `${props.column.name} is ${filter.value.value[1]} or less` } return `${props.column.name} is between ${filter.value.value[0]} and ${filter.value.value[1]}` }) </script> <template> <div> <div class="flex gap-2"> <FormControl type="number" placeholder="Min" label="Min" v-model="filter.value[0]" /> <FormControl type="number" placeholder="Max" label="Max" v-model="filter.value[1]" /> </div> <p class="mt-1 text-xs leading-4 text-gray-600"> {{ numberFilterDescription }} </p> </div> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnFilterTypeNumber.vue
Vue
agpl-3.0
2,139
<script setup lang="ts"> import { computed } from 'vue' import ColumnFilterValueSelector from './ColumnFilterValueSelector.vue' import { FilterOperator, FilterValue, QueryResultColumn } from '../../types/query.types' const props = defineProps<{ column: QueryResultColumn valuesProvider: (search: string) => Promise<string[]> }>() const filter = defineModel<{ operator: FilterOperator; value: FilterValue }>({ type: Object, default: () => ({ operator: '=', value: [] }), }) const operatorOptions = [ { label: 'is', value: '=' }, { label: 'is not', value: '!=' }, { label: 'contains', value: 'contains' }, { label: 'not contains', value: 'not_contains' }, { label: 'is set', value: 'is_set' }, { label: 'is not set', value: 'is_not_set' }, ] const isString = computed(() => props.column.type === 'String') const isEqualityCheck = computed(() => ['=', '!='].includes(filter.value.operator)) const isNullCheck = computed(() => ['is_set', 'is_not_set'].includes(filter.value.operator)) const isLikeCheck = computed(() => ['contains', 'not_contains'].includes(filter.value.operator)) function onOperatorChange() { if (isEqualityCheck.value) filter.value.value = [] if (isNullCheck.value) filter.value.value = undefined if (isLikeCheck.value) filter.value.value = '' } const placeholder = computed(() => { if (isNullCheck.value) return '' if (filter.value.operator.includes('contains')) return 'eg. %foo%' }) </script> <template> <div class="flex flex-col gap-2"> <FormControl type="select" :options="operatorOptions" v-model="filter.operator" @update:modelValue="onOperatorChange" /> <ColumnFilterValueSelector v-if="isString && isEqualityCheck && Array.isArray(filter.value)" v-model="filter.value" :column="props.column" :valuesProvider="props.valuesProvider" /> <FormControl v-else-if="!isNullCheck" :placeholder="placeholder" v-model="filter.value" /> </div> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnFilterTypeText.vue
Vue
agpl-3.0
1,925
<script setup lang="ts"> import { watchDebounced } from '@vueuse/core' import { LoadingIndicator } from 'frappe-ui' import { CheckSquare, SearchIcon, Square } from 'lucide-vue-next' import { ref } from 'vue' import { QueryResultColumn } from '../../types/query.types' const props = defineProps<{ column: QueryResultColumn valuesProvider: (search: string) => Promise<string[]> }>() const selectedValues = defineModel<any[]>({ type: Array, default: () => [], }) const distinctColumnValues = ref<any[]>([]) const searchInput = ref('') const fetchingValues = ref(false) watchDebounced( () => searchInput.value, (searchTxt) => { fetchingValues.value = true props .valuesProvider(searchTxt) .then((values: string[]) => (distinctColumnValues.value = values)) .finally(() => (fetchingValues.value = false)) }, { debounce: 300, immediate: true } ) function toggleValue(value: string) { if (selectedValues.value.includes(value)) { selectedValues.value = selectedValues.value.filter((v) => v !== value) } else { selectedValues.value = [...selectedValues.value, value] } } </script> <template> <div class="flex flex-col gap-2"> <FormControl placeholder="Search" v-model="searchInput" autocomplete="off"> <template #prefix> <SearchIcon class="h-4 w-4 text-gray-400" /> </template> <template #suffix> <LoadingIndicator v-if="fetchingValues" class="h-4 w-4 text-gray-600" /> </template> </FormControl> <div class="max-h-[10rem] overflow-y-scroll"> <div v-for="(value, idx) in distinctColumnValues.slice(0, 50)" :key="value || idx" class="flex cursor-pointer items-center justify-between gap-2 rounded px-1 py-1.5 text-base hover:bg-gray-100" @click.prevent.stop="toggleValue(value)" > <component :is="selectedValues.includes(value) ? CheckSquare : Square" class="h-4 w-4 text-gray-600" /> <span class="flex-1 truncate"> {{ value }} </span> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnFilterValueSelector.vue
Vue
agpl-3.0
1,967
<script setup lang="ts"> import { Trash } from 'lucide-vue-next' import { QueryResultColumn } from '../../types/query.types' const emit = defineEmits(['remove']) const props = defineProps<{ column: QueryResultColumn }>() </script> <template> <Button theme="red" variant="ghost" @click="emit('remove')" class="w-full !justify-start"> <template #icon> <div class="flex h-7 w-full items-center gap-2 pl-2 pr-1.5 text-base"> <Trash class="h-4 w-4 flex-shrink-0" stroke-width="1.5" /> <div class="flex flex-1 items-center justify-between"> <span class="truncate">Remove</span> </div> </div> </template> </Button> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnRemove.vue
Vue
agpl-3.0
652
<script setup lang="ts"> import { ChevronRight, TextCursorInput } from 'lucide-vue-next' import { ref } from 'vue' import { QueryResultColumn } from '../../types/query.types' const emit = defineEmits({ rename: (newName: string) => true, }) const props = defineProps<{ column: QueryResultColumn }>() const newName = ref('') function onRename() { emit('rename', newName.value) newName.value = '' } </script> <template> <Popover placement="right-start"> <template #target="{ togglePopover, isOpen }"> <Button variant="ghost" @click="togglePopover" class="w-full !justify-start" :class="{ ' !bg-gray-100': isOpen }" > <template #icon> <div class="flex w-full items-center gap-2 px-1.5 text-base"> <TextCursorInput class="h-4 w-4 flex-shrink-0" /> <div class="flex flex-1 items-center justify-between"> <span class="truncate">Rename</span> <ChevronRight class="h-4 w-4" /> </div> </div> </template> </Button> </template> <template #body-main="{ togglePopover }"> <div class="flex flex-col gap-2 px-2.5 py-2"> <FormControl v-model="newName" label="New Column Name" /> <div class="flex justify-end gap-1"> <Button @click="togglePopover" icon="x"></Button> <Button variant="solid" icon="check" @click=";[onRename(), togglePopover()]"> </Button> </div> </div> </template> </Popover> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnRename.vue
Vue
agpl-3.0
1,409
<script setup lang="ts"> import { QueryResultColumn } from '../../types/query.types' const emit = defineEmits({ sort: (value: 'asc' | 'desc' | '') => true, }) const props = defineProps<{ column: QueryResultColumn }>() </script> <template> <div class="flex flex-col"> <Button variant="ghost" class="w-full !justify-start" icon-left="arrow-up" @click="emit('sort', 'asc')" > <span class="truncate">Ascending</span> </Button> <Button variant="ghost" class="w-full !justify-start" icon-left="arrow-down" @click="emit('sort', 'desc')" > <span class="truncate">Descending</span> </Button> <Button variant="ghost" class="w-full !justify-start" icon-left="x" @click="emit('sort', '')" > <span class="truncate">Remove Sort</span> </Button> </div> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnSort.vue
Vue
agpl-3.0
818
<script setup lang="ts"> import { COLUMN_TYPES } from '../../helpers/constants' import DataTypeIcon from './DataTypeIcon.vue' import { ColumnDataType, QueryResultColumn } from '../../types/query.types' const emit = defineEmits({ typeChange: (newType: ColumnDataType) => true, }) const props = defineProps<{ column: QueryResultColumn }>() function onTypeChange(newType: ColumnDataType, togglePopover: () => void) { emit('typeChange', newType) togglePopover() } </script> <template> <Popover placement="bottom-start"> <template #target="{ togglePopover, isOpen }"> <Button variant="ghost" class="rounded-sm" @click="togglePopover" :class="isOpen ? '!bg-gray-100' : ''" > <template #icon> <DataTypeIcon :columnType="column.type" /> </template> </Button> </template> <template #body-main="{ togglePopover, isOpen }"> <div v-if="isOpen" class="flex min-w-[10rem] flex-col p-1.5"> <Button v-for="type in COLUMN_TYPES" :key="type.value" variant="ghost" class="w-full !justify-start" @click="onTypeChange(type.value as ColumnDataType, togglePopover)" > <template #prefix> <DataTypeIcon :columnType="(type.value as ColumnDataType)" /> </template> <span class="truncate">{{ type.label }}</span> </Button> </div> </template> </Popover> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnTypeChange.vue
Vue
agpl-3.0
1,354
<script setup lang="ts"> import DraggableList from '../../components/DraggableList.vue' import { ColumnsIcon } from 'lucide-vue-next' import { inject } from 'vue' import { Query } from '../query' const query = inject('query') as Query </script> <template> <Popover placement="bottom-start"> <template #target="{ togglePopover, isOpen }"> <Button variant="ghost" size="lg" class="rounded-none" :class="{ 'bg-gray-100': isOpen }" @click="togglePopover" > <template #icon> <ColumnsIcon class="h-5 w-5 text-gray-700" stroke-width="1.5" /> </template> </Button> </template> <template #body-main="{ togglePopover, isOpen }"> <div class="flex flex-col p-2"> <!-- select all --> <div class="mb-2 flex items-center gap-1"> <Checkbox class="flex-1" :label="'Select all'" :modelValue="true" :size="'sm'" /> </div> <DraggableList :items="query.result.columns" empty-text="No columns selected" group="columns" @update:items="() => {}" > <template #item="{ item: column }"> <Checkbox :label="column.name" :modelValue="true" :size="'sm'" /> </template> </DraggableList> </div> </template> </Popover> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnsSelector.vue
Vue
agpl-3.0
1,252
<script setup lang="ts"> import { CheckSquare, SearchIcon, SquareIcon } from 'lucide-vue-next' import { computed, inject, ref } from 'vue' import { QueryResultColumn, SelectArgs } from '../../types/query.types' import { Query } from '../query' import DataTypeIcon from './DataTypeIcon.vue' const props = defineProps<{ columns?: SelectArgs }>() const emit = defineEmits({ select: (args: SelectArgs) => true, }) const showDialog = defineModel() const query = inject('query') as Query const columns = ref<QueryResultColumn[]>([]) query.getColumnsForSelection().then((cols: QueryResultColumn[]) => { columns.value = cols selectedColumns.value = props.columns ? columns.value.filter((c) => props.columns?.column_names.includes(c.name)) : [] }) const columnSearchQuery = ref('') const filteredColumns = computed(() => { if (!columns.value.length) return [] if (!columnSearchQuery.value) return columns.value return columns.value.filter((column) => { return column.name.toLowerCase().includes(columnSearchQuery.value.toLowerCase()) }) }) const selectedColumns = ref<QueryResultColumn[]>([]) function isSelected(column: QueryResultColumn) { return selectedColumns.value.includes(column) } function toggleColumn(column: QueryResultColumn) { const index = selectedColumns.value.indexOf(column) if (index === -1) { selectedColumns.value.push(column) } else { selectedColumns.value.splice(index, 1) } } function toggleSelectAll() { if (areAllSelected.value) { selectedColumns.value = [] } else { selectedColumns.value = [...columns.value] } } const areAllSelected = computed(() => selectedColumns.value.length === columns.value.length) const areNoneSelected = computed(() => selectedColumns.value.length === 0) function confirmSelection() { emit('select', { column_names: selectedColumns.value.map((c) => c.name), }) showDialog.value = false } </script> <template> <Dialog v-model="showDialog" :options="{ size: 'sm', title: 'Select Columns', actions: [ { label: 'Confirm', variant: 'solid', disabled: areNoneSelected, onClick: confirmSelection, }, { label: 'Cancel', onClick: () => (showDialog = false), }, ], }" > <template #body-content> <div class="-mb-5 flex max-h-[20rem] flex-col gap-2 p-0.5"> <div class="flex gap-2"> <FormControl class="flex-1" autocomplete="off" placeholder="Search by name" v-model="columnSearchQuery" > <template #prefix> <SearchIcon class="h-4 w-4 text-gray-500" /> </template> </FormControl> <Button @click="toggleSelectAll"> {{ areAllSelected ? `Deselect All (${selectedColumns.length})` : `Select All (${selectedColumns.length})` }} </Button> </div> <div class="flex flex-col overflow-y-scroll rounded border p-0.5 text-base"> <template v-for="column in filteredColumns"> <div class="flex h-7 flex-shrink-0 cursor-pointer items-center justify-between rounded px-2 hover:bg-gray-100" @click="toggleColumn(column)" > <div class="flex items-center gap-1.5"> <DataTypeIcon :columnType="column.type" /> <span>{{ column.name }}</span> </div> <component class="h-4 w-4" stroke-width="1.5" :is="isSelected(column) ? CheckSquare : SquareIcon" :class="isSelected(column) ? 'text-gray-900' : 'text-gray-600'" /> </div> </template> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/ColumnsSelectorDialog.vue
Vue
agpl-3.0
3,542
<script setup lang="ts"> import { computed, ref } from 'vue' import { ColumnOption, CustomOperationArgs } from '../../types/query.types' import { expression } from '../helpers' import ExpressionEditor from './ExpressionEditor.vue' import { copy } from '../../helpers' const props = defineProps<{ operation?: CustomOperationArgs; columnOptions: ColumnOption[] }>() const emit = defineEmits({ select: (operation: CustomOperationArgs) => true }) const showDialog = defineModel() const newOperation = ref( props.operation ? copy(props.operation) : { expression: expression(''), } ) const isValid = computed(() => { return newOperation.value.expression.expression.trim().length > 0 }) function confirm() { if (!isValid.value) return emit('select', newOperation.value) reset() showDialog.value = false } function reset() { newOperation.value = { expression: expression(''), } } </script> <template> <Dialog :modelValue="showDialog" @after-leave="reset" @close="!newOperation.expression.expression && (showDialog = false)" :options="{ size: '4xl' }" > <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">Custom Operation</h3> <Button variant="ghost" @click="showDialog = false" icon="x" size="md"> </Button> </div> <div class="flex flex-col gap-2"> <ExpressionEditor class="h-[26rem]" v-model="newOperation.expression.expression" :column-options="props.columnOptions" /> </div> <div class="mt-2 flex items-center justify-between gap-2"> <div></div> <div class="flex items-center gap-2"> <Button label="Confirm" variant="solid" :disabled="!isValid" @click="confirm" /> </div> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/CustomScriptDialog.vue
Vue
agpl-3.0
1,909
<script setup lang="ts"> import { Baseline, Calendar, CalendarClock, Clock, Hash, ShieldQuestion, Type, } from 'lucide-vue-next' import { computed } from 'vue' import { ColumnDataType } from '../../types/query.types' const props = defineProps<{ columnType: ColumnDataType }>() const icon = computed(() => { switch (props.columnType) { case 'Integer': case 'Decimal': return Hash case 'Date': return Calendar case 'Datetime': return CalendarClock case 'Time': return Clock case 'Text': return Type case 'String': return Baseline default: return ShieldQuestion } }) </script> <template> <component :is="icon" class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template>
2302_79757062/insights
frontend/src2/query/components/DataTypeIcon.vue
Vue
agpl-3.0
720
<template> <div class="flex w-[210px] select-none flex-col gap-2 bg-white text-base"> <div class="flex items-center justify-between text-gray-700"> <Button @click="prevMonth" icon="chevron-left" /> <Button @dblclick="clearDates"> {{ formatMonth() }} </Button> <Button @click="nextMonth" icon="chevron-right" /> </div> <div class="flex gap-2"> <FormControl class="flex-1" placeholder="Enter date" v-model="fromDateTxt" autocomplete="off" ></FormControl> <FormControl v-if="range" class="flex-1" placeholder="Enter date" v-model="toDateTxt" autocomplete="off" ></FormControl> </div> <div class="tnum flex flex-col items-center justify-center text-base"> <div class="grid w-full grid-cols-7"> <div v-for="(d, i) in ['S', 'M', 'T', 'W', 'T', 'F', 'S']" :key="i" class="flex h-[30px] w-[30px] items-center justify-center text-sm text-gray-600" > {{ d }} </div> <template v-for="(week, i) in daysAsWeeks" :key="i"> <div v-for="date in week" :key="toValue(date)" class="flex h-[30px] w-[30px] cursor-pointer items-center justify-center text-sm" :class="{ 'font-bold': toValue(date) === toValue(today), ' rounded-l bg-gray-800 text-white': fromDateTxt && toValue(date) === toValue(fromDateTxt), ' rounded-r bg-gray-800 text-white': toDateTxt && toValue(date) === toValue(toDateTxt), 'bg-gray-100 font-medium text-gray-800': isInRange(date), }" @click="() => handleDateClick(date)" > {{ date.getDate() }} </div> </template> </div> <p v-if="range" class="mt-1 text-xs leading-4 text-gray-600"> {{ description }} </p> </div> </div> </template> <script setup lang="ts"> import { computed, onBeforeMount, ref } from 'vue' const props = defineProps({ range: { type: Boolean, default: true, }, }) const selectedDates = defineModel<string[]>({ type: Array, default: () => [], }) const today = new Date() const currentYear = ref<number>(today.getFullYear()) const currentMonth = ref<number>(today.getMonth() + 1) const fromDateTxt = ref<string>(selectedDates.value[0] || '') const toDateTxt = ref<string>(selectedDates.value[1] || '') onBeforeMount(() => { selectCurrentMonthYear() }) function selectCurrentMonthYear() { const date = toDateTxt.value ? new Date(toDateTxt.value) : today currentYear.value = date.getFullYear() currentMonth.value = date.getMonth() + 1 } const daysAsWeeks = computed(() => { const datesAsWeeks = [] const _dates = dates.value.slice() while (_dates.length) { const week = _dates.splice(0, 7) datesAsWeeks.push(week) } return datesAsWeeks }) const dates = computed(() => { if (!(currentYear.value && currentMonth.value)) { return [] } const monthIndex = currentMonth.value - 1 const year = currentYear.value const firstDayOfMonth = getDate(year, monthIndex, 1) const lastDayOfMonth = getDate(year, monthIndex + 1, 0) const leftPaddingCount = firstDayOfMonth.getDay() const rightPaddingCount = 6 - lastDayOfMonth.getDay() const leftPadding = getDatesAfter(firstDayOfMonth, -leftPaddingCount) const rightPadding = getDatesAfter(lastDayOfMonth, rightPaddingCount) const daysInMonth = getDaysInMonth(monthIndex, year) const datesInMonth = getDatesAfter(firstDayOfMonth, daysInMonth - 1) let _dates = [...leftPadding, firstDayOfMonth, ...datesInMonth, ...rightPadding] if (_dates.length < 42) { const lastDate = _dates.at(-1) if (lastDate) { const finalPadding = getDatesAfter(lastDate, 42 - _dates.length) _dates = _dates.concat(...finalPadding) } } return _dates }) function getDatesAfter(firstDayOfMonth: Date, count: number) { let incrementer = 1 if (count < 0) { incrementer = -1 count = Math.abs(count) } let dates = [] while (count) { firstDayOfMonth = getDate( firstDayOfMonth.getFullYear(), firstDayOfMonth.getMonth(), firstDayOfMonth.getDate() + incrementer ) dates.push(firstDayOfMonth) count-- } if (incrementer === -1) { return dates.reverse() } return dates } function getDaysInMonth(monthIndex: number, year: number) { let daysInMonthMap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] let daysInMonth = daysInMonthMap[monthIndex] if (monthIndex === 1 && isLeapYear(year)) { return 29 } return daysInMonth } function isLeapYear(year: number) { if (year % 400 === 0) return true if (year % 100 === 0) return false if (year % 4 === 0) return true return false } function formatMonth() { const date = getDate(currentYear.value, currentMonth.value - 1, 1) return date.toLocaleString('en-US', { month: 'short', year: 'numeric', }) } function formatDate(date: Date, options: { year?: boolean } = {}) { return date.toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: options.year ? 'numeric' : undefined, }) } function handleDateClick(date: Date) { if (!props.range) { fromDateTxt.value = toValue(date) selectDates() return } if (fromDateTxt.value && toDateTxt.value) { fromDateTxt.value = toValue(date) toDateTxt.value = '' } else if (fromDateTxt.value && !toDateTxt.value) { toDateTxt.value = toValue(date) } else { fromDateTxt.value = toValue(date) } swapDatesIfNecessary() selectDates() } function swapDatesIfNecessary() { if (!fromDateTxt.value || !toDateTxt.value) { return } let fromDate = getDate(fromDateTxt.value) let toDate = getDate(toDateTxt.value) if (fromDate > toDate) { let temp = fromDate fromDate = toDate toDate = temp } fromDateTxt.value = toValue(fromDate) toDateTxt.value = toValue(toDate) } function selectDates() { if (!props.range) { selectedDates.value = [fromDateTxt.value] return } if (!fromDateTxt.value && !toDateTxt.value) { selectedDates.value = [] return } selectedDates.value = [fromDateTxt.value, toDateTxt.value] } function prevMonth() { changeMonth(-1) } function nextMonth() { changeMonth(1) } function changeMonth(adder: number) { currentMonth.value = currentMonth.value + adder if (currentMonth.value < 1) { currentMonth.value = 12 currentYear.value = currentYear.value - 1 } if (currentMonth.value > 12) { currentMonth.value = 1 currentYear.value = currentYear.value + 1 } } function isInRange(date: Date) { if (!fromDateTxt.value || !toDateTxt.value) { return false } return date >= getDate(fromDateTxt.value) && date <= getDate(toDateTxt.value) } function clearDates() { fromDateTxt.value = '' toDateTxt.value = '' selectCurrentMonthYear() selectDates() } function toValue(date: Date | string) { if (!date) { return '' } if (typeof date === 'string') { return date } // toISOString is buggy and reduces the day by one // this is because it considers the UTC timestamp // in order to circumvent that we need to use luxon/moment // but that refactor could take some time, so fixing the time difference // as suggested in this answer. // https://stackoverflow.com/a/16084846/3541205 date.setHours(0, -date.getTimezoneOffset(), 0, 0) return date.toISOString().slice(0, 10) } function getDate(...args: any) { // @ts-ignore return new Date(...args) } const description = computed(() => { const fromDate = fromDateTxt.value ? getDate(fromDateTxt.value) : null const toDate = toDateTxt.value ? getDate(toDateTxt.value) : null const fromDateYear = fromDate?.getFullYear() const toDateYear = toDate?.getFullYear() const formatted = (date: Date) => formatDate(date, { year: fromDateYear !== toDateYear }) if (fromDate && toDate && fromDate.getTime() === toDate.getTime()) { return `Equals: ${formatted(fromDate)}` } if (fromDate && toDate) { return `Between: ${formatted(fromDate)} and ${formatted(toDate)}` } if (fromDate) { return `Greater than: ${formatted(fromDate)}` } if (toDate) { return `Less than: ${formatted(toDate)}` } return '' }) </script>
2302_79757062/insights
frontend/src2/query/components/DatePicker.vue
Vue
agpl-3.0
7,903
<script setup lang="ts"> import { Calendar } from 'lucide-vue-next' import { computed } from 'vue' import DatePicker from './DatePicker.vue' const props = defineProps({ placeholder: { type: String, default: 'Select Date', }, range: { type: Boolean, default: false, }, }) const dates = defineModel<string[]>({ default: () => [], required: true, }) const formatDate = (dates: string | string[] | Date | Date[]) => { const _dates: Date[] = [] if (typeof dates === 'string') { _dates.push(new Date(dates)) } else if (Array.isArray(dates) && dates.every((date) => typeof date === 'string')) { _dates.push(new Date(dates[0])) _dates.push(new Date(dates[1])) } else if (dates instanceof Date) { _dates.push(dates) } else if (Array.isArray(dates) && dates.every((date) => date instanceof Date)) { _dates.push(dates[0] as Date) _dates.push(dates[1] as Date) } // if year is same, show only month and day const [start, end] = _dates if (start && !end) { return start.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: start.getFullYear() === new Date().getFullYear() ? undefined : 'numeric', }) } if (start && end) { return `${start.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: start.getFullYear() === new Date().getFullYear() ? undefined : 'numeric', })} - ${end.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: end.getFullYear() === new Date().getFullYear() ? undefined : 'numeric', })}` } return '' } const areAllDatesValid = computed(() => dates.value.length && dates.value.every((date) => date)) const displayDate = computed(() => { if (areAllDatesValid.value) { return props.range ? formatDate(dates.value) : formatDate(dates.value[0]) } return props.placeholder }) </script> <template> <Popover placement="bottom-start"> <template #target="{ togglePopover }"> <Button class="w-full items-center !justify-start overflow-hidden" @click="togglePopover" > <template #prefix> <Calendar class="h-4 w-4 flex-shrink-0 text-gray-600" stroke-width="1.5" /> </template> <span class="truncate" :class="areAllDatesValid ? 'text-gray-900' : 'text-gray-600'" > {{ displayDate }} </span> </Button> </template> <template #body-main> <div class="flex p-2"> <DatePicker v-model="dates" :range="props.range"></DatePicker> </div> </template> </Popover> </template>
2302_79757062/insights
frontend/src2/query/components/DatePickerControl.vue
Vue
agpl-3.0
2,463
<script setup lang="ts"> import { call } from 'frappe-ui' import { ref } from 'vue' import Code from '../../components/Code.vue' import { ColumnOption } from '../../types/query.types' const props = defineProps<{ columnOptions: ColumnOption[] }>() const expression = defineModel<string>({ required: true, }) const functionList = ref<string[]>([]) call('insights.insights.doctype.insights_data_source_v3.ibis_functions.get_function_list').then( (res: any) => { functionList.value = res } ) function getCompletions(context: any, syntaxTree: any) { const word = context.matchBefore(/\w+/) const nodeBefore = syntaxTree.resolveInner(context.pos, -1) if (nodeBefore.name === 'VariableName') { const columnMatches = getColumnMatches(word.text) const functionMatches = getFunctionMatches(word.text) return { from: word.from, options: [...columnMatches, ...functionMatches], } } if (nodeBefore.name) { const columnMatches = getColumnMatches(nodeBefore.name) const functionMatches = getFunctionMatches(nodeBefore.name) return { from: nodeBefore.from, options: [...columnMatches, ...functionMatches], } } } function getColumnMatches(word: string) { return props.columnOptions .filter((c) => c.value.includes(word)) .map((c) => ({ label: c.value, detail: 'column', })) } function getFunctionMatches(word: string) { return functionList.value .filter((f) => f.includes(word)) .map((f) => ({ label: f, apply: `${f}()`, detail: 'function', })) } </script> <template> <div ref="codeContainer" class="flex h-[14rem] w-full overflow-scroll rounded border text-base"> <Code ref="codeEditor" language="python" class="column-expression" v-model="expression" :completions="getCompletions" ></Code> </div> </template> <style lang="scss"> .column-expression { .cm-content { height: 100% !important; } .cm-gutters { height: 100% !important; } .cm-tooltip-autocomplete { position: absolute !important; z-index: 1000 !important; } } </style>
2302_79757062/insights
frontend/src2/query/components/ExpressionEditor.vue
Vue
agpl-3.0
2,025
<script setup lang="ts"> import { FIELDTYPES } from '../../helpers/constants' import { debounce } from 'frappe-ui' import { computed, onMounted, ref } from 'vue' import { column } from '../helpers' import { getCachedQuery } from '../query' import DatePickerControl from './DatePickerControl.vue' import { getValueSelectorType } from './filter_utils' import { ColumnDataType, FilterOperator, FilterRule } from '../../types/query.types' const filter = defineModel<FilterRule>({ required: true }) const props = defineProps<{ columnOptions: { label: string value: string query: string data_type: ColumnDataType }[] }>() onMounted(() => { if (valueSelectorType.value === 'select') fetchColumnValues() }) function onColumnChange(column_name: string) { filter.value.column = column(column_name) filter.value.operator = operatorOptions.value[0]?.value filter.value.value = undefined if (valueSelectorType.value === 'select') { filter.value.value = [] fetchColumnValues() } } const columnType = computed(() => { if (!props.columnOptions?.length) return if (!filter.value.column.column_name) return const col = props.columnOptions.find((c) => c.value === filter.value.column.column_name) if (!col) throw new Error(`Column not found: ${filter.value.column.column_name}`) return col.data_type }) const operatorOptions = computed(() => { const type = columnType.value if (!type) return [] const options = [] as { label: string; value: FilterOperator }[] if (FIELDTYPES.TEXT.includes(type)) { options.push({ label: 'is', value: 'in' }) // value selector options.push({ label: 'is not', value: 'not_in' }) // value selector options.push({ label: 'contains', value: 'contains' }) // text options.push({ label: 'does not contain', value: 'not_contains' }) // text options.push({ label: 'starts with', value: 'starts_with' }) // text options.push({ label: 'ends with', value: 'ends_with' }) // text options.push({ label: 'is set', value: 'is_set' }) // no value options.push({ label: 'is not set', value: 'is_not_set' }) // no value } if (FIELDTYPES.NUMBER.includes(type)) { options.push({ label: 'equals', value: '=' }) options.push({ label: 'not equals', value: '!=' }) options.push({ label: 'greater than', value: '>' }) options.push({ label: 'greater than or equals', value: '>=' }) options.push({ label: 'less than', value: '<' }) options.push({ label: 'less than or equals', value: '<=' }) } if (FIELDTYPES.DATE.includes(type)) { options.push({ label: 'equals', value: '=' }) options.push({ label: 'not equals', value: '!=' }) options.push({ label: 'greater than', value: '>' }) options.push({ label: 'greater than or equals', value: '>=' }) options.push({ label: 'less than', value: '<' }) options.push({ label: 'less than or equals', value: '<=' }) options.push({ label: 'between', value: 'between' }) } return options }) function onOperatorChange(operator: FilterOperator) { filter.value.operator = operator filter.value.value = undefined } const valueSelectorType = computed( () => columnType.value && getValueSelectorType(filter.value, columnType.value) ) const distinctColumnValues = ref<any[]>([]) const fetchingValues = ref(false) const fetchColumnValues = debounce((searchTxt: string) => { const option = props.columnOptions.find((c) => c.value === filter.value.column.column_name) if (!option?.query) { fetchingValues.value = false console.warn('Query not found for column:', filter.value.column.column_name) return } // if column_name is 'query'.'column_name' extract column_name const pattern = /'([^']+)'\.'([^']+)'/g const match = pattern.exec(filter.value.column.column_name) const column_name = match ? match[2] : filter.value.column.column_name fetchingValues.value = true return getCachedQuery(option.query) ?.getDistinctColumnValues(column_name, searchTxt) .then((values: string[]) => (distinctColumnValues.value = values)) .finally(() => (fetchingValues.value = false)) }, 300) </script> <template> <div class="flex flex-1 gap-2"> <div id="column_name" class="!min-w-[140px] flex-1 flex-shrink-0"> <Autocomplete placeholder="Column" :modelValue="filter.column.column_name" :options="props.columnOptions" @update:modelValue="onColumnChange($event?.value)" /> </div> <div id="operator" class="!min-w-[100px] flex-1"> <FormControl type="select" placeholder="Operator" :disabled="!columnType" :modelValue="filter.operator" :options="operatorOptions" @update:modelValue="onOperatorChange($event)" /> </div> <div id="value" class="!min-w-[140px] flex-1 flex-shrink-0"> <FormControl v-if="valueSelectorType === 'text'" v-model="filter.value" placeholder="Value" autocomplete="off" /> <FormControl v-else-if="valueSelectorType === 'number'" type="number" :modelValue="filter.value" placeholder="Value" @update:modelValue="filter.value = Number($event)" /> <DatePickerControl v-else-if="valueSelectorType === 'date'" placeholder="Select Date" :modelValue="[filter.value as string]" @update:modelValue="filter.value = $event[0]" /> <DatePickerControl v-else-if="valueSelectorType === 'date_range'" :range="true" v-model="(filter.value as string[])" placeholder="Select Date" /> <Autocomplete v-else-if="valueSelectorType === 'select'" class="max-w-[200px]" placeholder="Value" :multiple="true" :modelValue="filter.value || []" :options="distinctColumnValues" :loading="fetchingValues" @update:query="fetchColumnValues" @update:modelValue="filter.value = $event.map((v: any) => v.value)" /> <FormControl v-else disabled /> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/components/FilterRule.vue
Vue
agpl-3.0
5,761
<script setup lang="ts"> import { PlusIcon } from 'lucide-vue-next' import { computed, reactive } from 'vue' import { copy } from '../../helpers' import { ColumnOption, FilterGroupArgs } from '../../types/query.types' import { column, expression } from '../helpers' import FilterRule from './FilterRule.vue' import InlineExpression from './InlineExpression.vue' import { isFilterExpressionValid, isFilterValid } from './filter_utils' const props = defineProps<{ filterGroup?: FilterGroupArgs columnOptions: ColumnOption[] }>() const emit = defineEmits({ select: (args: FilterGroupArgs) => true, close: () => true, }) const filterGroup = reactive<FilterGroupArgs>( props.filterGroup ? copy(props.filterGroup) : { logical_operator: 'And', filters: [], } ) function addFilter() { filterGroup.filters.push({ column: column(''), operator: '=', value: undefined, }) } const areAllFiltersValid = computed(() => { if (!filterGroup.filters.length) return true return filterGroup.filters.every((filter) => { if ('expression' in filter) return isFilterExpressionValid(filter) const column = props.columnOptions.find((c) => c.value === filter.column.column_name) if (!column) return false return isFilterValid(filter, column.data_type) }) }) const areFiltersUpdated = computed(() => { if (!props.filterGroup) return true return JSON.stringify(filterGroup) !== JSON.stringify(props.filterGroup) }) </script> <template> <div class="min-w-[36rem] rounded-lg 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">Filter</h3> <Button variant="ghost" @click="emit('close')" icon="x" size="md"> </Button> </div> <div v-if="filterGroup.filters.length" v-for="(_, i) in filterGroup.filters" :key="i" id="filter-list" class="mb-3 flex items-start justify-between gap-2" > <div class="flex flex-1 items-start gap-2"> <div class="flex h-7 w-13 flex-shrink-0 items-center text-base text-gray-600"> <span v-if="i == 0">Where</span> <Button v-else @click=" filterGroup.logical_operator = filterGroup.logical_operator === 'And' ? 'Or' : 'And' " > {{ filterGroup.logical_operator }} </Button> </div> <InlineExpression v-if="'expression' in filterGroup.filters[i]" v-model="filterGroup.filters[i].expression" /> <FilterRule v-if="'column' in filterGroup.filters[i]" :modelValue="filterGroup.filters[i]" :columnOptions="props.columnOptions" @update:modelValue="filterGroup.filters[i] = $event" /> </div> <div class="flex h-full flex-shrink-0 items-start"> <Dropdown placement="right" :button="{ icon: 'more-horizontal', variant: 'ghost', }" :options="[ { label: 'Convert to Expression', onClick: () => { filterGroup.filters[i] = { expression: expression('') } }, }, { label: 'Duplicate', onClick: () => { filterGroup.filters.splice( i + 1, 0, JSON.parse(JSON.stringify(filterGroup.filters[i])) ) }, }, { label: 'Remove', onClick: () => filterGroup.filters.splice(i, 1), }, ]" /> </div> </div> <div v-else class="mb-3 flex h-7 items-center px-0 text-sm text-gray-600"> Empty - Click 'Add Filter' to add a filter </div> <div class="mt-2 flex items-center justify-between gap-2"> <Button @click="addFilter" label="Add Filter"> <template #prefix> <PlusIcon class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> <div class="flex items-center gap-2"> <Button label="Clear" variant="outline" @click="filterGroup.filters = []" /> <Button label="Apply Filters" variant="solid" :disabled="!areAllFiltersValid || !areFiltersUpdated" @click="emit('select', filterGroup)" /> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/components/FiltersSelector.vue
Vue
agpl-3.0
4,041
<script setup lang="ts"> import { ColumnOption, FilterArgs, FilterGroupArgs } from '../../types/query.types' import FiltersSelector from './FiltersSelector.vue' const props = defineProps<{ filterGroup?: FilterGroupArgs columnOptions: ColumnOption[] }>() const emit = defineEmits({ select: (args: FilterGroupArgs) => true }) const showDialog = defineModel() </script> <template> <Dialog v-model="showDialog" :options="{ size: '2xl' }"> <template #body> <FiltersSelector :filterGroup="props.filterGroup" :columnOptions="props.columnOptions" @close="showDialog = false" @select=" (args) => { emit('select', args) showDialog = false } " /> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/FiltersSelectorDialog.vue
Vue
agpl-3.0
728
<script setup lang="ts"> import Code from '../../components/Code.vue' import { Expression } from '../../types/query.types' import { expression } from '../helpers' const props = defineProps<{ placeholder?: string }>() const modelValue = defineModel<Expression>({ default: () => expression(''), required: true, }) </script> <template> <div class="min-h-[1.75rem] w-full rounded border text-sm"> <Code class="inline-expression" v-model="modelValue.expression" language="python" :placeholder="placeholder" /> </div> </template> <style lang="scss"> .inline-expression { .cm-content { padding: 0 !important; line-height: 26px !important; } .cm-placeholder { line-height: 26px !important; } .cm-gutters { line-height: 26px !important; } } </style>
2302_79757062/insights
frontend/src2/query/components/InlineExpression.vue
Vue
agpl-3.0
778
<script setup lang="ts"> import { Braces } from 'lucide-vue-next' import { computed, inject, reactive, watch } from 'vue' import useTableStore from '../../data_source/tables' import { wheneverChanges } from '../../helpers' import { joinTypes } from '../../helpers/constants' import { JoinArgs, JoinType } from '../../types/query.types' import { workbookKey } from '../../workbook/workbook' import { column, expression, query_table, table } from '../helpers' import { getCachedQuery, Query } from '../query' import InlineExpression from './InlineExpression.vue' import { handleOldProps, useTableColumnOptions, useTableOptions } from './join_utils' const props = defineProps<{ join?: JoinArgs }>() const emit = defineEmits({ select: (join: JoinArgs) => true, }) const showDialog = defineModel() if (props.join) { handleOldProps(props.join) } const join = reactive<JoinArgs>( props.join ? { ...props.join } : { join_type: 'inner', table: table({}), join_condition: { left_column: column(''), right_column: column(''), }, select_columns: [], } ) const selectedTableOption = computed({ get() { if (join.table.type === 'table' && join.table.table_name) { return `${join.table.data_source}.${join.table.table_name}` } if (join.table.type === 'query' && join.table.query_name) { return join.table.query_name } }, set(option: any) { if (option.data_source && option.table_name) { join.table = table({ data_source: option.data_source, table_name: option.table_name, }) } if (option.query_name) { join.table = query_table({ workbook: option.workbook, query_name: option.query_name, }) } }, }) const query = inject('query') as Query const data_source = computed(() => { // allow only one data source joins for now // TODO: support multiple data source joins if live connection is disabled // if (!query.doc.use_live_connection) return undefined const operations = query.getOperationsForExecution() const source = operations.find((op) => op.type === 'source') return source && source.table.type === 'table' ? source.table.data_source : '' }) wheneverChanges(selectedTableOption, () => { if (!selectedTableOption.value) return // reset previous values if table is changed join.select_columns = [] if ('right_column' in join.join_condition && join.join_condition.right_column.column_name) { join.join_condition.right_column.column_name = '' } if ('join_expression' in join.join_condition && join.join_condition.join_expression) { join.join_condition.join_expression = expression('') } }) const rightTable = computed(() => { return join.table.type === 'table' ? join.table.table_name : '' }) const tableOptions = useTableOptions({ data_source, initialSearchText: rightTable.value, }) const rightTableColumnOptions = useTableColumnOptions(data_source, rightTable) watch( () => rightTableColumnOptions.options, () => { if ('join_expression' in join.join_condition) return if (!rightTableColumnOptions.options.length) return if ( 'right_column' in join.join_condition && !join.join_condition.right_column.column_name ) { autoMatchColumns() } } ) const tableStore = useTableStore() async function autoMatchColumns() { const selected_tables = query .getOperationsForExecution() .filter((op) => op.type === 'source' || op.type === 'join') .map((op) => { if (op.type === 'source' && op.table.type === 'table') { return op.table.table_name } if (op.type === 'join' && op.table.type === 'table') { return op.table.table_name } return '' }) .filter((table) => table !== rightTable.value) const right_table = rightTable.value const resultColumns = query.result.columns.map((c) => c.name) for (const left_table of selected_tables) { const links = await tableStore.getTableLinks(data_source.value, left_table, right_table) if (!links?.length) { continue } // find a link where left column is present in query.result.columns const link = links.find((l) => resultColumns.includes(l.left_column)) if (!link) continue if ('left_column' in join.join_condition) { join.join_condition.left_column.column_name = link.left_column join.join_condition.right_column.column_name = link.right_column break } } } const workbook = inject(workbookKey)! const linkedQueries = workbook.getLinkedQueries(query.doc.name) const queryTableOptions = workbook.doc.queries .filter((q) => q.name !== query.doc.name && !linkedQueries.includes(q.name)) .map((q) => { return { workbook: workbook.doc.name, query_name: q.name, label: q.title, value: q.name, description: 'Query', } }) const groupedTableOptions = computed(() => { return [ { group: 'Queries', items: queryTableOptions, }, { group: 'Tables', items: tableOptions.options, }, ] }) const queryTableColumnOptions = computed(() => { if (join.table.type !== 'query') return [] const query = getCachedQuery(join.table.query_name) if (!query) return [] return query.result.columnOptions }) const showJoinConditionEditor = computed(() => 'join_expression' in join.join_condition) function toggleJoinConditionEditor() { if (showJoinConditionEditor.value) { join.join_condition = { left_column: column(''), right_column: column(''), } } else { join.join_condition = { join_expression: expression(''), } } } const isValid = computed(() => { const isRightTableSelected = (join.table.type === 'table' && join.table.table_name) || (join.table.type === 'query' && join.table.query_name) const hasValidJoinExpression = 'join_expression' in join.join_condition ? join.join_condition.join_expression.expression : false const hasValidJoinColumns = 'left_column' in join.join_condition && 'right_column' in join.join_condition ? join.join_condition.left_column.column_name && join.join_condition.right_column.column_name : false return ( isRightTableSelected && join.join_type && join.select_columns.length > 0 && (hasValidJoinExpression || hasValidJoinColumns) ) }) function confirm() { if (!isValid.value) return emit('select', { ...join }) showDialog.value = false reset() } function reset() { Object.assign(join, { join_type: 'inner', table: table({}), join_condition: { left_column: column(''), right_column: column(''), }, select_columns: [], }) } </script> <template> <Dialog :modelValue="showDialog"> <template #body> <div class="rounded-lg bg-white px-4 pb-6 pt-5 sm:px-6"> <!-- Title & Close --> <div class="flex items-center justify-between pb-4"> <h3 class="text-2xl font-semibold leading-6 text-gray-900">Join Table</h3> <Button variant="ghost" @click="showDialog = false" icon="x" size="md"> </Button> </div> <!-- Fields --> <div class="flex w-full flex-col gap-3 overflow-auto p-0.5 text-base"> <div> <label class="mb-1 block text-xs text-gray-600">Select Table to Join</label> <Autocomplete placeholder="Table" v-model="selectedTableOption" :loading="tableOptions.loading" :options="groupedTableOptions" @update:query="tableOptions.searchText = $event" /> </div> <div> <label class="mb-1 block text-xs text-gray-600"> {{ showJoinConditionEditor ? 'Custom Join Condition' : 'Select Matching Columns' }} </label> <div class="flex gap-2"> <template v-if=" 'left_column' in join.join_condition && 'right_column' in join.join_condition " > <div class="flex-1"> <Autocomplete placeholder="Column" :options="query.result.columnOptions" :modelValue="join.join_condition.left_column.column_name" @update:modelValue=" join.join_condition.left_column.column_name = $event?.value " /> </div> <div class="flex flex-shrink-0 items-center font-mono">=</div> <div class="flex-1"> <Autocomplete placeholder="Column" :loading="rightTableColumnOptions.loading" :options="[ ...rightTableColumnOptions.options, ...queryTableColumnOptions, ]" :modelValue="join.join_condition.right_column.column_name" @update:modelValue=" join.join_condition.right_column.column_name = $event?.value " /> </div> </template> <template v-else-if="'join_expression' in join.join_condition"> <InlineExpression v-model="join.join_condition.join_expression" placeholder="Example: (t1.column_name = t2.column_name) & (t1.column_name > 10)" /> </template> <div class="flex flex-shrink-0 items-start"> <Tooltip text="Custom Join Condition" :hover-delay="0.5"> <Button @click="toggleJoinConditionEditor"> <template #icon> <Braces class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> </Tooltip> </div> </div> </div> <div> <label class="mb-1 block text-xs text-gray-600">Select Join Type</label> <div class="flex gap-2"> <div v-for="joinType in joinTypes" :key="joinType.label" class="flex flex-1 flex-col items-center justify-center rounded border py-3 transition-all" :class=" join.join_type === joinType.value ? 'border-gray-700' : 'cursor-pointer hover:border-gray-400' " @click="join.join_type = joinType.value" > <component :is="joinType.icon" class="h-6 w-6 text-gray-600" stroke-width="1.5" /> <span class="block text-center text-xs">{{ joinType.label }}</span> </div> </div> <div class="mt-1 text-xs text-gray-600"> {{ joinTypes.find((j) => j.value === join.join_type)?.description }} </div> </div> <div> <label class="mb-1 block text-xs text-gray-600" >Select Columns to Add</label > <Autocomplete :multiple="true" placeholder="Columns" :loading="rightTableColumnOptions.loading" :options="[ ...rightTableColumnOptions.options, ...queryTableColumnOptions, ]" :modelValue="join.select_columns?.map((c) => c.column_name)" @update:modelValue=" join.select_columns = $event?.map((o: any) => column(o.value)) || [] " /> </div> </div> <!-- Actions --> <div class="mt-4 flex justify-end gap-2"> <Button variant="outline" label="Cancel" @click="showDialog = false" /> <Button variant="solid" label="Confirm" :disabled="!isValid" @click="confirm" /> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/JoinSelectorDialog.vue
Vue
agpl-3.0
10,933
<script setup lang="ts"> import { computed, ref } from 'vue' import { COLUMN_TYPES } from '../../helpers/constants' import { ColumnDataType, ColumnOption, MutateArgs } from '../../types/query.types' import { expression } from '../helpers' import ExpressionEditor from './ExpressionEditor.vue' const props = defineProps<{ mutation?: MutateArgs; columnOptions: ColumnOption[] }>() const emit = defineEmits({ select: (column: MutateArgs) => true }) const showDialog = defineModel() const columnTypes = COLUMN_TYPES.map((t) => t.value as ColumnDataType) const newColumn = ref( props.mutation ? { name: props.mutation.new_name, type: props.mutation.data_type, expression: props.mutation.expression.expression, } : { name: 'new_column', type: columnTypes[0], expression: '', } ) const isValid = computed(() => { return newColumn.value.name && newColumn.value.type && newColumn.value.expression.trim() }) function confirmCalculation() { if (!isValid.value) return emit('select', { new_name: newColumn.value.name, data_type: newColumn.value.type, expression: expression(newColumn.value.expression), }) resetNewColumn() showDialog.value = false } function resetNewColumn() { newColumn.value = { name: 'New Column', type: columnTypes[0], expression: '', } } </script> <template> <Dialog :modelValue="showDialog" @after-leave="resetNewColumn" @close="!newColumn.expression && (showDialog = false)" > <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">Create Column</h3> <Button variant="ghost" @click="showDialog = false" icon="x" size="md"> </Button> </div> <div class="flex flex-col gap-2"> <ExpressionEditor v-model="newColumn.expression" :column-options="props.columnOptions" /> <div class="flex gap-2"> <FormControl type="text" class="flex-1" label="Column Name" autocomplete="off" placeholder="Column Name" v-model="newColumn.name" /> <FormControl type="select" class="flex-1" label="Column Type" autocomplete="off" :options="columnTypes" v-model="newColumn.type" /> </div> </div> <div class="mt-2 flex items-center justify-between gap-2"> <div></div> <div class="flex items-center gap-2"> <Button label="Confirm" variant="solid" :disabled="!isValid" @click="confirmCalculation" /> </div> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/NewColumnSelectorDialog.vue
Vue
agpl-3.0
2,672
<script setup lang="ts"> import { Table } from 'lucide-vue-next' import { inject, ref } from 'vue' import { Query } from '../query' import SourceSelectorDialog from './source_selector/SourceSelectorDialog.vue' const query = inject('query') as Query const showSourceSelectorDialog = ref(true) </script> <template> <div class="flex h-full w-full items-center justify-center bg-gray-50"> <div class="flex items-center gap-4"> <div class="flex h-[18rem] w-[24rem] flex-col items-center justify-center rounded bg-white px-8 text-center shadow-sm" > <Table class="mb-2 h-12 w-12 text-gray-400" stroke-width="1.5" /> <span class="text-lg font-medium">Select a Source</span> <span class="text-sm text-gray-600"> Select a source to start building your query </span> <Button class="mt-2" variant="outline" @click="showSourceSelectorDialog = true"> Open Source Selector </Button> </div> </div> </div> <SourceSelectorDialog v-if="showSourceSelectorDialog" v-model="showSourceSelectorDialog" @select="query.setSource($event)" /> </template>
2302_79757062/insights
frontend/src2/query/components/QueryBuilderSourceSelector.vue
Vue
agpl-3.0
1,092
<script setup lang="tsx"> import { LoadingIndicator } from 'frappe-ui' import { computed, inject } from 'vue' import DataTable from '../../components/DataTable.vue' import { Query } from '../query' import QueryBuilderTableColumn from './QueryBuilderTableColumn.vue' const query = inject('query') as Query const columns = computed(() => query.result.columns) const rows = computed(() => query.result.formattedRows) const previewRowCount = computed(() => query.result.rows.length.toLocaleString()) const totalRowCount = computed(() => query.result.totalRowCount.toLocaleString()) </script> <template> <div class="relative flex w-full flex-1 flex-col overflow-hidden bg-white"> <div v-if="query.executing" class="absolute top-10 z-10 flex h-[calc(100%-2rem)] w-full items-center justify-center rounded bg-gray-50/30 backdrop-blur-sm" > <LoadingIndicator class="h-8 w-8 text-gray-700" /> </div> <DataTable :columns="columns" :rows="rows"> <template #column-header="{ column }"> <QueryBuilderTableColumn :column="column" /> </template> <template #footer> <div class="flex flex-shrink-0 items-center gap-3 border-t p-2"> <p class="tnum text-sm text-gray-600"> Showing {{ previewRowCount }} of {{ totalRowCount }} rows </p> </div> </template> </DataTable> </div> </template>
2302_79757062/insights
frontend/src2/query/components/QueryBuilderTable.vue
Vue
agpl-3.0
1,333
<script setup lang="ts"> import { MoreHorizontal } from 'lucide-vue-next' import { inject } from 'vue' import ContentEditable from '../../components/ContentEditable.vue' import { ColumnDataType, FilterOperator, FilterValue, QueryResultColumn, } from '../../types/query.types' import { column } from '../helpers' import { Query } from '../query' import ColumnFilter from './ColumnFilter.vue' import ColumnRemove from './ColumnRemove.vue' import ColumnSort from './ColumnSort.vue' import ColumnTypeChange from './ColumnTypeChange.vue' const props = defineProps<{ column: QueryResultColumn }>() const query = inject('query') as Query function onRename(new_name: string) { if (new_name === props.column.name) return query.renameColumn(props.column.name, new_name) } function onTypeChange(new_type: ColumnDataType) { if (new_type === props.column.type) return query.changeColumnType(props.column.name, new_type) } function onRemove(togglePopover: () => void) { query.removeColumn(props.column.name) togglePopover() } function onSort(sort_order: 'asc' | 'desc' | '', togglePopover: () => void) { if (!sort_order) { query.removeOrderBy(props.column.name) togglePopover() return } query.addOrderBy({ column: column(props.column.name), direction: sort_order, }) togglePopover() } function onFilter( filter_operator: FilterOperator, filter_value: FilterValue, togglePopover: () => void ) { query.addFilterGroup({ logical_operator: 'And', filters: [ { column: column(props.column.name), operator: filter_operator, value: filter_value, }, ], }) togglePopover() } </script> <template> <div class="flex w-full items-center justify-between gap-8"> <div class="flex items-center"> <ColumnTypeChange :column="props.column" @typeChange="onTypeChange" /> <ContentEditable :modelValue="props.column.name" placeholder="Column Name" class="flex h-6 items-center whitespace-nowrap rounded-sm px-0.5 text-base focus:ring-1 focus:ring-gray-700 focus:ring-offset-1" @returned="onRename" @blur="onRename" /> </div> <Popover placement="bottom-end"> <template #target="{ togglePopover, isOpen }"> <Button variant="ghost" class="rounded-sm" @click="togglePopover" :class="isOpen ? '!bg-gray-100' : ''" > <template #icon> <MoreHorizontal class="h-4 w-4 text-gray-700" /> </template> </Button> </template> <template #body-main="{ togglePopover, isOpen }"> <div v-if="isOpen" class="flex min-w-[10rem] flex-col p-1"> <!-- Rename, Sort, Filter, Summarize, Describe, Pivot, Remove --> <ColumnSort :column="props.column" @sort="onSort($event, togglePopover)" /> <ColumnFilter :column="props.column" @filter="(op, val) => onFilter(op, val, togglePopover)" :valuesProvider=" (searchTxt: string) => query.getDistinctColumnValues(props.column.name, searchTxt) " /> <ColumnRemove :column="props.column" @remove="onRemove(togglePopover)" /> </div> </template> </Popover> </div> </template>
2302_79757062/insights
frontend/src2/query/components/QueryBuilderTableColumn.vue
Vue
agpl-3.0
3,082
<script setup lang="ts"> import { Tooltip } from 'frappe-ui' import { BetweenHorizonalStart, BlendIcon, Braces, CodeIcon, ColumnsIcon, Combine, Database, Download, FilterIcon, FunctionSquare, PlayIcon, Sigma, } from 'lucide-vue-next' import { h, inject, ref, watch } from 'vue' import { Operation } from '../../types/query.types' import { Query } from '../query' import ColumnsSelectorDialog from './ColumnsSelectorDialog.vue' import FiltersSelectorDialog from './FiltersSelectorDialog.vue' import JoinSelectorDialog from './JoinSelectorDialog.vue' import UnionSelectorDialog from './UnionSelectorDialog.vue' import NewColumnSelectorDialog from './NewColumnSelectorDialog.vue' import SourceSelectorDialog from './source_selector/SourceSelectorDialog.vue' import SummarySelectorDialog from './SummarySelectorDialog.vue' import ViewSQLDialog from './ViewSQLDialog.vue' import CustomScriptDialog from './CustomScriptDialog.vue' const query = inject('query') as Query const showSourceSelectorDialog = ref(false) const showJoinSelectorDialog = ref(false) const showUnionSelectorDialog = ref(false) const showColumnsSelectorDialog = ref(false) const showFiltersSelectorDialog = ref(false) const showNewColumnSelectorDialog = ref(false) const showSummarySelectorDialog = ref(false) const showCustomScriptDialog = ref(false) const showViewSQLDialog = ref(false) watch( () => query.activeEditOperation, (operation: Operation) => { switch (operation.type) { case 'source': showSourceSelectorDialog.value = true break case 'join': showJoinSelectorDialog.value = true break case 'union': showUnionSelectorDialog.value = true break case 'select': showColumnsSelectorDialog.value = true break case 'filter': case 'filter_group': showFiltersSelectorDialog.value = true break case 'mutate': showNewColumnSelectorDialog.value = true break case 'summarize': showSummarySelectorDialog.value = true break case 'custom_operation': showCustomScriptDialog.value = true break default: break } } ) const actions = [ { label: 'Change Source', icon: Database, onClick: () => (showSourceSelectorDialog.value = true), }, { label: 'Select Columns', icon: ColumnsIcon, onClick: () => (showColumnsSelectorDialog.value = true), }, { label: 'Filter Rows', icon: FilterIcon, onClick: () => (showFiltersSelectorDialog.value = true), }, { label: 'Join Table', icon: h(BlendIcon, { class: '-rotate-45' }), onClick: () => (showJoinSelectorDialog.value = true), }, { label: 'Append Table', icon: BetweenHorizonalStart, onClick: () => (showUnionSelectorDialog.value = true), }, // { // label: 'Sort Rows', // icon: ArrowUpDown, // }, { label: 'Create Columns', icon: FunctionSquare, onClick: () => (showNewColumnSelectorDialog.value = true), }, { label: 'Summarize', icon: Combine, onClick: () => (showSummarySelectorDialog.value = true), }, { label: 'Custom Script', icon: Braces, onClick: () => (showCustomScriptDialog.value = true), }, // { // label: 'Pivot', // icon: GitBranch, // }, // { // label: 'Unpivot', // icon: GitMerge, // }, { type: 'separator', }, { label: 'Download Data', icon: Download, onClick: () => query.downloadResults(), }, { label: 'View SQL', icon: CodeIcon, onClick: () => (showViewSQLDialog.value = true), }, { label: 'Execute', icon: PlayIcon, onClick: () => query.execute(), }, ] </script> <template> <div class="flex w-full flex-shrink-0 justify-between"> <div class="flex w-full items-center gap-2"> <template v-for="(action, idx) in actions" :key="idx"> <div v-if="action.type === 'separator'" class="h-8 flex-1"></div> <Tooltip v-else placement="top" :hover-delay="0.1" :text="action.label"> <Button :variant="'ghost'" @click="action.onClick" class="h-8 w-8 bg-white shadow" > <template #icon> <component :is="action.icon" class="h-4.5 w-4.5 text-gray-700" stroke-width="1.5" /> </template> </Button> </Tooltip> </template> </div> </div> <SourceSelectorDialog v-if="showSourceSelectorDialog" v-model="showSourceSelectorDialog" @update:model-value="!$event && query.setActiveEditIndex(-1)" :source=" query.activeEditOperation.type === 'source' ? query.activeEditOperation : undefined " @select="query.setSource($event)" /> <JoinSelectorDialog v-if="showJoinSelectorDialog" v-model="showJoinSelectorDialog" @update:model-value="!$event && query.setActiveEditIndex(-1)" :join="query.activeEditOperation.type === 'join' ? query.activeEditOperation : undefined" @select="query.addJoin($event)" /> <UnionSelectorDialog v-if="showUnionSelectorDialog" v-model="showUnionSelectorDialog" @update:model-value="!$event && query.setActiveEditIndex(-1)" :union="query.activeEditOperation.type === 'union' ? query.activeEditOperation : undefined" @select="query.addUnion($event)" /> <ColumnsSelectorDialog v-if="showColumnsSelectorDialog" v-model="showColumnsSelectorDialog" @update:model-value="!$event && query.setActiveEditIndex(-1)" :columns=" query.activeEditOperation.type === 'select' ? query.activeEditOperation : undefined " @select="query.selectColumns($event)" /> <FiltersSelectorDialog v-if="showFiltersSelectorDialog" v-model="showFiltersSelectorDialog" @update:model-value="!$event && query.setActiveEditIndex(-1)" :filter=" query.activeEditOperation.type === 'filter' ? query.activeEditOperation : undefined " :filter-group=" query.activeEditOperation.type === 'filter_group' ? query.activeEditOperation : undefined " :column-options="query.result.columnOptions" @select="query.addFilterGroup($event)" /> <NewColumnSelectorDialog v-if="showNewColumnSelectorDialog" v-model="showNewColumnSelectorDialog" @update:model-value="!$event && query.setActiveEditIndex(-1)" :mutation=" query.activeEditOperation.type === 'mutate' ? query.activeEditOperation : undefined " :column-options="query.result.columnOptions" @select="query.addMutate($event)" /> <SummarySelectorDialog v-if="showSummarySelectorDialog" v-model="showSummarySelectorDialog" @update:model-value="!$event && query.setActiveEditIndex(-1)" :summary=" query.activeEditOperation.type === 'summarize' ? query.activeEditOperation : undefined " @select="query.addSummarize($event)" /> <CustomScriptDialog v-if="showCustomScriptDialog" v-model="showCustomScriptDialog" @update:model-value="!$event && query.setActiveEditIndex(-1)" :operation=" query.activeEditOperation.type === 'custom_operation' ? query.activeEditOperation : undefined " :column-options="query.result.columnOptions" @select="query.addCustomOperation($event)" /> <ViewSQLDialog v-if="showViewSQLDialog" v-model="showViewSQLDialog" /> </template>
2302_79757062/insights
frontend/src2/query/components/QueryBuilderToolbar.vue
Vue
agpl-3.0
6,965
<script setup lang="ts"> import { inject } from 'vue' import InlineFormControlLabel from '../../components/InlineFormControlLabel.vue' import { Query } from '../query' const query = inject('query') as Query window.toggleLiveConnection = () => { query.doc.use_live_connection = !query.doc.use_live_connection } </script> <template> <div class="flex flex-col px-2.5 py-2"> <div class="mb-1 flex h-6 items-center justify-between"> <div class="flex items-center gap-1"> <div class="text-sm font-medium">Metadata</div> </div> <div></div> </div> <div class="flex flex-shrink-0 flex-col gap-2.5 px-0.5"> <InlineFormControlLabel label="Query Title"> <FormControl v-model="query.doc.title" autocomplete="off" placeholder="Title" /> </InlineFormControlLabel> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/components/QueryInfo.vue
Vue
agpl-3.0
811
<script setup lang="ts"> import { CircleDotIcon, Edit, Sparkles, XIcon } from 'lucide-vue-next' import { inject } from 'vue' import { query_operation_types } from '../helpers' import { Query } from '../query' const query = inject('query') as Query </script> <template> <div v-if="query.doc.operations.length" class="flex flex-col px-2.5 py-2"> <div class="mb-1 flex h-6 items-center justify-between"> <div class="flex items-center gap-1"> <div class="text-sm font-medium">Operations</div> </div> <div></div> </div> <div class="relative ml-1.5 mt-1 border-l border-gray-300 text-xs"> <div v-for="(op, idx) in query.doc.operations" :key="idx" class="group relative ml-3 mb-3 cursor-pointer last:mb-0" :class="idx <= query.activeOperationIdx ? 'opacity-100' : 'opacity-40'" @click="query.setActiveOperation(idx)" > <CircleDotIcon class="absolute -left-4 top-1 h-2 w-2 bg-white text-gray-600" /> <div class="flex items-center justify-between gap-2 overflow-hidden"> <div class="flex flex-1 flex-col gap-1 overflow-hidden"> <div class="font-medium text-gray-900"> {{ query_operation_types[op.type].label }} </div> <div class="text-gray-700" data-state="closed"> {{ query_operation_types[op.type].getDescription(op as any) }} </div> </div> <div v-show=" query.activeOperationIdx === idx || (query.activeEditIndex === -1 && idx === query.doc.operations.length - 1) " class="flex-shrink-0 opacity-0 transition-opacity group-hover:opacity-100" > <Button variant="ghost" @click.prevent.stop="query.setActiveEditIndex(idx)"> <template #icon> <Edit class="h-3.5 w-3.5 text-gray-500" /> </template> </Button> <Button variant="ghost" @click.prevent.stop="query.removeOperation(idx)"> <template #icon> <XIcon class="h-3.5 w-3.5 text-gray-500" /> </template> </Button> </div> </div> </div> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/components/QueryOperations.vue
Vue
agpl-3.0
2,037
<script setup lang="ts"> import { computed, inject, ref } from 'vue' import { FIELDTYPES } from '../../helpers/constants' import { aggregations, ColumnMeasure, Dimension, DimensionDataType, MeasureDataType, QueryResultColumn, SummarizeArgs, } from '../../types/query.types' import { Query } from '../query' const props = defineProps<{ summary?: SummarizeArgs }>() const emit = defineEmits({ select: (args: SummarizeArgs) => true }) const showDialog = defineModel() const query = inject<Query>('query')! const columnOptions = ref<QueryResultColumn[]>([]) query.getColumnsForSelection().then((cols: QueryResultColumn[]) => { columnOptions.value = cols.map((col) => ({ ...col, value: col.name, })) }) const numberColumns = computed(() => columnOptions.value.filter((col) => FIELDTYPES.NUMBER.includes(col.type)) ) const nonNumberColumns = computed(() => columnOptions.value.filter((col) => !FIELDTYPES.NUMBER.includes(col.type)) ) const measures = ref<ColumnMeasure[]>((props.summary?.measures as ColumnMeasure[]) || []) const dimensions = ref<Dimension[]>(props.summary?.dimensions || []) const areAllMeasuresValid = computed( () => measures.value.length && measures.value.every((m) => m.column_name) ) const areAllDimensionsValid = computed( () => dimensions.value.length && dimensions.value.every((d) => d.column_name) ) function addMeasure() { measures.value.push({ measure_name: '', column_name: '', aggregation: 'sum', data_type: 'Decimal', }) } function addDimension() { dimensions.value.push({ column_name: '', data_type: 'String', granularity: 'month', }) } function resetSelections() { measures.value = [] dimensions.value = [] } function confirmSelections() { console.log('measures', measures.value) console.log('dimensions', dimensions.value) emit('select', { measures: measures.value, dimensions: dimensions.value, }) showDialog.value = false } </script> <template> <Dialog :modelValue="showDialog" :options="{ size: '2xl' }"> <template #body> <div class="min-w-[36rem] rounded-lg 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">Summarize</h3> <Button variant="ghost" @click="showDialog = false" icon="x" size="md"> </Button> </div> <div class="flex flex-col gap-4"> <div class="flex items-start gap-4"> <span class="w-[68px] flex-shrink-0 text-right text-base leading-7 text-gray-600" >Aggregate</span > <div class="flex flex-1 flex-wrap gap-2"> <div v-for="(measure, idx) in measures" :key="idx" class="flex"> <Autocomplete button-classes="rounded-r-none" placeholder="Agg" :options="aggregations" :modelValue="measure.aggregation" @update:modelValue="measure.aggregation = $event.value" :hide-search="true" /> <Autocomplete button-classes="rounded-l-none" :placeholder="measure.aggregation" :options="columnOptions" :modelValue="measure.column_name" @update:model-value="(e: QueryResultColumn) => { measure.column_name = e.name measure.data_type = e.type as MeasureDataType measure.measure_name = `${measure.aggregation}(${e.name})` }" /> </div> <Button icon="plus" @click="addMeasure"> </Button> </div> </div> <div class="flex items-start gap-4"> <span class="w-[68px] flex-shrink-0 text-right text-base leading-7 text-gray-600" > Group By </span> <div class="flex flex-1 flex-wrap gap-2"> <div v-for="(dimension, idx) in dimensions" :key="idx" class="flex"> <Autocomplete placeholder="Column" :options="nonNumberColumns" :modelValue="dimension.column_name" @update:model-value="(e: QueryResultColumn) => { dimension.column_name = e.name dimension.data_type = e.type as DimensionDataType }" /> </div> <Button icon="plus" @click="addDimension"> </Button> </div> </div> <div class="mt-2 flex justify-end"> <div class="flex gap-2"> <Button label="Clear" variant="outline" @click="resetSelections" /> <Button label="Done" variant="solid" :disabled="!areAllMeasuresValid || !areAllDimensionsValid" @click="confirmSelections" /> </div> </div> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/SummarySelectorDialog.vue
Vue
agpl-3.0
4,564
<script setup lang="ts"> import { computed, inject, reactive } from 'vue' import { UnionArgs } from '../../types/query.types' import { workbookKey } from '../../workbook/workbook' import { query_table, table } from '../helpers' import { Query } from '../query' import { useTableOptions } from './join_utils' const props = defineProps<{ union?: UnionArgs }>() const emit = defineEmits({ select: (join: UnionArgs) => true, }) const showDialog = defineModel() const union = reactive<UnionArgs>( props.union ? { ...props.union } : { table: table({}), distinct: false, } ) const selectedTableOption = computed({ get() { if (union.table.type === 'table' && union.table.table_name) { return `${union.table.data_source}.${union.table.table_name}` } if (union.table.type === 'query' && union.table.query_name) { return union.table.query_name } }, set(option: any) { if (option.data_source && option.table_name) { union.table = table({ data_source: option.data_source, table_name: option.table_name, }) } if (option.query_name) { union.table = query_table({ workbook: option.workbook, query_name: option.query_name, }) } }, }) const query = inject('query') as Query const data_source = computed(() => { // allow only one data source joins for now // TODO: support multiple data source joins if live connection is disabled // if (!query.doc.use_live_connection) return undefined const operations = query.getOperationsForExecution() const source = operations.find((op) => op.type === 'source') return source && source.table.type === 'table' ? source.table.data_source : '' }) const rightTable = computed(() => { return union.table.type === 'table' ? union.table.table_name : '' }) const tableOptions = useTableOptions({ data_source, initialSearchText: rightTable.value, }) const workbook = inject(workbookKey)! const linkedQueries = workbook.getLinkedQueries(query.doc.name) const queryTableOptions = workbook.doc.queries .filter((q) => q.name !== query.doc.name && !linkedQueries.includes(q.name)) .map((q) => { return { workbook: workbook.doc.name, query_name: q.name, label: q.title, value: q.name, description: 'Query', } }) const groupedTableOptions = computed(() => { return [ { group: 'Queries', items: queryTableOptions, }, { group: 'Tables', items: tableOptions.options, }, ] }) const isValid = computed(() => { return ( (union.table.type === 'table' && union.table.table_name) || (union.table.type === 'query' && union.table.query_name) ) }) function confirm() { if (!isValid.value) return emit('select', { ...union }) showDialog.value = false reset() } function reset() { Object.assign(union, { table: table({}), distinct: false, }) } </script> <template> <Dialog :modelValue="showDialog"> <template #body> <div class="rounded-lg bg-white px-4 pb-6 pt-5 sm:px-6"> <!-- Title & Close --> <div class="flex items-center justify-between pb-4"> <h3 class="text-2xl font-semibold leading-6 text-gray-900">Append Rows</h3> <Button variant="ghost" @click="showDialog = false" icon="x" size="md"> </Button> </div> <!-- Fields --> <div class="flex w-full flex-col gap-3 overflow-auto p-0.5 text-base"> <div> <label class="mb-1 block text-xs text-gray-600">Select Table</label> <Autocomplete placeholder="Table" v-model="selectedTableOption" :loading="tableOptions.loading" :options="groupedTableOptions" @update:query="tableOptions.searchText = $event" /> </div> <div> <FormControl type="select" label="Drop Duplicates" :modelValue="union.distinct ? 'true' : 'false'" @update:modelValue="union.distinct = $event === 'true'" :options="[ { label: 'Yes', value: 'true' }, { label: 'No', value: 'false' }, ]" /> </div> </div> <!-- Actions --> <div class="mt-4 flex justify-end gap-2"> <Button variant="outline" label="Cancel" @click="showDialog = false" /> <Button variant="solid" label="Confirm" :disabled="!isValid" @click="confirm" /> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/UnionSelectorDialog.vue
Vue
agpl-3.0
4,239
<script setup lang="ts"> import { inject } from 'vue' import Code from '../../components/Code.vue' import { copyToClipboard } from '../../helpers' import { Query } from '../query' const showDialog = defineModel() const query = inject('query') as Query </script> <template> <Dialog v-model="showDialog" :options="{ title: 'Generated SQL', size: '3xl' }" :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.result.executedSQL" :read-only="true" :hide-line-numbers="true" /> </div> <Button icon="copy" variant="outline" class="absolute bottom-2 right-2" @click="copyToClipboard(query.result.executedSQL)" ></Button> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/ViewSQLDialog.vue
Vue
agpl-3.0
873
import { FIELDTYPES } from '../../helpers/constants' import { ColumnDataType, FilterExpression, FilterRule } from '../../types/query.types' export function getValueSelectorType(filter: FilterRule, columnType: ColumnDataType) { if (!filter.column.column_name || !filter.operator) return 'text' // default to text if (['is_set', 'is_not_set'].includes(filter.operator)) return if (FIELDTYPES.TEXT.includes(columnType)) { return ['in', 'not_in'].includes(filter.operator) ? 'select' : 'text' } if (FIELDTYPES.NUMBER.includes(columnType)) return 'number' if (FIELDTYPES.DATE.includes(columnType)) { return filter.operator === 'between' ? 'date_range' : 'date' } return 'text' } export function isFilterExpressionValid(filter: FilterExpression) { return filter.expression.expression.trim().length > 0 } export function isFilterValid(filter: FilterRule, columnType: ColumnDataType) { if (!filter.column.column_name || !filter.operator) { return false } if (!filter.column.column_name || !filter.operator) { return false } const valueSelectorType = getValueSelectorType(filter, columnType) // if selector type is none, no need to validate if (!valueSelectorType) { return true } if (!filter.value && filter.value !== 0) { return false } // for number, validate if it's a number if (FIELDTYPES.NUMBER.includes(columnType)) { return !isNaN(filter.value as any) } // for text, // if it's a select, validate if it's an array of strings // if it's a text, validate if it's a string if (FIELDTYPES.TEXT.includes(columnType)) { if (valueSelectorType === 'select') { return Boolean( Array.isArray(filter.value) && filter.value.length && filter.value.every((v: any) => typeof v === 'string') ) } else { return typeof filter.value === 'string' } } // for date, // if it's a date, validate if it's a date string // if it's a date range, validate if it's an array of 2 date strings if (FIELDTYPES.DATE.includes(columnType)) { if (valueSelectorType === 'date') { return typeof filter.value === 'string' } else if (valueSelectorType === 'date_range') { return Boolean( Array.isArray(filter.value) && filter.value.length === 2 && filter.value.every((v: any) => typeof v === 'string') ) } } return false }
2302_79757062/insights
frontend/src2/query/components/filter_utils.ts
TypeScript
agpl-3.0
2,299
import { watchDebounced } from '@vueuse/core' import { computed, ComputedRef, reactive, Ref, ref } from 'vue' import useTableStore from '../../data_source/tables' import { wheneverChanges } from '../../helpers' import { JoinArgs } from '../../types/query.types' export function handleOldProps(join: JoinArgs) { // handle backward compatibility // move left_column and right_column under join_condition const _join: any = { ...join } if (join && _join.left_column?.column_name && _join.right_column?.column_name) { join.join_condition = { left_column: _join.left_column, right_column: _join.right_column, } // @ts-ignore delete join.left_column // @ts-ignore delete join.right_column } } type TableOption = { label: string value: string description: string data_source: string table_name: string } type UseTableOptions = { data_source: Ref<string> | ComputedRef<string> initialSearchText?: string } export function useTableOptions(options: UseTableOptions) { const tableStore = useTableStore() const tableOptions = computed<TableOption[]>(() => { if (!tableStore.tables.length) return [] return tableStore.tables.map((t) => ({ table_name: t.table_name, data_source: t.data_source, description: t.data_source, label: t.table_name, value: `${t.data_source}.${t.table_name}`, })) }) const searchText = ref(options.initialSearchText || '') watchDebounced( searchText, () => tableStore.getTables(options.data_source.value, searchText.value), { debounce: 300, immediate: true, } ) return reactive({ options: tableOptions, loading: tableStore.loading, searchText, }) } export function useTableColumnOptions(data_source: Ref<string>, table_name: Ref<string>) { const tableColumnOptions = ref<DropdownOption[]>([]) const fetchingColumnOptions = ref(false) const tableStore = useTableStore() wheneverChanges( table_name, () => { if (!table_name.value) { tableColumnOptions.value = [] return } fetchingColumnOptions.value = true tableStore .getTableColumns(data_source.value, table_name.value) .then((columns) => { tableColumnOptions.value = columns.map((c: any) => ({ label: c.name, value: c.name, description: c.type, data_type: c.type, })) }) .finally(() => { fetchingColumnOptions.value = false }) }, { immediate: true } ) return reactive({ options: tableColumnOptions, loading: fetchingColumnOptions, }) }
2302_79757062/insights
frontend/src2/query/components/join_utils.ts
TypeScript
agpl-3.0
2,484
<script setup> import { ChevronDown, ListFilter } from 'lucide-vue-next' import { computed } from 'vue' import useDataSourceStore from '../../../data_source/data_source' const currentSourceName = defineModel() const props = defineProps({ placeholder: { type: String, default: 'Data source', }, }) const dataSourceStore = useDataSourceStore() const currentSource = computed(() => { return dataSourceStore.sources.find((source) => source.name === currentSourceName.value) }) const dataSourceOptions = computed(() => { return dataSourceStore.sources.map((source) => ({ label: source.title, value: source.name, })) }) </script> <template> <Autocomplete :options="dataSourceOptions" :modelValue="currentSourceName" @update:modelValue="currentSourceName = $event.value" > <template #target="{ togglePopover }"> <Button variant="outline" @click="togglePopover"> <template #prefix> <ListFilter class="h-4 w-4 flex-shrink-0" stroke-width="1.5" /> </template> <span class="flex-1 truncate"> {{ currentSource?.title || placeholder }} </span> <template #suffix> <ChevronDown class="h-4 w-4 flex-shrink-0" stroke-width="1.5" /> </template> </Button> </template> </Autocomplete> </template>
2302_79757062/insights
frontend/src2/query/components/source_selector/DataSourceSelector.vue
Vue
agpl-3.0
1,251
<script setup lang="ts"> import { ListEmptyState, ListView } from 'frappe-ui' import { CheckIcon, RefreshCcw, SearchIcon, Table2Icon } from 'lucide-vue-next' import { h, ref } from 'vue' import useTableStore from '../../../data_source/tables' import { wheneverChanges } from '../../../helpers' import { TableArgs } from '../../../types/query.types' const props = defineProps<{ data_source: string }>() const tableStore = useTableStore() tableStore.getTables() const selectedTable = defineModel<TableArgs>('selectedTable') const tableSearchQuery = ref(selectedTable.value?.table_name || '') wheneverChanges( () => [tableSearchQuery.value, props.data_source], () => tableStore.getTables(props.data_source, tableSearchQuery.value), { debounce: 300, immediate: true } ) const listColumns = [ { label: 'Table', key: 'table_name', width: 2, prefix: () => h(Table2Icon, { class: 'h-4 w-4 text-gray-600' }), }, { label: 'Data Source', key: 'data_source', width: 1, }, { label: '', key: 'selected', width: '40px', getLabel: () => '', prefix: (props: any) => props.row.table_name === selectedTable.value?.table_name && h(CheckIcon, { class: 'h-4 w-4' }), }, ] </script> <template> <div class="flex h-full flex-col gap-2 overflow-auto p-0.5"> <div class="flex justify-between overflow-visible py-1"> <div class="flex gap-2"> <FormControl placeholder="Search by Title" v-model="tableSearchQuery" autocomplete="off" > <template #prefix> <SearchIcon class="h-4 w-4 text-gray-500" /> </template> </FormControl> </div> <div> <Button variant="outline" label="Refresh Tables" :loading="tableStore.updatingDataSourceTables" @click="tableStore.updateDataSourceTables(props.data_source)" > <template #prefix> <RefreshCcw class="h-4 w-4 text-gray-700" stroke-width="1.5" /> </template> </Button> </div> </div> <ListView class="h-full" :columns="listColumns" :rows="tableStore.tables" :row-key="'name'" :options="{ selectable: false, showTooltip: false, onRowClick: (row: any) => (selectedTable = row), emptyState: { title: 'No Tables Found', description: 'Sync tables from your data source to get started', button: { variant: 'outline', label: 'Refresh Tables', onClick: () => tableStore.updateDataSourceTables(props.data_source), }, }, }" > </ListView> </div> </template>
2302_79757062/insights
frontend/src2/query/components/source_selector/DataSourceTableList.vue
Vue
agpl-3.0
2,486
<script setup lang="tsx"> import { DatabaseIcon, Table2Icon } from 'lucide-vue-next' import { computed, inject, ref } from 'vue' import useDataSourceStore from '../../../data_source/data_source' import { wheneverChanges } from '../../../helpers' import { QueryTableArgs, SourceArgs, TableArgs } from '../../../types/query.types' import { Workbook, workbookKey } from '../../../workbook/workbook' import { query_table, table } from '../../helpers' import DataSourceTableList from './DataSourceTableList.vue' import TabbedSidebarLayout, { Tab, TabGroup } from './TabbedSidebarLayout.vue' import WorkbookQueryList from './WorkbookQueryList.vue' const emit = defineEmits({ select: (source: SourceArgs) => true }) const props = defineProps<{ source?: SourceArgs }>() const showDialog = defineModel() const selectedTable = ref<TableArgs>( props.source && props.source.table.type == 'table' ? { ...props.source.table } : { type: 'table', data_source: '', table_name: '', } ) const dataSourceStore = useDataSourceStore() const tabGroups = ref<TabGroup[]>([ { groupLabel: 'Data Sources', tabs: [], }, ]) const activeTab = ref<Tab | undefined>() wheneverChanges( () => activeTab.value?.label, () => { selectedTable.value = { type: 'table', data_source: '', table_name: '', } selectedQuery.value = { type: 'query', workbook: '', query_name: '', } } ) dataSourceStore.getSources().then(() => { tabGroups.value[0].tabs = dataSourceStore.sources.map((source) => ({ label: source.name, icon: DatabaseIcon, component: () => ( <DataSourceTableList v-model:selectedTable={selectedTable.value} data_source={source.name} /> ), })) activeTab.value = tabGroups.value[0].tabs[0] }) const selectedQuery = ref<QueryTableArgs>( props.source && props.source.table.type == 'query' ? { ...props.source.table } : { type: 'query', workbook: '', query_name: '', } ) const workbook = inject<Workbook>(workbookKey)! if (workbook.doc.queries.length > 1) { tabGroups.value.push({ groupLabel: 'Workbook', tabs: [ { label: 'Queries', icon: Table2Icon, component: () => <WorkbookQueryList v-model:selectedQuery={selectedQuery.value} />, }, ], }) } const confirmDisabled = computed(() => { return !selectedTable.value.table_name && !selectedQuery.value.query_name }) function onConfirm() { if (confirmDisabled.value) return emit( 'select', selectedQuery.value.query_name ? { table: query_table(selectedQuery.value), } : { table: table(selectedTable.value), } ) showDialog.value = false } </script> <template> <Dialog v-model="showDialog" :options="{ size: '4xl' }"> <template #body> <div class="relative flex pb-10" :style="{ height: 'calc(100vh - 12rem)' }"> <TabbedSidebarLayout title="Pick Starting Data" :tabs="tabGroups" v-model:activeTab="activeTab" /> <div class="absolute bottom-3 right-3 flex gap-2"> <Button @click="showDialog = false"> Close </Button> <Button variant="solid" :disabled="confirmDisabled" @click="onConfirm"> Confirm </Button> </div> </div> </template> </Dialog> </template>
2302_79757062/insights
frontend/src2/query/components/source_selector/SourceSelectorDialog.vue
Vue
agpl-3.0
3,196
<script setup lang="ts"> import { computed } from 'vue' import SidebarLink from '../../../components/SidebarLink.vue' export type Tab = { label: string component?: any icon?: any } export type TabGroup = { groupLabel: string tabs: Tab[] } export type Tabs = Tab[] | TabGroup[] const props = defineProps<{ title?: string; tabs: Tabs }>() const tabGroups = computed(() => { if (!props.tabs.length) { return [] } if (props.tabs[0].hasOwnProperty('tabs')) { return props.tabs as TabGroup[] } return [{ groupLabel: '', tabs: props.tabs as Tab[] }] }) const activeTab = defineModel<Tab>('activeTab', { type: Object, }) </script> <template> <div class="flex h-full w-full"> <div class="flex w-52 shrink-0 flex-col overflow-hidden bg-gray-50 p-2"> <h1 v-if="props.title" class="mb-3 px-2 pt-2 text-lg font-semibold"> {{ props.title }} </h1> <div v-for="group in tabGroups" class="flex flex-col overflow-hidden"> <div v-if="group.groupLabel" class="mb-2 mt-3 flex flex-shrink-0 cursor-pointer gap-1.5 px-2 text-base font-medium text-gray-600 transition-all duration-300 ease-in-out" > <span>{{ group.groupLabel }}</span> </div> <nav class="flex-1 space-y-1 overflow-y-scroll"> <SidebarLink v-for="tab in group.tabs" :icon="tab.icon" :label="tab.label" class="w-full" :class=" activeTab?.label == tab.label ? 'bg-white shadow-sm' : 'hover:bg-gray-100' " @click="activeTab = tab" /> </nav> </div> </div> <div class="flex h-full flex-1 flex-col px-3 py-3"> <component v-if="activeTab && activeTab.component" :is="activeTab.component" /> </div> </div> </template>
2302_79757062/insights
frontend/src2/query/components/source_selector/TabbedSidebarLayout.vue
Vue
agpl-3.0
1,709
<script setup lang="ts"> import { ListView } from 'frappe-ui' import { CheckIcon, SearchIcon, Table2Icon } from 'lucide-vue-next' import { computed, h, inject, ref } from 'vue' import { QueryTableArgs } from '../../../types/query.types' import { Workbook, workbookKey } from '../../../workbook/workbook' import { Query } from '../../query' const workbook = inject<Workbook>(workbookKey)! const currentQuery = inject<Query>('query')! const selectedQuery = defineModel<QueryTableArgs>('selectedQuery') const querySearchTxt = ref(selectedQuery.value?.query_name || '') const linkedQueries = workbook.getLinkedQueries(currentQuery.doc.name) const validQueries = workbook.doc.queries.filter( (q) => q.name !== currentQuery.doc.name && !linkedQueries.includes(q.name) ) const queries = computed(() => { if (!querySearchTxt.value) { return validQueries } return validQueries.filter((query) => { return ( query.name.includes(querySearchTxt.value) || query.title?.includes(querySearchTxt.value) ) }) }) const listColumns = [ { label: 'Title', key: 'title', width: 2, prefix: () => h(Table2Icon, { class: 'h-4 w-4 text-gray-600' }), }, { label: 'Source', key: 'source', width: 1, getLabel: (props: any) => props.row.operations?.[0]?.table?.table_name, }, { label: '', key: 'selected', width: '40px', getLabel: () => '', prefix: (props: any) => { if (props.row.name === selectedQuery.value?.query_name) { return h(CheckIcon, { class: 'h-4 w-4' }) } }, }, ] </script> <template> <div class="flex h-full flex-col gap-2 overflow-auto p-0.5"> <div class="flex justify-between overflow-visible py-1"> <div class="flex gap-2"> <FormControl placeholder="Search by Title" v-model="querySearchTxt" autocomplete="off" > <template #prefix> <SearchIcon class="h-4 w-4 text-gray-500" /> </template> </FormControl> </div> </div> <ListView v-if="queries.length" class="h-full" :columns="listColumns" :rows="queries" :row-key="'name'" :options="{ selectable: false, showTooltip: false, onRowClick: (row: any) => { selectedQuery = { type: 'query', workbook: workbook.doc.name, query_name: row.name, } }, emptyState: { title: 'No Queries Found' }, }" > </ListView> </div> </template>
2302_79757062/insights
frontend/src2/query/components/source_selector/WorkbookQueryList.vue
Vue
agpl-3.0
2,356