A local-first personal finance app
Enhancements: Formula Card and Rule Action (#5985)
lelemmf2c83fd13b13
diff --git a/packages/desktop-client/src/components/filters/AppliedFilters.tsx b/packages/desktop-client/src/components/filters/AppliedFilters.tsxindex f0c21e5e76..547f4c579c 100644--- a/packages/desktop-client/src/components/filters/AppliedFilters.tsx+++ b/packages/desktop-client/src/components/filters/AppliedFilters.tsx@@ -1,5 +1,6 @@import React from 'react';+import { type CSSProperties } from '@actual-app/components/styles';import { View } from '@actual-app/components/view';import { type RuleConditionEntity } from 'loot-core/types/models';@@ -16,6 +17,7 @@ type AppliedFiltersProps = {onDelete: (filter: RuleConditionEntity) => void;conditionsOp: 'and' | 'or';onConditionsOpChange: (value: 'and' | 'or') => void;+ style?: CSSProperties;};export function AppliedFilters({@@ -24,6 +26,7 @@ export function AppliedFilters({onDelete,conditionsOp,onConditionsOpChange,+ style = {},}: AppliedFiltersProps) {return (<View@@ -31,6 +34,7 @@ export function AppliedFilters({flexDirection: 'row',alignItems: 'flex-start',flexWrap: 'wrap',+ ...style,}}><ConditionsOpMenudiff --git a/packages/desktop-client/src/components/formula/QueryManager.tsx b/packages/desktop-client/src/components/formula/QueryManager.tsxindex 5ee5b13224..f833783a24 100644--- a/packages/desktop-client/src/components/formula/QueryManager.tsx+++ b/packages/desktop-client/src/components/formula/QueryManager.tsx@@ -856,6 +856,7 @@ function QueryItem({onDelete={filters.onDelete}conditionsOp={filters.conditionsOp}onConditionsOpChange={filters.onConditionsOpChange}+ style={{ maxWidth: '100%' }}/>)}<FilterButtondiff --git a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsxindex c3dff985b6..008278ce00 100644--- a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx+++ b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx@@ -391,6 +391,15 @@ const transactionFields: Completion[] = ['Boolean reconciled status. TRUE if transaction is reconciled, FALSE otherwise.',),},+ {+ label: 'balance',+ type: 'variable',+ section: '💰 Transaction Fields',+ boost: 5,+ info: t(+ 'Account balance as of the date of the transaction, excluding the transaction amount. Use for calculations and comparisons.\n\nExample: `=IF(balance < 0, "Negative Balance", "Positive Balance")`',+ ),+ },];// Convert function definitions to completions with groupingdiff --git a/packages/desktop-client/src/components/formula/queryModeFunctions.ts b/packages/desktop-client/src/components/formula/queryModeFunctions.tsindex 01826429f1..c2ea6c38a4 100644--- a/packages/desktop-client/src/components/formula/queryModeFunctions.ts+++ b/packages/desktop-client/src/components/formula/queryModeFunctions.ts@@ -403,6 +403,19 @@ export const queryModeFunctions: Record<string, FunctionDef> = {description: t('Combines several text strings into one.'),parameters: [{ name: 'texts', description: 'Text1, Text2, ...TextN' }],},+ INTEGER_TO_AMOUNT: {+ name: 'INTEGER_TO_AMOUNT',+ description: t(+ 'Converts integer amount to decimal amount (e.g., 1234 -> 12.34).',+ ),+ parameters: [+ { name: 'integer_amount', description: 'Integer amount in cents' },+ {+ name: 'decimal_places',+ description: 'Number of decimal places (default: 2)',+ },+ ],+ },UPPER: {name: 'UPPER',description: t('Converts text to uppercase.'),diff --git a/packages/desktop-client/src/components/formula/transactionModeFunctions.ts b/packages/desktop-client/src/components/formula/transactionModeFunctions.tsindex e0a0ff57bd..01ae0df11a 100644--- a/packages/desktop-client/src/components/formula/transactionModeFunctions.ts+++ b/packages/desktop-client/src/components/formula/transactionModeFunctions.ts@@ -45,6 +45,19 @@ export const transactionModeFunctions: Record<string, FunctionDef> = {{ name: 'num_chars', description: 'Number' },],},+ INTEGER_TO_AMOUNT: {+ name: 'INTEGER_TO_AMOUNT',+ description: t(+ 'Converts integer amount to decimal amount (e.g., 1234 -> 12.34).',+ ),+ parameters: [+ { name: 'integer_amount', description: 'Integer amount in cents' },+ {+ name: 'decimal_places',+ description: 'Number of decimal places (default: 2)',+ },+ ],+ },MID: {name: 'MID',description: t('Returns substring from specified position.'),diff --git a/packages/desktop-client/src/components/reports/FormulaResult.tsx b/packages/desktop-client/src/components/reports/FormulaResult.tsxindex c27859f4d6..9c79ff258c 100644--- a/packages/desktop-client/src/components/reports/FormulaResult.tsx+++ b/packages/desktop-client/src/components/reports/FormulaResult.tsx@@ -89,7 +89,9 @@ export function FormulaResult({// Debounce the calculation to avoid too many recalculationsconst debouncedCalculateFontSize = useRef(debounce(() => {- calculateFontSize();+ if (fontSizeMode === 'dynamic') {+ calculateFontSize();+ }}, 100),);@@ -97,13 +99,15 @@ export function FormulaResult({useEffect(() => {debouncedCalculateFontSize.current.cancel?.();debouncedCalculateFontSize.current = debounce(() => {- calculateFontSize();+ if (fontSizeMode === 'dynamic') {+ calculateFontSize();+ }}, 100);return () => {debouncedCalculateFontSize.current.cancel?.();};- }, [calculateFontSize]);+ }, [calculateFontSize, fontSizeMode]);const ref = useResizeObserver(() => {if (fontSizeMode === 'dynamic') {@@ -135,7 +139,7 @@ export function FormulaResult({: theme.pageText;return (- <>+ <View style={{ flex: 1 }}>{loading && <LoadingIndicator />}{!loading && (<View@@ -162,6 +166,6 @@ export function FormulaResult({</span></View>)}- </>+ </View>);}diff --git a/packages/desktop-client/src/components/reports/reports/Formula.tsx b/packages/desktop-client/src/components/reports/reports/Formula.tsxindex def6cbb1e4..3dfbd3bc13 100644--- a/packages/desktop-client/src/components/reports/reports/Formula.tsx+++ b/packages/desktop-client/src/components/reports/reports/Formula.tsx@@ -14,6 +14,7 @@ import { Button } from '@actual-app/components/button';import { useResponsive } from '@actual-app/components/hooks/useResponsive';import { Input } from '@actual-app/components/input';import { Select } from '@actual-app/components/select';+import { styles } from '@actual-app/components/styles';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';@@ -253,13 +254,16 @@ function FormulaInner({ widget }: FormulaInnerProps) {<Viewstyle={{padding: 20,+ flexDirection: 'column',+ justifyContent: 'space-between',+ gap: 10,+ minHeight: 120,}}><divstyle={{fontSize: 14,color: theme.pageTextSubdued,- marginBottom: 8,}}><Trans>Result:</Trans>@@ -268,6 +272,13 @@ function FormulaInner({ widget }: FormulaInnerProps) {style={{height: 120,width: '100%',+ overflow: 'auto',+ backgroundColor: theme.cardBackground,+ borderRadius: 6,+ ...styles.horizontalScrollbar,+ '::-webkit-scrollbar': {+ height: '8px',+ },}}><FormulaResult@@ -284,7 +295,7 @@ function FormulaInner({ widget }: FormulaInnerProps) {<Viewstyle={{flex: 1,- minHeight: 300,+ minHeight: 50,margin: 20,overflow: 'hidden',}}@@ -358,8 +369,6 @@ function FormulaInner({ widget }: FormulaInnerProps) {onChange={(e: ChangeEvent<HTMLInputElement>) =>setStaticFontSize(Number(e.target.value))}- min="8"- max="200"/></View>)}diff --git a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsxindex 9f0ffe55a1..da9ba31032 100644--- a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx@@ -47,7 +47,7 @@ export function FormulaCard({RESULT: result ?? 0,...Object.entries(themeColors).reduce((acc, [key, value]) => {- acc[`theme.${key}`] = value;+ acc[`theme_${key}`] = value;return acc;},{} as Record<string, string>,diff --git a/packages/desktop-client/src/components/rules/FormulaActionEditor.tsx b/packages/desktop-client/src/components/rules/FormulaActionEditor.tsxindex b118244acb..e54ab64cbf 100644--- a/packages/desktop-client/src/components/rules/FormulaActionEditor.tsx+++ b/packages/desktop-client/src/components/rules/FormulaActionEditor.tsx@@ -32,7 +32,7 @@ export function FormulaActionEditor({flex: 1,border: `1px solid ${theme.formInputBorder}`,borderRadius: 4,- overflow: 'hidden',+ overflow: 'visible',backgroundColor: disabled? theme.formInputBackgroundSelection: theme.tableBackground,diff --git a/packages/loot-core/src/server/rules/action.ts b/packages/loot-core/src/server/rules/action.tsindex 5a78c53368..f9cf87d3e5 100644--- a/packages/loot-core/src/server/rules/action.ts+++ b/packages/loot-core/src/server/rules/action.ts@@ -8,6 +8,7 @@ import { parseDate, format, currentDay } from '../../shared/months';import { FIELD_TYPES } from '../../shared/rules';import { TransactionForRules } from '../transactions/transaction-rules';+import { CustomFunctionsPlugin } from './customFunctions';import { assert } from './rule-utils';const ACTION_OPS = [@@ -248,6 +249,8 @@ export class Action {}try {+ HyperFormula.registerFunctionPlugin(CustomFunctionsPlugin);+hfInstance = HyperFormula.buildEmpty({licenseKey: 'gpl-v3',});@@ -270,52 +273,24 @@ export class Action {category_name: transaction._category_name || '',};- let row = 1;for (const key of Object.keys(fieldValues)) {- hfInstance.setCellContents({ sheet: sheetId, col: 0, row }, [['']]);- hfInstance.addNamedExpression(key, `=Sheet1!$A$${row + 1}`);-- row++;- }-- hfInstance.setCellContents({ sheet: sheetId, col: 0, row: 0 }, [- [formula],- ]);-- const parserCache = (- hfInstance as unknown as {- _parser: { cache: { cache: Map<string, { ast: unknown }> } };- }- )._parser.cache.cache;- const cacheEntry = parserCache.get(formula);- const usedVariables = new Set<string>();-- if (cacheEntry && cacheEntry.ast) {- const extractedVars = this.extractVariablesFromAST(cacheEntry.ast);- for (const variable of extractedVars) {- usedVariables.add(variable);- }- }-- row = 1;- for (const [, value] of Object.entries(fieldValues)) {let cellValue: string | number | boolean;if (- value === undefined ||- value === null ||- typeof value === 'object'+ fieldValues[key] === undefined ||+ fieldValues[key] === null ||+ typeof fieldValues[key] === 'object') {cellValue = '';} else {- cellValue = value;+ cellValue = fieldValues[key];}-- hfInstance.setCellContents({ sheet: sheetId, col: 0, row }, [- [cellValue],- ]);- row++;+ hfInstance.addNamedExpression(key, cellValue);}+ hfInstance.setCellContents({ sheet: sheetId, col: 0, row: 0 }, [+ [formula],+ ]);+const cellAddress = { sheet: sheetId, col: 0, row: 0 };const cellValue = hfInstance.getCellValue(cellAddress);diff --git a/packages/loot-core/src/server/rules/customFunctions.ts b/packages/loot-core/src/server/rules/customFunctions.tsnew file mode 100644index 0000000000..9c450dcfa3--- /dev/null+++ b/packages/loot-core/src/server/rules/customFunctions.ts@@ -0,0 +1,32 @@+import { FunctionPlugin, FunctionArgumentType } from 'hyperformula';+import { InterpreterState } from 'hyperformula/typings/interpreter/InterpreterState';+import { ProcedureAst } from 'hyperformula/typings/parser';++import { integerToAmount } from '../../shared/util';++export class CustomFunctionsPlugin extends FunctionPlugin {+ integerToAmount(ast: ProcedureAst, state: InterpreterState) {+ return this.runFunction(+ ast.args,+ state,+ this.metadata('INTEGER_TO_AMOUNT'),+ (integerAmount: number, decimalPlaces: number = 2) => {+ return integerToAmount(integerAmount, decimalPlaces);+ },+ );+ }+}++CustomFunctionsPlugin.implementedFunctions = {+ INTEGER_TO_AMOUNT: {+ method: 'integerToAmount',+ parameters: [+ { argumentType: FunctionArgumentType.NUMBER },+ {+ argumentType: FunctionArgumentType.NUMBER,+ optionalArg: true,+ defaultValue: 2,+ },+ ],+ },+};diff --git a/packages/loot-core/src/server/rules/formula-action.test.ts b/packages/loot-core/src/server/rules/formula-action.test.tsindex 90114c223c..0ae255b338 100644--- a/packages/loot-core/src/server/rules/formula-action.test.ts+++ b/packages/loot-core/src/server/rules/formula-action.test.ts@@ -5,190 +5,171 @@ import { TransactionForRules } from '../transactions/transaction-rules';import { Action } from './action';describe('Formula-based rule actions', () => {- describe('executeFormulaSync', () => {- it('should execute a simple math formula', () => {- const action = new Action('set', 'amount', null, {- formula: '=100 + 200',- });+ it('should execute a simple math formula', () => {+ const action = new Action('set', 'amount', null, {});+ const transaction: Partial<TransactionForRules> = { amount: 500 };+ const result = action.executeFormulaSync('=100 + 200', transaction);- const transaction: Partial<TransactionForRules> = { amount: 500 };- const result = action.executeFormulaSync('=100 + 200', transaction);-- expect(result).toBe(300);- });+ expect(result).toBe(300);+ });- it('should use transaction field variables', () => {- const action = new Action('set', 'notes', null, {- formula: '=amount / 100',- });+ it('should use transaction field variables', () => {+ const action = new Action('set', 'notes', null, {});+ const transaction = { amount: 5000 };+ const result = action.executeFormulaSync('=amount / 100', transaction);- const transaction = { amount: 5000 };- const result = action.executeFormulaSync('=amount / 100', transaction);+ expect(result).toBe(50);+ });- expect(result).toBe(50);- });+ it('should support IF function with transaction fields', () => {+ const action = new Action('set', 'notes', null, {});++ const transaction1 = { amount: 1000 };+ const result1 = action.executeFormulaSync(+ '=IF(amount > 0, "Income", "Expense")',+ transaction1,+ );+ expect(result1).toBe('Income');++ const transaction2 = { amount: -1000 };+ const result2 = action.executeFormulaSync(+ '=IF(amount > 0, "Income", "Expense")',+ transaction2,+ );+ expect(result2).toBe('Expense');+ });- it('should support IF function with transaction fields', () => {- const action = new Action('set', 'notes', null, {- formula: '=IF(amount > 0, "Income", "Expense")',- });-- const transaction1 = { amount: 1000 };- const result1 = action.executeFormulaSync(- '=IF(amount > 0, "Income", "Expense")',- transaction1,- );- expect(result1).toBe('Income');-- const transaction2 = { amount: -1000 };- const result2 = action.executeFormulaSync(- '=IF(amount > 0, "Income", "Expense")',- transaction2,- );- expect(result2).toBe('Expense');- });+ it('should support UPPER string function', () => {+ const action = new Action('set', 'notes', null, {});+ const transaction = { notes: 'hello world' };+ const result = action.executeFormulaSync('=UPPER(notes)', transaction);- it('should support UPPER string function', () => {- const action = new Action('set', 'notes', null, {- formula: '=UPPER(notes)',- });+ expect(result).toBe('HELLO WORLD');+ });- const transaction = { notes: 'hello world' };- const result = action.executeFormulaSync('=UPPER(notes)', transaction);+ it('should support CONCATENATE function', () => {+ const action = new Action('set', 'notes', null, {});+ const transaction = {+ imported_payee: 'Store Name',+ notes: 'Purchase',+ };+ const result = action.executeFormulaSync(+ '=CONCATENATE(imported_payee, " - ", notes)',+ transaction,+ );++ expect(result).toBe('Store Name - Purchase');+ });- expect(result).toBe('HELLO WORLD');- });+ it('should support LEFT function', () => {+ const action = new Action('set', 'notes', null, {});+ const transaction = { imported_payee: 'Store Name' };+ const result = action.executeFormulaSync(+ '=LEFT(imported_payee, 5)',+ transaction,+ );- it('should support CONCATENATE function', () => {- const action = new Action('set', 'notes', null, {- formula: '=CONCATENATE(imported_payee, " - ", notes)',- });-- const transaction = {- imported_payee: 'Store Name',- notes: 'Purchase',- };- const result = action.executeFormulaSync(- '=CONCATENATE(imported_payee, " - ", notes)',- transaction,- );-- expect(result).toBe('Store Name - Purchase');- });+ expect(result).toBe('Store');+ });- it('should support LEFT function', () => {- const action = new Action('set', 'notes', null, {- formula: '=LEFT(imported_payee, 5)',- });+ it('should provide today variable', () => {+ const action = new Action('set', 'date', null, {});+ const transaction = { date: '2024-01-01' };+ const result = action.executeFormulaSync('=today', transaction);- const transaction = { imported_payee: 'Store Name' };- const result = action.executeFormulaSync(- '=LEFT(imported_payee, 5)',- transaction,- );+ // Should be a date string in YYYY-MM-DD format+ expect(typeof result).toBe('string');+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });- expect(result).toBe('Store');- });+ it('should throw error for invalid formula', () => {+ const action = new Action('set', 'notes', null, {});+ const transaction = { amount: 100 };- it('should provide today variable', () => {- const action = new Action('set', 'date', null, {- formula: '=today',- });+ expect(() => {+ action.executeFormulaSync('=INVALID_FUNCTION()', transaction);+ }).toThrow();+ });- const transaction = { date: '2024-01-01' };- const result = action.executeFormulaSync('=today', transaction);+ it('should throw error for formula without = prefix', () => {+ const action = new Action('set', 'notes', null, {});+ const transaction = { amount: 100 };- // Should be a date string in YYYY-MM-DD format- expect(typeof result).toBe('string');- expect(result).toMatch(/^\d{4}-\d{2}-\d{2}$/);- });+ expect(() => {+ action.executeFormulaSync('amount + 100', transaction);+ }).toThrow('Formula must start with =');+ });- it('should throw error for invalid formula', () => {- const action = new Action('set', 'notes', null, {- formula: '=INVALID_FUNCTION()',- });+ it('should support balance field variable', () => {+ const action = new Action('set', 'notes', null, {});+ const transaction: Partial<TransactionForRules> = {+ balance: 1500,+ notes: 'original',+ };+ const result = action.executeFormulaSync('=balance * 2', transaction);- const transaction = { amount: 100 };+ expect(result).toBe(3000);+ });- expect(() => {- action.executeFormulaSync('=INVALID_FUNCTION()', transaction);- }).toThrow();+ it('should execute formula and convert to number type', () => {+ const action = new Action('set', 'amount', null, {+ formula: '=500 + 250',});- it('should throw error for formula without = prefix', () => {- const action = new Action('set', 'notes', null, {- formula: 'amount + 100',- });+ const transaction = { amount: 100 };+ action.exec(transaction);- const transaction = { amount: 100 };-- expect(() => {- action.executeFormulaSync('amount + 100', transaction);- }).toThrow('Formula must start with =');- });+ expect(transaction.amount).toBe(750);});- describe('Action.exec with formula option', () => {- it('should execute formula and convert to number type', () => {- const action = new Action('set', 'amount', null, {- formula: '=500 + 250',- });-- const transaction = { amount: 100 };- action.exec(transaction);-- expect(transaction.amount).toBe(750);+ it('should execute formula and convert to string type', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=UPPER("hello")',});- it('should execute formula and convert to string type', () => {- const action = new Action('set', 'notes', null, {- formula: '=UPPER("hello")',- });+ const transaction = { notes: 'original' };+ action.exec(transaction);- const transaction = { notes: 'original' };- action.exec(transaction);+ expect(transaction.notes).toBe('HELLO');+ });- expect(transaction.notes).toBe('HELLO');+ it('should handle formula errors gracefully', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=1/0', // Division by zero});- it('should handle formula errors gracefully', () => {- const action = new Action('set', 'notes', null, {- formula: '=1/0', // Division by zero- });+ const transaction = { notes: 'original' };- const transaction = { notes: 'original' };+ // Should not throw, but keep original value on error+ expect(() => {+ action.exec(transaction);+ }).not.toThrow();- // Should not throw, but keep original value on error- expect(() => {- action.exec(transaction);- }).not.toThrow();+ // Original value should be preserved+ expect(transaction.notes).toBe('original');+ });- // Original value should be preserved- expect(transaction.notes).toBe('original');+ it('should validate numeric field output', () => {+ const action = new Action('set', 'amount', null, {+ formula: '=UPPER("test")', // Returns string for numeric field});- it('should validate numeric field output', () => {- const action = new Action('set', 'amount', null, {- formula: '=UPPER("test")', // Returns string for numeric field- });+ const transaction = { amount: 100 };+ action.exec(transaction);- const transaction = { amount: 100 };- action.exec(transaction);+ // Should keep original value when formula produces non-numeric result+ expect(transaction.amount).toBe(100);+ });- // Should keep original value when formula produces non-numeric result- expect(transaction.amount).toBe(100);+ it('should convert non-string results to string for text fields', () => {+ const action = new Action('set', 'notes', null, {+ formula: '=500 + 250', // Returns number});- it('should convert non-string results to string for text fields', () => {- const action = new Action('set', 'notes', null, {- formula: '=500 + 250', // Returns number- });-- const transaction = { notes: 'original' };- action.exec(transaction);+ const transaction = { notes: 'original' };+ action.exec(transaction);- // Should convert number to string- expect(transaction.notes).toBe('750');- });+ // Should convert number to string+ expect(transaction.notes).toBe('750');});});diff --git a/tsconfig.json b/tsconfig.jsonindex 32f514cb1d..f3d6a50054 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -33,7 +33,9 @@// TEMPORARY: Until we can fix the "exports" in the loot-core package.json"loot-core/*": ["./packages/loot-core/src/*"],"@desktop-client/*": ["./packages/desktop-client/src/*"],- "@desktop-client/e2e/*": ["./packages/desktop-client/e2e/*"]+ "@desktop-client/e2e/*": ["./packages/desktop-client/e2e/*"],+ // Allow importing from hyperformula's internal typings for custom function plugins+ "hyperformula/typings/*": ["./node_modules/hyperformula/typings/*"]},"plugins": [{diff --git a/upcoming-release-notes/5985.md b/upcoming-release-notes/5985.mdnew file mode 100644index 0000000000..c8a4414b4f--- /dev/null+++ b/upcoming-release-notes/5985.md@@ -0,0 +1,7 @@+---+category: Enhancements+authors: [lelemm]+---++Add INTEGER_TO_AMOUNT function, enhance formula card styling, and introduce balance field to formula rule action execution.+