A local-first personal finance app
[AI] Add configurable average ranges to Monthly Spending report (#7920)
Matt Farrell317d1739222e
diff --git a/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-1-chromium-linux.png b/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-1-chromium-linux.pngindex adb77193e7..6054c475f9 100644Binary files a/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-1-chromium-linux.png and b/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-2-chromium-linux.png b/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-2-chromium-linux.pngindex b9a7b17203..8cb53dcad4 100644Binary files a/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-2-chromium-linux.png and b/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-3-chromium-linux.png b/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-3-chromium-linux.pngindex 9309286711..c6dd0477c1 100644Binary files a/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-3-chromium-linux.png and b/packages/desktop-client/e2e/command-bar.test.ts-snapshots/Command-bar-Check-the-command-bar-search-works-correctly-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-1-chromium-linux.pngindex 8184a47309..7c9232a71b 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-2-chromium-linux.pngindex 48429fc10b..54de10b38e 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-3-chromium-linux.pngindex 4fd3a09aa7..350df9fc81 100644Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-and-cash-flow-reports-3-chromium-linux.png differdiff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex a2522a3c5d..0fc3ba468e 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -64,6 +64,7 @@"#components/reports/ReportOptions": "./src/components/reports/ReportOptions.ts","#components/reports/reportRanges": "./src/components/reports/reportRanges.ts","#components/reports/setSessionReport": "./src/components/reports/setSessionReport.ts",+ "#components/reports/spendingAverageRange": "./src/components/reports/spendingAverageRange.ts","#components/reports/spreadsheets/cash-flow-spreadsheet": "./src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx","#components/reports/spreadsheets/*": "./src/components/reports/spreadsheets/*.ts","#components/reports/useDashboardWidgetCopyMenu": "./src/components/reports/useDashboardWidgetCopyMenu.ts",diff --git a/packages/desktop-client/src/components/reports/DateRange.tsx b/packages/desktop-client/src/components/reports/DateRange.tsxindex a1eddcc1ce..80e7a4d22f 100644--- a/packages/desktop-client/src/components/reports/DateRange.tsx+++ b/packages/desktop-client/src/components/reports/DateRange.tsx@@ -15,6 +15,7 @@ type DateRangeProps = {start: string;end: string;type?: string;+ comparisonLabel?: string;};function checkDate(date: string) {@@ -26,7 +27,12 @@ function checkDate(date: string) {}}-export function DateRange({ start, end, type }: DateRangeProps): ReactElement {+export function DateRange({+ start,+ end,+ type,+ comparisonLabel,+}: DateRangeProps): ReactElement {const { t } = useTranslation();const locale = useLocale();const checkStart = checkDate(start);@@ -50,7 +56,8 @@ export function DateRange({ start, end, type }: DateRangeProps): ReactElement {let typeOrFormattedEndDate: string;if (type && ['budget', 'average'].includes(type)) {- typeOrFormattedEndDate = type === 'budget' ? t('budgeted') : t('average');+ typeOrFormattedEndDate =+ comparisonLabel ?? (type === 'budget' ? t('budgeted') : t('average'));} else {typeOrFormattedEndDate = formattedEndDate;}diff --git a/packages/desktop-client/src/components/reports/reports/Spending.tsx b/packages/desktop-client/src/components/reports/reports/Spending.tsxindex f573f7b74e..31a9609bbb 100644--- a/packages/desktop-client/src/components/reports/reports/Spending.tsx+++ b/packages/desktop-client/src/components/reports/reports/Spending.tsx@@ -33,6 +33,14 @@ import { LegendItem } from '#components/reports/LegendItem';import { LoadingIndicator } from '#components/reports/LoadingIndicator';import { ModeButton } from '#components/reports/ModeButton';import { calculateSpendingReportTimeRange } from '#components/reports/reportRanges';+import {+ getSpendingAverageRangeLabel,+ getSpendingAverageRangeOptions,+ getSpendingAverageSummaryLabel,+ normalizeSpendingAverageRange,+ spendingAverageRangeFromKey,+ spendingAverageRangeToKey,+} from '#components/reports/spendingAverageRange';import { createSpendingSpreadsheet } from '#components/reports/spreadsheets/spending-spreadsheet';import { useReport } from '#components/reports/useReport';import { fromDateRepr } from '#components/reports/util';@@ -94,6 +102,9 @@ function SpendingInternal({ widget }: SpendingInternalProps) {);const [compare, setCompare] = useState(initialCompare);const [compareTo, setCompareTo] = useState(initialCompareTo);+ const [averageRange, setAverageRange] = useState(+ normalizeSpendingAverageRange(widget?.meta?.averageRange),+ );const [isLive, setIsLive] = useState(widget?.meta?.isLive ?? true);const [reportMode, setReportMode] = useState(initialReportMode);@@ -144,9 +155,10 @@ function SpendingInternal({ widget }: SpendingInternalProps) {conditionsOp,compare,compareTo,+ averageRange,budgetType,}),- [conditions, conditionsOp, compare, compareTo, budgetType],+ [conditions, conditionsOp, compare, compareTo, averageRange, budgetType],);const data = useReport('default', getGraphData);@@ -170,6 +182,7 @@ function SpendingInternal({ widget }: SpendingInternalProps) {conditionsOp,compare,compareTo,+ averageRange,isLive,mode: reportMode,},@@ -195,10 +208,8 @@ function SpendingInternal({ widget }: SpendingInternalProps) {}const showAverage =- data.intervalData[27].months[monthUtils.subMonths(compare, 3)] &&- Math.abs(- data.intervalData[27].months[monthUtils.subMonths(compare, 3)].cumulative,- ) > 0;+ (data.averageRange?.months.length ?? 0) > 0 &&+ data.intervalData.some(interval => Math.abs(interval.average) > 0);const todayDay =compare !== monthUtils.currentMonth()@@ -213,6 +224,27 @@ function SpendingInternal({ widget }: SpendingInternalProps) {const showCompare =compare === monthUtils.currentMonth() ||Math.abs(data.intervalData[27].compare) > 0;+ const averageRangeLabel = getSpendingAverageRangeLabel(averageRange, t);+ const averageRangeOptions = getSpendingAverageRangeOptions(t);+ const comparisonValue =+ reportMode === 'single-month'+ ? compareTo+ : reportMode === 'average'+ ? spendingAverageRangeToKey(averageRange)+ : 'label';+ const comparisonOptions =+ reportMode === 'single-month'+ ? allIntervals.map(({ name, pretty }) => [name, pretty] as const)+ : reportMode === 'average'+ ? averageRangeOptions+ : [['label', t('Budgeted')] as const];+ const onComparisonChange = (value: string) => {+ if (reportMode === 'single-month') {+ setCompareTo(value);+ } else if (reportMode === 'average') {+ setAverageRange(spendingAverageRangeFromKey(value));+ }+ };const title = widget?.meta?.name || t('Monthly Spending');const onSaveWidgetName = async (newName: string) => {@@ -304,21 +336,10 @@ function SpendingInternal({ widget }: SpendingInternalProps) {<Trans>to</Trans></Text><Select- value={reportMode === 'single-month' ? compareTo : 'label'}- onChange={setCompareTo}- options={- reportMode === 'single-month'- ? allIntervals.map(({ name, pretty }) => [name, pretty])- : [- [- 'label',- reportMode === 'budget'- ? t('Budgeted')- : t('Average spent'),- ],- ]- }- disabled={reportMode !== 'single-month'}+ value={comparisonValue}+ onChange={onComparisonChange}+ options={comparisonOptions}+ disabled={reportMode === 'budget'}style={{ width: 150 }}popoverStyle={{ width: 150 }}/>@@ -493,7 +514,7 @@ function SpendingInternal({ widget }: SpendingInternalProps) {? monthUtils.format(compareTo, 'MMM yyyy', locale): reportMode === 'budget'? t('Budgeted')- : t('Average')+ : averageRangeLabel}style={{ padding: 0, paddingBottom: 10 }}/>@@ -607,21 +628,12 @@ function SpendingInternal({ widget }: SpendingInternalProps) {style={{ marginBottom: 5, minWidth: 210 }}left={<Block>- {compare === monthUtils.currentMonth()- ? t('Spent Average {{monthYearFormatted}} MTD:', {- monthYearFormatted: monthUtils.format(- compare,- 'MMM yyyy',- locale,- ),- })- : t('Spent Average {{monthYearFormatted}}:', {- monthYearFormatted: monthUtils.format(- compare,- 'MMM yyyy',- locale,- ),- })}+ {getSpendingAverageSummaryLabel({+ averageRange,+ isCurrentMonth:+ compare === monthUtils.currentMonth(),+ t,+ })}</Block>}right={@@ -660,7 +672,8 @@ function SpendingInternal({ widget }: SpendingInternalProps) {</Paragraph><Paragraph>They are both the average cumulative spending by day for- the three months before the selected "compare" month.+ the selected average range before the selected "compare"+ month.</Paragraph></Trans></View>diff --git a/packages/desktop-client/src/components/reports/reports/SpendingCard.tsx b/packages/desktop-client/src/components/reports/reports/SpendingCard.tsxindex 18f3e0b5e1..75be6633f3 100644--- a/packages/desktop-client/src/components/reports/reports/SpendingCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/SpendingCard.tsx@@ -16,6 +16,10 @@ import { LoadingIndicator } from '#components/reports/LoadingIndicator';import { ReportCard } from '#components/reports/ReportCard';import { ReportCardName } from '#components/reports/ReportCardName';import { calculateSpendingReportTimeRange } from '#components/reports/reportRanges';+import {+ getSpendingAverageRangeLabel,+ normalizeSpendingAverageRange,+} from '#components/reports/spendingAverageRange';import { createSpendingSpreadsheet } from '#components/reports/spreadsheets/spending-spreadsheet';import { useDashboardWidgetCopyMenu } from '#components/reports/useDashboardWidgetCopyMenu';import { useReport } from '#components/reports/useReport';@@ -52,6 +56,8 @@ export function SpendingCard({useDashboardWidgetCopyMenu(onCopy);const spendingReportMode = meta?.mode ?? 'single-month';+ const averageRange = normalizeSpendingAverageRange(meta?.averageRange);+ const averageRangeLabel = getSpendingAverageRangeLabel(averageRange, t);const [compare, compareTo] = calculateSpendingReportTimeRange(meta ?? {});@@ -63,9 +69,17 @@ export function SpendingCard({conditionsOp: meta?.conditionsOp,compare,compareTo,+ averageRange,budgetType,});- }, [meta?.conditions, meta?.conditionsOp, compare, compareTo, budgetType]);+ }, [+ meta?.conditions,+ meta?.conditionsOp,+ compare,+ compareTo,+ averageRange,+ budgetType,+ ]);const data = useReport('default', getGraphData);const todayDay =@@ -134,6 +148,9 @@ export function SpendingCard({start={compare}end={compareTo}type={spendingReportMode}+ comparisonLabel={+ spendingReportMode === 'average' ? averageRangeLabel : undefined+ }/></View>{data && (diff --git a/packages/desktop-client/src/components/reports/spendingAverageRange.test.ts b/packages/desktop-client/src/components/reports/spendingAverageRange.test.tsnew file mode 100644index 0000000000..21a92e0563--- /dev/null+++ b/packages/desktop-client/src/components/reports/spendingAverageRange.test.ts@@ -0,0 +1,171 @@+import {+ DEFAULT_SPENDING_AVERAGE_RANGE,+ getSpendingAverageSummaryLabel,+ resolveSpendingAverageRange,+ spendingAverageRangeFromKey,+ spendingAverageRangeToKey,+} from './spendingAverageRange';++const t = (key: string, options?: Record<string, string | number>) =>+ options+ ? Object.entries(options).reduce(+ (message, [optionKey, value]) =>+ message.replace(`{{${optionKey}}}`, String(value)),+ key,+ )+ : key;++describe('spending average range metadata', () => {+ it('defaults missing metadata to the existing last 3 months behavior', () => {+ expect(spendingAverageRangeToKey()).toBe('last-3-months');+ expect(DEFAULT_SPENDING_AVERAGE_RANGE).toEqual({+ mode: 'last-n-months',+ months: 3,+ });+ });++ it('round-trips supported dropdown options', () => {+ expect(spendingAverageRangeFromKey('last-6-months')).toEqual({+ mode: 'last-n-months',+ months: 6,+ });+ expect(+ spendingAverageRangeToKey({+ mode: 'last-n-months',+ months: 12,+ }),+ ).toBe('last-12-months');+ expect(spendingAverageRangeFromKey('year-to-date')).toEqual({+ mode: 'year-to-date',+ });+ expect(spendingAverageRangeFromKey('all-time')).toEqual({+ mode: 'all-time',+ });+ });+});++describe('resolveSpendingAverageRange', () => {+ it('uses months before the selected compare month for last-n-months ranges', () => {+ expect(+ resolveSpendingAverageRange({+ averageRange: { mode: 'last-n-months', months: 6 },+ compare: '2026-05',+ }),+ ).toEqual({+ startMonth: '2025-11',+ endMonth: '2026-04',+ months: [+ '2025-11',+ '2025-12',+ '2026-01',+ '2026-02',+ '2026-03',+ '2026-04',+ ],+ });+ });++ it('uses elapsed months in the compare year for year-to-date ranges', () => {+ expect(+ resolveSpendingAverageRange({+ averageRange: { mode: 'year-to-date' },+ compare: '2026-05',+ }),+ ).toEqual({+ startMonth: '2026-01',+ endMonth: '2026-04',+ months: ['2026-01', '2026-02', '2026-03', '2026-04'],+ });+ });++ it('returns an empty range for year-to-date January comparisons', () => {+ expect(+ resolveSpendingAverageRange({+ averageRange: { mode: 'year-to-date' },+ compare: '2026-01',+ }),+ ).toEqual({+ startMonth: null,+ endMonth: null,+ months: [],+ });+ });++ it('uses all complete months before compare for all-time ranges', () => {+ expect(+ resolveSpendingAverageRange({+ averageRange: { mode: 'all-time' },+ compare: '2026-05',+ earliestMonth: '2024-02',+ }),+ ).toEqual({+ startMonth: '2024-02',+ endMonth: '2026-04',+ months: [+ '2024-02',+ '2024-03',+ '2024-04',+ '2024-05',+ '2024-06',+ '2024-07',+ '2024-08',+ '2024-09',+ '2024-10',+ '2024-11',+ '2024-12',+ '2025-01',+ '2025-02',+ '2025-03',+ '2025-04',+ '2025-05',+ '2025-06',+ '2025-07',+ '2025-08',+ '2025-09',+ '2025-10',+ '2025-11',+ '2025-12',+ '2026-01',+ '2026-02',+ '2026-03',+ '2026-04',+ ],+ });+ });++ it('returns an empty all-time range when there are no complete months before compare', () => {+ expect(+ resolveSpendingAverageRange({+ averageRange: { mode: 'all-time' },+ compare: '2026-05',+ earliestMonth: '2026-05',+ }),+ ).toEqual({+ startMonth: null,+ endMonth: null,+ months: [],+ });+ });+});++describe('getSpendingAverageSummaryLabel', () => {+ it('describes current-month average MTD by selected range', () => {+ expect(+ getSpendingAverageSummaryLabel({+ averageRange: { mode: 'all-time' },+ isCurrentMonth: true,+ t,+ }),+ ).toBe('Spent Average MTD (All time):');+ });++ it('describes completed-month averages by selected range', () => {+ expect(+ getSpendingAverageSummaryLabel({+ averageRange: { mode: 'last-n-months', months: 12 },+ isCurrentMonth: false,+ t,+ }),+ ).toBe('Spent Average (Last 12 months):');+ });+});diff --git a/packages/desktop-client/src/components/reports/spendingAverageRange.ts b/packages/desktop-client/src/components/reports/spendingAverageRange.tsnew file mode 100644index 0000000000..214f6861ea--- /dev/null+++ b/packages/desktop-client/src/components/reports/spendingAverageRange.ts@@ -0,0 +1,174 @@+import * as monthUtils from '@actual-app/core/shared/months';+import type { SpendingAverageRange } from '@actual-app/core/types/models';++export type SpendingAverageRangeKey =+ | 'last-3-months'+ | 'last-6-months'+ | 'last-12-months'+ | 'year-to-date'+ | 'all-time';++export const DEFAULT_SPENDING_AVERAGE_RANGE: SpendingAverageRange = {+ mode: 'last-n-months',+ months: 3,+};++const supportedLastNMonths = [3, 6, 12] as const;++function isSupportedLastNMonths(+ months: number,+): months is (typeof supportedLastNMonths)[number] {+ return supportedLastNMonths.some(supported => supported === months);+}++export function normalizeSpendingAverageRange(+ averageRange?: SpendingAverageRange,+): SpendingAverageRange {+ if (!averageRange) {+ return DEFAULT_SPENDING_AVERAGE_RANGE;+ }++ if (+ averageRange.mode === 'last-n-months' &&+ !isSupportedLastNMonths(averageRange.months)+ ) {+ return DEFAULT_SPENDING_AVERAGE_RANGE;+ }++ return averageRange;+}++export function spendingAverageRangeFromKey(key: string): SpendingAverageRange {+ switch (key) {+ case 'last-6-months':+ return { mode: 'last-n-months', months: 6 };+ case 'last-12-months':+ return { mode: 'last-n-months', months: 12 };+ case 'year-to-date':+ return { mode: 'year-to-date' };+ case 'all-time':+ return { mode: 'all-time' };+ case 'last-3-months':+ default:+ return DEFAULT_SPENDING_AVERAGE_RANGE;+ }+}++export function spendingAverageRangeToKey(+ averageRange?: SpendingAverageRange,+): SpendingAverageRangeKey {+ const normalizedRange = normalizeSpendingAverageRange(averageRange);++ switch (normalizedRange.mode) {+ case 'last-n-months':+ return `last-${normalizedRange.months}-months`;+ case 'year-to-date':+ return 'year-to-date';+ case 'all-time':+ return 'all-time';+ default:+ return 'last-3-months';+ }+}++type ResolveSpendingAverageRangeProps = {+ averageRange?: SpendingAverageRange;+ compare: string;+ earliestMonth?: string | null;+};++type ResolvedSpendingAverageRange = {+ startMonth: string | null;+ endMonth: string | null;+ months: string[];+};++export function resolveSpendingAverageRange({+ averageRange,+ compare,+ earliestMonth,+}: ResolveSpendingAverageRangeProps): ResolvedSpendingAverageRange {+ const normalizedRange = normalizeSpendingAverageRange(averageRange);+ const endMonth = monthUtils.subMonths(compare, 1);+ let startMonth: string | null;++ switch (normalizedRange.mode) {+ case 'last-n-months':+ startMonth = monthUtils.subMonths(compare, normalizedRange.months);+ break;+ case 'year-to-date':+ startMonth = `${monthUtils.getYear(compare)}-01`;+ break;+ case 'all-time':+ startMonth = earliestMonth ?? null;+ break;+ default:+ startMonth = monthUtils.subMonths(compare, 3);+ break;+ }++ if (!startMonth || startMonth > endMonth) {+ return {+ startMonth: null,+ endMonth: null,+ months: [],+ };+ }++ return {+ startMonth,+ endMonth,+ months: monthUtils.rangeInclusive(startMonth, endMonth),+ };+}++type Translate = (+ key: string,+ options?: Record<string, string | number>,+) => string;++export function getSpendingAverageRangeLabel(+ averageRange: SpendingAverageRange | undefined,+ t: Translate,+): string {+ const normalizedRange = normalizeSpendingAverageRange(averageRange);++ switch (normalizedRange.mode) {+ case 'last-n-months':+ return t('Last {{count}} months', { count: normalizedRange.months });+ case 'year-to-date':+ return t('YTD');+ case 'all-time':+ return t('All time');+ default:+ return t('Last 3 months');+ }+}++export function getSpendingAverageSummaryLabel({+ averageRange,+ isCurrentMonth,+ t,+}: {+ averageRange?: SpendingAverageRange;+ isCurrentMonth: boolean;+ t: Translate;+}): string {+ const rangeLabel = getSpendingAverageRangeLabel(averageRange, t);++ return isCurrentMonth+ ? t('Spent Average MTD ({{rangeLabel}}):', { rangeLabel })+ : t('Spent Average ({{rangeLabel}}):', { rangeLabel });+}++export function getSpendingAverageRangeOptions(+ t: Translate,+): Array<readonly [SpendingAverageRangeKey, string]> {+ return [+ ['last-3-months', t('Last 3 months')],+ ['last-6-months', t('Last 6 months')],+ ['last-12-months', t('Last 12 months')],+ ['year-to-date', t('YTD')],+ ['all-time', t('All time')],+ ];+}diff --git a/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.tsindex 46405a61e8..9afdf02e74 100644--- a/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts+++ b/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts@@ -3,12 +3,15 @@ import * as monthUtils from '@actual-app/core/shared/months';import { q } from '@actual-app/core/shared/query';import type {RuleConditionEntity,+ SpendingAverageRange,SpendingEntity,SpendingMonthEntity,} from '@actual-app/core/types/models';// @ts-strict-ignoreimport keyBy from 'lodash/keyBy';+import { resolveSpendingAverageRange } from '#components/reports/spendingAverageRange';+import { fromDateRepr } from '#components/reports/util';import type { useSpreadsheet } from '#hooks/useSpreadsheet';import { aqlQuery } from '#queries/aqlQuery';@@ -19,6 +22,7 @@ type createSpendingSpreadsheetProps = {conditionsOp?: string;compare?: string;compareTo?: string;+ averageRange?: SpendingAverageRange;budgetType?: 'envelope' | 'tracking';};@@ -27,15 +31,17 @@ export function createSpendingSpreadsheet({conditionsOp,compare,compareTo,+ averageRange,budgetType = 'envelope',}: createSpendingSpreadsheetProps) {- const startDate = monthUtils.subMonths(compare, 3) + '-01';- const endDate = monthUtils.getMonthEnd(compare + '-01');- const startDateTo = compareTo + '-01';- const endDateTo = monthUtils.getMonthEnd(compareTo + '-01');+ const compareMonth = compare ?? monthUtils.currentMonth();+ const compareToMonth = compareTo ?? monthUtils.subMonths(compareMonth, 1);+ const endDate = monthUtils.getMonthEnd(compareMonth + '-01');+ const startDateTo = compareToMonth + '-01';+ const endDateTo = monthUtils.getMonthEnd(compareToMonth + '-01');const interval = 'Daily';const compareInterval = monthUtils.dayRangeInclusive(- compare + '-01',+ compareMonth + '-01',endDate,);@@ -43,6 +49,21 @@ export function createSpendingSpreadsheet({spreadsheet: ReturnType<typeof useSpreadsheet>,setData: (data: SpendingEntity) => void,) => {+ const earliestTrans =+ averageRange?.mode === 'all-time'+ ? await send('get-earliest-transaction')+ : null;+ const earliestMonth = earliestTrans+ ? monthUtils.monthFromDate(fromDateRepr(earliestTrans.date))+ : null;+ const resolvedAverageRange = resolveSpendingAverageRange({+ averageRange,+ compare: compareMonth,+ earliestMonth,+ });+ const averageMonths = new Set(resolvedAverageRange.months);+ const startDate = (resolvedAverageRange.startMonth ?? compareMonth) + '-01';+const { filters } = await send('make-filters-from-conditions', {conditions: conditions.filter(cond => !cond.customName),});@@ -112,8 +133,34 @@ export function createSpendingSpreadsheet({const combineAssets = [...assets, ...overlapAssets];const combineDebts = [...debts, ...overlapDebts];+ const totalsByDate = new Map<+ string,+ { perIntervalAssets: number; perIntervalDebts: number }+ >();++ combineAssets+ .filter(e => !e.categoryIncome && !e.accountOffBudget)+ .forEach(asset => {+ const totals = totalsByDate.get(asset.date) ?? {+ perIntervalAssets: 0,+ perIntervalDebts: 0,+ };+ totals.perIntervalAssets += asset.amount;+ totalsByDate.set(asset.date, totals);+ });++ combineDebts+ .filter(e => !e.categoryIncome && !e.accountOffBudget)+ .forEach(debt => {+ const totals = totalsByDate.get(debt.date) ?? {+ perIntervalAssets: 0,+ perIntervalDebts: 0,+ };+ totals.perIntervalDebts += debt.amount;+ totalsByDate.set(debt.date, totals);+ });- const budgetMonth = parseInt(compare.replace('-', ''));+ const budgetMonth = parseInt(compareMonth.replace('-', ''));const budgetTable =budgetType === 'tracking' ? 'reflect_budgets' : 'zero_budgets';const [budgets] = await Promise.all([@@ -156,7 +203,7 @@ export function createSpendingSpreadsheet({if (endDateTo < startDate || startDateTo > endDate) {months.unshift({- month: compareTo,+ month: compareToMonth,perMonthAssets: 0,perMonthDebts: 0,});@@ -178,17 +225,9 @@ export function createSpendingSpreadsheet({month.month === monthUtils.getMonth(intervalItem) &&day === offsetDay) {- const intervalAssets = combineAssets- .filter(e => !e.categoryIncome && !e.accountOffBudget)- .filter(asset => asset.date === intervalItem)- .reduce((a, v) => a + v.amount, 0);- perIntervalAssets += intervalAssets;-- const intervalDebts = combineDebts- .filter(e => !e.categoryIncome && !e.accountOffBudget)- .filter(debt => debt.date === intervalItem)- .reduce((a, v) => a + v.amount, 0);- perIntervalDebts += intervalDebts;+ const totals = totalsByDate.get(intervalItem);+ perIntervalAssets += totals?.perIntervalAssets ?? 0;+ perIntervalDebts += totals?.perIntervalDebts ?? 0;totalAssets += perIntervalAssets;totalDebts += perIntervalDebts;@@ -196,7 +235,7 @@ export function createSpendingSpreadsheet({let cumulativeAssets = 0;let cumulativeDebts = 0;- if (month.month === compare) {+ if (month.month === compareMonth) {totalBudget -= dailyBudget;}@@ -208,10 +247,7 @@ export function createSpendingSpreadsheet({return null;});- if (- month.month >= monthUtils.monthFromDate(startDate) &&- month.month < compare- ) {+ if (averageMonths.has(month.month)) {if (day === '28') {if (monthUtils.getMonthEnd(intervalItem) === intervalItem) {averageSum += cumulativeAssets + cumulativeDebts;@@ -254,15 +290,17 @@ export function createSpendingSpreadsheet({return {months: indexedData,day,- average: Math.round(averageSum / monthCount),- compare: dayData.filter(c => c.month === compare)[0].cumulative,- compareTo: dayData.filter(c => c.month === compareTo)[0].cumulative,+ average: monthCount === 0 ? 0 : Math.round(averageSum / monthCount),+ compare: dayData.filter(c => c.month === compareMonth)[0].cumulative,+ compareTo: dayData.filter(c => c.month === compareToMonth)[0]+ .cumulative,budget: totalBudget,};});setData({intervalData,+ averageRange: resolvedAverageRange,startDate,endDate,totalDebts,diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 303c53679c..e374ebbb5c 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -57,6 +57,19 @@ export type CashFlowWidget = AbstractWidget<showBalance?: boolean;} | null>;++export type SpendingAverageRange =+ | {+ mode: 'last-n-months';+ months: 3 | 6 | 12;+ }+ | {+ mode: 'year-to-date';+ }+ | {+ mode: 'all-time';+ };+export type SpendingWidget = AbstractWidget<'spending-card',{@@ -67,6 +80,7 @@ export type SpendingWidget = AbstractWidget<compareTo?: string;isLive?: boolean;mode?: 'single-month' | 'budget' | 'average';+ averageRange?: SpendingAverageRange;} | null>;export type BudgetAnalysisWidget = AbstractWidget<diff --git a/packages/loot-core/src/types/models/reports.ts b/packages/loot-core/src/types/models/reports.tsindex b283e51b6f..9b734d76c2 100644--- a/packages/loot-core/src/types/models/reports.ts+++ b/packages/loot-core/src/types/models/reports.ts@@ -63,6 +63,11 @@ export type SpendingEntity = {compareTo: number;budget: number;}[];+ averageRange?: {+ startMonth: string | null;+ endMonth: string | null;+ months: string[];+ };startDate?: string;endDate?: string;totalDebts: number;diff --git a/upcoming-release-notes/7920.md b/upcoming-release-notes/7920.mdnew file mode 100644index 0000000000..bbe7828478--- /dev/null+++ b/upcoming-release-notes/7920.md@@ -0,0 +1,6 @@+---+category: Features+authors: [MattFaz]+---++Add configurable average ranges to Monthly Spending report