A local-first personal finance app
[AI] Add BALANCE_OF() function to fetch balance of an arbitrary account (#7335)
Stephen Brown II54a26ae19993
diff --git a/packages/desktop-client/e2e/page-models/account-page.ts b/packages/desktop-client/e2e/page-models/account-page.tsindex efa785be10..e8337341ea 100644--- a/packages/desktop-client/e2e/page-models/account-page.ts+++ b/packages/desktop-client/e2e/page-models/account-page.ts@@ -26,6 +26,9 @@ export class AccountPage {readonly filterSelectTooltip: Locator;readonly selectButton: Locator;readonly selectTooltip: Locator;+ readonly sidebarAllAccountsBalance: Locator;+ readonly sidebarOnBudgetBalance: Locator;+ readonly sidebarOffBudgetBalance: Locator;constructor(page: Page) {this.page = page;@@ -54,6 +57,16 @@ export class AccountPage {this.selectButton = this.page.getByTestId('transactions-select-button');this.selectTooltip = this.page.getByTestId('transactions-select-tooltip');++ this.sidebarAllAccountsBalance = this.page.getByTestId(+ 'sidebar-all-accounts-balance',+ );+ this.sidebarOnBudgetBalance = this.page.getByTestId(+ 'sidebar-on-budget-balance',+ );+ this.sidebarOffBudgetBalance = this.page.getByTestId(+ 'sidebar-off-budget-balance',+ );}async waitFor(...options: Parameters<Locator['waitFor']>) {diff --git a/packages/desktop-client/e2e/transactions.test.ts b/packages/desktop-client/e2e/transactions.test.tsindex 120e2f1547..da6a93fc7d 100644--- a/packages/desktop-client/e2e/transactions.test.ts+++ b/packages/desktop-client/e2e/transactions.test.ts@@ -257,6 +257,11 @@ test.describe('Transactions', () => {const balanceBeforeTransaction =await accountPage.accountBalance.textContent();+ const allAccountsBefore =+ await accountPage.sidebarAllAccountsBalance.textContent();+ const onBudgetBefore =+ await accountPage.sidebarOnBudgetBalance.textContent();+await accountPage.addEnteredTransaction();transaction = accountPage.getNthTransaction(0);@@ -273,6 +278,15 @@ test.describe('Transactions', () => {expect(balanceAfterTransaction).not.toBe(balanceBeforeTransaction);}).toPass();+ // For an on-budget transfer, net totals should be unchanged+ await expect(async () => {+ const allAccounts =+ await accountPage.sidebarAllAccountsBalance.textContent();+ const onBudget = await accountPage.sidebarOnBudgetBalance.textContent();+ expect(allAccounts).toBe(allAccountsBefore);+ expect(onBudget).toBe(onBudgetBefore);+ }).toPass();+await expect(page).toMatchThemeScreenshots();});});diff --git a/packages/desktop-client/src/components/formula/transactionModeFunctions.ts b/packages/desktop-client/src/components/formula/transactionModeFunctions.tsindex 74466ccfde..3ddc6540a5 100644--- a/packages/desktop-client/src/components/formula/transactionModeFunctions.ts+++ b/packages/desktop-client/src/components/formula/transactionModeFunctions.ts@@ -58,6 +58,18 @@ export const transactionModeFunctions: Record<string, FunctionDef> = {},],},+ BALANCE_OF: {+ name: 'BALANCE_OF',+ description: t(+ 'Running balance for another account (cents) at this transaction, same cutoff as balance. Use a quoted account id for a deterministic match, or a quoted account name. Use the balance variable instead for the current account.',+ ),+ parameters: [+ {+ name: 'account_id_or_name',+ description: t('Quoted account id or exact account name'),+ },+ ],+ },MID: {name: 'MID',description: t('Returns substring from specified position.'),diff --git a/packages/desktop-client/src/components/sidebar/Account.tsx b/packages/desktop-client/src/components/sidebar/Account.tsxindex 01a7aa851e..5b89730273 100644--- a/packages/desktop-client/src/components/sidebar/Account.tsx+++ b/packages/desktop-client/src/components/sidebar/Account.tsx@@ -66,6 +66,7 @@ type AccountProps<FieldName extends SheetFields<'account'>> = {onDrop?: OnDropCallback;titleAccount?: boolean;isExactPathMatch?: boolean;+ balanceTestId?: string;};export function Account<FieldName extends SheetFields<'account'>>({@@ -83,6 +84,7 @@ export function Account<FieldName extends SheetFields<'account'>>({onDrop,titleAccount,isExactPathMatch,+ balanceTestId,}: AccountProps<FieldName>) {const isTestEnv = useIsTestEnv();const { t } = useTranslation();@@ -128,6 +130,8 @@ export function Account<FieldName extends SheetFields<'account'>>({const reopenAccount = useReopenAccountMutation();const updateAccount = useUpdateAccountMutation();+ const balanceCell = <CellValue binding={query} type="financial" />;+const accountRow = (<ViewinnerRef={dropRef}@@ -230,7 +234,13 @@ export function Account<FieldName extends SheetFields<'account'>>({name)}- right={<CellValue binding={query} type="financial" />}+ right={+ balanceTestId ? (+ <View data-testid={balanceTestId}>{balanceCell}</View>+ ) : (+ balanceCell+ )+ }/></Link>{account && (diff --git a/packages/desktop-client/src/components/sidebar/Accounts.tsx b/packages/desktop-client/src/components/sidebar/Accounts.tsxindex 17de6621fc..49aabbaf36 100644--- a/packages/desktop-client/src/components/sidebar/Accounts.tsx+++ b/packages/desktop-client/src/components/sidebar/Accounts.tsx@@ -97,6 +97,7 @@ export function Accounts() {query={bindings.allAccountBalance()}style={{ fontWeight, marginTop: 15 }}isExactPathMatch+ balanceTestId="sidebar-all-accounts-balance"/>{onBudgetAccounts.length > 0 && (@@ -110,6 +111,7 @@ export function Accounts() {marginBottom: 5,}}titleAccount+ balanceTestId="sidebar-on-budget-balance"/>)}@@ -141,6 +143,7 @@ export function Accounts() {marginBottom: 5,}}titleAccount+ balanceTestId="sidebar-off-budget-balance"/>)}diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.ts b/packages/desktop-client/src/hooks/useFormulaExecution.tsindex 40c60914a6..7f0ed7747a 100644--- a/packages/desktop-client/src/hooks/useFormulaExecution.ts+++ b/packages/desktop-client/src/hooks/useFormulaExecution.ts@@ -326,8 +326,8 @@ export function useFormulaExecution(// Create HyperFormula instancehfInstance = HyperFormula.buildEmpty({licenseKey: 'gpl-v3',- localeLang: typeof locale === 'string' ? locale : 'en-US',language: 'enUS',+ localeLang: typeof locale === 'string' ? locale : 'en-US',dateFormats: ['DD/MM/YYYY', 'YYYY-MM-DD', 'YYYY/MM/DD'],});diff --git a/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts b/packages/desktop-client/src/hooks/useTransactionFormulaExecution.tsindex 6f49acc1c1..60ca06b310 100644--- a/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts+++ b/packages/desktop-client/src/hooks/useTransactionFormulaExecution.ts@@ -1,7 +1,20 @@import { useEffect, useState } from 'react';+import {+ CustomFunctionsPlugin,+ customFunctionsTranslations,+} from '@actual-app/core/server/rules/customFunctions';+import { HyperFormula } from 'hyperformula';+import enUS from 'hyperformula/i18n/languages/enUS';+import { useLocale } from './useLocale';+HyperFormula.registerLanguage('enUS', enUS);+HyperFormula.registerFunctionPlugin(+ CustomFunctionsPlugin,+ customFunctionsTranslations,+);+type TransactionContext = {amount?: number;date?: string;@@ -26,8 +39,7 @@ export function useTransactionFormulaExecution(useEffect(() => {let cancelled = false;- async function executeFormula() {- const { HyperFormula } = await import('hyperformula');+ function executeFormula() {let hfInstance: ReturnType<typeof HyperFormula.buildEmpty> | null = null;if (!formula || !formula.startsWith('=')) {@@ -40,8 +52,13 @@ export function useTransactionFormulaExecution(// Create HyperFormula instancehfInstance = HyperFormula.buildEmpty({licenseKey: 'gpl-v3',+ language: 'enUS',localeLang: typeof locale === 'string' ? locale : 'en-US',dateFormats: ['DD/MM/YYYY', 'YYYY-MM-DD', 'YYYY/MM/DD'],+ context: {+ // No server prefetch in preview+ balanceOfPrefetch: new Map(),+ },});// Add a sheet@@ -60,7 +77,12 @@ export function useTransactionFormulaExecution(};for (const [key, value] of Object.entries(fieldValues)) {- if (value !== undefined && value !== null) {+ if (+ value !== undefined &&+ value !== null &&+ typeof value !== 'object' &&+ !key.startsWith('_')+ ) {// Set the value in a cellhfInstance.setCellContents({ sheet: sheetId, col: 0, row }, [[value],@@ -114,7 +136,7 @@ export function useTransactionFormulaExecution(}}- void executeFormula();+ executeFormula();return () => {cancelled = true;diff --git a/packages/docs/docs/experimental/formulas.md b/packages/docs/docs/experimental/formulas.mdindex 06a6f0111d..6d9be82f53 100644--- a/packages/docs/docs/experimental/formulas.md+++ b/packages/docs/docs/experimental/formulas.md@@ -55,6 +55,7 @@ If a function isn’t listed here, it still might work. Actual uses HyperFormula| `AND` | Query, Rules | Returns TRUE if all arguments are TRUE. | `=AND(1=1, 2=2)` | Accepts more than 2 conditions || `AVERAGE` | Query | Returns the average of all numbers in a range. | `=AVERAGE(1, 2, 3)` | Accepts more than 2 values || `AVERAGEA` | Query | Returns the average, including text and logical values. | `=AVERAGEA(1, TRUE, "2")` | Accepts more than 2 values |+| `BALANCE_OF` | Rules | Returns running balance for another account in cents; pass a quoted account id or exact account name. | `=BALANCE_OF("550e8400-e29b-41d4-a716-446655440000"); =BALANCE_OF("Checking")` | — || `BUDGET_QUERY` | Query | Returns a budget dimension total for a set of categories over a month range. Dimension is one of: `budgeted`, `spent`, `balance_start`, `balance_end`, `goal`. | `=BUDGET_QUERY("spent", QUERY_EXTRACT_CATEGORIES("q"), QUERY_EXTRACT_TIMEFRAME_START("q"), QUERY_EXTRACT_TIMEFRAME_END("q"))` | — || `CEILING` | Query, Rules | Rounds up to nearest multiple of significance. | `=CEILING(10.2, 1)` | — || `CHAR` | Query, Rules | Converts number to character. | `=CHAR(65)` | — |@@ -305,6 +306,21 @@ Rule formulas evaluate with named variables from the transaction context, includTip: if you want “dollars” from `amount`, use `=amount / 100`.+### Available functions++**`BALANCE_OF` (other accounts):**++```text+=BALANCE_OF("550e8400-e29b-41d4-a716-446655440000")+=BALANCE_OF("Checking")+```++- `BALANCE_OF("…")` — Running balance for another account, in **cents**, using the same cutoff as `balance` (same `date`, `sort_order`, and `id` ordering as the current transaction).+- Pass a **quoted account id** (matches an account id in your budget) for a deterministic result, or a **quoted account name** for an exact name match. If the account name is ambiguous (duplicates), the first match is used.+- If the account is not found, the value is **0**.+- For the **current** transaction’s account, use the `balance` variable instead of `BALANCE_OF`.+- Returns an integer in cents. For the amount in dollars, divide by 100 or `=INTEGER_TO_AMOUNT(BALANCE_OF("Checking"))`.+### Result typesWhen a rule runs, Actual converts the formula result to the field type:diff --git a/packages/loot-core/src/server/budget/schedule-template.test.ts b/packages/loot-core/src/server/budget/schedule-template.test.tsindex 143a6a4762..56786b4d78 100644--- a/packages/loot-core/src/server/budget/schedule-template.test.ts+++ b/packages/loot-core/src/server/budget/schedule-template.test.ts@@ -20,6 +20,7 @@ vi.mock('#server/schedules/app', async () => {describe('runSchedule', () => {beforeEach(() => {vi.clearAllMocks();+ vi.mocked(db.getAccounts).mockResolvedValue([]);});it('should return correct budget when recurring schedule set', async () => {diff --git a/packages/loot-core/src/server/budget/schedule-template.ts b/packages/loot-core/src/server/budget/schedule-template.tsindex b24de37c89..eb2c64fe0b 100644--- a/packages/loot-core/src/server/budget/schedule-template.ts+++ b/packages/loot-core/src/server/budget/schedule-template.ts@@ -1,7 +1,9 @@// @ts-strict-ignoreimport * as db from '#server/db';+import { collectFormulasFromActions } from '#server/rules/balanceOfFormula';import { getRuleForSchedule } from '#server/schedules/app';+import { prefetchBalanceOfForTransaction } from '#server/transactions/transaction-rules';import type { Currency } from '#shared/currencies';import * as monthUtils from '#shared/months';import {@@ -10,7 +12,7 @@ import {getNextDate,} from '#shared/schedules';import { amountToInteger } from '#shared/util';-import type { CategoryEntity } from '#types/models';+import type { CategoryEntity, TransactionEntity } from '#types/models';import type { ScheduleTemplate, Template } from '#types/models/templates';import { getSheetValue, isReflectBudget } from './actions';@@ -35,6 +37,8 @@ async function createScheduleList() {const t: Array<ScheduleTemplateTarget> = [];const errors: string[] = [];+ const accounts = (await db.getAccounts()) ?? [];+ const accountsMap = new Map(accounts.map(a => [a.id, a]));for (const template of templates) {const { id: sid, completed } = await db.first<@@ -74,10 +78,38 @@ async function createScheduleList(scheduleAmount = Math.round(scheduleAmount);- const { amount: postRuleAmount, subtransactions } = rule.execActions({+ const next_date_string = getNextDate(+ dateConditions,+ monthUtils._parse(current_month),+ );++ // Schedule templates call rule.execActions() on the rule attached to each+ // schedule, so we prefetch balances and pass _balanceOfPrefetched here too.+ // Without that, BALANCE_OF would behave wrong or always look empty for+ // schedule rules.+ const formulaStrings = collectFormulasFromActions(rule.actions);++ // Use the schedule's next occurrence date so "balance as of this moment"+ // matches the scheduled date; id/sort_order are unset so we don't exclude a+ // non-existent transaction from the balance query.+ const scheduleRuleContext: TransactionEntity = {amount: scheduleAmount,category: category.id,subtransactions: [],+ ...(next_date_string ? { date: next_date_string } : {}),+ id: null,+ sort_order: null,+ } as TransactionEntity;++ const balanceOfPrefetched = await prefetchBalanceOfForTransaction(+ scheduleRuleContext,+ accountsMap,+ formulaStrings,+ );++ const { amount: postRuleAmount, subtransactions } = rule.execActions({+ ...scheduleRuleContext,+ _balanceOfPrefetched: balanceOfPrefetched,});const categorySubtransactions = subtransactions?.filter(t => t.category === category.id,@@ -91,10 +123,6 @@ async function createScheduleList(? categorySubtransactions.reduce((acc, t) => acc + t.amount, 0): (postRuleAmount ?? scheduleAmount));- const next_date_string = getNextDate(- dateConditions,- monthUtils._parse(current_month),- );const target_interval = dateConditions.value.interval? dateConditions.value.interval: 1;diff --git a/packages/loot-core/src/server/rules/action.ts b/packages/loot-core/src/server/rules/action.tsindex 81bac97f0a..435c175b55 100644--- a/packages/loot-core/src/server/rules/action.ts+++ b/packages/loot-core/src/server/rules/action.ts@@ -304,6 +304,9 @@ export class Action {licenseKey: 'gpl-v3',language: 'enUS',dateFormats: ['DD/MM/YYYY', 'YYYY-MM-DD', 'YYYY/MM/DD'],+ context: {+ balanceOfPrefetch: transaction['_balanceOfPrefetched'] ?? new Map(),+ },});const sheetName = hfInstance.addSheet('Sheet1');@@ -325,6 +328,9 @@ export class Action {};for (const key of Object.keys(fieldValues)) {+ if (key === '_balanceOfPrefetched') {+ continue;+ }let cellValue: string | number | boolean;if (fieldValues[key] === undefined ||diff --git a/packages/loot-core/src/server/rules/balanceOfFormula.test.ts b/packages/loot-core/src/server/rules/balanceOfFormula.test.tsnew file mode 100644index 0000000000..b199e528e0--- /dev/null+++ b/packages/loot-core/src/server/rules/balanceOfFormula.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import type * as db from '#server/db';++import {+ decodeBalanceOfQuotedLiteral,+ extractBalanceOfLiterals,+ resolveAccountIdForBalanceOf,+} from './balanceOfFormula';++describe('balanceOfFormula', () => {+ it('extractBalanceOfLiterals returns distinct decoded literals', () => {+ expect(+ extractBalanceOfLiterals(+ '=BALANCE_OF("Checking") + BALANCE_OF("Checking")',+ ),+ ).toEqual(['Checking']);+ expect(extractBalanceOfLiterals('=balance_of("Savings")')).toEqual([+ 'Savings',+ ]);+ });++ it('decodeBalanceOfQuotedLiteral unescapes quotes and backslashes', () => {+ expect(decodeBalanceOfQuotedLiteral(String.raw`\"x\"`)).toBe('"x"');+ });++ it('resolveAccountIdForBalanceOf prefers map key then name', () => {+ const id = 'acc-1';+ const a1: db.DbAccount = {+ id,+ name: 'Dup',+ offbudget: 0,+ } as db.DbAccount;+ const a2: db.DbAccount = {+ id: 'acc-2',+ name: 'Other',+ offbudget: 0,+ } as db.DbAccount;+ const map = new Map<string, db.DbAccount>([+ [id, a1],+ ['acc-2', a2],+ ]);+ expect(resolveAccountIdForBalanceOf(id, map)).toBe(id);+ expect(resolveAccountIdForBalanceOf('Other', map)).toBe('acc-2');+ expect(resolveAccountIdForBalanceOf('Nope', map)).toBe(null);+ });+});diff --git a/packages/loot-core/src/server/rules/balanceOfFormula.ts b/packages/loot-core/src/server/rules/balanceOfFormula.tsnew file mode 100644index 0000000000..650695c87d--- /dev/null+++ b/packages/loot-core/src/server/rules/balanceOfFormula.ts@@ -0,0 +1,56 @@+import type * as db from '#server/db';++/** Collect formula strings from serialized or live rule actions. */+export function collectFormulasFromActions(+ actions: Array<{ options?: { formula?: string } }>,+): string[] {+ const out: string[] = [];+ for (const action of actions) {+ const f = action.options?.formula;+ if (typeof f === 'string') {+ out.push(f);+ }+ }+ return out;+}++/** Decode escape sequences inside a double-quoted formula string literal. */+export function decodeBalanceOfQuotedLiteral(inner: string): string {+ return inner.replace(/\\"/g, '"').replace(/\\\\/g, '\\');+}++/**+ * Distinct decoded string literals from BALANCE_OF("…") calls in a formula.+ */+export function extractBalanceOfLiterals(formula: string): string[] {+ const seen = new Set<string>();+ const out: string[] = [];+ const re = /BALANCE_OF\s*\(\s*"((?:[^"\\]|\\.)*)"\s*\)/gi;+ let m: RegExpExecArray | null;+ while ((m = re.exec(formula)) !== null) {+ const decoded = decodeBalanceOfQuotedLiteral(m[1]);+ if (!seen.has(decoded)) {+ seen.add(decoded);+ out.push(decoded);+ }+ }+ return out;+}++/**+ * Resolve account id: map key (id) first, else first exact name match.+ */+export function resolveAccountIdForBalanceOf(+ literal: string,+ accountsMap: Map<string, db.DbAccount>,+): string | null {+ if (accountsMap.has(literal)) {+ return literal;+ }+ for (const acc of accountsMap.values()) {+ if (acc.name === literal) {+ return acc.id;+ }+ }+ return null;+}diff --git a/packages/loot-core/src/server/rules/customFunctions.ts b/packages/loot-core/src/server/rules/customFunctions.tsindex cc5a818d51..d2791aafc4 100644--- a/packages/loot-core/src/server/rules/customFunctions.ts+++ b/packages/loot-core/src/server/rules/customFunctions.ts@@ -26,28 +26,46 @@ export class CustomFunctionsPlugin extends FunctionPlugin {},);}++ balanceOf(ast: ProcedureAst, state: InterpreterState) {+ return this.runFunction(+ ast.args,+ state,+ this.metadata('BALANCE_OF'),+ (accountKey: string) => {+ const ctx = this.config.context as+ | { balanceOfPrefetch?: Map<string, number> }+ | undefined;+ return ctx?.balanceOfPrefetch?.get(accountKey) ?? 0;+ },+ );+ }}CustomFunctionsPlugin.implementedFunctions = {- INTEGER_TO_AMOUNT: {- method: 'integerToAmount',+ BALANCE_OF: {+ method: 'balanceOf',+ parameters: [{ argumentType: FunctionArgumentType.STRING }],+ },+ FIXED: {+ method: 'fixed',parameters: [{ argumentType: FunctionArgumentType.NUMBER },{argumentType: FunctionArgumentType.NUMBER,optionalArg: true,- defaultValue: 2,+ defaultValue: 0,},],},- FIXED: {- method: 'fixed',+ INTEGER_TO_AMOUNT: {+ method: 'integerToAmount',parameters: [{ argumentType: FunctionArgumentType.NUMBER },{argumentType: FunctionArgumentType.NUMBER,optionalArg: true,- defaultValue: 0,+ defaultValue: 2,},],},@@ -55,7 +73,8 @@ CustomFunctionsPlugin.implementedFunctions = {export const customFunctionsTranslations = {enUS: {- INTEGER_TO_AMOUNT: 'INTEGER_TO_AMOUNT',+ BALANCE_OF: 'BALANCE_OF',FIXED: 'FIXED',+ INTEGER_TO_AMOUNT: 'INTEGER_TO_AMOUNT',},};diff --git a/packages/loot-core/src/server/rules/formula-action.test.ts b/packages/loot-core/src/server/rules/formula-action.test.tsindex af4276b48e..43ce5ed2ce 100644--- a/packages/loot-core/src/server/rules/formula-action.test.ts+++ b/packages/loot-core/src/server/rules/formula-action.test.ts@@ -114,6 +114,41 @@ describe('Formula-based rule actions', () => {expect(result).toBe(300000);});+ it('should support BALANCE_OF with prefetched map', () => {+ const action = new Action('set', 'notes', null, {});+ const transaction: Partial<TransactionForRules> = {+ notes: 'original',+ _balanceOfPrefetched: new Map([+ ['Savings', 50000],+ ['550e8400-e29b-41d4-a716-446655440000', 1200],+ ]),+ };+ const byName = action.executeFormulaSync(+ '=BALANCE_OF("Savings") + 100',+ transaction,+ );+ expect(byName).toBe(5010000);++ const byId = action.executeFormulaSync(+ '=BALANCE_OF("550e8400-e29b-41d4-a716-446655440000")',+ transaction,+ );+ expect(byId).toBe(120000);+ });++ it('should return 0 for BALANCE_OF when literal missing from prefetch map', () => {+ const action = new Action('set', 'amount', null, {});+ const transaction: Partial<TransactionForRules> = {+ amount: 100,+ _balanceOfPrefetched: new Map(),+ };+ const result = action.executeFormulaSync(+ '=BALANCE_OF("Unknown")',+ transaction,+ );+ expect(result).toBe(0);+ });+it('should execute formula and convert to number type', () => {const action = new Action('set', 'amount', null, {formula: '=500 + 250',diff --git a/packages/loot-core/src/server/rules/rule.ts b/packages/loot-core/src/server/rules/rule.tsindex 551fe8a0c1..465170f3da 100644--- a/packages/loot-core/src/server/rules/rule.ts+++ b/packages/loot-core/src/server/rules/rule.ts@@ -45,6 +45,8 @@ function execSplitActions(actions: Action[], transaction) {}newTransactions[splitTransactionIndex].parent_amount = transaction.amount;newTransactions[splitTransactionIndex].balance = transaction.balance;+ newTransactions[splitTransactionIndex]._balanceOfPrefetched =+ transaction._balanceOfPrefetched;action.exec(newTransactions[splitTransactionIndex]);});diff --git a/packages/loot-core/src/server/sync/index.ts b/packages/loot-core/src/server/sync/index.tsindex 35fedc8182..f22e0ab44f 100644--- a/packages/loot-core/src/server/sync/index.ts+++ b/packages/loot-core/src/server/sync/index.ts@@ -23,6 +23,7 @@ import { postBinary } from '#server/post';import * as prefs from '#server/prefs';import { getServer } from '#server/server-config';import * as sheet from '#server/sheet';+import { resolveName } from '#server/spreadsheet/util';import * as undo from '#server/undo';import { once, sequential } from '#shared/async';import { getIn, setIn } from '#shared/util';@@ -280,7 +281,7 @@ export const applyMessages = sequential(async (messages: Message[]) => {return 0;});- const idsPerTable = {};+ const idsPerTable: Record<string, string[]> = {};messages.forEach(msg => {if (msg.dataset === 'prefs') {return;@@ -405,6 +406,26 @@ export const applyMessages = sequential(async (messages: Message[]) => {sheet.get().triggerDatabaseChanges(oldData, newData);sheet.endTransaction();+ // Transfers insert the source row in one sync batch and the counterparty in+ // a second. triggerDatabaseChanges should dirty aggregate query cells, but+ // explicitly recompute global account totals so the second batch always+ // refreshes sidebar "All accounts" / On budget / etc. (see bindings.ts).+ if (idsPerTable.transactions?.length) {+ const s = sheet.get();+ const globalAggregateCells = [+ 'accounts-balance',+ 'onbudget-accounts-balance',+ 'offbudget-accounts-balance',+ 'closed-accounts-balance',+ ] as const;+ for (const cellName of globalAggregateCells) {+ const fullName = resolveName('__global', cellName);+ if (s.hasCell(fullName)) {+ s.recompute(fullName);+ }+ }+ }+// Allow the cache to be used in the future. At this point it's guaranteed// to be up-to-date because we are done mutating any other datasheet.get().endCacheBarrier();diff --git a/packages/loot-core/src/server/transactions/transaction-rules.ts b/packages/loot-core/src/server/transactions/transaction-rules.tsindex 539e3255e0..e8b2e67d82 100644--- a/packages/loot-core/src/server/transactions/transaction-rules.ts+++ b/packages/loot-core/src/server/transactions/transaction-rules.ts@@ -23,6 +23,11 @@ import {Rule,RuleIndexer,} from '#server/rules';+import {+ collectFormulasFromActions,+ extractBalanceOfLiterals,+ resolveAccountIdForBalanceOf,+} from '#server/rules/balanceOfFormula';import { addSyncListener, batchMessages } from '#server/sync';import {addDays,@@ -345,6 +350,15 @@ export async function runRules(),);+ const formulaStrings = rules.flatMap(rule =>+ collectFormulasFromActions(rule.actions),+ );+ finalTrans._balanceOfPrefetched = await prefetchBalanceOfForTransaction(+ finalTrans,+ accountsMap,+ formulaStrings,+ );+for (let i = 0; i < rules.length; i++) {// If there is a scheduleRuleID (meaning this transaction came from a schedule) then exclude rules linked to other schedules.if (scheduleRuleID !== '') {@@ -708,6 +722,16 @@ export async function applyActions(),);+ const formulaStrings = collectFormulasFromActions(parsedActions);+ const balanceOfPrefetchResults = await Promise.all(+ transactionsForRules.map(trans =>+ prefetchBalanceOfForTransaction(trans, accountsMap, formulaStrings),+ ),+ );+ transactionsForRules.forEach((trans, i) => {+ trans._balanceOfPrefetched = balanceOfPrefetchResults[i];+ });+const updated = transactionsForRules.flatMap(trans => {return ungroupTransaction(execActions(parsedActions, trans));});@@ -941,8 +965,81 @@ export type TransactionForRules = TransactionEntity & {_category_name?: string;_account_name?: string;parent_amount?: number;+ /** Prefetched cent balances for BALANCE_OF("…") in rule formulas; cleared in finalize */+ _balanceOfPrefetched?: Map<string, number>;};+/**+ * Running balance for `accountId` before the current transaction row (same cutoff as `balance`).+ */+export async function getRunningBalanceBeforeTransaction(+ trans: TransactionEntity,+ accountId: string,+): Promise<number> {+ const dateBoundary = trans.date ?? currentDay();+ let query = q('transactions')+ .filter({ account: accountId, is_parent: false })+ .options({ splits: 'inline' });++ if (trans.id) {+ query = query.filter({ id: { $ne: trans.id } });+ }++ const sameDayFilter =+ trans.sort_order != null+ ? {+ $and: [+ { date: dateBoundary },+ { sort_order: { $lt: trans.sort_order } },+ ],+ }+ : {+ $and: [+ { date: dateBoundary },+ {+ $or: [+ { sort_order: { $ne: null } }, // ordered items come before null sort_order+ ...(trans.id ? [{ id: { $lt: trans.id } }] : []), // among nulls, tie-break by id+ ],+ },+ ],+ };++ const { data: balance } = await aqlQuery(+ query+ .filter({ $or: [{ date: { $lt: dateBoundary } }, sameDayFilter] })+ .calculate({ $sum: '$amount' }),+ );++ return balance ?? 0;+}++export async function prefetchBalanceOfForTransaction(+ trans: TransactionEntity,+ accountsMap: Map<string, db.DbAccount>,+ formulas: string[],+): Promise<Map<string, number>> {+ const map = new Map<string, number>();+ const literals = new Set<string>();+ for (const f of formulas) {+ for (const lit of extractBalanceOfLiterals(f)) {+ literals.add(lit);+ }+ }+ for (const literal of literals) {+ const accountId = resolveAccountIdForBalanceOf(literal, accountsMap);+ if (accountId) {+ map.set(+ literal,+ await getRunningBalanceBeforeTransaction(trans, accountId),+ );+ } else {+ map.set(literal, 0);+ }+ }+ return map;+}+export async function prepareTransactionForRules(trans: TransactionEntity,accounts: Map<string, db.DbAccount> | null = null,@@ -966,42 +1063,7 @@ export async function prepareTransactionForRules(r._account_name = r._account?.name || '';}- const dateBoundary = trans.date ?? currentDay();- let query = q('transactions')- .filter({ account: trans.account, is_parent: false })- .options({ splits: 'inline' });-- if (trans.id) {- query = query.filter({ id: { $ne: trans.id } });- }-- const sameDayFilter =- trans.sort_order != null- ? {- $and: [- { date: dateBoundary },- { sort_order: { $lt: trans.sort_order } },- ],- }- : {- $and: [- { date: dateBoundary },- {- $or: [- { sort_order: { $ne: null } }, // ordered items come before null sort_order- ...(trans.id ? [{ id: { $lt: trans.id } }] : []), // among nulls, tie-break by id- ],- },- ],- };-- const { data: balance } = await aqlQuery(- query- .filter({ $or: [{ date: { $lt: dateBoundary } }, sameDayFilter] })- .calculate({ $sum: '$amount' }),- );-- r.balance = balance ?? 0;+ r.balance = await getRunningBalanceBeforeTransaction(trans, trans.account);}if (trans.category) {@@ -1038,6 +1100,10 @@ export async function finalizeTransactionForRules(delete trans.balance;}+ if ('_balanceOfPrefetched' in trans) {+ delete trans._balanceOfPrefetched;+ }+if ('parent_amount' in trans) {delete trans.parent_amount;}@@ -1048,6 +1114,10 @@ export async function finalizeTransactionForRules(delete stx.balance;}+ if ('_balanceOfPrefetched' in stx) {+ delete stx._balanceOfPrefetched;+ }+if ('parent_amount' in stx) {delete stx.parent_amount;}diff --git a/upcoming-release-notes/7335.md b/upcoming-release-notes/7335.mdnew file mode 100644index 0000000000..3df1f7ec3c--- /dev/null+++ b/upcoming-release-notes/7335.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [StephenBrown2]+---++Add BALANCE_OF function to rules formulas for other account balances