Skip to content

A local-first personal finance app

Add Formula Rule function to set-split-amount (#6414)

scojoee8f8bfbba62
diff --git a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx
index c4debfbddc..58944b58ac 100644
--- a/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx
+++ b/packages/desktop-client/src/components/formula/codeMirror-excelLanguage.tsx
@@ -403,6 +403,15 @@ const transactionFields: Completion[] = [
'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")`',
),
},
+ {
+ label: 'parent_amount',
+ type: 'variable',
+ section: '💰 Transaction Fields',
+ boost: 5,
+ info: t(
+ 'The amount of the parent transaction in cents in split transactions.\n\nExample: `=(parent_amount / 100) * .05`',
+ ),
+ },
];
// Convert function definitions to completions with grouping
diff --git a/packages/desktop-client/src/components/rules/ActionExpression.tsx b/packages/desktop-client/src/components/rules/ActionExpression.tsx
index fe50097883..3382111aa4 100644
--- a/packages/desktop-client/src/components/rules/ActionExpression.tsx
+++ b/packages/desktop-client/src/components/rules/ActionExpression.tsx
@@ -99,6 +99,7 @@ function SetSplitAmountActionExpression({
value,
options,
}: SetSplitAmountRuleActionEntity) {
+ const { t } = useTranslation();
const method = options?.method;
if (!method) {
return null;
@@ -109,10 +110,16 @@ function SetSplitAmountActionExpression({
<Text>{friendlyOp(op)}</Text>{' '}
<Text style={valueStyle}>{getAllocationMethods()[method]}</Text>
{method !== 'remainder' && ': '}
- {method === 'fixed-amount' && (
+ {options?.method === 'formula' ? (
+ <>
+ <Text>{t('formula ')}</Text>
+ <Text style={valueStyle}>{options.formula}</Text>
+ </>
+ ) : method === 'fixed-amount' ? (
<Value style={valueStyle} value={value} field="amount" />
- )}
- {method === 'fixed-percent' && <Text style={valueStyle}>{value}%</Text>}
+ ) : method === 'fixed-percent' ? (
+ <Text style={valueStyle}>{value}%</Text>
+ ) : null}
</>
);
}
diff --git a/packages/desktop-client/src/components/rules/RuleEditor.tsx b/packages/desktop-client/src/components/rules/RuleEditor.tsx
index c8b37e479a..55f30f206e 100644
--- a/packages/desktop-client/src/components/rules/RuleEditor.tsx
+++ b/packages/desktop-client/src/components/rules/RuleEditor.tsx
@@ -449,8 +449,8 @@ function getSplitActionFields() {
([field]) => !parentOnlyFields.includes(field),
);
}
-function getAllocationMethodOptions() {
- return Object.entries(getAllocationMethods());
+function getAllocationMethodOptions(isFormulaEnabled = false) {
+ return Object.entries(getAllocationMethods(isFormulaEnabled));
}
type ActionEditorProps = {
@@ -569,31 +569,15 @@ function ActionEditor({
: onChange('formula', options.formula || value || '=')
}
>
- {hasFormula ? (
- <span
- style={{
- fontSize: 14,
- fontFamily: 'serif',
- textAlign: 'center',
- }}
- >
- ƒ
- </span>
- ) : hasFormula ? (
- <SvgCode
- style={{ width: 12, height: 12, color: 'inherit' }}
- />
- ) : (
- <span
- style={{
- fontSize: 14,
- fontFamily: 'serif',
- textAlign: 'center',
- }}
- >
- ƒ
- </span>
- )}
+ <span
+ style={{
+ fontSize: 14,
+ fontFamily: 'serif',
+ textAlign: 'center',
+ }}
+ >
+ ƒ
+ </span>
</Button>
)}
{isTemplatingEnabled &&
@@ -629,7 +613,7 @@ function ActionEditor({
</View>
<SplitAmountMethodSelect
- options={getAllocationMethodOptions()}
+ options={getAllocationMethodOptions(isFormulaEnabled)}
value={options.method}
onChange={onChange}
/>
@@ -640,7 +624,12 @@ function ActionEditor({
minWidth: options.method === 'fixed-percent' ? 45 : 70,
}}
>
- {options.method !== 'remainder' && (
+ {options.method === 'formula' ? (
+ <FormulaActionEditor
+ value={options?.formula || '='}
+ onChange={v => onChange('formula', v, { formula: true })}
+ />
+ ) : options.method !== 'remainder' ? (
<GenericInput
key={inputKey}
// @ts-expect-error fix this
@@ -653,8 +642,34 @@ function ActionEditor({
value={value}
onChange={v => onChange('value', v)}
/>
- )}
+ ) : null}
</View>
+ {options.method === 'formula' && (
+ <View
+ style={{
+ padding: 5,
+ backgroundColor: theme.buttonPrimaryBackground,
+ height: 24,
+ width: 24,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ borderRadius: 4,
+ }}
+ aria-label={t('Formula mode indicator')}
+ role="img"
+ >
+ <span
+ style={{
+ fontSize: 14,
+ fontFamily: 'serif',
+ textAlign: 'center',
+ }}
+ >
+ ƒ
+ </span>
+ </View>
+ )}
</>
) : op === 'link-schedule' ? (
<>
diff --git a/packages/loot-core/src/server/rules/action.ts b/packages/loot-core/src/server/rules/action.ts
index 275f1c9ea7..e5ccdf6c57 100644
--- a/packages/loot-core/src/server/rules/action.ts
+++ b/packages/loot-core/src/server/rules/action.ts
@@ -193,6 +193,39 @@ export class Action {
case 'fixed-amount':
object.amount = this.value;
break;
+ case 'formula':
+ if (!object._ruleErrors) {
+ object._ruleErrors = [];
+ }
+ if (!this.options?.formula) {
+ object._ruleErrors.push(
+ 'Formula method selected but no formula specified',
+ );
+ break;
+ }
+ try {
+ const result = this.executeFormulaSync(
+ this.options.formula,
+ object,
+ );
+ const numValue =
+ typeof result === 'number'
+ ? result
+ : parseFloat(String(result));
+
+ if (isNaN(numValue)) {
+ object._ruleErrors.push(
+ `Formula for split amount must produce a numeric value. Got: ${JSON.stringify(result)}`,
+ );
+ } else {
+ object.amount = numValue;
+ }
+ } catch (err) {
+ object._ruleErrors.push(
+ `Error executing formula for split amount: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ break;
default:
break;
}
diff --git a/packages/loot-core/src/server/rules/index.test.ts b/packages/loot-core/src/server/rules/index.test.ts
index 3a5c10a429..b985299522 100644
--- a/packages/loot-core/src/server/rules/index.test.ts
+++ b/packages/loot-core/src/server/rules/index.test.ts
@@ -863,6 +863,102 @@ describe('Rule', () => {
subtransactions: [{ amount: 100 }, { amount: 100 }],
});
});
+
+ describe('formula support', () => {
+ test('fixed-amount with formula calculates split amount', () => {
+ const rule = new Rule({
+ conditionsOp: 'and',
+ conditions: [{ op: 'is', field: 'imported_payee', value: 'James' }],
+ actions: [
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 0,
+ options: { splitIndex: 1, method: 'formula', formula: '=300' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 0,
+ options: {
+ splitIndex: 2,
+ method: 'remainder',
+ },
+ },
+ ],
+ });
+
+ // Fixed amount 300, remainder = 700
+ expect(
+ rule.exec({ imported_payee: 'James', amount: 100000 }),
+ ).toMatchObject({
+ subtransactions: [{ amount: 30000 }, { amount: 70000 }],
+ });
+ });
+
+ test('fixed-percent formula calculates 50/50 split', () => {
+ const rule = new Rule({
+ conditionsOp: 'and',
+ conditions: [{ op: 'is', field: 'imported_payee', value: 'James' }],
+ actions: [
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 0,
+ options: {
+ splitIndex: 1,
+ method: 'formula',
+ formula: '=INTEGER_TO_AMOUNT(parent_amount) * 0.5',
+ },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 0,
+ options: {
+ splitIndex: 2,
+ method: 'remainder',
+ },
+ },
+ ],
+ });
+
+ // Fixed amount 10000 (100 in formula = $100.00 = 10000 cents), remainder = 10000
+ expect(
+ rule.exec({ imported_payee: 'James', amount: 20000 }),
+ ).toMatchObject({
+ subtransactions: [{ amount: 10000 }, { amount: 10000 }],
+ });
+ });
+
+ test('multiple fixed-amount formulas work together', () => {
+ const rule = new Rule({
+ conditionsOp: 'and',
+ conditions: [{ op: 'is', field: 'imported_payee', value: 'James' }],
+ actions: [
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 0,
+ options: { splitIndex: 1, method: 'formula', formula: '=100' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 0,
+ options: { splitIndex: 2, method: 'formula', formula: '=100' },
+ },
+ ],
+ });
+
+ // Both splits get 100 each
+ expect(
+ rule.exec({ imported_payee: 'James', amount: 20000 }),
+ ).toMatchObject({
+ subtransactions: [{ amount: 10000 }, { amount: 10000 }],
+ });
+ });
+ });
});
test('rules are deterministically ranked', () => {
diff --git a/packages/loot-core/src/server/rules/rule.ts b/packages/loot-core/src/server/rules/rule.ts
index a3c727ea4f..134d19f3a7 100644
--- a/packages/loot-core/src/server/rules/rule.ts
+++ b/packages/loot-core/src/server/rules/rule.ts
@@ -7,6 +7,7 @@ import {
ungroupTransaction,
} from '../../shared/transactions';
import type { RuleEntity } from '../../types/models';
+import type { TransactionForRules } from '../transactions/transaction-rules';
import { Action } from './action';
import { Condition } from './condition';
@@ -32,7 +33,7 @@ function execSplitActions(actions: Action[], transaction) {
ungroupTransaction(transaction),
transaction.id,
);
- let newTransactions = data;
+ let newTransactions: TransactionForRules[] = data;
// Add empty splits, and apply non-set-amount actions.
// This also populates any fixed-amount splits.
@@ -42,6 +43,8 @@ function execSplitActions(actions: Action[], transaction) {
const { data } = addSplitTransaction(newTransactions, transaction.id);
newTransactions = data;
}
+ newTransactions[splitTransactionIndex].parent_amount = transaction.amount;
+ newTransactions[splitTransactionIndex].balance = transaction.balance;
action.exec(newTransactions[splitTransactionIndex]);
});
diff --git a/packages/loot-core/src/server/transactions/transaction-rules.ts b/packages/loot-core/src/server/transactions/transaction-rules.ts
index 3c619800b5..68c860fc2f 100644
--- a/packages/loot-core/src/server/transactions/transaction-rules.ts
+++ b/packages/loot-core/src/server/transactions/transaction-rules.ts
@@ -937,6 +937,7 @@ export type TransactionForRules = TransactionEntity & {
balance?: number;
_category_name?: string;
_account_name?: string;
+ parent_amount?: number;
};
export async function prepareTransactionForRules(
@@ -1034,5 +1035,21 @@ export async function finalizeTransactionForRules(
delete trans.balance;
}
+ if ('parent_amount' in trans) {
+ delete trans.parent_amount;
+ }
+
+ if (trans.subtransactions?.length) {
+ trans.subtransactions.forEach(stx => {
+ if ('balance' in stx) {
+ delete stx.balance;
+ }
+
+ if ('parent_amount' in stx) {
+ delete stx.parent_amount;
+ }
+ });
+ }
+
return trans;
}
diff --git a/packages/loot-core/src/shared/rules.ts b/packages/loot-core/src/shared/rules.ts
index 8811dedd8d..bd5bad9547 100644
--- a/packages/loot-core/src/shared/rules.ts
+++ b/packages/loot-core/src/shared/rules.ts
@@ -118,10 +118,11 @@ export function getValidOps(field: keyof FieldValueTypes): RuleConditionOp[] {
);
}
-export function getAllocationMethods() {
+export function getAllocationMethods(hasFormulaMode = false) {
return {
'fixed-amount': t('a fixed amount'),
'fixed-percent': t('a fixed percent of the remainder'),
+ ...(hasFormulaMode && { formula: t('based on a formula') }),
remainder: t('an equal portion of the remainder'),
};
}
diff --git a/packages/loot-core/src/types/models/rule.ts b/packages/loot-core/src/types/models/rule.ts
index f3089be7f4..1cfb2aa6b1 100644
--- a/packages/loot-core/src/types/models/rule.ts
+++ b/packages/loot-core/src/types/models/rule.ts
@@ -146,10 +146,11 @@ export type SetRuleActionEntity = {
export type SetSplitAmountRuleActionEntity = {
op: 'set-split-amount';
- value: number;
+ value: number | null;
options?: {
splitIndex?: number;
- method: 'fixed-amount' | 'fixed-percent' | 'remainder';
+ method: 'fixed-amount' | 'fixed-percent' | 'formula' | 'remainder';
+ formula?: string;
};
};
diff --git a/upcoming-release-notes/6414.md b/upcoming-release-notes/6414.md
new file mode 100644
index 0000000000..98e8f15230
--- /dev/null
+++ b/upcoming-release-notes/6414.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [sjones512]
+---
+
+Add the ability to use Formula Rules when setting the split amount.