Skip to content

A local-first personal finance app

[AI] Keep net worth stable across transfer dates (#8829)

Sam Bai1e1c20358279
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.test.ts b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.test.ts
new file mode 100644
index 0000000000..1889d685ec
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.test.ts
@@ -0,0 +1,376 @@
+import {
+ clearServer,
+ initServer,
+} from '@actual-app/core/platform/client/connection';
+import type { AccountEntity } from '@actual-app/core/types/models';
+import { enUS } from 'date-fns/locale';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createSpreadsheet } from './net-worth-spreadsheet';
+
+vi.mock(
+ '@actual-app/core/platform/client/connection',
+ () => import('#mocks/connection'),
+);
+
+type SpreadsheetData = Parameters<
+ Parameters<ReturnType<typeof createSpreadsheet>>[1]
+>[0];
+
+type LinkedTransfer = {
+ id: string;
+ account: string;
+ amount: number;
+ date: string;
+ transfer_id: string;
+};
+
+type AccountQueryResult = number | Array<{ date: string; amount: number }>;
+
+const accounts = [
+ createAccount('checking', 'Checking'),
+ createAccount('savings', 'Savings'),
+] satisfies AccountEntity[];
+
+function createAccount(id: string, name: string): AccountEntity {
+ return {
+ id,
+ name,
+ offbudget: 0,
+ closed: 0,
+ sort_order: 0,
+ last_reconciled: null,
+ tombstone: 0,
+ account_group_id: null,
+ account_id: null,
+ bank: null,
+ bankName: null,
+ bankId: null,
+ mask: null,
+ official_name: null,
+ balance_current: null,
+ balance_available: null,
+ balance_limit: null,
+ account_sync_source: null,
+ last_sync: null,
+ bank_sync_status: null,
+ };
+}
+
+async function runReport({
+ accounts,
+ accountQueryResults,
+ linkedTransfers = [],
+ start = '2026-07',
+ end = '2026-08',
+ interval = 'Monthly',
+ earliestTransactionDate = '2026-07-01',
+}: {
+ accounts: AccountEntity[];
+ accountQueryResults: AccountQueryResult[];
+ linkedTransfers?: LinkedTransfer[];
+ start?: string;
+ end?: string;
+ interval?: string;
+ earliestTransactionDate?: string;
+}) {
+ const remainingAccountResults = [...accountQueryResults];
+
+ initServer({
+ 'make-filters-from-conditions': async () => ({ filters: [] }),
+ 'get-earliest-transaction': async () => ({
+ date: earliestTransactionDate,
+ }),
+ query: async query => {
+ if (query.selectExpressions.includes('transfer_id')) {
+ const transferFilter = query.filterExpressions.find(
+ expression => 'transfer_id' in expression,
+ );
+ const accountIds = getOneOfValues(transferFilter?.account);
+ const transactionIds = getOneOfValues(transferFilter?.id);
+ const endDate = getUpperBound(transferFilter?.date);
+
+ return {
+ data: linkedTransfers.filter(
+ leg =>
+ (accountIds.length === 0 || accountIds.includes(leg.account)) &&
+ (transactionIds.length === 0 ||
+ transactionIds.includes(leg.id)) &&
+ (!endDate || leg.date <= endDate),
+ ),
+ dependencies: [],
+ };
+ }
+
+ const data = remainingAccountResults.shift();
+ if (data === undefined) {
+ throw new Error('Unexpected account query');
+ }
+ return { data, dependencies: [] };
+ },
+ });
+
+ let report: SpreadsheetData | undefined;
+ const spreadsheet = createSpreadsheet(
+ start,
+ end,
+ accounts,
+ [],
+ 'and',
+ enUS,
+ interval,
+ '0',
+ value => String(value),
+ );
+
+ // The net worth factory does not use its spreadsheet dependency.
+ await spreadsheet(undefined as never, data => {
+ report = data;
+ });
+
+ if (!report) {
+ throw new Error('Spreadsheet did not produce report data');
+ }
+ return report;
+}
+
+function getOneOfValues(value: unknown) {
+ if (
+ typeof value === 'object' &&
+ value !== null &&
+ '$oneof' in value &&
+ Array.isArray(value.$oneof)
+ ) {
+ return value.$oneof.filter(item => typeof item === 'string');
+ }
+ return [];
+}
+
+function getUpperBound(value: unknown) {
+ if (
+ typeof value === 'object' &&
+ value !== null &&
+ '$lte' in value &&
+ typeof value.$lte === 'string'
+ ) {
+ return value.$lte;
+ }
+ return null;
+}
+
+afterEach(async () => {
+ await clearServer();
+});
+
+describe('net worth transfers', () => {
+ it('keeps a linked transfer neutral when its two legs cross months', async () => {
+ const report = await runReport({
+ accounts,
+ accountQueryResults: [
+ 100_000,
+ [{ date: '2026-07', amount: -10_000 }],
+ 0,
+ [{ date: '2026-08', amount: 10_000 }],
+ ],
+ linkedTransfers: [
+ {
+ id: 'checking-transfer',
+ account: 'checking',
+ amount: -10_000,
+ date: '2026-07-31',
+ transfer_id: 'savings-transfer',
+ },
+ {
+ id: 'savings-transfer',
+ account: 'savings',
+ amount: 10_000,
+ date: '2026-08-01',
+ transfer_id: 'checking-transfer',
+ },
+ ],
+ });
+
+ expect(report.graphData.data.map(point => point.y)).toEqual([
+ 100_000, 100_000,
+ ]);
+ });
+
+ it('preserves a real expense as a net worth loss', async () => {
+ const report = await runReport({
+ accounts: [accounts[0]],
+ accountQueryResults: [100_000, [{ date: '2026-07', amount: -10_000 }]],
+ });
+
+ expect(report.graphData.data.map(point => point.y)).toEqual([
+ 90_000, 90_000,
+ ]);
+ });
+
+ it('preserves a transfer out of the selected account set as a loss', async () => {
+ const report = await runReport({
+ accounts: [accounts[0]],
+ accountQueryResults: [100_000, [{ date: '2026-07', amount: -10_000 }]],
+ linkedTransfers: [
+ {
+ id: 'checking-transfer',
+ account: 'checking',
+ amount: -10_000,
+ date: '2026-07-31',
+ transfer_id: 'savings-transfer',
+ },
+ {
+ id: 'savings-transfer',
+ account: 'savings',
+ amount: 10_000,
+ date: '2026-08-01',
+ transfer_id: 'checking-transfer',
+ },
+ ],
+ });
+
+ expect(report.graphData.data.map(point => point.y)).toEqual([
+ 90_000, 90_000,
+ ]);
+ });
+
+ it('keeps funds in the source account until a later counterpart arrives', async () => {
+ const report = await runReport({
+ accounts,
+ accountQueryResults: [
+ 100_000,
+ [{ date: '2026-08', amount: -10_000 }],
+ 0,
+ [],
+ ],
+ linkedTransfers: [
+ {
+ id: 'checking-transfer',
+ account: 'checking',
+ amount: -10_000,
+ date: '2026-08-31',
+ transfer_id: 'savings-transfer',
+ },
+ {
+ id: 'savings-transfer',
+ account: 'savings',
+ amount: 10_000,
+ date: '2026-09-01',
+ transfer_id: 'checking-transfer',
+ },
+ ],
+ });
+
+ expect(report.graphData.data.map(point => point.y)).toEqual([
+ 100_000, 100_000,
+ ]);
+ expect(report.graphData.data.at(-1)).toMatchObject({ checking: 100_000 });
+ });
+
+ it('keeps a transfer neutral when it spans the entire report range', async () => {
+ const report = await runReport({
+ accounts,
+ accountQueryResults: [90_000, [], 0, []],
+ linkedTransfers: [
+ {
+ id: 'checking-transfer',
+ account: 'checking',
+ amount: -10_000,
+ date: '2026-06-30',
+ transfer_id: 'savings-transfer',
+ },
+ {
+ id: 'savings-transfer',
+ account: 'savings',
+ amount: 10_000,
+ date: '2026-09-01',
+ transfer_id: 'checking-transfer',
+ },
+ ],
+ start: '2026-08',
+ end: '2026-08',
+ earliestTransactionDate: '2026-06-30',
+ });
+
+ expect(report.graphData.data.map(point => point.y)).toEqual([
+ 100_000, 100_000,
+ ]);
+ });
+
+ it.each([
+ {
+ interval: 'Daily',
+ start: '2016-07',
+ end: '2016-07',
+ earliestTransactionDate: '2016-07-30',
+ earlierDate: '2016-07-30',
+ laterDate: '2016-07-31',
+ earlierBalanceDate: '2016-07-30',
+ laterBalanceDate: '2016-07-31',
+ },
+ {
+ interval: 'Weekly',
+ start: '2016-07',
+ end: '2016-07',
+ earliestTransactionDate: '2016-07-30',
+ earlierDate: '2016-07-30',
+ laterDate: '2016-07-31',
+ earlierBalanceDate: '2016-07-30',
+ laterBalanceDate: '2016-07-31',
+ },
+ {
+ interval: 'Yearly',
+ start: '2016-01',
+ end: '2017-01',
+ earliestTransactionDate: '2016-12-31',
+ earlierDate: '2016-12-31',
+ laterDate: '2017-01-01',
+ earlierBalanceDate: '2016',
+ laterBalanceDate: '2017',
+ },
+ ])(
+ 'keeps a linked transfer neutral across $interval intervals',
+ async ({
+ interval,
+ start,
+ end,
+ earliestTransactionDate,
+ earlierDate,
+ laterDate,
+ earlierBalanceDate,
+ laterBalanceDate,
+ }) => {
+ const report = await runReport({
+ accounts,
+ accountQueryResults: [
+ 100_000,
+ [{ date: earlierBalanceDate, amount: -10_000 }],
+ 0,
+ [{ date: laterBalanceDate, amount: 10_000 }],
+ ],
+ linkedTransfers: [
+ {
+ id: 'checking-transfer',
+ account: 'checking',
+ amount: -10_000,
+ date: earlierDate,
+ transfer_id: 'savings-transfer',
+ },
+ {
+ id: 'savings-transfer',
+ account: 'savings',
+ amount: 10_000,
+ date: laterDate,
+ transfer_id: 'checking-transfer',
+ },
+ ],
+ start,
+ end,
+ interval,
+ earliestTransactionDate,
+ });
+
+ const totals = report.graphData.data.map(point => point.y);
+ expect(totals).toEqual(totals.map(() => 100_000));
+ },
+ );
+});
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
index ff4e8031e2..51fe9ec568 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
@@ -4,6 +4,7 @@ import { q } from '@actual-app/core/shared/query';
import type {
AccountEntity,
RuleConditionEntity,
+ TransactionEntity,
} from '@actual-app/core/types/models';
import * as d from 'date-fns';
import type { Locale } from 'date-fns';
@@ -19,6 +20,27 @@ type Balance = {
amount: number;
};
+type AccountBalanceData = {
+ id: string;
+ name: string;
+ balances: Record<string, Balance>;
+ starting: number;
+};
+
+type TransferLeg = Pick<
+ TransactionEntity,
+ 'id' | 'account' | 'amount' | 'date'
+> & {
+ transfer_id: string;
+};
+
+type IntervalRange = {
+ startDate: string;
+ endDate: string;
+ interval: string;
+ firstDayOfWeekIdx: string;
+};
+
export function createSpreadsheet(
start: string,
end: string,
@@ -95,7 +117,24 @@ export function createSpreadsheet(
}
}
- const data = await Promise.all(
+ const accountIds = accounts.map(account => account.id);
+ const transferLegsPromise =
+ accountIds.length === 0
+ ? Promise.resolve<TransferLeg[]>([])
+ : aqlQuery(
+ q('transactions')
+ .filter({
+ [conditionsOpKey]: filters,
+ })
+ .filter({
+ account: { $oneof: accountIds },
+ transfer_id: { $ne: null },
+ date: { $lte: endDate },
+ })
+ .select(['id', 'account', 'amount', 'date', 'transfer_id']),
+ ).then(({ data }: { data: TransferLeg[] }) => data);
+
+ const accountDataPromise = Promise.all(
accounts.map(async acct => {
const [starting, balances]: [number, Balance[]] = await Promise.all([
aqlQuery(
@@ -169,6 +208,45 @@ export function createSpreadsheet(
};
}),
);
+ const [data, transferLegs] = await Promise.all([
+ accountDataPromise,
+ transferLegsPromise,
+ ]);
+
+ const loadedTransferIds = new Set(transferLegs.map(leg => leg.id));
+ const missingCounterpartIds = [
+ ...new Set(
+ transferLegs
+ .map(leg => leg.transfer_id)
+ .filter(id => !loadedTransferIds.has(id)),
+ ),
+ ];
+
+ let allTransferLegs = transferLegs;
+ if (missingCounterpartIds.length > 0) {
+ const counterpartLegs: TransferLeg[] = await aqlQuery(
+ q('transactions')
+ .filter({
+ [conditionsOpKey]: filters,
+ })
+ .filter({
+ id: { $oneof: missingCounterpartIds },
+ account: { $oneof: accountIds },
+ transfer_id: { $ne: null },
+ })
+ .select(['id', 'account', 'amount', 'date', 'transfer_id']),
+ ).then(({ data }: { data: TransferLeg[] }) => data);
+ allTransferLegs = [...transferLegs, ...counterpartLegs];
+ }
+
+ // Prevent paired internal transfers from changing net worth between their
+ // two posting dates.
+ alignInternalTransferDates(data, allTransferLegs, {
+ startDate,
+ endDate,
+ interval,
+ firstDayOfWeekIdx,
+ });
setData(
recalculate(
@@ -185,13 +263,106 @@ export function createSpreadsheet(
};
}
+function alignInternalTransferDates(
+ data: AccountBalanceData[],
+ transferLegs: TransferLeg[],
+ range: IntervalRange,
+) {
+ const accountsById = new Map(data.map(account => [account.id, account]));
+ const transfersById = new Map(transferLegs.map(leg => [leg.id, leg]));
+ const processed = new Set<string>();
+
+ transferLegs.forEach(leg => {
+ if (processed.has(leg.id)) {
+ return;
+ }
+
+ const counterpart = transfersById.get(leg.transfer_id);
+ if (
+ !counterpart ||
+ counterpart.transfer_id !== leg.id ||
+ counterpart.account === leg.account ||
+ counterpart.amount + leg.amount !== 0 ||
+ !accountsById.has(leg.account) ||
+ !accountsById.has(counterpart.account)
+ ) {
+ return;
+ }
+
+ processed.add(leg.id);
+ processed.add(counterpart.id);
+
+ if (leg.date === counterpart.date) {
+ return;
+ }
+
+ const [earlier, later] =
+ leg.date < counterpart.date ? [leg, counterpart] : [counterpart, leg];
+
+ const account = accountsById.get(earlier.account);
+ if (account) {
+ moveTransferLeg(account, earlier, later.date, range);
+ }
+ });
+}
+
+function moveTransferLeg(
+ account: AccountBalanceData,
+ leg: TransferLeg,
+ laterDate: string,
+ range: IntervalRange,
+) {
+ const { startDate, endDate, interval, firstDayOfWeekIdx } = range;
+ if (laterDate < startDate) {
+ return;
+ }
+
+ if (leg.date < startDate) {
+ account.starting -= leg.amount;
+ } else {
+ if (leg.date > endDate) {
+ return;
+ }
+ const originalKey = getIntervalKey(leg.date, interval, firstDayOfWeekIdx);
+ const originalBalance = account.balances[originalKey];
+ if (!originalBalance) {
+ return;
+ }
+ originalBalance.amount -= leg.amount;
+ }
+
+ if (laterDate > endDate) {
+ return;
+ }
+
+ const intervalKey = getIntervalKey(laterDate, interval, firstDayOfWeekIdx);
+ const balance = account.balances[intervalKey];
+ if (balance) {
+ balance.amount += leg.amount;
+ } else {
+ account.balances[intervalKey] = { date: intervalKey, amount: leg.amount };
+ }
+}
+
+function getIntervalKey(
+ date: string,
+ interval: string,
+ firstDayOfWeekIdx: string,
+) {
+ if (interval === 'Daily') {
+ return date;
+ }
+ if (interval === 'Weekly') {
+ return monthUtils.weekFromDate(date, firstDayOfWeekIdx);
+ }
+ if (interval === 'Yearly') {
+ return date.slice(0, 4);
+ }
+ return monthUtils.getMonth(date);
+}
+
function recalculate(
- data: Array<{
- id: string;
- name: string;
- balances: Record<string, Balance>;
- starting: number;
- }>,
+ data: AccountBalanceData[],
startDate: string,
endDate: string,
locale: Locale,
diff --git a/upcoming-release-notes/fix-cross-month-net-worth-transfers.md b/upcoming-release-notes/fix-cross-month-net-worth-transfers.md
new file mode 100644
index 0000000000..310963d1fc
--- /dev/null
+++ b/upcoming-release-notes/fix-cross-month-net-worth-transfers.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [sambai-dev]
+---
+
+Keep net worth reports stable while linked transfers cross reporting intervals