A local-first personal finance app
Add Age of Money report (#2994) (#6685)
Tamás Szeleie3dd3d1d5ad8
diff --git a/packages/desktop-client/src/components/reports/Overview.tsx b/packages/desktop-client/src/components/reports/Overview.tsxindex 75e80bad20..323eb143ef 100644--- a/packages/desktop-client/src/components/reports/Overview.tsx+++ b/packages/desktop-client/src/components/reports/Overview.tsx@@ -26,6 +26,7 @@ import { NON_DRAGGABLE_AREA_CLASS_NAME } from './constants';import { DashboardHeader } from './DashboardHeader';import { DashboardSelector } from './DashboardSelector';import { LoadingIndicator } from './LoadingIndicator';+import { AgeOfMoneyCard } from './reports/AgeOfMoneyCard';import { BudgetAnalysisCard } from './reports/BudgetAnalysisCard';import { CalendarCard } from './reports/CalendarCard';import { CashFlowCard } from './reports/CashFlowCard';@@ -35,8 +36,8 @@ import { FormulaCard } from './reports/FormulaCard';import { MarkdownCard } from './reports/MarkdownCard';import { NetWorthCard } from './reports/NetWorthCard';import { SankeyCard } from './reports/SankeyCard';-import { SpendingCard } from './reports/SpendingCard';import './overview.scss';+import { SpendingCard } from './reports/SpendingCard';import { SummaryCard } from './reports/SummaryCard';import { MOBILE_NAV_HEIGHT } from '@desktop-client/components/mobile/MobileNavTabs';@@ -84,6 +85,7 @@ export function Overview({ dashboard }: OverviewProps) {const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';const crossoverReportEnabled = useFeatureFlag('crossoverReport');+ const ageOfMoneyReportEnabled = useFeatureFlag('ageOfMoneyReport');const budgetAnalysisReportEnabled = useFeatureFlag('budgetAnalysisReport');const formulaMode = useFeatureFlag('formulaMode');@@ -579,6 +581,14 @@ export function Overview({ dashboard }: OverviewProps) {},]: []),+ ...(ageOfMoneyReportEnabled+ ? [+ {+ name: 'age-of-money-card' as const,+ text: t('Age of Money'),+ },+ ]+ : []),{name: 'spending-card' as const,text: t('Spending analysis'),@@ -785,6 +795,18 @@ export function Overview({ dashboard }: OverviewProps) {onCopyWidget(item.i, targetDashboardId)}/>+ ) : widget.type === 'age-of-money-card' &&+ ageOfMoneyReportEnabled ? (+ <AgeOfMoneyCard+ widgetId={item.i}+ isEditing={isEditing}+ meta={widget.meta}+ onMetaChange={newMeta => onMetaChange(item, newMeta)}+ onRemove={() => onRemoveWidget(item.i)}+ onCopy={targetDashboardId =>+ onCopyWidget(item.i, targetDashboardId)+ }+ />) : widget.type === 'cash-flow-card' ? (<CashFlowCardwidgetId={item.i}diff --git a/packages/desktop-client/src/components/reports/ReportRouter.tsx b/packages/desktop-client/src/components/reports/ReportRouter.tsxindex 90241b7a39..e2b63f55ee 100644--- a/packages/desktop-client/src/components/reports/ReportRouter.tsx+++ b/packages/desktop-client/src/components/reports/ReportRouter.tsx@@ -1,6 +1,7 @@import React from 'react';import { Route, Routes } from 'react-router';+import { AgeOfMoney } from './reports/AgeOfMoney';import { BudgetAnalysis } from './reports/BudgetAnalysis';import { Calendar } from './reports/Calendar';import { CashFlow } from './reports/CashFlow';@@ -17,6 +18,7 @@ import { useFeatureFlag } from '@desktop-client/hooks/useFeatureFlag';export function ReportRouter() {const crossoverReportEnabled = useFeatureFlag('crossoverReport');+ const ageOfMoneyReportEnabled = useFeatureFlag('ageOfMoneyReport');const budgetAnalysisReportEnabled = useFeatureFlag('budgetAnalysisReport');const sankeyReportEnabled = useFeatureFlag('sankeyReport');@@ -32,6 +34,12 @@ export function ReportRouter() {<Route path="/crossover/:id" element={<Crossover />} /></>)}+ {ageOfMoneyReportEnabled && (+ <>+ <Route path="/age-of-money" element={<AgeOfMoney />} />+ <Route path="/age-of-money/:id" element={<AgeOfMoney />} />+ </>+ )}<Route path="/cash-flow" element={<CashFlow />} /><Route path="/cash-flow/:id" element={<CashFlow />} /><Route path="/custom" element={<CustomReport />} />diff --git a/packages/desktop-client/src/components/reports/graphs/AgeOfMoneyGraph.tsx b/packages/desktop-client/src/components/reports/graphs/AgeOfMoneyGraph.tsxnew file mode 100644index 0000000000..5a8b45c247--- /dev/null+++ b/packages/desktop-client/src/components/reports/graphs/AgeOfMoneyGraph.tsx@@ -0,0 +1,195 @@+import { useId } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import type { CSSProperties } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import { css } from '@emotion/css';+import {+ Area,+ AreaChart,+ CartesianGrid,+ ReferenceLine,+ Tooltip,+ XAxis,+ YAxis,+} from 'recharts';++import { useRechartsAnimation } from '@desktop-client/components/reports/chart-theme';+import { Container } from '@desktop-client/components/reports/Container';+import { usePrivacyMode } from '@desktop-client/hooks/usePrivacyMode';++type PayloadItem = {+ payload: {+ date: string;+ ageOfMoney: number;+ };+};++type CustomTooltipProps = {+ active?: boolean;+ payload?: PayloadItem[];+};++function CustomTooltip({ active, payload }: CustomTooltipProps) {+ const { t } = useTranslation();++ if (active && payload && payload.length) {+ return (+ <div+ className={css({+ zIndex: 1000,+ pointerEvents: 'none',+ borderRadius: 2,+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',+ backgroundColor: theme.menuBackground,+ color: theme.menuItemText,+ padding: 10,+ })}+ >+ <div style={{ marginBottom: 5 }}>+ <strong>{payload[0].payload.date}</strong>+ </div>+ <div>+ {t('Age of Money: {{days}} days', {+ days: payload[0].payload.ageOfMoney,+ })}+ </div>+ </div>+ );+ }+ return null;+}++type AgeOfMoneyGraphProps = {+ style?: CSSProperties;+ data: Array<{+ date: string;+ ageOfMoney: number;+ }>;+ compact?: boolean;+ showTooltip?: boolean;+};++export function AgeOfMoneyGraph({+ style,+ data,+ compact = false,+ showTooltip = true,+}: AgeOfMoneyGraphProps) {+ const { t } = useTranslation();+ const animationProps = useRechartsAnimation();+ const privacyMode = usePrivacyMode();+ const id = useId();+ const gradientId = `aom-gradient-${id}`;++ // Calculate the maximum value for Y axis scaling+ const maxAge = Math.max(...data.map(d => d.ageOfMoney), 30);+ const yAxisMax = Math.ceil(maxAge / 10) * 10 + 10;++ // 30 days approximates "living on last month's income"+ // This value is used as a marked reference value on the graph.+ const targetReferenceAge = 30;++ return (+ <Container+ style={{+ ...style,+ ...(compact && { height: 'auto' }),+ }}+ >+ {(width, height) =>+ data && data.length > 0 ? (+ <div>+ {!compact && <div style={{ marginTop: '15px' }} />}+ <AreaChart+ width={width}+ height={height}+ data={data}+ margin={{+ top: 10,+ right: 10,+ left: compact ? 0 : 10,+ bottom: 10,+ }}+ >+ <defs>+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">+ <stop+ offset="0%"+ stopColor={theme.reportsChartFill}+ stopOpacity={0.3}+ />+ <stop+ offset="100%"+ stopColor={theme.reportsChartFill}+ stopOpacity={0.05}+ />+ </linearGradient>+ </defs>+ {!compact && (+ <CartesianGrid strokeDasharray="3 3" vertical={false} />+ )}+ {!compact && (+ <XAxis+ dataKey="date"+ tick={{ fill: theme.reportsLabel, fontSize: 12 }}+ tickLine={{ stroke: theme.reportsLabel }}+ />+ )}+ {!compact && (+ <YAxis+ tickFormatter={value => (privacyMode ? '•••' : `${value}d`)}+ tick={{ fill: theme.reportsLabel, fontSize: 12 }}+ tickLine={{ stroke: theme.reportsLabel }}+ domain={[0, yAxisMax]}+ />+ )}+ {showTooltip && (+ <Tooltip+ content={<CustomTooltip />}+ isAnimationActive={false}+ />+ )}+ {!compact && (+ <ReferenceLine+ y={targetReferenceAge}+ stroke={theme.reportsGreen}+ strokeDasharray="5 5"+ label={{+ value: t('30 days'),+ position: 'insideTopRight',+ fill: theme.reportsGreen,+ fontSize: 10,+ }}+ />+ )}+ <Area+ type="monotone"+ dataKey="ageOfMoney"+ stroke={theme.reportsChartFill}+ strokeWidth={2}+ fill={`url(#${gradientId})`}+ fillOpacity={1}+ dot={!compact && data.length <= 90}+ activeDot={{ r: 6, fill: theme.reportsChartFill }}+ {...animationProps}+ />+ </AreaChart>+ </div>+ ) : (+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ color: theme.pageTextSubdued,+ }}+ >+ <Trans>No data available</Trans>+ </div>+ )+ }+ </Container>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/AgeOfMoney.tsx b/packages/desktop-client/src/components/reports/reports/AgeOfMoney.tsxnew file mode 100644index 0000000000..05a7c00764--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/AgeOfMoney.tsx@@ -0,0 +1,450 @@+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { Trans, useTranslation } from 'react-i18next';+import { useParams } from 'react-router';++import { Button } from '@actual-app/components/button';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import { SvgCalendar } from '@actual-app/components/icons/v1';+import { Menu } from '@actual-app/components/menu';+import { Paragraph } from '@actual-app/components/paragraph';+import { Popover } from '@actual-app/components/popover';+import { styles } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';+import * as d from 'date-fns';++import { send } from 'loot-core/platform/client/connection';+import * as monthUtils from 'loot-core/shared/months';+import type {+ AgeOfMoneyGranularity,+ AgeOfMoneyWidget,+ TimeFrame,+} from 'loot-core/types/models';++import { getAgeColor } from './AgeOfMoneyCard';++import { EditablePageHeaderTitle } from '@desktop-client/components/EditablePageHeaderTitle';+import { MobileBackButton } from '@desktop-client/components/mobile/MobileBackButton';+import {+ MobilePageHeader,+ Page,+ PageHeader,+} from '@desktop-client/components/Page';+import { PrivacyFilter } from '@desktop-client/components/PrivacyFilter';+import { AgeOfMoneyGraph } from '@desktop-client/components/reports/graphs/AgeOfMoneyGraph';+import { Header } from '@desktop-client/components/reports/Header';+import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndicator';+import { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';+import { createAgeOfMoneySpreadsheet } from '@desktop-client/components/reports/spreadsheets/age-of-money-spreadsheet';+import { useReport } from '@desktop-client/components/reports/useReport';+import { fromDateRepr } from '@desktop-client/components/reports/util';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';+import { useLocale } from '@desktop-client/hooks/useLocale';+import { useNavigate } from '@desktop-client/hooks/useNavigate';+import { useRuleConditionFilters } from '@desktop-client/hooks/useRuleConditionFilters';+import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';+import { addNotification } from '@desktop-client/notifications/notificationsSlice';+import { useDispatch } from '@desktop-client/redux';++export function AgeOfMoney() {+ const params = useParams();+ const { data: widget, isLoading } = useDashboardWidget<AgeOfMoneyWidget>({+ id: params.id,+ type: 'age-of-money-card',+ });++ if (isLoading) {+ return <LoadingIndicator />;+ }++ return <AgeOfMoneyInner widget={widget} />;+}++type AgeOfMoneyInnerProps = {+ widget?: AgeOfMoneyWidget;+};++function AgeOfMoneyInner({ widget }: AgeOfMoneyInnerProps) {+ const locale = useLocale();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ const {+ conditions,+ conditionsOp,+ onApply: onApplyFilter,+ onDelete: onDeleteFilter,+ onUpdate: onUpdateFilter,+ onConditionsOpChange,+ } = useRuleConditionFilters(+ widget?.meta?.conditions,+ widget?.meta?.conditionsOp,+ );++ const [allMonths, setAllMonths] = useState<Array<{+ name: string;+ pretty: string;+ }> | null>(null);++ const [start, setStart] = useState(monthUtils.currentMonth());+ const [end, setEnd] = useState(monthUtils.currentMonth());+ const [mode, setMode] = useState<TimeFrame['mode']>('sliding-window');+ const [granularity, setGranularity] = useState<AgeOfMoneyGranularity>(+ widget?.meta?.granularity ?? 'monthly',+ );++ const [latestTransaction, setLatestTransaction] = useState('');+ const [earliestTransaction, setEarliestTransaction] = useState('');++ const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');+ const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';++ const reportParams = useMemo(+ () =>+ createAgeOfMoneySpreadsheet({+ start,+ end,+ conditions,+ conditionsOp,+ granularity,+ }),+ [start, end, conditions, conditionsOp, granularity],+ );+ const data = useReport('age_of_money', reportParams);++ useEffect(() => {+ async function run() {+ const earliestTrans = await send('get-earliest-transaction');+ setEarliestTransaction(+ earliestTrans ? earliestTrans.date : monthUtils.currentDay(),+ );++ const latestTrans = await send('get-latest-transaction');+ setLatestTransaction(+ latestTrans ? latestTrans.date : monthUtils.currentDay(),+ );++ const currentMonth = monthUtils.currentMonth();+ let earliestMonth = earliestTrans+ ? monthUtils.monthFromDate(d.parseISO(fromDateRepr(earliestTrans.date)))+ : currentMonth;+ const latestTransactionMonth = latestTrans+ ? monthUtils.monthFromDate(d.parseISO(fromDateRepr(latestTrans.date)))+ : currentMonth;++ const latestMonth =+ latestTransactionMonth > currentMonth+ ? latestTransactionMonth+ : currentMonth;++ const yearAgo = monthUtils.subMonths(latestMonth, 12);+ if (earliestMonth > yearAgo) {+ earliestMonth = yearAgo;+ }++ const months = monthUtils+ .rangeInclusive(earliestMonth, latestMonth)+ .map(month => ({+ name: month,+ pretty: monthUtils.format(month, 'MMMM, yyyy', locale),+ }))+ .reverse();++ setAllMonths(months);+ }+ void run();+ }, [locale]);++ useEffect(() => {+ if (latestTransaction) {+ const [initialStart, initialEnd, initialMode] = calculateTimeRange(+ widget?.meta?.timeFrame,+ undefined,+ latestTransaction,+ );+ setStart(initialStart);+ setEnd(initialEnd);+ setMode(initialMode);+ }+ }, [latestTransaction, widget?.meta?.timeFrame]);++ const onChangeDates = useCallback(+ (newStart: string, newEnd: string, newMode: TimeFrame['mode']) => {+ setStart(newStart);+ setEnd(newEnd);+ setMode(newMode);+ },+ [],+ );++ const onSaveWidget = useCallback(async () => {+ if (!widget) {+ throw new Error('No widget that could be saved.');+ }++ await send('dashboard-update-widget', {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ conditions,+ conditionsOp,+ timeFrame: {+ start,+ end,+ mode,+ },+ granularity,+ },+ });+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );+ }, [+ widget,+ conditions,+ conditionsOp,+ start,+ end,+ mode,+ granularity,+ dispatch,+ t,+ ]);++ const navigate = useNavigate();+ const { isNarrowWidth } = useResponsive();++ const title = widget?.meta?.name || t('Age of Money');+ const onSaveWidgetName = useCallback(+ async (newName: string) => {+ if (!widget) {+ throw new Error('No widget that could be saved.');+ }++ const name = newName || t('Age of Money');+ await send('dashboard-update-widget', {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ },+ });+ },+ [widget, t],+ );++ if (!allMonths || !data) {+ return <LoadingIndicator />;+ }++ return (+ <Page+ header={+ isNarrowWidth ? (+ <MobilePageHeader+ title={title}+ leftContent={+ <MobileBackButton onPress={() => navigate('/reports')} />+ }+ />+ ) : (+ <PageHeader+ title={+ widget ? (+ <EditablePageHeaderTitle+ title={title}+ onSave={onSaveWidgetName}+ />+ ) : (+ title+ )+ }+ />+ )+ }+ padding={0}+ >+ <Header+ allMonths={allMonths}+ start={start}+ end={end}+ earliestTransaction={earliestTransaction}+ latestTransaction={latestTransaction}+ firstDayOfWeekIdx={firstDayOfWeekIdx}+ mode={mode}+ onChangeDates={onChangeDates}+ filters={conditions}+ onApply={onApplyFilter}+ onUpdateFilter={onUpdateFilter}+ onDeleteFilter={onDeleteFilter}+ conditionsOp={conditionsOp}+ onConditionsOpChange={onConditionsOpChange}+ inlineContent={+ <GranularitySelector+ granularity={granularity}+ onChange={setGranularity}+ />+ }+ >+ {widget && (+ <Button variant="primary" onPress={onSaveWidget}>+ <Trans>Save widget</Trans>+ </Button>+ )}+ </Header>++ <View+ style={{+ backgroundColor: theme.tableBackground,+ padding: 20,+ paddingTop: 0,+ flex: '1 0 auto',+ overflowY: 'auto',+ }}+ >+ <View+ style={{+ textAlign: 'right',+ paddingTop: 20,+ }}+ >+ <View+ style={{+ ...styles.largeText,+ fontWeight: 400,+ marginBottom: 5,+ color: getAgeColor(data.currentAge),+ }}+ >+ <PrivacyFilter>+ {data.currentAge !== null+ ? t('{{days}} days', { days: data.currentAge })+ : t('N/A')}+ </PrivacyFilter>+ </View>+ <View style={{ color: theme.pageTextSubdued }}>+ {data.trend === 'up'+ ? t('↑ Improving')+ : data.trend === 'down'+ ? t('↓ Declining')+ : t('→ Stable')}+ </View>+ {data.insufficientData && (+ <View+ style={{ color: theme.warningText, fontSize: 12, marginTop: 5 }}+ >+ {t(+ 'Note: Some expenses could not be matched to income (spending exceeded income in this period)',+ )}+ </View>+ )}+ </View>++ <AgeOfMoneyGraph data={data.graphData} />++ <View style={{ marginTop: 30, userSelect: 'none' }}>+ <Paragraph>+ <strong>+ <Trans>What is Age of Money?</Trans>+ </strong>+ </Paragraph>+ <Paragraph>+ <Trans>+ Age of Money shows how many days, on average, your money sits in+ your budget before you spend it. It measures the gap between when+ you earn money and when you spend it.+ </Trans>+ </Paragraph>+ <Paragraph>+ <Trans>+ A higher Age of Money means you're spending older money, which+ indicates you're living on last month's income rather than+ paycheck-to-paycheck. An age of 30 days or more is considered+ ideal—it means you're typically spending money you earned a month+ ago.+ </Trans>+ </Paragraph>+ <Paragraph>+ <strong>+ <Trans>How is it calculated?</Trans>+ </strong>+ </Paragraph>+ <Paragraph>+ <Trans>+ The calculation uses the FIFO (First In, First Out) method: when+ you spend money, it's considered to come from your oldest income+ first. The age is the difference in days between when you received+ that income and when you spent it. The displayed value is the+ average age of your last 10 expenses.+ </Trans>+ </Paragraph>+ </View>+ </View>+ </Page>+ );+}++function GranularitySelector({+ granularity,+ onChange,+}: {+ granularity: AgeOfMoneyGranularity;+ onChange: (val: AgeOfMoneyGranularity) => void;+}) {+ const { t } = useTranslation();++ const triggerRef = useRef<HTMLButtonElement | null>(null);+ const [isOpen, setIsOpen] = useState(false);++ const options: Array<{ key: AgeOfMoneyGranularity; description: string }> = [+ { key: 'daily', description: t('Daily') },+ { key: 'weekly', description: t('Weekly') },+ { key: 'monthly', description: t('Monthly') },+ ];++ const currentLabel =+ options.find(opt => opt.key === granularity)?.description ?? granularity;++ return (+ <>+ <Button+ ref={triggerRef}+ variant="bare"+ onPress={() => setIsOpen(true)}+ aria-label={t('Change granularity')}+ >+ <SvgCalendar style={{ width: 12, height: 12 }} />+ <span style={{ marginLeft: 5 }}>{currentLabel}</span>+ </Button>++ <Popover+ triggerRef={triggerRef}+ placement="bottom start"+ isOpen={isOpen}+ onOpenChange={() => setIsOpen(false)}+ >+ <Menu+ onMenuSelect={item => {+ onChange(item as AgeOfMoneyGranularity);+ setIsOpen(false);+ }}+ items={options.map(({ key, description }) => ({+ name: key,+ text: description,+ }))}+ />+ </Popover>+ </>+ );+}diff --git a/packages/desktop-client/src/components/reports/reports/AgeOfMoneyCard.tsx b/packages/desktop-client/src/components/reports/reports/AgeOfMoneyCard.tsxnew file mode 100644index 0000000000..88d4a8932a--- /dev/null+++ b/packages/desktop-client/src/components/reports/reports/AgeOfMoneyCard.tsx@@ -0,0 +1,208 @@+import React, { useCallback, useEffect, useMemo, useState } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Block } from '@actual-app/components/block';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';+import { styles } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import { send } from 'loot-core/platform/client/connection';+import * as monthUtils from 'loot-core/shared/months';+import type { AgeOfMoneyWidget } from 'loot-core/types/models';++import { PrivacyFilter } from '@desktop-client/components/PrivacyFilter';+import { DateRange } from '@desktop-client/components/reports/DateRange';+import { AgeOfMoneyGraph } from '@desktop-client/components/reports/graphs/AgeOfMoneyGraph';+import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndicator';+import { ReportCard } from '@desktop-client/components/reports/ReportCard';+import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';+import { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';+import { createAgeOfMoneySpreadsheet } from '@desktop-client/components/reports/spreadsheets/age-of-money-spreadsheet';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';+import { useReport } from '@desktop-client/components/reports/useReport';++// Determine status color based on age+export function getAgeColor(age: number | null) {+ if (age === null) return theme.reportsNumberNeutral;+ if (age >= 30) return theme.reportsNumberPositive; // Green - good+ if (age >= 14) return theme.warningText; // Yellow - getting there+ return theme.reportsNumberNegative; // Red - needs work+}++// Trend indicator+function getTrendIndicator(trend: 'up' | 'down' | 'stable') {+ switch (trend) {+ case 'up':+ return '↑';+ case 'down':+ return '↓';+ default:+ return '→';+ }+}++type AgeOfMoneyCardProps = {+ widgetId: string;+ isEditing?: boolean;+ meta?: AgeOfMoneyWidget['meta'];+ onMetaChange: (newMeta: AgeOfMoneyWidget['meta']) => void;+ onRemove: () => void;+ onCopy: (targetDashboardId: string) => void;+};++export function AgeOfMoneyCard({+ widgetId,+ isEditing,+ meta = {},+ onMetaChange,+ onRemove,+ onCopy,+}: AgeOfMoneyCardProps) {+ const { t } = useTranslation();+ const { isNarrowWidth } = useResponsive();++ const [latestTransaction, setLatestTransaction] = useState<string>('');+ const [nameMenuOpen, setNameMenuOpen] = useState(false);+ const [isCardHovered, setIsCardHovered] = useState(false);++ const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =+ useDashboardWidgetCopyMenu(onCopy);++ useEffect(() => {+ async function fetchLatestTransaction() {+ const latestTrans = await send('get-latest-transaction');+ setLatestTransaction(+ latestTrans ? latestTrans.date : monthUtils.currentDay(),+ );+ }+ void fetchLatestTransaction();+ }, []);++ const [start, end] = calculateTimeRange(+ meta?.timeFrame,+ undefined,+ latestTransaction,+ );++ const onCardHover = useCallback(() => setIsCardHovered(true), []);+ const onCardHoverEnd = useCallback(() => setIsCardHovered(false), []);++ const params = useMemo(+ () =>+ createAgeOfMoneySpreadsheet({+ start,+ end,+ conditions: meta?.conditions,+ conditionsOp: meta?.conditionsOp,+ granularity: meta?.granularity ?? 'monthly',+ }),+ [start, end, meta?.conditions, meta?.conditionsOp, meta?.granularity],+ );+ const data = useReport('age_of_money', params);++ return (+ <ReportCard+ isEditing={isEditing}+ disableClick={nameMenuOpen}+ to={`/reports/age-of-money/${widgetId}`}+ menuItems={[+ { name: 'rename', text: t('Rename') },+ { name: 'remove', text: t('Remove') },+ ...copyMenuItems,+ ]}+ onMenuSelect={item => {+ if (handleCopyMenuSelect(item)) return;+ switch (item) {+ case 'rename':+ setNameMenuOpen(true);+ break;+ case 'remove':+ onRemove();+ break;+ default:+ throw new Error(`Unrecognized selection: ${item}`);+ }+ }}+ >+ <View+ style={{ flex: 1 }}+ onPointerEnter={onCardHover}+ onPointerLeave={onCardHoverEnd}+ >+ <View style={{ flexDirection: 'row', padding: 20 }}>+ <View style={{ flex: 1 }}>+ <ReportCardName+ name={meta?.name || t('Age of Money')}+ isEditing={nameMenuOpen}+ onChange={newName => {+ onMetaChange({+ ...meta,+ name: newName,+ });+ setNameMenuOpen(false);+ }}+ onClose={() => setNameMenuOpen(false)}+ />+ <DateRange start={start} end={end} />+ </View>+ {data && (+ <View style={{ textAlign: 'right' }}>+ <Block+ style={{+ ...styles.largeText,+ fontWeight: 500,+ marginBottom: 5,+ color: getAgeColor(data.currentAge),+ }}+ >+ <PrivacyFilter activationFilters={[!isCardHovered]}>+ {data.currentAge !== null+ ? t('{{days}} days', { days: data.currentAge })+ : t('N/A')}+ </PrivacyFilter>+ </Block>+ {data.currentAge !== null && (+ <Block+ style={{+ fontSize: 12,+ color: theme.pageTextSubdued,+ }}+ >+ {getTrendIndicator(data.trend)}{' '}+ {data.trend === 'up'+ ? t('Improving')+ : data.trend === 'down'+ ? t('Declining')+ : t('Stable')}+ </Block>+ )}+ {data.insufficientData && (+ <Block+ style={{+ fontSize: 10,+ color: theme.warningText,+ marginTop: 2,+ }}+ >+ <Trans>Incomplete data</Trans>+ </Block>+ )}+ </View>+ )}+ </View>++ {data ? (+ <AgeOfMoneyGraph+ data={data.graphData}+ compact+ showTooltip={!isEditing && !isNarrowWidth}+ style={{ height: 'auto', flex: 1 }}+ />+ ) : (+ <LoadingIndicator />+ )}+ </View>+ </ReportCard>+ );+}diff --git a/packages/desktop-client/src/components/reports/spreadsheets/age-of-money-spreadsheet.test.ts b/packages/desktop-client/src/components/reports/spreadsheets/age-of-money-spreadsheet.test.tsnew file mode 100644index 0000000000..3c2585539e--- /dev/null+++ b/packages/desktop-client/src/components/reports/spreadsheets/age-of-money-spreadsheet.test.ts@@ -0,0 +1,695 @@+import { describe, expect, it } from 'vitest';++import type {+ Transaction,+ TransactionWithCategory,+} from './age-of-money-spreadsheet';+import {+ calculateAgeOfMoney,+ calculateAverageAge,+ calculateGraphData,+ calculateTrend,+ classifyTransactions,+ formatPeriodLabel,+} from './age-of-money-spreadsheet';++describe('Age of Money calculations', () => {+ describe('calculateAgeOfMoney', () => {+ it('calculates age correctly with simple FIFO matching', () => {+ const income: Transaction[] = [+ { id: '1', date: '2024-01-01', amount: 1000 },+ ];+ const expenses: Transaction[] = [+ { id: '2', date: '2024-01-15', amount: -500 },+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(1);+ expect(result.ages[0].age).toBe(14); // 14 days between Jan 1 and Jan 15+ expect(result.insufficientData).toBe(false);+ });++ it('uses FIFO order - oldest income first', () => {+ const income: Transaction[] = [+ { id: '1', date: '2024-01-01', amount: 500 },+ { id: '2', date: '2024-01-15', amount: 500 },+ ];+ const expenses: Transaction[] = [+ { id: '3', date: '2024-02-01', amount: -400 },+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(1);+ // Should use Jan 1 income (oldest), so age is 31 days+ expect(result.ages[0].age).toBe(31);+ });++ it('spans multiple income buckets for large expenses', () => {+ const income: Transaction[] = [+ { id: '1', date: '2024-01-01', amount: 200 },+ { id: '2', date: '2024-01-15', amount: 300 },+ ];+ const expenses: Transaction[] = [+ { id: '3', date: '2024-02-01', amount: -400 },+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(1);+ // Expense spans both buckets, uses last bucket date (Jan 15)+ // Age = Feb 1 - Jan 15 = 17 days+ expect(result.ages[0].age).toBe(17);+ });++ it('handles multiple expenses consuming buckets sequentially', () => {+ const income: Transaction[] = [+ { id: '1', date: '2024-01-01', amount: 1000 },+ ];+ const expenses: Transaction[] = [+ { id: '2', date: '2024-01-10', amount: -300 },+ { id: '3', date: '2024-01-20', amount: -300 },+ { id: '4', date: '2024-01-30', amount: -300 },+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(3);+ expect(result.ages[0].age).toBe(9); // Jan 10 - Jan 1+ expect(result.ages[1].age).toBe(19); // Jan 20 - Jan 1+ expect(result.ages[2].age).toBe(29); // Jan 30 - Jan 1+ expect(result.insufficientData).toBe(false);+ });++ it('flags insufficient data when expenses exceed income', () => {+ const income: Transaction[] = [+ { id: '1', date: '2024-01-01', amount: 100 },+ ];+ const expenses: Transaction[] = [+ { id: '2', date: '2024-01-15', amount: -500 },+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.insufficientData).toBe(true);+ });++ it('returns empty ages array when no income', () => {+ const income: Transaction[] = [];+ const expenses: Transaction[] = [+ { id: '1', date: '2024-01-15', amount: -500 },+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(0);+ expect(result.insufficientData).toBe(true);+ });++ it('returns empty ages array when no expenses', () => {+ const income: Transaction[] = [+ { id: '1', date: '2024-01-01', amount: 1000 },+ ];+ const expenses: Transaction[] = [];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(0);+ expect(result.insufficientData).toBe(false);+ });++ it('handles income and expenses on the same day (age = 0)', () => {+ const income: Transaction[] = [+ { id: '1', date: '2024-01-15', amount: 1000 },+ ];+ const expenses: Transaction[] = [+ { id: '2', date: '2024-01-15', amount: -500 },+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(1);+ expect(result.ages[0].age).toBe(0);+ });++ it('sorts transactions by date regardless of input order', () => {+ const income: Transaction[] = [+ { id: '2', date: '2024-01-15', amount: 500 },+ { id: '1', date: '2024-01-01', amount: 500 }, // Earlier but listed second+ ];+ const expenses: Transaction[] = [+ { id: '4', date: '2024-02-15', amount: -200 },+ { id: '3', date: '2024-02-01', amount: -200 }, // Earlier but listed second+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(2);+ // First expense (Feb 1) should use Jan 1 income+ expect(result.ages[0].date).toBe('2024-02-01');+ expect(result.ages[0].age).toBe(31);+ // Second expense (Feb 15) should continue from Jan 1 income+ expect(result.ages[1].date).toBe('2024-02-15');+ expect(result.ages[1].age).toBe(45);+ });+ });++ describe('calculateAverageAge', () => {+ it('returns null for empty array', () => {+ const result = calculateAverageAge([]);+ expect(result).toBeNull();+ });++ it('calculates average of all ages when less than count', () => {+ const ages = [+ { date: '2024-01-01', age: 10 },+ { date: '2024-01-02', age: 20 },+ { date: '2024-01-03', age: 30 },+ ];++ const result = calculateAverageAge(ages, 10);++ expect(result).toBe(20); // (10 + 20 + 30) / 3 = 20+ });++ it('calculates average of last N ages when more than count', () => {+ const ages = [+ { date: '2024-01-01', age: 5 },+ { date: '2024-01-02', age: 10 },+ { date: '2024-01-03', age: 15 },+ { date: '2024-01-04', age: 20 },+ { date: '2024-01-05', age: 25 },+ ];++ const result = calculateAverageAge(ages, 3);++ expect(result).toBe(20); // (15 + 20 + 25) / 3 = 20+ });++ it('rounds the result to nearest integer', () => {+ const ages = [+ { date: '2024-01-01', age: 10 },+ { date: '2024-01-02', age: 11 },+ ];++ const result = calculateAverageAge(ages, 10);++ expect(result).toBe(11); // (10 + 11) / 2 = 10.5, rounded to 11+ });++ it('uses default count of 10', () => {+ const ages = Array.from({ length: 15 }, (_, i) => ({+ date: `2024-01-${String(i + 1).padStart(2, '0')}`,+ age: (i + 1) * 10,+ }));++ const result = calculateAverageAge(ages);++ // Last 10 ages: 60, 70, 80, 90, 100, 110, 120, 130, 140, 150+ // Average: 105+ expect(result).toBe(105);+ });+ });++ describe('calculateTrend', () => {+ it('returns stable for empty data', () => {+ const result = calculateTrend([]);+ expect(result).toBe('stable');+ });++ it('returns stable for single data point', () => {+ const result = calculateTrend([{ date: 'Jan 2024', ageOfMoney: 30 }]);+ expect(result).toBe('stable');+ });++ it('returns up when age increased by more than threshold', () => {+ const data = [+ { date: 'Jan 2024', ageOfMoney: 20 },+ { date: 'Feb 2024', ageOfMoney: 25 },+ ];++ const result = calculateTrend(data);++ expect(result).toBe('up');+ });++ it('returns down when age decreased by more than threshold', () => {+ const data = [+ { date: 'Jan 2024', ageOfMoney: 30 },+ { date: 'Feb 2024', ageOfMoney: 25 },+ ];++ const result = calculateTrend(data);++ expect(result).toBe('down');+ });++ it('returns stable when change is within threshold', () => {+ const data = [+ { date: 'Jan 2024', ageOfMoney: 30 },+ { date: 'Feb 2024', ageOfMoney: 31 },+ ];++ const result = calculateTrend(data);++ expect(result).toBe('stable'); // Threshold is 2, diff is 1+ });++ it('uses only the last two data points', () => {+ const data = [+ { date: 'Jan 2024', ageOfMoney: 10 },+ { date: 'Feb 2024', ageOfMoney: 50 },+ { date: 'Mar 2024', ageOfMoney: 30 },+ { date: 'Apr 2024', ageOfMoney: 35 },+ ];++ const result = calculateTrend(data);++ // Only compares Apr (35) to Mar (30), diff = 5 > 2+ expect(result).toBe('up');+ });+ });++ describe('classifyTransactions', () => {+ it('classifies positive amount with income category as income', () => {+ const transactions: TransactionWithCategory[] = [+ { id: '1', date: '2024-01-01', amount: 1000, categoryIsIncome: true },+ ];++ const { income, expenses } = classifyTransactions(transactions);++ expect(income).toHaveLength(1);+ expect(income[0].amount).toBe(1000);+ expect(expenses).toHaveLength(0);+ });++ it('classifies positive amount without income category (refund) as income', () => {+ const transactions: TransactionWithCategory[] = [+ // This is a refund - positive amount but NOT an income category+ // For AoM purposes, refunds are treated as income (money entering your pool)+ { id: '1', date: '2024-01-15', amount: 50, categoryIsIncome: false },+ ];++ const { income, expenses } = classifyTransactions(transactions);++ expect(income).toHaveLength(1);+ expect(income[0].amount).toBe(50);+ expect(expenses).toHaveLength(0);+ });++ it('classifies negative amount as expense regardless of category', () => {+ const transactions: TransactionWithCategory[] = [+ { id: '1', date: '2024-01-10', amount: -200, categoryIsIncome: false },+ ];++ const { income, expenses } = classifyTransactions(transactions);++ expect(income).toHaveLength(0);+ expect(expenses).toHaveLength(1);+ expect(expenses[0].amount).toBe(-200);+ });++ it('correctly separates mixed transactions', () => {+ const transactions: TransactionWithCategory[] = [+ // Salary - income category+ { id: '1', date: '2024-01-01', amount: 3000, categoryIsIncome: true },+ // Groceries - expense+ { id: '2', date: '2024-01-05', amount: -150, categoryIsIncome: false },+ // Refund from store - positive but NOT income category (still income for AoM)+ { id: '3', date: '2024-01-10', amount: 25, categoryIsIncome: false },+ // Freelance work - income category+ { id: '4', date: '2024-01-15', amount: 500, categoryIsIncome: true },+ // Rent - expense+ { id: '5', date: '2024-01-20', amount: -1200, categoryIsIncome: false },+ ];++ const { income, expenses } = classifyTransactions(transactions);++ // All positive amounts are income (including refunds)+ expect(income).toHaveLength(3);+ expect(income.map(t => t.id)).toEqual(['1', '3', '4']);++ // Only negative amounts are expenses+ expect(expenses).toHaveLength(2);+ expect(expenses.map(t => t.id)).toEqual(['2', '5']);+ });++ it('handles uncategorized transactions based on amount sign', () => {+ const transactions: TransactionWithCategory[] = [+ { id: '1', date: '2024-01-01', amount: 100, categoryIsIncome: null },+ { id: '2', date: '2024-01-02', amount: -50, categoryIsIncome: null },+ ];++ const { income, expenses } = classifyTransactions(transactions);++ // Positive amount = income, negative = expense (regardless of category)+ expect(income).toHaveLength(1);+ expect(income[0].id).toBe('1');+ expect(expenses).toHaveLength(1);+ expect(expenses[0].id).toBe('2');+ });++ it('demonstrates refund impact on Age of Money calculation', () => {+ // Scenario: $1000 income on Jan 1, $50 refund on Jan 5, $200 expense on Jan 15+ // The refund ADDS to the income pool as a new bucket+ const transactions: TransactionWithCategory[] = [+ { id: '1', date: '2024-01-01', amount: 1000, categoryIsIncome: true },+ { id: '2', date: '2024-01-05', amount: 50, categoryIsIncome: false }, // Refund+ { id: '3', date: '2024-01-15', amount: -200, categoryIsIncome: false },+ ];++ const { income, expenses } = classifyTransactions(transactions);++ // Refund is classified as income+ expect(income).toHaveLength(2);+ expect(income.map(t => t.id)).toEqual(['1', '2']);++ // Only the negative transaction is an expense+ expect(expenses).toHaveLength(1);+ expect(expenses[0].id).toBe('3');++ // Calculate age using the properly classified transactions+ const result = calculateAgeOfMoney(income, expenses);++ // The $200 expense on Jan 15 draws from the oldest income (Jan 1)+ // Age = Jan 15 - Jan 1 = 14 days+ expect(result.ages).toHaveLength(1);+ expect(result.ages[0].date).toBe('2024-01-15');+ expect(result.ages[0].age).toBe(14);+ });+ });++ describe('formatPeriodLabel', () => {+ it('includes year for daily granularity to avoid duplicates across years', () => {+ // The same calendar day in different years must produce different labels,+ // otherwise recharts highlights the wrong dot (first occurrence)+ const label2024 = formatPeriodLabel('2024-03-15', 'daily');+ const label2025 = formatPeriodLabel('2025-03-15', 'daily');++ expect(label2024).not.toBe(label2025);+ });++ it('includes year for weekly granularity to avoid duplicates across years', () => {+ const label2024 = formatPeriodLabel('2024-03-11', 'weekly');+ const label2025 = formatPeriodLabel('2025-03-10', 'weekly');++ expect(label2024).not.toBe(label2025);+ });++ it('includes year for monthly granularity', () => {+ const label = formatPeriodLabel('2024-03', 'monthly');++ expect(label).toContain('2024');+ });+ });++ describe('calculateGraphData - multi-year daily', () => {+ // NOTE: in tests `monthUtils.currentDay()` is hardcoded to '2017-01-01'+ // (loot-core/src/shared/months.ts:155). The fix for daily/weekly mode+ // clamps the end date to today, so test data here uses dates before+ // 2017-01-01 to keep the multi-year scenarios in range.++ it('produces unique date labels across years with daily granularity', () => {+ // Create ages spanning two years with the same calendar day+ const ages = [+ { date: '2015-03-15', age: 30 },+ { date: '2016-03-15', age: 45 },+ ];++ const graphData = calculateGraphData(ages, '2015-03', '2016-03', 'daily');++ // Find all entries for March 15 in different years+ const mar15entries = graphData.filter(d => d.date.includes('Mar 15'));++ // There should be exactly 2 entries for Mar 15 (one per year)+ expect(mar15entries).toHaveLength(2);++ // And they must have DIFFERENT date labels (otherwise recharts highlights wrong dot)+ expect(mar15entries[0].date).not.toBe(mar15entries[1].date);+ });++ it('does not produce duplicate date labels in daily mode over 2 years', () => {+ // Generate ages for the same day in two consecutive years+ const ages = [+ { date: '2015-06-01', age: 20 },+ { date: '2015-12-15', age: 25 },+ { date: '2016-06-01', age: 35 },+ ];++ const graphData = calculateGraphData(ages, '2015-06', '2016-06', 'daily');++ // Check that all date labels are unique+ const dateLabels = graphData.map(d => d.date);+ const uniqueLabels = new Set(dateLabels);+ expect(uniqueLabels.size).toBe(dateLabels.length);+ });+ });++ describe('off-budget transfers affect Age of Money', () => {+ // These tests demonstrate how including off-budget transfers in the+ // calculation changes the result. The queries now include transfers+ // to/from off-budget accounts (e.g. investment, savings accounts+ // tracked outside the budget) because Actual treats them as+ // categorized spending/income.++ it('transfer to off-budget counts as spending and consumes income buckets', () => {+ // Scenario:+ // Jan 1: Paycheck +$2000 (income)+ // Jan 20: Transfer -$500 to investment account (off-budget)+ // Feb 1: Groceries -$300+ //+ // The $500 transfer to off-budget is real spending (it leaves the+ // budget). It draws from the Jan 1 income bucket first (FIFO).+ //+ // Without off-budget transfers: only the $300 groceries would be+ // counted, giving age = 31 days (Feb 1 - Jan 1).+ //+ // With off-budget transfers: the $500 transfer on Jan 20 also+ // draws from the Jan 1 bucket, giving age = 19 days (Jan 20 - Jan 1).+ // Then groceries on Feb 1 draws from the remaining Jan 1 income,+ // giving age = 31 days.++ const income: Transaction[] = [+ { id: 'paycheck', date: '2024-01-01', amount: 2000 },+ ];++ // With off-budget transfer included as spending+ const expensesWithTransfer: Transaction[] = [+ { id: 'to-investment', date: '2024-01-20', amount: -500 },+ { id: 'groceries', date: '2024-02-01', amount: -300 },+ ];++ // Without off-budget transfer (old behavior)+ const expensesWithoutTransfer: Transaction[] = [+ { id: 'groceries', date: '2024-02-01', amount: -300 },+ ];++ const withTransfer = calculateAgeOfMoney(income, expensesWithTransfer);+ const withoutTransfer = calculateAgeOfMoney(+ income,+ expensesWithoutTransfer,+ );++ // With transfer: two ages calculated+ expect(withTransfer.ages).toHaveLength(2);+ expect(withTransfer.ages[0]).toEqual({+ date: '2024-01-20',+ age: 19, // Jan 20 - Jan 1+ });+ expect(withTransfer.ages[1]).toEqual({+ date: '2024-02-01',+ age: 31, // Feb 1 - Jan 1 (still drawing from same bucket)+ });++ // Without transfer: only one age+ expect(withoutTransfer.ages).toHaveLength(1);+ expect(withoutTransfer.ages[0]).toEqual({+ date: '2024-02-01',+ age: 31, // Feb 1 - Jan 1+ });++ // The average age is lower when off-budget spending is included+ // because the transfer consumes time from the pool+ const avgWith = calculateAverageAge(withTransfer.ages);+ const avgWithout = calculateAverageAge(withoutTransfer.ages);+ expect(avgWith).toBe(25); // (19 + 31) / 2+ expect(avgWithout).toBe(31); // 31 / 1+ });++ it('transfer from off-budget counts as income and creates a new bucket', () => {+ // Scenario:+ // Jan 1: Paycheck +$1000 (income)+ // Jan 15: Transfer +$2000 from savings (off-budget → on-budget)+ // Feb 10: Rent -$1500+ //+ // The $2000 transfer from off-budget enters the budget as new+ // income, creating a bucket dated Jan 15.+ //+ // Without off-budget transfers: only $1000 income on Jan 1.+ // The $1500 rent exceeds the $1000 bucket → insufficient data.+ //+ // With off-budget transfers: $1000 (Jan 1) + $2000 (Jan 15).+ // Rent draws $1000 from Jan 1 bucket, then $500 from Jan 15 bucket.+ // Age = Jan 15 (last bucket used) to Feb 10 = 26 days.++ const incomeWithTransfer: Transaction[] = [+ { id: 'paycheck', date: '2024-01-01', amount: 1000 },+ { id: 'from-savings', date: '2024-01-15', amount: 2000 },+ ];++ const incomeWithoutTransfer: Transaction[] = [+ { id: 'paycheck', date: '2024-01-01', amount: 1000 },+ ];++ const expenses: Transaction[] = [+ { id: 'rent', date: '2024-02-10', amount: -1500 },+ ];++ const withTransfer = calculateAgeOfMoney(incomeWithTransfer, expenses);+ const withoutTransfer = calculateAgeOfMoney(+ incomeWithoutTransfer,+ expenses,+ );++ // With transfer: rent spans two buckets, uses Jan 15 date+ expect(withTransfer.ages).toHaveLength(1);+ expect(withTransfer.ages[0]).toEqual({+ date: '2024-02-10',+ age: 26, // Feb 10 - Jan 15 (last bucket used)+ });+ expect(withTransfer.insufficientData).toBe(false);++ // Without transfer: only $1000 income can't fully cover $1500 rent+ expect(withoutTransfer.ages).toHaveLength(1);+ expect(withoutTransfer.ages[0]).toEqual({+ date: '2024-02-10',+ age: 40, // Feb 10 - Jan 1 (only bucket, partially covers)+ });+ expect(withoutTransfer.insufficientData).toBe(true);+ });++ it('round-trip: money leaves to off-budget and returns later', () => {+ // Scenario:+ // Jan 1: Paycheck +$3000 (income)+ // Jan 10: Transfer -$1000 to investment (off-budget spending)+ // Mar 1: Transfer +$1000 from investment (off-budget income)+ // Mar 15: Groceries -$2500+ //+ // The $1000 that went to investment on Jan 10 consumed from the+ // Jan 1 bucket. When it returns on Mar 1, it creates a NEW bucket+ // dated Mar 1 (it's younger money now).+ //+ // Groceries on Mar 15:+ // - Draw $2000 remaining from Jan 1 bucket (exhausts it)+ // - Draw $500 from Mar 1 bucket+ // - Age = Mar 15 - Mar 1 = 14 days (last bucket date used)+ //+ // Without the round-trip (no transfers, just $3000 income + $2500 expense):+ // Groceries would draw entirely from Jan 1 → age = 73 days.+ // The round-trip lowers the grocery age from 73 to 14 because the+ // returned money creates a younger bucket (Mar 1 vs Jan 1).++ const income: Transaction[] = [+ { id: 'paycheck', date: '2024-01-01', amount: 3000 },+ { id: 'from-investment', date: '2024-03-01', amount: 1000 },+ ];+ const expenses: Transaction[] = [+ { id: 'to-investment', date: '2024-01-10', amount: -1000 },+ { id: 'groceries', date: '2024-03-15', amount: -2500 },+ ];++ const result = calculateAgeOfMoney(income, expenses);++ expect(result.ages).toHaveLength(2);+ // Transfer to investment: draws from Jan 1 bucket+ expect(result.ages[0]).toEqual({+ date: '2024-01-10',+ age: 9, // Jan 10 - Jan 1+ });+ // Groceries: draws $2000 from Jan 1, $500 from Mar 1+ // Uses last bucket date (Mar 1)+ expect(result.ages[1]).toEqual({+ date: '2024-03-15',+ age: 14, // Mar 15 - Mar 1+ });++ expect(result.insufficientData).toBe(false);+ });+ });++ describe('calculateGraphData - clamps end date to today', () => {+ // In tests, monthUtils.currentDay() is hardcoded to '2017-01-01'+ // (see packages/loot-core/src/shared/months.ts:155). The tests below+ // exploit that fixed "today" to verify daily/weekly granularities do+ // not generate periods that extend past it.++ it('does not generate daily periods past today', () => {+ // End month spans into the future (Jan 2017 is the test "today" month+ // and would otherwise produce 31 daily entries through Jan 31).+ const ages = [+ { date: '2016-12-15', age: 5 },+ { date: '2016-12-31', age: 10 },+ { date: '2017-01-01', age: 12 },+ ];++ const graphData = calculateGraphData(ages, '2016-12', '2017-01', 'daily');++ // Rolling-avg rows are emitted from the first day with data onward.+ // With the clamp: Dec 15..31 (17 days) + Jan 1 (1 day) = 18 rows.+ // Without the clamp: 17 + 31 = 48 rows.+ expect(graphData).toHaveLength(18);++ // The very last entry must be Jan 1 (today), not Jan 2 or later.+ const lastLabel = graphData[graphData.length - 1].date;+ expect(lastLabel).toBe(formatPeriodLabel('2017-01-01', 'daily'));+ });++ it('does not generate weekly periods past today', () => {+ // End month spans well into the future. Without the clamp this would+ // generate weekly buckets through the end of February.+ const ages = [+ { date: '2016-12-15', age: 5 },+ { date: '2017-01-01', age: 12 },+ ];++ const graphData = calculateGraphData(+ ages,+ '2016-12',+ '2017-02',+ 'weekly',+ );++ // Today (2017-01-01) falls in the week starting Mon Dec 26, 2016.+ // With the clamp, generated weeks are: Nov 28, Dec 5, Dec 12, Dec 19,+ // Dec 26 → 5 weeks. Rows are emitted starting from Dec 12 (first+ // week with data) → 3 rows: Dec 12, Dec 19, Dec 26.+ expect(graphData).toHaveLength(3);++ // Last entry must be the week containing today, not a later week.+ const lastLabel = graphData[graphData.length - 1].date;+ expect(lastLabel).toBe(formatPeriodLabel('2016-12-26', 'weekly'));+ });++ it('still includes the current month for monthly granularity', () => {+ // Monthly granularity intentionally keeps the current month visible+ // even if it isn't over yet — this matches user expectations and+ // mirrors how other monthly reports behave.+ const ages = [+ { date: '2016-12-15', age: 8 },+ { date: '2017-01-01', age: 10 },+ ];++ const graphData = calculateGraphData(+ ages,+ '2016-12',+ '2017-01',+ 'monthly',+ );++ // Two months: Dec 2016 and Jan 2017. The Jan entry must still appear.+ expect(graphData).toHaveLength(2);+ expect(graphData[1].date).toBe(formatPeriodLabel('2017-01', 'monthly'));+ });+ });+});diff --git a/packages/desktop-client/src/components/reports/spreadsheets/age-of-money-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/age-of-money-spreadsheet.tsnew file mode 100644index 0000000000..2fccf5a812--- /dev/null+++ b/packages/desktop-client/src/components/reports/spreadsheets/age-of-money-spreadsheet.ts@@ -0,0 +1,416 @@+import * as d from 'date-fns';++import { send } from 'loot-core/platform/client/connection';+import * as monthUtils from 'loot-core/shared/months';+import { q } from 'loot-core/shared/query';+import type {+ AgeOfMoneyGranularity,+ RuleConditionEntity,+} from 'loot-core/types/models';++import { runAll } from '@desktop-client/components/reports/util';+import type { useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';++export type AgeOfMoneyData = {+ graphData: Array<{+ date: string; // Month label (e.g., "Jan 2024")+ ageOfMoney: number; // Days+ }>;+ currentAge: number | null; // Current AoM in days, null if no data+ trend: 'up' | 'down' | 'stable';+ insufficientData: boolean; // True if not enough income to cover expenses+};++type IncomeBucket = {+ date: string;+ remainingAmount: number;+};++export type Transaction = {+ id: string;+ date: string;+ amount: number;+};++export type TransactionWithCategory = Transaction & {+ categoryIsIncome: boolean | null;+};++/**+ * Classify transactions into income and expenses based on amount sign.+ * Income = positive amounts (including refunds - money entering your pool)+ * Expenses = negative amounts+ *+ * Note: We use amount-based classification for Age of Money because+ * refunds (positive amounts without income category) should still add+ * to the money pool. The categoryIsIncome field is preserved for+ * potential future use but not used for this classification.+ */+export function classifyTransactions(transactions: TransactionWithCategory[]): {+ income: Transaction[];+ expenses: Transaction[];+} {+ const income: Transaction[] = [];+ const expenses: Transaction[] = [];++ for (const t of transactions) {+ if (t.amount > 0) {+ income.push({ id: t.id, date: t.date, amount: t.amount });+ } else {+ expenses.push({ id: t.id, date: t.date, amount: t.amount });+ }+ }++ return { income, expenses };+}++/**+ * Calculate the age of money for a given set of expense transactions+ * using the FIFO (First In, First Out) method.+ *+ * Income becomes "buckets" sorted by date. When money is spent,+ * it's deducted from the oldest bucket first. The age is the+ * difference between the expense date and the bucket date.+ */+export function calculateAgeOfMoney(+ incomeTransactions: Transaction[],+ expenseTransactions: Transaction[],+): { ages: Array<{ date: string; age: number }>; insufficientData: boolean } {+ // Sort income by date ascending (oldest first)+ const sortedIncome = [...incomeTransactions].sort((a, b) =>+ a.date.localeCompare(b.date),+ );++ // Create income buckets+ const buckets: IncomeBucket[] = sortedIncome.map(t => ({+ date: t.date,+ remainingAmount: t.amount, // Income is positive+ }));++ // Sort expenses by date ascending+ const sortedExpenses = [...expenseTransactions].sort((a, b) =>+ a.date.localeCompare(b.date),+ );++ const ages: Array<{ date: string; age: number }> = [];+ let currentBucketIdx = 0;+ let insufficientData = false;++ for (const expense of sortedExpenses) {+ // Expense amounts are negative, so we work with absolute value+ let remainingExpense = Math.abs(expense.amount);+ let lastBucketDate: string | null = null;++ // Deduct from oldest buckets with remaining balance+ while (remainingExpense > 0 && currentBucketIdx < buckets.length) {+ const bucket = buckets[currentBucketIdx];++ if (bucket.remainingAmount > 0) {+ const deduction = Math.min(bucket.remainingAmount, remainingExpense);+ bucket.remainingAmount -= deduction;+ remainingExpense -= deduction;+ lastBucketDate = bucket.date;+ }++ // Move to next bucket if current is exhausted+ if (bucket.remainingAmount <= 0) {+ currentBucketIdx++;+ }+ }++ // If we couldn't fully cover the expense, we have insufficient data+ if (remainingExpense > 0) {+ insufficientData = true;+ // Continue processing but note the issue+ }++ // Calculate age if we had a bucket to draw from+ if (lastBucketDate) {+ const expenseDate = d.parseISO(expense.date);+ const bucketDate = d.parseISO(lastBucketDate);+ const ageInDays = d.differenceInDays(expenseDate, bucketDate);+ ages.push({ date: expense.date, age: Math.max(0, ageInDays) });+ }+ }++ return { ages, insufficientData };+}++/**+ * Calculate the average of the last N ages+ */+export function calculateAverageAge(+ ages: Array<{ date: string; age: number }>,+ count: number = 10,+): number | null {+ if (ages.length === 0) return null;++ const lastN = ages.slice(-count);+ const sum = lastN.reduce((acc, item) => acc + item.age, 0);+ return Math.round(sum / lastN.length);+}++/**+ * Get the period key for a given date based on granularity+ */+export function getPeriodKey(+ date: string,+ granularity: AgeOfMoneyGranularity,+): string {+ const parsed = d.parseISO(date);+ switch (granularity) {+ case 'daily':+ return date; // YYYY-MM-DD+ case 'weekly': {+ // Use start of week (Monday) as key+ const weekStart = d.startOfWeek(parsed, { weekStartsOn: 1 });+ return d.format(weekStart, 'yyyy-MM-dd');+ }+ case 'monthly':+ default:+ return monthUtils.getMonth(date); // YYYY-MM+ }+}++/**+ * Format a period key for display based on granularity+ */+export function formatPeriodLabel(+ periodKey: string,+ granularity: AgeOfMoneyGranularity,+): string {+ switch (granularity) {+ case 'daily':+ return d.format(d.parseISO(periodKey), 'MMM d, yyyy');+ case 'weekly':+ return d.format(d.parseISO(periodKey), 'MMM d, yyyy');+ case 'monthly':+ default:+ return d.format(d.parseISO(periodKey + '-01'), 'MMM yyyy');+ }+}++/**+ * Generate all periods between start and end based on granularity+ */+export function generatePeriods(+ startDate: string,+ endDate: string,+ granularity: AgeOfMoneyGranularity,+): string[] {+ const periods: string[] = [];+ let current = d.parseISO(startDate);+ const end = d.parseISO(endDate);++ switch (granularity) {+ case 'daily':+ while (current <= end) {+ periods.push(d.format(current, 'yyyy-MM-dd'));+ current = d.addDays(current, 1);+ }+ break;+ case 'weekly':+ // Start from the beginning of the week containing startDate+ current = d.startOfWeek(current, { weekStartsOn: 1 });+ while (current <= end) {+ periods.push(d.format(current, 'yyyy-MM-dd'));+ current = d.addWeeks(current, 1);+ }+ break;+ case 'monthly':+ default: {+ const months = monthUtils.rangeInclusive(+ monthUtils.getMonth(startDate),+ monthUtils.getMonth(endDate),+ );+ return months;+ }+ }++ return periods;+}++/**+ * Group ages by period and calculate rolling average for each period+ */+export function calculateGraphData(+ ages: Array<{ date: string; age: number }>,+ startMonth: string,+ endMonth: string,+ granularity: AgeOfMoneyGranularity = 'monthly',+): Array<{ date: string; ageOfMoney: number }> {+ const startDate = monthUtils.firstDayOfMonth(startMonth);+ let endDate = monthUtils.lastDayOfMonth(endMonth);++ // For daily/weekly granularities, don't generate periods past today —+ // future days/weeks would otherwise carry forward the last rolling+ // average and show as a flat horizontal line for the rest of the month.+ // Monthly granularity intentionally keeps the current month visible.+ if (granularity === 'daily' || granularity === 'weekly') {+ const today = monthUtils.currentDay();+ if (monthUtils.isAfter(endDate, today)) {+ endDate = today;+ }+ }++ const periods = generatePeriods(startDate, endDate, granularity);+ const result: Array<{ date: string; ageOfMoney: number }> = [];++ // Group ages by period+ const agesByPeriod: Record<string, number[]> = {};+ for (const { date, age } of ages) {+ const periodKey = getPeriodKey(date, granularity);+ if (!agesByPeriod[periodKey]) {+ agesByPeriod[periodKey] = [];+ }+ agesByPeriod[periodKey].push(age);+ }++ // Calculate cumulative rolling average (last 10 expenses up to each period)+ let allAgesUpToPeriod: number[] = [];++ for (const period of periods) {+ // Add ages from this period+ if (agesByPeriod[period]) {+ allAgesUpToPeriod = allAgesUpToPeriod.concat(agesByPeriod[period]);+ }++ // Calculate average of last 10 ages+ if (allAgesUpToPeriod.length > 0) {+ const lastN = allAgesUpToPeriod.slice(-10);+ const avg = Math.round(lastN.reduce((a, b) => a + b, 0) / lastN.length);+ result.push({+ date: formatPeriodLabel(period, granularity),+ ageOfMoney: avg,+ });+ }+ }++ return result;+}++/**+ * Determine the trend based on the last few data points+ */+export function calculateTrend(+ graphData: Array<{ date: string; ageOfMoney: number }>,+): 'up' | 'down' | 'stable' {+ if (graphData.length < 2) return 'stable';++ const last = graphData[graphData.length - 1].ageOfMoney;+ const secondLast = graphData[graphData.length - 2].ageOfMoney;++ const diff = last - secondLast;+ const threshold = 2; // Days threshold for "stable"++ if (diff > threshold) return 'up';+ if (diff < -threshold) return 'down';+ return 'stable';+}++export type AgeOfMoneyParams = {+ start: string;+ end: string;+ conditions?: RuleConditionEntity[];+ conditionsOp?: 'and' | 'or';+ granularity?: AgeOfMoneyGranularity;+};++export function createAgeOfMoneySpreadsheet({+ start,+ end,+ conditions = [],+ conditionsOp = 'and',+ granularity = 'monthly',+}: AgeOfMoneyParams) {+ return async (+ spreadsheet: ReturnType<typeof useSpreadsheet>,+ setData: (data: AgeOfMoneyData) => void,+ ) => {+ const endDate = monthUtils.lastDayOfMonth(end);+ const today = monthUtils.currentDay();+ const fixedEnd = endDate > today ? today : endDate;++ const { filters } = await send('make-filters-from-conditions', {+ conditions: conditions.filter(cond => !cond.customName),+ });+ const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';++ // Query for ALL income transactions up to the end date+ // FIFO requires complete income history to calculate ages correctly+ // Includes: regular income + transfers from off-budget accounts (money entering budget)+ // Excludes: on-budget-to-on-budget transfers (just moving money between accounts)+ function makeIncomeQuery() {+ return q('transactions')+ .filter({+ [conditionsOpKey]: filters,+ })+ .filter({+ date: { $lte: fixedEnd },+ 'account.offbudget': false,+ $or: [+ { 'payee.transfer_acct': null },+ { 'payee.transfer_acct.offbudget': true },+ ],+ amount: { $gt: 0 },+ })+ .select(['id', 'date', 'amount']);+ }++ // Query for ALL expense transactions up to the end date+ // FIFO requires complete expense history to properly consume income buckets+ // Includes: regular expenses + transfers to off-budget accounts (categorized spending)+ // Excludes: on-budget-to-on-budget transfers (just moving money between accounts)+ function makeExpenseQuery() {+ return q('transactions')+ .filter({+ [conditionsOpKey]: filters,+ })+ .filter({+ date: { $lte: fixedEnd },+ 'account.offbudget': false,+ $or: [+ { 'payee.transfer_acct': null },+ { 'payee.transfer_acct.offbudget': true },+ ],+ amount: { $lt: 0 },+ })+ .select(['id', 'date', 'amount']);+ }++ return runAll([makeIncomeQuery(), makeExpenseQuery()], data => {+ const [incomeData, expenseData] = data as [Transaction[], Transaction[]];++ // Calculate ages using FIFO method on ALL historical data+ const { ages, insufficientData } = calculateAgeOfMoney(+ incomeData,+ expenseData,+ );++ // Filter ages to only those within the display range+ const displayStart = monthUtils.firstDayOfMonth(start);+ const filteredAges = ages.filter(({ date }) => date >= displayStart);++ // Generate graph data from filtered ages with specified granularity+ const graphData = calculateGraphData(+ filteredAges,+ start,+ end,+ granularity,+ );++ // Calculate current age from ages within the display range+ const currentAge = calculateAverageAge(filteredAges, 10);++ // Determine trend+ const trend = calculateTrend(graphData);++ setData({+ graphData,+ currentAge,+ trend,+ insufficientData,+ });+ });+ };+}diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsxindex 8a709d7747..414ae1de61 100644--- a/packages/desktop-client/src/components/settings/Experimental.tsx+++ b/packages/desktop-client/src/components/settings/Experimental.tsx@@ -208,6 +208,12 @@ export function ExperimentalFeatures() {><Trans>Crossover Report</Trans></FeatureToggle>+ <FeatureToggle+ flag="ageOfMoneyReport"+ feedbackLink="https://github.com/actualbudget/actual/issues/2994"+ >+ <Trans>Age of Money Report</Trans>+ </FeatureToggle><FeatureToggleflag="customThemes"feedbackLink="https://github.com/actualbudget/actual/issues/6607"diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.tsindex 643eabf2a2..793e48be16 100644--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts@@ -9,6 +9,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {formulaMode: false,currency: false,crossoverReport: false,+ ageOfMoneyReport: false,customThemes: false,budgetAnalysisReport: false,payeeLocations: false,diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex a3eec2e969..4fc92fe9f6 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -105,6 +105,19 @@ export type MarkdownWidget = AbstractWidget<{ content: string; text_align?: 'left' | 'right' | 'center' }>;+export type AgeOfMoneyGranularity = 'daily' | 'weekly' | 'monthly';++export type AgeOfMoneyWidget = AbstractWidget<+ 'age-of-money-card',+ {+ name?: string;+ conditions?: RuleConditionEntity[];+ conditionsOp?: 'and' | 'or';+ timeFrame?: TimeFrame;+ granularity?: AgeOfMoneyGranularity;+ } | null+>;+type SpecializedWidget =| NetWorthWidget| CashFlowWidget@@ -115,7 +128,8 @@ type SpecializedWidget =| SummaryWidget| CalendarWidget| FormulaWidget- | SankeyWidget;+ | SankeyWidget+ | AgeOfMoneyWidget;export type DashboardWidgetEntity = SpecializedWidget | CustomReportWidget;export type NewDashboardWidgetEntity = Omit<DashboardWidgetEntity,diff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.tsindex 4bc02d92e9..8ac7256d52 100644--- a/packages/loot-core/src/types/prefs.ts+++ b/packages/loot-core/src/types/prefs.ts@@ -5,6 +5,7 @@ export type FeatureFlag =| 'formulaMode'| 'currency'| 'crossoverReport'+ | 'ageOfMoneyReport'| 'customThemes'| 'budgetAnalysisReport'| 'payeeLocations'diff --git a/upcoming-release-notes/6685.md b/upcoming-release-notes/6685.mdnew file mode 100644index 0000000000..29334f8837--- /dev/null+++ b/upcoming-release-notes/6685.md@@ -0,0 +1,6 @@+---+category: Features+authors: [sztomi]+---++Added Age of Money report.