A local-first personal finance app
✨ Excel formula feedbacks (#6432)
lelemmb54fdd688840
diff --git a/packages/desktop-client/src/components/codemirror/autocompleteTabAccept.ts b/packages/desktop-client/src/components/codemirror/autocompleteTabAccept.tsnew file mode 100644index 0000000000..2745a57bf0--- /dev/null+++ b/packages/desktop-client/src/components/codemirror/autocompleteTabAccept.ts@@ -0,0 +1,21 @@+import { acceptCompletion, completionStatus } from '@codemirror/autocomplete';+import { Prec } from '@codemirror/state';+import { keymap } from '@codemirror/view';++export const autocompleteTabAccept = keymap.of([+ {+ key: 'Tab',+ run: view => {+ if (completionStatus(view.state) === 'active') {+ return acceptCompletion(view);+ }+ return false;+ },+ },+]);++/**+ * Give this keymap highest priority so it wins over `basicSetup` bindings like+ * `indentWithTab`.+ */+export const autocompleteTabAcceptHighest = Prec.highest(autocompleteTabAccept);diff --git a/packages/desktop-client/src/components/formula/FormulaEditor.tsx b/packages/desktop-client/src/components/formula/FormulaEditor.tsxindex 7f6ff58793..d14a123f5a 100644--- a/packages/desktop-client/src/components/formula/FormulaEditor.tsx+++ b/packages/desktop-client/src/components/formula/FormulaEditor.tsx@@ -8,6 +8,7 @@ import CodeMirror, {import { excelFormulaExtension } from './codeMirror-excelLanguage';+import { autocompleteTabAcceptHighest } from '@desktop-client/components/codemirror/autocompleteTabAccept';import { useTheme } from '@desktop-client/style/theme';type FormulaMode = 'transaction' | 'query';@@ -71,6 +72,8 @@ export function FormulaEditor({...excelFormulaExtension(mode, queries, isDarkTheme, variables),EditorView.lineWrapping,EditorView.editable.of(!disabled),+ // Must come late + highest precedence so Tab accepts completion when the popup is open+ autocompleteTabAcceptHighest,],[mode, queries, isDarkTheme, disabled, singleLine, variables],);diff --git a/packages/desktop-client/src/components/formula/QueryManager.tsx b/packages/desktop-client/src/components/formula/QueryManager.tsxindex f833783a24..c7f3bb9dc9 100644--- a/packages/desktop-client/src/components/formula/QueryManager.tsx+++ b/packages/desktop-client/src/components/formula/QueryManager.tsx@@ -21,6 +21,11 @@ import {type TimeFrame,} from 'loot-core/types/models';+import {+ normalizeQueryTimeFrameEnd,+ normalizeQueryTimeFrameStart,+} from './queryTimeFrame';+import { AppliedFilters } from '@desktop-client/components/filters/AppliedFilters';import { FilterButton } from '@desktop-client/components/filters/FiltersMenu';import { getLiveRange } from '@desktop-client/components/reports/getLiveRange';@@ -168,7 +173,7 @@ export function QueryManager({ queries, onQueriesChange }: QueryManagerProps) {<Text style={{ fontSize: 12, marginTop: 8 }}><Trans>Queries allow you to reference filtered transaction data in your- formulas using QUERY(‘queryName’)+ formulas using QUERY(‘queryName’) or QUERY_COUNT(‘queryName’)</Trans></Text></View>@@ -367,23 +372,23 @@ function QueryItem({]);function handleStartDateChange(newStart: string) {- setStartDate(monthUtils.dayFromDate(newStart));+ setStartDate(normalizeQueryTimeFrameStart(newStart));sendUpdate(filters.conditions,filters.conditionsOp,- monthUtils.dayFromDate(newStart),+ normalizeQueryTimeFrameStart(newStart),endDate,timeRangeRef.current as TimeFrame['mode'],);}function handleEndDateChange(newEnd: string) {- setEndDate(monthUtils.dayFromDate(newEnd));+ setEndDate(normalizeQueryTimeFrameEnd(newEnd));sendUpdate(filters.conditions,filters.conditionsOp,startDate,- monthUtils.dayFromDate(newEnd),+ normalizeQueryTimeFrameEnd(newEnd),timeRangeRef.current as TimeFrame['mode'],);}@@ -433,17 +438,22 @@ function QueryItem({timeRangeRef.current = config.timeFrame.mode;setStartDate(- config.timeFrame.start ||- monthUtils.dayFromDate(monthUtils.currentMonth()),+ config.timeFrame.start+ ? normalizeQueryTimeFrameStart(config.timeFrame.start)+ : monthUtils.dayFromDate(monthUtils.currentMonth()),+ );+ setEndDate(+ config.timeFrame.end+ ? normalizeQueryTimeFrameEnd(config.timeFrame.end)+ : monthUtils.currentDay(),);- setEndDate(config.timeFrame.end || monthUtils.currentDay());// Update the querysendUpdate(config.conditions,config.conditionsOp,- config.timeFrame.start,- config.timeFrame.end,+ normalizeQueryTimeFrameStart(config.timeFrame.start),+ normalizeQueryTimeFrameEnd(config.timeFrame.end),config.timeFrame.mode,);setImportJsonText('');@@ -677,7 +687,7 @@ function QueryItem({);start = monthUtils.firstDayOfMonth(prevMonth);end = monthUtils.lastDayOfMonth(prevMonth);- mode = quickSelectMode;+ mode = 'lastMonth';break;}case '1-month': {diff --git a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsxindex b9f06d0385..f56a9a2187 100644--- a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx+++ b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx@@ -193,6 +193,7 @@ const DATE_FUNCTIONS = new Set([const QUERY_FUNCTIONS = new Set(['QUERY',+ 'QUERY_COUNT','LOOKUP','VLOOKUP','HLOOKUP',@@ -466,16 +467,31 @@ export function excelFormulaAutocomplete(const functionCompletions = getFunctionCompletions(mode);const queryCompletions: Completion[] = queries- ? Object.keys(queries).map(queryName => ({- label: `QUERY("${queryName}")`,- type: 'function',- section: '🔍 Query Functions',- info: t('Execute the {{queryName}} query and return the result.', {- queryName,- }),- apply: `QUERY("${queryName}")`,- boost: 15, // Boost query completions to appear at top of Query Functions section- }))+ ? Object.keys(queries).flatMap(queryName => [+ {+ label: `QUERY("${queryName}")`,+ type: 'function',+ section: '🔍 Query Functions',+ info: t('Execute the {{queryName}} query and return the result.', {+ queryName,+ }),+ apply: `QUERY("${queryName}")`,+ boost: 15, // Boost query completions to appear at top of Query Functions section+ },+ {+ label: `QUERY_COUNT("${queryName}")`,+ type: 'function',+ section: '🔍 Query Functions',+ info: t(+ 'Execute the {{queryName}} query and return the number of matching rows.',+ {+ queryName,+ },+ ),+ apply: `QUERY_COUNT("${queryName}")`,+ boost: 14,+ },+ ]): [];const variableCompletions: Completion[] = variablesdiff --git a/packages/desktop-client/src/components/formula/queryModeFunctions.ts b/packages/desktop-client/src/components/formula/queryModeFunctions.tsindex c2ea6c38a4..2fba45bbdf 100644--- a/packages/desktop-client/src/components/formula/queryModeFunctions.ts+++ b/packages/desktop-client/src/components/formula/queryModeFunctions.ts@@ -785,4 +785,11 @@ export const queryModeFunctions: Record<string, FunctionDef> = {{ name: 'queryName', description: 'Name of the query to execute' },],},+ QUERY_COUNT: {+ name: 'QUERY_COUNT',+ description: t('Execute a query and return the number of matching rows.'),+ parameters: [+ { name: 'queryName', description: 'Name of the query to execute' },+ ],+ },};diff --git a/packages/desktop-client/src/components/formula/queryTimeFrame.ts b/packages/desktop-client/src/components/formula/queryTimeFrame.tsnew file mode 100644index 0000000000..9089167d00--- /dev/null+++ b/packages/desktop-client/src/components/formula/queryTimeFrame.ts@@ -0,0 +1,22 @@+import * as monthUtils from 'loot-core/shared/months';++function isMonthString(dateOrMonth: string) {+ // Month format: YYYY-MM+ return dateOrMonth.split('-').length === 2;+}++/**+ * Query formulas use day-level filtering in AQL (`$gte/$lte` on YYYY-MM-DD).+ * The query editor UI selects months, so we normalize month strings to days.+ */+export function normalizeQueryTimeFrameStart(dateOrMonth: string) {+ return isMonthString(dateOrMonth)+ ? monthUtils.firstDayOfMonth(dateOrMonth)+ : monthUtils.dayFromDate(dateOrMonth);+}++export function normalizeQueryTimeFrameEnd(dateOrMonth: string) {+ return isMonthString(dateOrMonth)+ ? monthUtils.lastDayOfMonth(dateOrMonth)+ : monthUtils.dayFromDate(dateOrMonth);+}diff --git a/packages/desktop-client/src/hooks/querySlidingWindow.ts b/packages/desktop-client/src/hooks/querySlidingWindow.tsnew file mode 100644index 0000000000..93b5b790fb--- /dev/null+++ b/packages/desktop-client/src/hooks/querySlidingWindow.ts@@ -0,0 +1,35 @@+import * as monthUtils from 'loot-core/shared/months';++function isMonthOnlyDate(s: string) {+ return s.includes('-') && s.split('-').length === 2;+}++function toMonth(dateOrMonth: string) {+ return isMonthOnlyDate(dateOrMonth)+ ? dateOrMonth+ : monthUtils.monthFromDate(dateOrMonth);+}++/**+ * Given a stored sliding-window start/end (which represent a window length),+ * return the live range anchored to the current day.+ *+ * Example: start=2024-01, end=2024-03 => 3-month window => liveStart is currentMonth-2.+ */+export function getLiveSlidingWindowRange(+ start: string,+ end: string,+ today: string = monthUtils.currentDay(),+) {+ const startMonth = toMonth(start);+ const endMonth = toMonth(end);+ const offset = monthUtils.differenceInCalendarMonths(endMonth, startMonth);++ const liveEndMonth = monthUtils.monthFromDate(today);+ const liveStartMonth = monthUtils.subMonths(liveEndMonth, offset);++ return {+ startDate: monthUtils.firstDayOfMonth(liveStartMonth),+ endDate: today,+ };+}diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.ts b/packages/desktop-client/src/hooks/useFormulaExecution.tsindex ad7292b467..71ec4c7b02 100644--- a/packages/desktop-client/src/hooks/useFormulaExecution.ts+++ b/packages/desktop-client/src/hooks/useFormulaExecution.ts@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react';import { send } from 'loot-core/platform/client/fetch';import * as monthUtils from 'loot-core/shared/months';-import { q } from 'loot-core/shared/query';+import { q, type Query } from 'loot-core/shared/query';import { integerToAmount } from 'loot-core/shared/util';import {type RuleConditionEntity,@@ -53,16 +53,25 @@ export function useFormulaExecution(setError(null);try {- // Extract QUERY() function calls+ // Extract QUERY() and QUERY_COUNT() function callsconst queryMatches = Array.from(formula.matchAll(/QUERY\s*\(\s*["']([^"']+)["']\s*\)/gi),);+ const queryCountMatches = Array.from(+ formula.matchAll(/QUERY_COUNT\s*\(\s*["']([^"']+)["']\s*\)/gi),+ );// Fetch data for each queryconst queryData: Record<string, number> = {};+ const queryCountData: Record<string, number> = {};++ // Deduplicate names (a query can appear multiple times in the same formula)+ const queryNames = Array.from(new Set(queryMatches.map(m => m[1])));+ const queryCountNames = Array.from(+ new Set(queryCountMatches.map(m => m[1])),+ );- for (const match of queryMatches) {- const queryName = match[1];+ for (const queryName of queryNames) {const queryConfig = queries[queryName];if (!queryConfig) {@@ -71,14 +80,24 @@ export function useFormulaExecution(continue;}- // Fetch the actual transaction data based on the query config- // For now, we'll use a simplified approach- // In a real implementation, this would call a backend API- const data = await fetchQueryData(queryConfig);+ const data = await fetchQuerySum(queryConfig);queryData[queryName] = integerToAmount(data, 2);}- // Replace QUERY() calls with actual values in the formula+ for (const queryName of queryCountNames) {+ const queryConfig = queries[queryName];++ if (!queryConfig) {+ console.warn(`Query “${queryName}” not found in queries config`);+ queryCountData[queryName] = 0;+ continue;+ }++ const count = await fetchQueryCount(queryConfig);+ queryCountData[queryName] = count;+ }++ // Replace QUERY() and QUERY_COUNT() calls with actual values in the formulalet processedFormula = formula;for (const [queryName, value] of Object.entries(queryData)) {const regex = new RegExp(@@ -87,6 +106,13 @@ export function useFormulaExecution();processedFormula = processedFormula.replace(regex, String(value));}+ for (const [queryName, value] of Object.entries(queryCountData)) {+ const regex = new RegExp(+ `QUERY_COUNT\\s*\\(\\s*["']${escapeRegExp(queryName)}["']\\s*\\)`,+ 'gi',+ );+ processedFormula = processedFormula.replace(regex, String(value));+ }// Create HyperFormula instancehfInstance = HyperFormula.buildEmpty({@@ -189,97 +215,135 @@ function timeFrameModeToCondition(mode: TimeFrame['mode']): string | null {}}-// Helper function to fetch query data-async function fetchQueryData(config: QueryConfig): Promise<number> {- try {- const conditions = config.conditions || [];- const conditionsOp = config.conditionsOp || 'and';- const timeFrame = config.timeFrame;-- // Convert conditions to query filters- const { filters: queryFilters } = await send(- 'make-filters-from-conditions',- {- conditions,- },- );-- const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';-- // Start building the query- let transQuery = q('transactions');-- // Add date range filter if provided- if (timeFrame && timeFrame.mode) {- let startDate: string | undefined;- let endDate: string | undefined;-- if (- (timeFrame.mode === 'sliding-window' || timeFrame.mode === 'static') &&- timeFrame.start &&- timeFrame.end- ) {- // For sliding-window and static modes, use the actual start/end dates from timeFrame- // Convert month format (YYYY-MM) to full date format (YYYY-MM-DD) if needed- startDate =- timeFrame.start.includes('-') &&- timeFrame.start.split('-').length === 2- ? timeFrame.start + '-01'- : timeFrame.start;- endDate =- timeFrame.end.includes('-') && timeFrame.end.split('-').length === 2- ? monthUtils.getMonthEnd(timeFrame.end + '-01')- : timeFrame.end;- } else {- // For other modes, use getLiveRange with the appropriate condition- const condition = timeFrameModeToCondition(timeFrame.mode);- if (condition) {- // Get earliest and latest transactions for getLiveRange- const earliestTransaction = await send('get-earliest-transaction');- const latestTransaction = await send('get-latest-transaction');-- const earliestDate = earliestTransaction- ? earliestTransaction.date- : monthUtils.currentDay();- const latestDate = latestTransaction- ? latestTransaction.date- : monthUtils.currentDay();-- const [calculatedStart, calculatedEnd] = getLiveRange(- condition,- earliestDate,- latestDate,- true, // includeCurrentInterval- );+function isMonthOnlyDate(s: string) {+ // YYYY-MM+ return s.includes('-') && s.split('-').length === 2;+}- startDate = calculatedStart;- endDate = calculatedEnd;- } else {- // No valid condition found, skip date filtering entirely- // Continue without adding date filter- }+function toMonth(dateOrMonth: string) {+ return isMonthOnlyDate(dateOrMonth)+ ? dateOrMonth+ : monthUtils.monthFromDate(dateOrMonth);+}++async function buildFilteredTransactionsQuery(+ config: QueryConfig,+): Promise<Query> {+ const conditions = config.conditions || [];+ const conditionsOp = config.conditionsOp || 'and';+ const timeFrame = config.timeFrame;++ // Convert conditions to query filters+ const { filters: queryFilters } = await send('make-filters-from-conditions', {+ conditions,+ });++ const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';++ // Start building the query+ let transQuery = q('transactions');++ // Add date range filter if provided+ if (timeFrame && timeFrame.mode) {+ let startDate: string | undefined;+ let endDate: string | undefined;++ if (+ (timeFrame.mode === 'sliding-window' || timeFrame.mode === 'static') &&+ timeFrame.start &&+ timeFrame.end+ ) {+ if (timeFrame.mode === 'sliding-window') {+ // Sliding-window should move with time. Interpret start/end as a window length+ // (in months) and always anchor the end to the current month/day.+ const startMonth = toMonth(timeFrame.start);+ const endMonth = toMonth(timeFrame.end);+ const offset = monthUtils.differenceInCalendarMonths(+ endMonth,+ startMonth,+ );++ const liveEndMonth = monthUtils.currentMonth();+ const liveStartMonth = monthUtils.subMonths(liveEndMonth, offset);++ startDate = monthUtils.firstDayOfMonth(liveStartMonth);+ endDate = monthUtils.currentDay();+ } else {+ // Static mode: use the actual stored start/end dates.+ // Convert month format (YYYY-MM) to full date format (YYYY-MM-DD) if needed+ startDate = isMonthOnlyDate(timeFrame.start)+ ? timeFrame.start + '-01'+ : timeFrame.start;+ endDate = isMonthOnlyDate(timeFrame.end)+ ? monthUtils.getMonthEnd(timeFrame.end + '-01')+ : timeFrame.end;}+ } else {+ // For other modes, use getLiveRange with the appropriate condition+ const condition = timeFrameModeToCondition(timeFrame.mode);+ if (condition) {+ // Get earliest and latest transactions for getLiveRange+ const earliestTransaction = await send('get-earliest-transaction');+ const latestTransaction = await send('get-latest-transaction');++ const earliestDate = earliestTransaction+ ? earliestTransaction.date+ : monthUtils.currentDay();+ const latestDate = latestTransaction+ ? latestTransaction.date+ : monthUtils.currentDay();++ const [calculatedStart, calculatedEnd] = getLiveRange(+ condition,+ earliestDate,+ latestDate,+ true, // includeCurrentInterval+ );- // Apply the date filter only if we have valid dates- if (startDate && endDate) {- transQuery = transQuery.filter({- $and: [{ date: { $gte: startDate } }, { date: { $lte: endDate } }],- });+ startDate = calculatedStart;+ endDate = calculatedEnd;+ } else {+ // No valid condition found, skip date filtering entirely+ // Continue without adding date filter}}- // Add user-defined filters- if (queryFilters.length > 0) {- transQuery = transQuery.filter({ [conditionsOpKey]: queryFilters });+ // Apply the date filter only if we have valid dates+ if (startDate && endDate) {+ transQuery = transQuery.filter({+ $and: [{ date: { $gte: startDate } }, { date: { $lte: endDate } }],+ });}+ }- // Calculate sum- transQuery = transQuery.calculate({ $sum: '$amount' });+ // Add user-defined filters+ if (queryFilters.length > 0) {+ transQuery = transQuery.filter({ [conditionsOpKey]: queryFilters });+ }++ return transQuery;+}- const { data } = await send('query', transQuery.serialize());+async function fetchQuerySum(config: QueryConfig): Promise<number> {+ try {+ const transQuery = await buildFilteredTransactionsQuery(config);+ const summedQuery = transQuery.calculate({ $sum: '$amount' });+ const { data } = await send('query', summedQuery.serialize());+ return data || 0;+ } catch (err) {+ console.error('Error fetching query sum:', err);+ return 0;+ }+}++async function fetchQueryCount(config: QueryConfig): Promise<number> {+ try {+ const transQuery = await buildFilteredTransactionsQuery(config);+ const countQuery = transQuery.calculate({ $count: '*' });+ const { data } = await send('query', countQuery.serialize());return data || 0;} catch (err) {- console.error('Error fetching query data:', err);+ console.error('Error fetching query count:', err);return 0;}}diff --git a/upcoming-release-notes/6432.md b/upcoming-release-notes/6432.mdnew file mode 100644index 0000000000..3ca53644aa--- /dev/null+++ b/upcoming-release-notes/6432.md@@ -0,0 +1,6 @@+---+category: Features+authors: [lelemm]+---++Add feedback mechanism for Excel formulas to enhance user experience and error handling.