A local-first personal finance app
[AI] Make BALANCE_OF available in formula reports (#8591)
youngcwc4bc3e57c8ba
diff --git a/packages/desktop-client/src/components/formula/formulaCatalog.test.ts b/packages/desktop-client/src/components/formula/formulaCatalog.test.tsindex dbb79cbc6e..ad06d2ec3c 100644--- a/packages/desktop-client/src/components/formula/formulaCatalog.test.ts+++ b/packages/desktop-client/src/components/formula/formulaCatalog.test.ts@@ -49,9 +49,7 @@ describe('formulaCatalog', () => {expect(reportFunctions.QUERY).toBeDefined();expect(reportFunctions.QUERY_COUNT).toBeDefined();expect(reportFunctions.BUDGET_QUERY).toBeDefined();- expect(reportFunctions.BALANCE_OF).toBeUndefined();- expect(ruleFunctions.BALANCE_OF).toBeDefined();expect(ruleFunctions.QUERY).toBeUndefined();expect(ruleFunctions.QUERY_COUNT).toBeUndefined();});@@ -65,6 +63,7 @@ describe('formulaCatalog', () => {'FORMATNUMBER','FORMATCURRENCY','INTEGER_TO_AMOUNT',+ 'BALANCE_OF',]) {expect(reportFunctions[functionName]).toBeDefined();expect(ruleFunctions[functionName]).toBeDefined();diff --git a/packages/desktop-client/src/components/formula/formulaCatalog.ts b/packages/desktop-client/src/components/formula/formulaCatalog.tsindex 6c2fa94d9e..c36ab5f691 100644--- a/packages/desktop-client/src/components/formula/formulaCatalog.ts+++ b/packages/desktop-client/src/components/formula/formulaCatalog.ts@@ -1003,9 +1003,9 @@ export function getFormulaFunctionCatalog(): Record<BALANCE_OF: {name: 'BALANCE_OF',category: 'other',- modes: ['transaction'],+ modes: ['query', 'transaction'],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.',+ "Balance for an account. In rule formulas, this is the running balance (in cents) at this transaction, same cutoff as balance (use the balance variable instead for the current account). In report/query formulas, this is the account's current balance (in money/display units). Use a quoted account id for a deterministic match, or a quoted account name.",),parameters: [{diff --git a/packages/desktop-client/src/components/reports/reports/Formula.tsx b/packages/desktop-client/src/components/reports/reports/Formula.tsxindex 921b5cdd0b..2d37fd6e6e 100644--- a/packages/desktop-client/src/components/reports/reports/Formula.tsx+++ b/packages/desktop-client/src/components/reports/reports/Formula.tsx@@ -19,6 +19,7 @@ import { MobileBackButton } from '#components/mobile/MobileBackButton';import { MobilePageHeader, Page, PageHeader } from '#components/Page';import { FormulaResult } from '#components/reports/FormulaResult';import { LoadingIndicator } from '#components/reports/LoadingIndicator';+import { useAccounts } from '#hooks/useAccounts';import { useCategories } from '#hooks/useCategories';import { useDashboardWidget } from '#hooks/useDashboardWidget';import { useFormulaExecution } from '#hooks/useFormulaExecution';@@ -67,6 +68,7 @@ function FormulaInner({ widget }: FormulaInnerProps) {grouped: [],},} = useCategories();+ const { data: accounts = [] } = useAccounts();const [formula, setFormula] = useState(widget?.meta?.formula || '=SUM(1, 2, 3)',@@ -85,11 +87,25 @@ function FormulaInner({ widget }: FormulaInnerProps) {const title = widget?.meta?.name || t('Formula');+ const simpleAccounts = useMemo(+ () =>+ accounts+ .filter(account => !account.tombstone)+ .map(account => ({ id: account.id, name: account.name })),+ [accounts],+ );+const {result,isLoading: isExecuting,error,- } = useFormulaExecution(formula, queriesRef.current, queriesVersion);+ } = useFormulaExecution(+ formula,+ queriesRef.current,+ queriesVersion,+ undefined,+ simpleAccounts,+ );const colorVariables = useMemo(() => ({@@ -126,6 +142,7 @@ function FormulaInner({ widget }: FormulaInnerProps) {queriesRef.current,queriesVersion,colorVariables,+ simpleAccounts,);const handleQueriesChange = useCallback(diff --git a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsxindex 3f3f70efdb..d194b78b6b 100644--- a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx@@ -7,6 +7,7 @@ import type { FormulaWidget } from '@actual-app/core/types/models';import { FormulaResult } from '#components/reports/FormulaResult';import { ReportCard } from '#components/reports/ReportCard';import { ReportCardName } from '#components/reports/ReportCardName';+import { useAccounts } from '#hooks/useAccounts';import { useFormulaExecution } from '#hooks/useFormulaExecution';import { useThemeColors } from '#hooks/useThemeColors';@@ -27,6 +28,7 @@ export function FormulaCard({const [nameMenuOpen, setNameMenuOpen] = useState(false);const themeColors = useThemeColors();const containerRef = useRef<HTMLDivElement>(null);+ const { data: accounts = [] } = useAccounts();const formula = meta?.formula || '=SUM(1, 2, 3)';const fontSize = meta?.fontSize;@@ -35,10 +37,20 @@ export function FormulaCard({const showTitle = meta?.showTitle ?? true;const colorFormula = meta?.colorFormula || '';+ const simpleAccounts = useMemo(+ () =>+ accounts+ .filter(account => !account.tombstone)+ .map(account => ({ id: account.id, name: account.name })),+ [accounts],+ );+const { result, isLoading, error } = useFormulaExecution(formula,meta?.queries || {},meta?.queriesVersion,+ undefined,+ simpleAccounts,);const colorVariables = useMemo(@@ -59,6 +71,7 @@ export function FormulaCard({meta?.queries || {},meta?.queriesVersion,colorVariables,+ simpleAccounts,);// Determine the custom color from color formula resultdiff --git a/packages/desktop-client/src/hooks/useFormulaExecution.test.ts b/packages/desktop-client/src/hooks/useFormulaExecution.test.tsindex 221507415e..7084e8f687 100644--- a/packages/desktop-client/src/hooks/useFormulaExecution.test.ts+++ b/packages/desktop-client/src/hooks/useFormulaExecution.test.ts@@ -223,3 +223,82 @@ describe('formula query timeframes', () => {);});});++describe('BALANCE_OF in query mode', () => {+ let queryPayloads: SerializedQuery[];++ beforeEach(() => {+ queryPayloads = [];+ initServer({+ 'formula-load-user-preferences': async () => ({+ currency: getCurrency('USD'),+ numberFormat: 'comma-dot',+ decimalPlaces: 2,+ thousandsSeparator: ',',+ decimalSeparator: '.',+ locale: 'en-US',+ currencySymbolPosition: 'before',+ currencySpaceBetweenAmountAndSymbol: false,+ }),+ query: async payload => {+ queryPayloads.push(payload as unknown as SerializedQuery);+ return { data: 12345, dependencies: [] };+ },+ });+ });++ afterEach(async () => {+ await clearServer();+ });++ it('resolves an account by id and queries its balance', async () => {+ const { result } = renderHook(+ () =>+ useFormulaExecution('=BALANCE_OF("acc1")', {}, 0, undefined, [+ { id: 'acc1', name: 'Checking' },+ ]),+ { wrapper: TestProviders },+ );++ await waitFor(() => expect(result.current.result).toBe(123.45));++ const balanceQuery = queryPayloads.find(payload =>+ payload.filterExpressions.some(+ expression => (expression as { account?: string }).account === 'acc1',+ ),+ );+ expect(balanceQuery).toBeDefined();+ });++ it('resolves an account by exact name', async () => {+ const { result } = renderHook(+ () =>+ useFormulaExecution('=BALANCE_OF("Checking")', {}, 0, undefined, [+ { id: 'acc1', name: 'Checking' },+ ]),+ { wrapper: TestProviders },+ );++ await waitFor(() => expect(result.current.result).toBe(123.45));++ const balanceQuery = queryPayloads.find(payload =>+ payload.filterExpressions.some(+ expression => (expression as { account?: string }).account === 'acc1',+ ),+ );+ expect(balanceQuery).toBeDefined();+ });++ it('returns 0 for an unknown account', async () => {+ const { result } = renderHook(+ () =>+ useFormulaExecution('=BALANCE_OF("nope")', {}, 0, undefined, [+ { id: 'acc1', name: 'Checking' },+ ]),+ { wrapper: TestProviders },+ );++ await waitFor(() => expect(result.current.result).toBe(0));+ expect(queryPayloads).toHaveLength(0);+ });+});diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.ts b/packages/desktop-client/src/hooks/useFormulaExecution.tsindex feebf2aaae..03fe9de28e 100644--- a/packages/desktop-client/src/hooks/useFormulaExecution.ts+++ b/packages/desktop-client/src/hooks/useFormulaExecution.ts@@ -42,6 +42,8 @@ type QueriesMap = Record<string, QueryConfig>;type FormulaCellValue = number | string | boolean | null;+export type SimpleAccount = { id: string; name: string };+function createFormulaQueryContext(): Required<FormulaQueryContext> {return {queryNames: new Set(),@@ -49,12 +51,14 @@ function createFormulaQueryContext(): Required<FormulaQueryContext> {queryExtractCategoryNames: new Set(),queryExtractTimeframeStartNames: new Set(),queryExtractTimeframeEndNames: new Set(),+ balanceOfNames: new Set(),budgetQueryRequests: new Map(),querySumPrefetch: new Map(),queryCountPrefetch: new Map(),queryExtractCategoriesPrefetch: new Map(),queryExtractTimeframeStartPrefetch: new Map(),queryExtractTimeframeEndPrefetch: new Map(),+ balanceOfPrefetch: new Map(),budgetQueryPrefetch: new Map(),budgetQueryErrors: new Map(),};@@ -136,6 +140,7 @@ export function useFormulaExecution(queries: QueriesMap,queriesVersion?: number,namedExpressions?: Record<string, number | string>,+ accounts?: SimpleAccount[],) {const locale = useLocale();const [language] = useGlobalPref('language');@@ -183,6 +188,7 @@ export function useFormulaExecution(});await prefetchFormulaQueries(formulaQueryContext, queries);+ await prefetchAccountBalances(formulaQueryContext, accounts ?? []);formulaQueryContext.budgetQueryRequests.clear();evaluateFormulaWithContext({@@ -223,7 +229,15 @@ export function useFormulaExecution(return () => {cancelled = true;};- }, [formula, queriesVersion, locale, language, queries, namedExpressions]);+ }, [+ formula,+ queriesVersion,+ locale,+ language,+ queries,+ namedExpressions,+ accounts,+ ]);return { result, isLoading, error };}@@ -285,6 +299,40 @@ async function prefetchFormulaQueries(}}+async function prefetchAccountBalances(+ formulaQueryContext: Required<FormulaQueryContext>,+ accounts: SimpleAccount[],+) {+ for (const literal of formulaQueryContext.balanceOfNames) {+ const account =+ accounts.find(candidate => candidate.id === literal) ??+ accounts.find(candidate => candidate.name === literal);++ if (!account) {+ formulaQueryContext.balanceOfPrefetch.set(literal, 0);+ continue;+ }++ formulaQueryContext.balanceOfPrefetch.set(+ literal,+ await fetchAccountBalance(account.id),+ );+ }+}++async function fetchAccountBalance(accountId: string): Promise<number> {+ try {+ const balanceQuery = q('transactions')+ .filter({ account: accountId })+ .calculate({ $sum: '$amount' });+ const { data } = await send('query', balanceQuery.serialize());+ return integerToAmount(data || 0, 2);+ } catch (err) {+ console.error('Error fetching account balance:', err);+ return 0;+ }+}+async function prefetchBudgetQueries(formulaQueryContext: Required<FormulaQueryContext>,) {diff --git a/packages/docs/docs/experimental/formulas.md b/packages/docs/docs/experimental/formulas.mdindex c2806502fb..a7f3fbfd78 100644--- a/packages/docs/docs/experimental/formulas.md+++ b/packages/docs/docs/experimental/formulas.md@@ -47,134 +47,134 @@ This list documents formula functions that are useful in Actual. The in-app **auIf a function isn’t listed here, it still might work. Actual uses HyperFormula under the hood, so you can also refer to [HyperFormula’s built-in functions list](https://hyperformula.handsontable.com/guide/built-in-functions.html).:::-| Function | Available in | Description | Syntax example | Optional params |-| ------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |-| `ABS` | Query, Rules | Returns the absolute value of a number. | `=ABS(-42)` | — |-| `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)` | — |-| `CHOOSE` | Query | Returns value from list based on index. | `=CHOOSE(2, "A", "B", "C")` | Accepts more than 2 values |-| `CLEAN` | Rules | Removes non-printable characters from text. | `=CLEAN(notes)` | — |-| `CODE` | Query, Rules | Returns numeric code for first character. | `=CODE("A")` | — |-| `CONCATENATE` | Query, Rules | Combines several text strings into one. | `=CONCATENATE("Paid ", payee_name)` | Accepts more than 2 texts |-| `COS` | Query | Returns the cosine of an angle. | `=COS(1)` | — |-| `COUNT` | Query | Counts the number of numeric values. | `=COUNT(1, 2, "x")` | Accepts more than 2 values |-| `COUNTA` | Query | Counts non-empty values. | `=COUNTA(1, "", "x")` | Accepts more than 2 values |-| `COUNTBLANK` | Query | Counts empty cells. | `=COUNTBLANK(A1:A10)` | — |-| `COUNTIF` | Query | Counts cells that meet a criteria. | `=COUNTIF(A1:A10, ">0")` | — |-| `COUNTIFS` | Query | Counts cells that meet multiple criteria. | `=COUNTIFS(A1:A10, ">0", B1:B10, "<=5")` | Repeat `(range, criteria)` pairs |-| `DATE` | Query, Rules | Returns date as number of days since null date. | `=DATE(2025, 12, 16)` | — |-| `DATEDIF` | Query, Rules | Calculates distance between dates. | `=DATEDIF("2025-01-01", "2025-12-31", "D")` | — |-| `DATEVALUE` | Rules | Parses a date string and returns it as a number. | `=DATEVALUE("2025-12-16")` | — |-| `DAY` | Query, Rules | Returns the day from a date. | `=DAY(date)` | — |-| `DAYS` | Query, Rules | Calculates difference between dates in days. | `=DAYS("2025-12-31", "2025-12-01")` | — |-| `EDATE` | Query, Rules | Returns date shifted by specified months. | `=EDATE(date, 1)` | — |-| `EOMONTH` | Query, Rules | Returns last day of month after specified months. | `=EOMONTH(date, 0)` | — |-| `EXACT` | Query, Rules | Returns TRUE if texts are exactly the same. | `=EXACT("A", "a")` | — |-| `EXP` | Query | Returns e raised to the power of number. | `=EXP(1)` | — |-| `FALSE` | Query, Rules | Returns the logical value FALSE. | `=FALSE()` | — |-| `FIND` | Query, Rules | Finds text within text (case-sensitive). | `=FIND("foo", notes)` | — |-| `FLOOR` | Query, Rules | Rounds down to nearest multiple of significance. | `=FLOOR(10.8, 1)` | — |-| `FORMATCURRENCY` | Query, Rules | Formats a number as currency using your app currency, number format, symbol position, and spacing settings by default. | `=FORMATCURRENCY(1234.5)` | `symbol`, `decimals`, `thousandsSeparator`, `decimalSeparator`, `symbolPosition`, `spaceBetweenAmountAndSymbol` |-| `FORMATNUMBER` | Query, Rules | Formats a number using your app number format settings by default. | `=FORMATNUMBER(1234.5, 2)` | `decimals`, `thousandsSeparator`, `decimalSeparator` |-| `FV` | Query | Calculates future value of investment. | `=FV(0.05/12, 12, -100)` | — |-| `HLOOKUP` | Query | Searches horizontally in first row and returns value. | `=HLOOKUP("key", A1:D10, 2, TRUE)` | — |-| `IF` | Query, Rules | Returns one value if condition is TRUE, another if FALSE. | `=IF(amount<0, "Expense", "Income")` | — |-| `IFERROR` | Query, Rules | Returns value if no error, otherwise returns alternative. | `=IFERROR(1/0, 0)` | — |-| `IFNA` | Query, Rules | Returns value if not #N/A error, otherwise returns alternative. | `=IFNA(VLOOKUP("x", A1:B10, 2, FALSE), 0)` | — |-| `IFS` | Query, Rules | Checks multiple conditions and returns corresponding values. | `=IFS(amount<0, "Expense", amount>0, "Income")` | Repeat `(condition, value)` pairs |-| `INDEX` | Query | Returns value at specified row and column. | `=INDEX(A1:C10, 2, 3)` | — |-| `INTEGER_TO_AMOUNT` | Query, Rules | Converts integer amount to decimal amount (e.g., 1234 -> 12.34). | `=INTEGER_TO_AMOUNT(amount, 2)` | `decimal_places` (default: 2) |-| `INT` | Rules | Rounds down to nearest integer. | `=INT(10.9)` | — |-| `IRR` | Query | Calculates internal rate of return. | `=IRR(A1:A12)` | — |-| `ISEVEN` | Rules | Returns TRUE if number is even. | `=ISEVEN(10)` | — |-| `ISODD` | Rules | Returns TRUE if number is odd. | `=ISODD(11)` | — |-| `ISBLANK` | Query, Rules | Returns TRUE if value is blank. | `=ISBLANK(notes)` | — |-| `ISERROR` | Query, Rules | Returns TRUE if value is any error. | `=ISERROR(1/0)` | — |-| `ISLOGICAL` | Query, Rules | Returns TRUE if value is logical (TRUE/FALSE). | `=ISLOGICAL(TRUE())` | — |-| `ISNA` | Query, Rules | Returns TRUE if value is #N/A error. | `=ISNA(NA())` | — |-| `ISNUMBER` | Query, Rules | Returns TRUE if value is a number. | `=ISNUMBER(amount)` | — |-| `ISOWEEKNUM` | Rules | Returns ISO week number. | `=ISOWEEKNUM(date)` | — |-| `ISREF` | Query, Rules | Returns TRUE if value is a reference. | `=ISREF(A1)` | — |-| `ISTEXT` | Query, Rules | Returns TRUE if value is text. | `=ISTEXT(notes)` | — |-| `LEFT` | Query, Rules | Returns leftmost characters from text. | `=LEFT(imported_payee, 10)` | — |-| `LEN` | Query, Rules | Returns length of text. | `=LEN(notes)` | — |-| `LN` | Query | Returns the natural logarithm. | `=LN(10)` | — |-| `LOG` | Query | Returns the logarithm to specified base. | `=LOG(100, 10)` | — |-| `LOG10` | Query | Returns the base-10 logarithm. | `=LOG10(1000)` | — |-| `LOOKUP` | Query | Looks up values in a vector or array. | `=LOOKUP("x", A1:A10)` | — |-| `LOWER` | Query, Rules | Converts text to lowercase. | `=LOWER(notes)` | — |-| `MATCH` | Query | Returns position of value in array. | `=MATCH("x", A1:A10, 0)` | — |-| `MAX` | Query | Returns the maximum value. | `=MAX(1, 2, 3)` | Accepts more than 2 values |-| `MAXA` | Query | Returns the maximum value, including text and logical values. | `=MAXA(1, TRUE, "2")` | Accepts more than 2 values |-| `MEDIAN` | Query | Returns the median value. | `=MEDIAN(1, 2, 100)` | Accepts more than 2 values |-| `MID` | Query, Rules | Returns substring from specified position. | `=MID(notes, 1, 10)` | — |-| `MIN` | Query | Returns the minimum value. | `=MIN(1, 2, 3)` | Accepts more than 2 values |-| `MINA` | Query | Returns the minimum value, including text and logical values. | `=MINA(1, TRUE, "2")` | Accepts more than 2 values |-| `MOD` | Query, Rules | Returns the remainder of division. | `=MOD(10, 3)` | — |-| `MODE` | Query | Returns the most frequently occurring value. | `=MODE(1, 1, 2)` | Accepts more than 2 values |-| `MONTH` | Query, Rules | Returns the month from a date. | `=MONTH(date)` | — |-| `N` | Rules | Converts value to a number. | `=N(TRUE())` | — |-| `NETWORKDAYS` | Query | Returns number of working days between dates. | `=NETWORKDAYS("2025-12-01", "2025-12-31")` | — |-| `NOT` | Query, Rules | Reverses the logical value. | `=NOT(amount<0)` | — |-| `NOW` | Query, Rules | Returns current date and time. | `=NOW()` | — |-| `NPV` | Query | Calculates net present value. | `=NPV(0.1, -1000, 200, 300)` | Accepts more than 2 values |-| `OR` | Query, Rules | Returns TRUE if any argument is TRUE. | `=OR(amount<0, amount>0)` | Accepts more than 2 conditions |-| `PERCENTILE` | Query | Returns the k-th percentile. | `=PERCENTILE(A1:A100, 0.9)` | — |-| `PI` | Query | Returns the value of PI. | `=PI()` | — |-| `PMT` | Query | Calculates payment for a loan. | `=PMT(0.05/12, 60, 10000)` | — |-| `POWER` | Query, Rules | Returns base raised to the power of exponent. | `=POWER(2, 8)` | — |-| `PROPER` | Query, Rules | Capitalizes first letter of each word. | `=PROPER(notes)` | — |-| `PRODUCT` | Query | Returns the product of all numbers. | `=PRODUCT(2, 3, 4)` | Accepts more than 2 values |-| `PV` | Query | Calculates present value of investment. | `=PV(0.05/12, 12, -100)` | — |-| `QUARTILE` | Query | Returns the quartile of a dataset. | `=QUARTILE(A1:A100, 1)` | — |-| `QUERY` | Query | Execute a query and return the result. | `=QUERY("expenses")` | — |-| `QUERY_COUNT` | Query | Execute a query and return the number of matching rows. | `=QUERY_COUNT("expenses")` | — |-| `QUERY_EXTRACT_CATEGORIES` | Query | Determines which categories to include based on a named query's category filters; used as the `categories` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_CATEGORIES("expenses")` | — |-| `QUERY_EXTRACT_TIMEFRAME_END` | Query | Extracts the end month from a named query's date range; used as the `endMonth` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_TIMEFRAME_END("expenses")` | — |-| `QUERY_EXTRACT_TIMEFRAME_START` | Query | Extracts the start month from a named query's date range; used as the `startMonth` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_TIMEFRAME_START("expenses")` | — |-| `RANK` | Query | Returns the rank of a number in a list. | `=RANK(10, A1:A10, 0)` | — |-| `RATE` | Query | Calculates interest rate per period. | `=RATE(60, -200, 10000)` | — |-| `REPLACE` | Query, Rules | Replaces substring at specified position. | `=REPLACE(notes, 1, 5, "")` | — |-| `REPT` | Query, Rules | Repeats text specified number of times. | `=REPT("*", 10)` | — |-| `RIGHT` | Query, Rules | Returns rightmost characters from text. | `=RIGHT(imported_payee, 4)` | — |-| `ROUND` | Query, Rules | Rounds a number to specified decimals. | `=ROUND(amount/100, 2)` | — |-| `ROUNDDOWN` | Query, Rules | Rounds down to specified decimals. | `=ROUNDDOWN(amount/100, 0)` | — |-| `ROUNDUP` | Query, Rules | Rounds up to specified decimals. | `=ROUNDUP(amount/100, 0)` | — |-| `SEARCH` | Query, Rules | Finds text within text (case-insensitive, supports wildcards). | `=SEARCH("foo", notes)` | — |-| `SIGN` | Rules | Returns -1 for negative, 0 for zero, 1 for positive. | `=SIGN(amount)` | — |-| `SIN` | Query | Returns the sine of an angle. | `=SIN(1)` | — |-| `SPLIT` | Rules | Splits text by space and returns part at index. | `=SPLIT(imported_payee, 0)` | — |-| `SQRT` | Query, Rules | Returns the square root. | `=SQRT(9)` | — |-| `STDEV` | Query | Returns the standard deviation of a sample. | `=STDEV(A1:A10)` | — |-| `STDEVP` | Query | Returns the standard deviation of a population. | `=STDEVP(A1:A10)` | — |-| `SUBSTITUTE` | Query, Rules | Replaces occurrences of text. | `=SUBSTITUTE(imported_payee, " 12345", "")` | — |-| `SUM` | Query, Rules | Returns the sum of all numbers in a range. | `=SUM(1, 2, 3)` | Accepts more than 2 values |-| `SUMIF` | Query | Sums cells that meet a criteria. | `=SUMIF(A1:A10, ">0", B1:B10)` | — |-| `SUMIFS` | Query | Sums cells that meet multiple criteria. | `=SUMIFS(B1:B10, A1:A10, ">0", C1:C10, "X")` | Repeat `(range, criteria)` pairs |-| `SUMPRODUCT` | Query | Multiplies corresponding elements and returns the sum. | `=SUMPRODUCT(A1:A10, B1:B10)` | Accepts more arrays |-| `SUMSQ` | Query | Returns the sum of the squares. | `=SUMSQ(1, 2, 3)` | Accepts more than 2 values |-| `SWITCH` | Query, Rules | Matches expression against values and returns corresponding result. | `=SWITCH(category_name, "Groceries", "Food", "Fuel", "Transport")` | Repeat `(value, result)` pairs; default supported |-| `T` | Rules | Returns text if value is text, empty string otherwise. | `=T(notes)` | — |-| `TAN` | Query | Returns the tangent of an angle. | `=TAN(1)` | — |-| `TEXT` | Query, Rules | Converts number to text with format. | `=TEXT(date, "MMMM yyyy")` | — |-| `TODAY` | Query, Rules | Returns current date. | `=TODAY()` | — |-| `TRIM` | Query, Rules | Removes extra spaces from text. | `=TRIM(notes)` | — |-| `TRUNC` | Rules | Truncates number to specified decimals. | `=TRUNC(amount/100, 0)` | — |-| `TRUE` | Query, Rules | Returns the logical value TRUE. | `=TRUE()` | — |-| `UPPER` | Query, Rules | Converts text to uppercase. | `=UPPER(notes)` | — |-| `VALUE` | Rules | Converts text to a number. | `=VALUE("123.45")` | — |-| `VAR` | Query | Returns the variance of a sample. | `=VAR(A1:A10)` | — |-| `VARP` | Query | Returns the variance of a population. | `=VARP(A1:A10)` | — |-| `VLOOKUP` | Query | Searches vertically in first column and returns value. | `=VLOOKUP("key", A1:D10, 2, TRUE)` | — |-| `WEEKDAY` | Query, Rules | Returns day of week (1-7). | `=WEEKDAY(date, 1)` | — |-| `WEEKNUM` | Query, Rules | Returns week number of year. | `=WEEKNUM(date, 1)` | — |-| `XOR` | Query, Rules | Returns TRUE if odd number of arguments are TRUE. | `=XOR(TRUE(), FALSE())` | Accepts more than 2 conditions |-| `YEAR` | Query, Rules | Returns the year from a date. | `=YEAR(date)` | — |+| Function | Available in | Description | Syntax example | Optional params |+| ------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |+| `ABS` | Query, Rules | Returns the absolute value of a number. | `=ABS(-42)` | — |+| `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` | Query, Rules | Balance for an account; pass a quoted account id or exact account name. In rules, the running balance (cents) at this transaction; in reports, the account's current balance (money units). | `=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)` | — |+| `CHOOSE` | Query | Returns value from list based on index. | `=CHOOSE(2, "A", "B", "C")` | Accepts more than 2 values |+| `CLEAN` | Rules | Removes non-printable characters from text. | `=CLEAN(notes)` | — |+| `CODE` | Query, Rules | Returns numeric code for first character. | `=CODE("A")` | — |+| `CONCATENATE` | Query, Rules | Combines several text strings into one. | `=CONCATENATE("Paid ", payee_name)` | Accepts more than 2 texts |+| `COS` | Query | Returns the cosine of an angle. | `=COS(1)` | — |+| `COUNT` | Query | Counts the number of numeric values. | `=COUNT(1, 2, "x")` | Accepts more than 2 values |+| `COUNTA` | Query | Counts non-empty values. | `=COUNTA(1, "", "x")` | Accepts more than 2 values |+| `COUNTBLANK` | Query | Counts empty cells. | `=COUNTBLANK(A1:A10)` | — |+| `COUNTIF` | Query | Counts cells that meet a criteria. | `=COUNTIF(A1:A10, ">0")` | — |+| `COUNTIFS` | Query | Counts cells that meet multiple criteria. | `=COUNTIFS(A1:A10, ">0", B1:B10, "<=5")` | Repeat `(range, criteria)` pairs |+| `DATE` | Query, Rules | Returns date as number of days since null date. | `=DATE(2025, 12, 16)` | — |+| `DATEDIF` | Query, Rules | Calculates distance between dates. | `=DATEDIF("2025-01-01", "2025-12-31", "D")` | — |+| `DATEVALUE` | Rules | Parses a date string and returns it as a number. | `=DATEVALUE("2025-12-16")` | — |+| `DAY` | Query, Rules | Returns the day from a date. | `=DAY(date)` | — |+| `DAYS` | Query, Rules | Calculates difference between dates in days. | `=DAYS("2025-12-31", "2025-12-01")` | — |+| `EDATE` | Query, Rules | Returns date shifted by specified months. | `=EDATE(date, 1)` | — |+| `EOMONTH` | Query, Rules | Returns last day of month after specified months. | `=EOMONTH(date, 0)` | — |+| `EXACT` | Query, Rules | Returns TRUE if texts are exactly the same. | `=EXACT("A", "a")` | — |+| `EXP` | Query | Returns e raised to the power of number. | `=EXP(1)` | — |+| `FALSE` | Query, Rules | Returns the logical value FALSE. | `=FALSE()` | — |+| `FIND` | Query, Rules | Finds text within text (case-sensitive). | `=FIND("foo", notes)` | — |+| `FLOOR` | Query, Rules | Rounds down to nearest multiple of significance. | `=FLOOR(10.8, 1)` | — |+| `FORMATCURRENCY` | Query, Rules | Formats a number as currency using your app currency, number format, symbol position, and spacing settings by default. | `=FORMATCURRENCY(1234.5)` | `symbol`, `decimals`, `thousandsSeparator`, `decimalSeparator`, `symbolPosition`, `spaceBetweenAmountAndSymbol` |+| `FORMATNUMBER` | Query, Rules | Formats a number using your app number format settings by default. | `=FORMATNUMBER(1234.5, 2)` | `decimals`, `thousandsSeparator`, `decimalSeparator` |+| `FV` | Query | Calculates future value of investment. | `=FV(0.05/12, 12, -100)` | — |+| `HLOOKUP` | Query | Searches horizontally in first row and returns value. | `=HLOOKUP("key", A1:D10, 2, TRUE)` | — |+| `IF` | Query, Rules | Returns one value if condition is TRUE, another if FALSE. | `=IF(amount<0, "Expense", "Income")` | — |+| `IFERROR` | Query, Rules | Returns value if no error, otherwise returns alternative. | `=IFERROR(1/0, 0)` | — |+| `IFNA` | Query, Rules | Returns value if not #N/A error, otherwise returns alternative. | `=IFNA(VLOOKUP("x", A1:B10, 2, FALSE), 0)` | — |+| `IFS` | Query, Rules | Checks multiple conditions and returns corresponding values. | `=IFS(amount<0, "Expense", amount>0, "Income")` | Repeat `(condition, value)` pairs |+| `INDEX` | Query | Returns value at specified row and column. | `=INDEX(A1:C10, 2, 3)` | — |+| `INTEGER_TO_AMOUNT` | Query, Rules | Converts integer amount to decimal amount (e.g., 1234 -> 12.34). | `=INTEGER_TO_AMOUNT(amount, 2)` | `decimal_places` (default: 2) |+| `INT` | Rules | Rounds down to nearest integer. | `=INT(10.9)` | — |+| `IRR` | Query | Calculates internal rate of return. | `=IRR(A1:A12)` | — |+| `ISEVEN` | Rules | Returns TRUE if number is even. | `=ISEVEN(10)` | — |+| `ISODD` | Rules | Returns TRUE if number is odd. | `=ISODD(11)` | — |+| `ISBLANK` | Query, Rules | Returns TRUE if value is blank. | `=ISBLANK(notes)` | — |+| `ISERROR` | Query, Rules | Returns TRUE if value is any error. | `=ISERROR(1/0)` | — |+| `ISLOGICAL` | Query, Rules | Returns TRUE if value is logical (TRUE/FALSE). | `=ISLOGICAL(TRUE())` | — |+| `ISNA` | Query, Rules | Returns TRUE if value is #N/A error. | `=ISNA(NA())` | — |+| `ISNUMBER` | Query, Rules | Returns TRUE if value is a number. | `=ISNUMBER(amount)` | — |+| `ISOWEEKNUM` | Rules | Returns ISO week number. | `=ISOWEEKNUM(date)` | — |+| `ISREF` | Query | Returns TRUE if value is a reference. | `=ISREF(A1)` | — |+| `ISTEXT` | Query, Rules | Returns TRUE if value is text. | `=ISTEXT(notes)` | — |+| `LEFT` | Query, Rules | Returns leftmost characters from text. | `=LEFT(imported_payee, 10)` | — |+| `LEN` | Query, Rules | Returns length of text. | `=LEN(notes)` | — |+| `LN` | Query | Returns the natural logarithm. | `=LN(10)` | — |+| `LOG` | Query | Returns the logarithm to specified base. | `=LOG(100, 10)` | — |+| `LOG10` | Query | Returns the base-10 logarithm. | `=LOG10(1000)` | — |+| `LOOKUP` | Query | Looks up values in a vector or array. | `=LOOKUP("x", A1:A10)` | — |+| `LOWER` | Query, Rules | Converts text to lowercase. | `=LOWER(notes)` | — |+| `MATCH` | Query | Returns position of value in array. | `=MATCH("x", A1:A10, 0)` | — |+| `MAX` | Query | Returns the maximum value. | `=MAX(1, 2, 3)` | Accepts more than 2 values |+| `MAXA` | Query | Returns the maximum value, including text and logical values. | `=MAXA(1, TRUE, "2")` | Accepts more than 2 values |+| `MEDIAN` | Query | Returns the median value. | `=MEDIAN(1, 2, 100)` | Accepts more than 2 values |+| `MID` | Query, Rules | Returns substring from specified position. | `=MID(notes, 1, 10)` | — |+| `MIN` | Query | Returns the minimum value. | `=MIN(1, 2, 3)` | Accepts more than 2 values |+| `MINA` | Query | Returns the minimum value, including text and logical values. | `=MINA(1, TRUE, "2")` | Accepts more than 2 values |+| `MOD` | Query, Rules | Returns the remainder of division. | `=MOD(10, 3)` | — |+| `MODE` | Query | Returns the most frequently occurring value. | `=MODE(1, 1, 2)` | Accepts more than 2 values |+| `MONTH` | Query, Rules | Returns the month from a date. | `=MONTH(date)` | — |+| `N` | Rules | Converts value to a number. | `=N(TRUE())` | — |+| `NETWORKDAYS` | Query | Returns number of working days between dates. | `=NETWORKDAYS("2025-12-01", "2025-12-31")` | — |+| `NOT` | Query, Rules | Reverses the logical value. | `=NOT(amount<0)` | — |+| `NOW` | Query, Rules | Returns current date and time. | `=NOW()` | — |+| `NPV` | Query | Calculates net present value. | `=NPV(0.1, -1000, 200, 300)` | Accepts more than 2 values |+| `OR` | Query, Rules | Returns TRUE if any argument is TRUE. | `=OR(amount<0, amount>0)` | Accepts more than 2 conditions |+| `PERCENTILE` | Query | Returns the k-th percentile. | `=PERCENTILE(A1:A100, 0.9)` | — |+| `PI` | Query | Returns the value of PI. | `=PI()` | — |+| `PMT` | Query | Calculates payment for a loan. | `=PMT(0.05/12, 60, 10000)` | — |+| `POWER` | Query, Rules | Returns base raised to the power of exponent. | `=POWER(2, 8)` | — |+| `PROPER` | Query, Rules | Capitalizes first letter of each word. | `=PROPER(notes)` | — |+| `PRODUCT` | Query | Returns the product of all numbers. | `=PRODUCT(2, 3, 4)` | Accepts more than 2 values |+| `PV` | Query | Calculates present value of investment. | `=PV(0.05/12, 12, -100)` | — |+| `QUARTILE` | Query | Returns the quartile of a dataset. | `=QUARTILE(A1:A100, 1)` | — |+| `QUERY` | Query | Execute a query and return the result. | `=QUERY("expenses")` | — |+| `QUERY_COUNT` | Query | Execute a query and return the number of matching rows. | `=QUERY_COUNT("expenses")` | — |+| `QUERY_EXTRACT_CATEGORIES` | Query | Determines which categories to include based on a named query's category filters; used as the `categories` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_CATEGORIES("expenses")` | — |+| `QUERY_EXTRACT_TIMEFRAME_END` | Query | Extracts the end month from a named query's date range; used as the `endMonth` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_TIMEFRAME_END("expenses")` | — |+| `QUERY_EXTRACT_TIMEFRAME_START` | Query | Extracts the start month from a named query's date range; used as the `startMonth` argument in `BUDGET_QUERY`. | `=QUERY_EXTRACT_TIMEFRAME_START("expenses")` | — |+| `RANK` | Query | Returns the rank of a number in a list. | `=RANK(10, A1:A10, 0)` | — |+| `RATE` | Query | Calculates interest rate per period. | `=RATE(60, -200, 10000)` | — |+| `REPLACE` | Query, Rules | Replaces substring at specified position. | `=REPLACE(notes, 1, 5, "")` | — |+| `REPT` | Query, Rules | Repeats text specified number of times. | `=REPT("*", 10)` | — |+| `RIGHT` | Query, Rules | Returns rightmost characters from text. | `=RIGHT(imported_payee, 4)` | — |+| `ROUND` | Query, Rules | Rounds a number to specified decimals. | `=ROUND(amount/100, 2)` | — |+| `ROUNDDOWN` | Query, Rules | Rounds down to specified decimals. | `=ROUNDDOWN(amount/100, 0)` | — |+| `ROUNDUP` | Query, Rules | Rounds up to specified decimals. | `=ROUNDUP(amount/100, 0)` | — |+| `SEARCH` | Query, Rules | Finds text within text (case-insensitive, supports wildcards). | `=SEARCH("foo", notes)` | — |+| `SIGN` | Rules | Returns -1 for negative, 0 for zero, 1 for positive. | `=SIGN(amount)` | — |+| `SIN` | Query | Returns the sine of an angle. | `=SIN(1)` | — |+| `SPLIT` | Rules | Splits text by space and returns part at index. | `=SPLIT(imported_payee, 0)` | — |+| `SQRT` | Query, Rules | Returns the square root. | `=SQRT(9)` | — |+| `STDEV` | Query | Returns the standard deviation of a sample. | `=STDEV(A1:A10)` | — |+| `STDEVP` | Query | Returns the standard deviation of a population. | `=STDEVP(A1:A10)` | — |+| `SUBSTITUTE` | Query, Rules | Replaces occurrences of text. | `=SUBSTITUTE(imported_payee, " 12345", "")` | — |+| `SUM` | Query, Rules | Returns the sum of all numbers in a range. | `=SUM(1, 2, 3)` | Accepts more than 2 values |+| `SUMIF` | Query | Sums cells that meet a criteria. | `=SUMIF(A1:A10, ">0", B1:B10)` | — |+| `SUMIFS` | Query | Sums cells that meet multiple criteria. | `=SUMIFS(B1:B10, A1:A10, ">0", C1:C10, "X")` | Repeat `(range, criteria)` pairs |+| `SUMPRODUCT` | Query | Multiplies corresponding elements and returns the sum. | `=SUMPRODUCT(A1:A10, B1:B10)` | Accepts more arrays |+| `SUMSQ` | Query | Returns the sum of the squares. | `=SUMSQ(1, 2, 3)` | Accepts more than 2 values |+| `SWITCH` | Query, Rules | Matches expression against values and returns corresponding result. | `=SWITCH(category_name, "Groceries", "Food", "Fuel", "Transport")` | Repeat `(value, result)` pairs; default supported |+| `T` | Rules | Returns text if value is text, empty string otherwise. | `=T(notes)` | — |+| `TAN` | Query | Returns the tangent of an angle. | `=TAN(1)` | — |+| `TEXT` | Query, Rules | Converts number to text with format. | `=TEXT(date, "MMMM yyyy")` | — |+| `TODAY` | Query, Rules | Returns current date. | `=TODAY()` | — |+| `TRIM` | Query, Rules | Removes extra spaces from text. | `=TRIM(notes)` | — |+| `TRUNC` | Rules | Truncates number to specified decimals. | `=TRUNC(amount/100, 0)` | — |+| `TRUE` | Query, Rules | Returns the logical value TRUE. | `=TRUE()` | — |+| `UPPER` | Query, Rules | Converts text to uppercase. | `=UPPER(notes)` | — |+| `VALUE` | Rules | Converts text to a number. | `=VALUE("123.45")` | — |+| `VAR` | Query | Returns the variance of a sample. | `=VAR(A1:A10)` | — |+| `VARP` | Query | Returns the variance of a population. | `=VARP(A1:A10)` | — |+| `VLOOKUP` | Query | Searches vertically in first column and returns value. | `=VLOOKUP("key", A1:D10, 2, TRUE)` | — |+| `WEEKDAY` | Query, Rules | Returns day of week (1-7). | `=WEEKDAY(date, 1)` | — |+| `WEEKNUM` | Query, Rules | Returns week number of year. | `=WEEKNUM(date, 1)` | — |+| `XOR` | Query, Rules | Returns TRUE if odd number of arguments are TRUE. | `=XOR(TRUE(), FALSE())` | Accepts more than 2 conditions |+| `YEAR` | Query, Rules | Returns the year from a date. | `=YEAR(date)` | — |### Formatting numbers and currency@@ -206,6 +206,24 @@ Example:=QUERY("income") - QUERY("expenses")```+### Account balances with `BALANCE_OF("name")`++Formula cards can also reference an account's **current balance** directly, without setting up a named query:++- `BALANCE_OF("Checking")` returns the account's current balance, in normal "money" units (e.g. `-123.45`), the same as `QUERY()`.+- Pass a **quoted account id** for a deterministic match, or a **quoted account name** for an exact name match.+- If the account isn't found, it evaluates as **0**.++Example:++```text+=BALANCE_OF("Checking") + BALANCE_OF("Savings")+```++:::tip+In rule formulas, `BALANCE_OF` instead returns the running balance **at a specific transaction**, in cents — see [Rule formulas](#rule-formulas) below.+:::+### Define a queryIn the Formula editor page, use **Query Definitions**:@@ -337,6 +355,7 @@ Tip: if you want “dollars” from `amount`, use `=amount / 100`.- 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"))`.+- `BALANCE_OF` is also available in Formula cards, where it returns the account's current balance instead — see [Account balances with `BALANCE_OF("name")`](#account-balances-with-balance_ofname) above.### Result typesdiff --git a/packages/loot-core/src/server/rules/customFunctions.test.ts b/packages/loot-core/src/server/rules/customFunctions.test.tsindex 0efdb118ad..a2313541ba 100644--- a/packages/loot-core/src/server/rules/customFunctions.test.ts+++ b/packages/loot-core/src/server/rules/customFunctions.test.ts@@ -16,12 +16,14 @@ function createFormulaQueryContext(): Required<FormulaQueryContext> {queryExtractCategoryNames: new Set(),queryExtractTimeframeStartNames: new Set(),queryExtractTimeframeEndNames: new Set(),+ balanceOfNames: new Set(),budgetQueryRequests: new Map(),querySumPrefetch: new Map(),queryCountPrefetch: new Map(),queryExtractCategoriesPrefetch: new Map(),queryExtractTimeframeStartPrefetch: new Map(),queryExtractTimeframeEndPrefetch: new Map(),+ balanceOfPrefetch: new Map(),budgetQueryPrefetch: new Map(),budgetQueryErrors: new Map(),};diff --git a/packages/loot-core/src/shared/formulas/customFunctions.ts b/packages/loot-core/src/shared/formulas/customFunctions.tsindex aee7223053..75900c7d2e 100644--- a/packages/loot-core/src/shared/formulas/customFunctions.ts+++ b/packages/loot-core/src/shared/formulas/customFunctions.ts@@ -30,12 +30,14 @@ export type FormulaQueryContext = {queryExtractCategoryNames?: Set<string>;queryExtractTimeframeStartNames?: Set<string>;queryExtractTimeframeEndNames?: Set<string>;+ balanceOfNames?: Set<string>;budgetQueryRequests?: Map<string, BudgetQueryRequest>;querySumPrefetch?: Map<string, number>;queryCountPrefetch?: Map<string, number>;queryExtractCategoriesPrefetch?: Map<string, string[]>;queryExtractTimeframeStartPrefetch?: Map<string, string>;queryExtractTimeframeEndPrefetch?: Map<string, string>;+ balanceOfPrefetch?: Map<string, number>;budgetQueryPrefetch?: Map<string, number>;budgetQueryErrors?: Map<string, string>;};@@ -205,7 +207,16 @@ export class CustomFunctionsPlugin extends FunctionPlugin {this.metadata('BALANCE_OF'),(accountKey: string) => {const ctx = this.getCustomFunctionsContext();- return ctx?.balanceOfPrefetch?.get(accountKey) ?? 0;+ if (ctx?.balanceOfPrefetch) {+ // Rule formulas: prefetched relative to the transaction being evaluated.+ return ctx.balanceOfPrefetch.get(accountKey) ?? 0;+ }++ // Report/query formulas: no single transaction to be "before", so this+ // resolves to the account's current balance.+ const formulaQueryCtx = this.getFormulaQueryContext();+ formulaQueryCtx?.balanceOfNames?.add(accountKey);+ return formulaQueryCtx?.balanceOfPrefetch?.get(accountKey) ?? 0;},);}diff --git a/upcoming-release-notes/balance-of-in-formula-cards.md b/upcoming-release-notes/balance-of-in-formula-cards.mdnew file mode 100644index 0000000000..40323e9727--- /dev/null+++ b/upcoming-release-notes/balance-of-in-formula-cards.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [youngcw]+---++Allow the BALANCE_OF function to be used in formula reports