A local-first personal finance app
🐛 Fix Formula query sliding-window timeframes (#8244)
lelemm72b28a6d2ad7
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex ee0ede2e7a..3851f0f348 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -51,6 +51,7 @@"#components/budget/goals/validateAutomation": "./src/components/budget/goals/validateAutomation.ts","#components/budget/util": "./src/components/budget/util.ts","#components/codemirror/autocompleteTabAccept": "./src/components/codemirror/autocompleteTabAccept.ts",+ "#components/formula/queryTimeFrame": "./src/components/formula/queryTimeFrame.ts","#components/mobile/utils": "./src/components/mobile/utils.ts","#components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations": "./src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts","#components/reports/chart-theme": "./src/components/reports/chart-theme.ts",diff --git a/packages/desktop-client/src/components/formula/QueryManager.tsx b/packages/desktop-client/src/components/formula/QueryManager.tsxindex 349d1ebd72..065817f14a 100644--- a/packages/desktop-client/src/components/formula/QueryManager.tsx+++ b/packages/desktop-client/src/components/formula/QueryManager.tsx@@ -47,6 +47,17 @@ type QueryConfig = {timeFrame?: TimeFrame;};+type PresetTimeRangeMode = Exclude<+ TimeFrame['mode'],+ 'sliding-window' | 'static'+>;++function isPresetTimeRangeMode(+ mode: TimeFrame['mode'],+): mode is PresetTimeRangeMode {+ return !['sliding-window', 'static'].includes(mode);+}+type QueryManagerProps = {queries: Record<string, QueryConfig>;onQueriesChange: (queries: Record<string, QueryConfig>) => void;@@ -480,6 +491,29 @@ function QueryItem({}}+ const timeRangeMode = timeRangeRef.current as TimeFrame['mode'];+ const isPresetTimeRange = isPresetTimeRangeMode(timeRangeMode);+ const timeRangeLabels = {+ 'sliding-window': t('Live'),+ static: t('Static'),+ full: t('All time'),+ lastMonth: t('Last month'),+ lastYear: t('Last year'),+ yearToDate: t('Year to date'),+ priorYearToDate: t('Prior year to date'),+ } satisfies Record<TimeFrame['mode'], string>;+ const timeRangeLabel = timeRangeLabels[timeRangeMode];+ const presetTimeRangeLabels = {+ full: t('All time transactions'),+ lastMonth: t('Last month transactions'),+ lastYear: t('Last year transactions'),+ yearToDate: t('Year to date transactions'),+ priorYearToDate: t('Prior year to date transactions'),+ } satisfies Record<PresetTimeRangeMode, string>;+ const presetTimeRangeLabel = isPresetTimeRange+ ? presetTimeRangeLabels[timeRangeMode]+ : null;+return (<Viewstyle={{@@ -630,12 +664,11 @@ function QueryItem({}}><Button- style={{ width: 50 }}- variant={timeRangeRef.current === 'static' ? 'normal' : 'primary'}+ style={{ minWidth: 50 }}+ variant={timeRangeMode === 'static' ? 'normal' : 'primary'}onPress={() => {- const currentMode = timeRangeRef.current as TimeFrame['mode'];const newMode =- currentMode === 'static' ? 'sliding-window' : 'static';+ timeRangeMode === 'static' ? 'sliding-window' : 'static';const [newStart, newEnd] = calculateTimeRange({start: startDate,end: endDate,@@ -654,7 +687,7 @@ function QueryItem({);}}>- {timeRangeRef.current === 'static' ? t('Static') : t('Live')}+ {timeRangeLabel}</Button><Buttonref={timeRangeMenuTriggerRef}@@ -793,7 +826,19 @@ function QueryItem({</Popover></View>- {/* Date range selectors */}+ {presetTimeRangeLabel ? (+ <Input+ value={presetTimeRangeLabel}+ readOnly+ disabled+ style={{+ width: '100%',+ marginTop: 8,+ textAlign: 'center',+ }}+ />+ ) : null}+{allMonths.length > 0 && (<Viewstyle={{@@ -805,7 +850,13 @@ function QueryItem({}}><Select+ disabled={isPresetTimeRange}value={fromDateRepr(startDate)}+ defaultLabel={monthUtils.format(+ fromDateRepr(startDate),+ 'MMMM yyyy',+ locale,+ )}onChange={newValue => {const [validatedStart] = validateStart(allMonths[allMonths.length - 1].name,@@ -822,7 +873,13 @@ function QueryItem({<Trans>to</Trans></Text><Select+ disabled={isPresetTimeRange}value={fromDateRepr(endDate)}+ defaultLabel={monthUtils.format(+ fromDateRepr(endDate),+ 'MMMM yyyy',+ locale,+ )}onChange={newValue => {const [, validatedEnd] = validateEnd(allMonths[allMonths.length - 1].name,diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.test.ts b/packages/desktop-client/src/hooks/useFormulaExecution.test.tsnew file mode 100644index 0000000000..221507415e--- /dev/null+++ b/packages/desktop-client/src/hooks/useFormulaExecution.test.ts@@ -0,0 +1,225 @@+import {+ clearServer,+ initServer,+} from '@actual-app/core/platform/client/connection';+import { getCurrency } from '@actual-app/core/shared/currencies';+import type {+ RuleConditionEntity,+ TimeFrame,+} from '@actual-app/core/types/models';+import { renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TestProviders } from '#mocks';++import {+ buildFilteredTransactionsQuery,+ useFormulaExecution,+} from './useFormulaExecution';++vi.mock(+ '@actual-app/core/platform/client/connection',+ () => import('#mocks/connection'),+);++type SerializedQuery = {+ filterExpressions: ReadonlyArray<Record<string, unknown>>;+ tableOptions?: Record<string, unknown>;+};++type QueryConfig = {+ conditions?: RuleConditionEntity[];+ conditionsOp?: 'and' | 'or';+ timeFrame?: Partial<TimeFrame>;+};++function categoryCondition(value: string) {+ return {+ field: 'category',+ op: 'is',+ value,+ type: 'id',+ } satisfies RuleConditionEntity;+}++function queryHasCategory(query: SerializedQuery, categoryId: string) {+ return query.filterExpressions.some(filterExpression => {+ const filters = filterExpression.$and;+ return (+ Array.isArray(filters) &&+ filters.some(+ filter =>+ typeof filter === 'object' &&+ filter !== null &&+ 'category' in filter &&+ filter.category === categoryId,+ )+ );+ });+}++function findQueryByCategory(+ queryPayloads: SerializedQuery[],+ categoryId: string,+) {+ const query = queryPayloads.find(payload =>+ queryHasCategory(payload, categoryId),+ );+ if (!query) {+ throw new Error(`No query found for category ${categoryId}`);+ }+ return query;+}++function expectQueryDateRange(+ queryPayloads: SerializedQuery[],+ categoryId: string,+ startDate: string,+ endDate: string,+) {+ expect(+ findQueryByCategory(queryPayloads, categoryId).filterExpressions[0],+ ).toEqual({+ $and: [{ date: { $gte: startDate } }, { date: { $lte: endDate } }],+ });+}++const formulaQueries: Record<string, QueryConfig> = {+ Income: {+ conditions: [categoryCondition('income-cat')],+ conditionsOp: 'and',+ timeFrame: {+ start: '2024-01-01',+ end: '2024-03-31',+ mode: 'sliding-window',+ },+ },+ Expenses: {+ conditions: [categoryCondition('expense-cat')],+ conditionsOp: 'and',+ timeFrame: {+ start: '2024-03-01',+ end: '2024-03-31',+ mode: 'sliding-window',+ },+ },+};++describe('formula query timeframes', () => {+ let previousCurrentMonth: typeof global.currentMonth;+ let queryPayloads: SerializedQuery[];++ beforeEach(() => {+ previousCurrentMonth = global.currentMonth;+ queryPayloads = [];+ initServer({+ 'formula-load-user-preferences': async () => ({+ currency: getCurrency('USD'),+ numberFormat: 'comma-dot',+ decimalPlaces: 2,+ thousandsSeparator: ',',+ decimalSeparator: '.',+ locale: 'en-US',+ currencySymbolPosition: 'before',+ currencySpaceBetweenAmountAndSymbol: false,+ }),+ 'make-filters-from-conditions': async ({ conditions }) => {+ const ruleConditions = Array.isArray(conditions) ? conditions : [];++ return {+ filters: ruleConditions.map(condition => {+ const { field, value } = condition as RuleConditionEntity;+ return { [field]: value };+ }),+ };+ },+ query: async payload => {+ queryPayloads.push(payload as unknown as SerializedQuery);+ return { data: queryPayloads.length * 100, dependencies: [] };+ },+ });+ });++ afterEach(async () => {+ global.currentMonth = previousCurrentMonth;+ await clearServer();+ });++ it('applies default bounds for partial static query timeframes', async () => {+ const query = await buildFilteredTransactionsQuery({+ timeFrame: {+ mode: 'static',+ start: '2016-10',+ },+ });++ expect(query.serialize().filterExpressions).toEqual([+ {+ $and: [+ { date: { $gte: '2016-10-01' } },+ { date: { $lte: '2017-01-31' } },+ ],+ },+ ]);+ });++ it('applies preset query timeframe modes through calculateTimeRange', async () => {+ const query = await buildFilteredTransactionsQuery({+ timeFrame: {+ mode: 'lastMonth',+ },+ });++ expect(query.serialize().filterExpressions).toEqual([+ {+ $and: [+ { date: { $gte: '2016-12-01' } },+ { date: { $lte: '2016-12-31' } },+ ],+ },+ ]);+ });++ it('shifts each formula report query window when the current month changes', async () => {+ async function executeFormula() {+ queryPayloads = [];++ const { result, unmount } = renderHook(+ () =>+ useFormulaExecution(+ '=QUERY("Income") + QUERY("Expenses")',+ formulaQueries,+ 0,+ ),+ { wrapper: TestProviders },+ );++ await waitFor(() => expect(result.current.result).toBe(3));+ unmount();++ return [...queryPayloads];+ }++ global.currentMonth = '2026-06';+ const juneQueries = await executeFormula();++ expectQueryDateRange(juneQueries, 'income-cat', '2026-04-01', '2026-06-30');+ expectQueryDateRange(+ juneQueries,+ 'expense-cat',+ '2026-06-01',+ '2026-06-30',+ );++ global.currentMonth = '2026-07';+ const julyQueries = await executeFormula();++ expectQueryDateRange(julyQueries, 'income-cat', '2026-05-01', '2026-07-31');+ expectQueryDateRange(+ julyQueries,+ 'expense-cat',+ '2026-07-01',+ '2026-07-31',+ );+ });+});diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.ts b/packages/desktop-client/src/hooks/useFormulaExecution.tsindex 1770506e81..b85ab98164 100644--- a/packages/desktop-client/src/hooks/useFormulaExecution.ts+++ b/packages/desktop-client/src/hooks/useFormulaExecution.ts@@ -17,7 +17,10 @@ import type {} from '@actual-app/core/types/models';import { HyperFormula } from 'hyperformula';-import { getLiveRange } from '#components/reports/getLiveRange';+import {+ normalizeQueryTimeFrameEnd,+ normalizeQueryTimeFrameStart,+} from '#components/formula/queryTimeFrame';import { calculateTimeRange } from '#components/reports/reportRanges';import { bootstrapHyperFormula } from '#util/bootstrapHyperFormula';@@ -29,7 +32,7 @@ bootstrapHyperFormula();type QueryConfig = {conditions?: RuleConditionEntity[];conditionsOp?: 'and' | 'or';- timeFrame?: TimeFrame;+ timeFrame?: Partial<TimeFrame>;};type QueriesMap = Record<string, QueryConfig>;@@ -307,43 +310,7 @@ async function prefetchBudgetQueries(}}-// Helper function to convert timeFrame mode to condition string for getLiveRange-function timeFrameModeToCondition(mode: TimeFrame['mode']): string | null {- // Map timeFrame modes to ReportOptions condition strings- switch (mode) {- case 'full':- return 'All time';- case 'lastMonth':- return 'Last month';- case 'lastYear':- return 'Last year';- case 'yearToDate':- return 'Year to date';- case 'priorYearToDate':- return 'Prior year to date';- case 'sliding-window':- // sliding-window requires actual start/end dates, not a condition- return null;- case 'static':- // static mode uses manually set start/end dates, not a condition- return null;- default:- return null;- }-}--function isMonthOnlyDate(s: string) {- // YYYY-MM- return s.includes('-') && s.split('-').length === 2;-}--function toMonth(dateOrMonth: string) {- return isMonthOnlyDate(dateOrMonth)- ? dateOrMonth- : monthUtils.monthFromDate(dateOrMonth);-}--async function buildFilteredTransactionsQuery(+export async function buildFilteredTransactionsQuery(config: QueryConfig,): Promise<Query> {const conditions = config.conditions || [];@@ -362,75 +329,13 @@ async function buildFilteredTransactionsQuery(// Add date range filter if providedif (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- );-- startDate = calculatedStart;- endDate = calculatedEnd;- } else {- // No valid condition found, skip date filtering entirely- // Continue without adding date filter- }- }+ const [calculatedStart, calculatedEnd] = calculateTimeRange(timeFrame);+ const startDate = normalizeQueryTimeFrameStart(calculatedStart);+ const endDate = normalizeQueryTimeFrameEnd(calculatedEnd);- // Apply the date filter only if we have valid dates- if (startDate && endDate) {- transQuery = transQuery.filter({- $and: [{ date: { $gte: startDate } }, { date: { $lte: endDate } }],- });- }+ transQuery = transQuery.filter({+ $and: [{ date: { $gte: startDate } }, { date: { $lte: endDate } }],+ });}// Add user-defined filtersdiff --git a/upcoming-release-notes/8244.md b/upcoming-release-notes/8244.mdnew file mode 100644index 0000000000..fc27ea8f09--- /dev/null+++ b/upcoming-release-notes/8244.md@@ -0,0 +1,6 @@+---+category: Bugfixes+authors: [lelemm]+---++Fix Formula card query sliding-window timeframes to use the same live range calculation as reports.