Skip to content

A local-first personal finance app

Clarify logic to generate splits from rules (#3641)

Julian Dominguez-Schatz259beb766559
diff --git a/packages/loot-core/src/server/accounts/rules.test.ts b/packages/loot-core/src/server/accounts/rules.test.ts
index 468a89dc95..6352bee9ae 100644
--- a/packages/loot-core/src/server/accounts/rules.test.ts
+++ b/packages/loot-core/src/server/accounts/rules.test.ts
@@ -516,6 +516,193 @@ describe('Rule', () => {
});
});
+ describe('split actions', () => {
+ const fixedAmountRule = new Rule({
+ conditionsOp: 'and',
+ conditions: [{ op: 'is', field: 'imported_payee', value: 'James' }],
+ actions: [
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 100,
+ options: { splitIndex: 1, method: 'fixed-amount' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 100,
+ options: { splitIndex: 2, method: 'fixed-amount' },
+ },
+ ],
+ });
+
+ test('basic fixed-amount', () => {
+ expect(
+ fixedAmountRule.exec({ imported_payee: 'James', amount: 200 }),
+ ).toMatchObject({
+ error: null,
+ subtransactions: [{ amount: 100 }, { amount: 100 }],
+ });
+ });
+
+ test('basic fixed-percent', () => {
+ const rule = new Rule({
+ conditionsOp: 'and',
+ conditions: [{ op: 'is', field: 'imported_payee', value: 'James' }],
+ actions: [
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 50,
+ options: { splitIndex: 1, method: 'fixed-percent' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 50,
+ options: { splitIndex: 2, method: 'fixed-percent' },
+ },
+ ],
+ });
+
+ expect(rule.exec({ imported_payee: 'James', amount: 200 })).toMatchObject(
+ {
+ error: null,
+ subtransactions: [{ amount: 100 }, { amount: 100 }],
+ },
+ );
+ });
+
+ test('basic remainder', () => {
+ const rule = new Rule({
+ conditionsOp: 'and',
+ conditions: [{ op: 'is', field: 'imported_payee', value: 'James' }],
+ actions: [
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ options: { splitIndex: 1, method: 'remainder' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ options: { splitIndex: 2, method: 'remainder' },
+ },
+ ],
+ });
+
+ expect(rule.exec({ imported_payee: 'James', amount: 200 })).toMatchObject(
+ {
+ error: null,
+ subtransactions: [{ amount: 100 }, { amount: 100 }],
+ },
+ );
+ });
+
+ const prioritizationRule = new Rule({
+ conditionsOp: 'and',
+ conditions: [{ op: 'is', field: 'imported_payee', value: 'James' }],
+ actions: [
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 100,
+ options: { splitIndex: 1, method: 'fixed-amount' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 50,
+ options: { splitIndex: 2, method: 'fixed-percent' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ options: { splitIndex: 3, method: 'remainder' },
+ },
+ ],
+ });
+
+ test('percent is of the post-fixed-amount total', () => {
+ // Percent is a percent of the amount pre-remainder
+ expect(
+ prioritizationRule.exec({ imported_payee: 'James', amount: 200 }),
+ ).toMatchObject({
+ error: null,
+ subtransactions: [{ amount: 100 }, { amount: 50 }, { amount: 50 }],
+ });
+ });
+
+ test('remainder/percent goes negative if less than expected after fixed amounts', () => {
+ // Remainder/percent goes negative if less than expected after fixed amounts
+ expect(
+ prioritizationRule.exec({ imported_payee: 'James', amount: 50 }),
+ ).toMatchObject({
+ error: null,
+ subtransactions: [{ amount: 100 }, { amount: -25 }, { amount: -25 }],
+ });
+ });
+
+ test('remainder zeroes out if nothing left', () => {
+ const rule = new Rule({
+ conditionsOp: 'and',
+ conditions: [{ op: 'is', field: 'imported_payee', value: 'James' }],
+ actions: [
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 100,
+ options: { splitIndex: 1, method: 'fixed-amount' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ value: 100,
+ options: { splitIndex: 2, method: 'fixed-percent' },
+ },
+ {
+ op: 'set-split-amount',
+ field: 'amount',
+ options: { splitIndex: 3, method: 'remainder' },
+ },
+ ],
+ });
+
+ expect(rule.exec({ imported_payee: 'James', amount: 150 })).toMatchObject(
+ {
+ error: null,
+ subtransactions: [{ amount: 100 }, { amount: 50 }, { amount: 0 }],
+ },
+ );
+ });
+
+ test('generate errors when fixed amounts exceed the total', () => {
+ expect(
+ fixedAmountRule.exec({ imported_payee: 'James', amount: 100 }),
+ ).toMatchObject({
+ error: {
+ difference: -100,
+ type: 'SplitTransactionError',
+ version: 1,
+ },
+ subtransactions: [{ amount: 100 }, { amount: 100 }],
+ });
+ });
+
+ test('generate errors when fixed amounts undershoot the total', () => {
+ expect(
+ fixedAmountRule.exec({ imported_payee: 'James', amount: 300 }),
+ ).toMatchObject({
+ error: {
+ difference: 100,
+ type: 'SplitTransactionError',
+ version: 1,
+ },
+ subtransactions: [{ amount: 100 }, { amount: 100 }],
+ });
+ });
+ });
+
test('rules are deterministically ranked', () => {
const rule = (id, conditions) =>
new Rule({
diff --git a/packages/loot-core/src/server/accounts/rules.ts b/packages/loot-core/src/server/accounts/rules.ts
index 8033f442c1..89cf1f86b6 100644
--- a/packages/loot-core/src/server/accounts/rules.ts
+++ b/packages/loot-core/src/server/accounts/rules.ts
@@ -22,6 +22,7 @@ import {
import { recurConfigToRSchedule } from '../../shared/schedules';
import {
addSplitTransaction,
+ groupTransaction,
recalculateSplit,
splitTransaction,
ungroupTransaction,
@@ -667,135 +668,96 @@ function execNonSplitActions(actions: Action[], transaction) {
return update;
}
-export function execActions(actions: Action[], transaction) {
- const parentActions = actions.filter(action => !action.options?.splitIndex);
- const childActions = actions.filter(action => action.options?.splitIndex);
- const totalSplitCount =
- actions.reduce(
- (prev, cur) => Math.max(prev, cur.options?.splitIndex ?? 0),
- 0,
- ) + 1;
-
- let update = execNonSplitActions(parentActions, transaction);
- if (totalSplitCount === 1) {
- // No splits, no need to do anything else.
- return update;
- }
-
- if (update.is_child) {
- // Rules with splits can't be applied to child transactions.
- return update;
- }
+function getSplitRemainder(transactions) {
+ const { error } = recalculateSplit(groupTransaction(transactions));
+ return error ? error.difference : 0;
+}
- const splitAmountActions = childActions.filter(
+function execSplitActions(actions: Action[], transaction) {
+ const splitAmountActions = actions.filter(
action => action.op === 'set-split-amount',
);
- const fixedSplitAmountActions = splitAmountActions.filter(
- action => action.options.method === 'fixed-amount',
- );
- const fixedAmountsBySplit: Record<number, number> = {};
- fixedSplitAmountActions.forEach(action => {
- const splitIndex = action.options.splitIndex ?? 0;
- fixedAmountsBySplit[splitIndex] = action.value;
- });
- const fixedAmountSplitCount = Object.keys(fixedAmountsBySplit).length;
- const totalFixedAmount = Object.values(fixedAmountsBySplit).reduce<number>(
- (prev, cur: number) => prev + cur,
- 0,
- );
- if (
- fixedAmountSplitCount === totalSplitCount &&
- totalFixedAmount !== (transaction.amount ?? totalFixedAmount)
- ) {
- // Not all value would be distributed to a split.
- return transaction;
- }
- const { data, newTransaction } = splitTransaction(
- ungroupTransaction(update),
+ // Convert the transaction to a split transaction.
+ const { data } = splitTransaction(
+ ungroupTransaction(transaction),
transaction.id,
);
- update = recalculateSplit(newTransaction);
- data[0] = update;
let newTransactions = data;
- for (const action of childActions) {
- const splitIndex = action.options?.splitIndex ?? 0;
- if (splitIndex >= update.subtransactions.length) {
- const { data, newTransaction } = addSplitTransaction(
- newTransactions,
- transaction.id,
- );
- update = recalculateSplit(newTransaction);
- data[0] = update;
+ // Add empty splits, and apply non-set-amount actions.
+ // This also populates any fixed-amount splits.
+ actions.forEach(action => {
+ const splitTransactionIndex = (action.options?.splitIndex ?? 0) + 1;
+ if (splitTransactionIndex >= newTransactions.length) {
+ const { data } = addSplitTransaction(newTransactions, transaction.id);
newTransactions = data;
}
- action.exec(update.subtransactions[splitIndex]);
- }
+ action.exec(newTransactions[splitTransactionIndex]);
+ });
+
+ // Distribute to fixed-percent splits.
+ const remainingAfterFixedAmounts = getSplitRemainder(newTransactions);
+ splitAmountActions
+ .filter(action => action.options.method === 'fixed-percent')
+ .forEach(action => {
+ const splitTransactionIndex = (action.options?.splitIndex ?? 0) + 1;
+ const percent = action.value / 100;
+ const amount = Math.round(remainingAfterFixedAmounts * percent);
+ newTransactions[splitTransactionIndex].amount = amount;
+ });
- // Make sure every transaction has an amount.
- if (fixedAmountSplitCount !== totalSplitCount) {
- // This is the amount that will be distributed to the splits that
- // don't have a fixed amount. The last split will get the remainder.
- // The amount will be zero if the parent transaction has no amount.
- const amountToDistribute =
- (transaction.amount ?? totalFixedAmount) - totalFixedAmount;
- let remainingAmount = amountToDistribute;
-
- // First distribute the fixed percentages.
- splitAmountActions
- .filter(action => action.options.method === 'fixed-percent')
- .forEach(action => {
- const splitIndex = action.options.splitIndex;
- const percent = action.value / 100;
- const amount = Math.round(amountToDistribute * percent);
- update.subtransactions[splitIndex].amount = amount;
- remainingAmount -= amount;
- });
-
- // Then distribute the remainder.
- const remainderSplitAmountActions = splitAmountActions.filter(
- action => action.options.method === 'remainder',
+ // Distribute to remainder splits.
+ const remainderActions = splitAmountActions.filter(
+ action => action.options.method === 'remainder',
+ );
+ const remainingAfterFixedPercents = getSplitRemainder(newTransactions);
+ if (remainderActions.length !== 0) {
+ const amountPerRemainderSplit = Math.round(
+ remainingAfterFixedPercents / remainderActions.length,
);
+ let lastNonFixedTransactionIndex = -1;
+ remainderActions.forEach(action => {
+ const splitTransactionIndex = (action.options?.splitIndex ?? 0) + 1;
+ newTransactions[splitTransactionIndex].amount = amountPerRemainderSplit;
+ lastNonFixedTransactionIndex = Math.max(
+ lastNonFixedTransactionIndex,
+ splitTransactionIndex,
+ );
+ });
- // Check if there is any value left to distribute after all fixed
- // (percentage and amount) splits have been distributed.
- if (remainingAmount !== 0) {
- // If there are no remainder splits explicitly added by the user,
- // distribute the remainder to a virtual split that will be
- // adjusted for the remainder.
- if (remainderSplitAmountActions.length === 0) {
- const splitIndex = totalSplitCount;
- const { newTransaction } = addSplitTransaction(
- newTransactions,
- transaction.id,
- );
- update = recalculateSplit(newTransaction);
- update.subtransactions[splitIndex].amount = remainingAmount;
- } else {
- const amountPerRemainderSplit = Math.round(
- remainingAmount / remainderSplitAmountActions.length,
- );
- let lastNonFixedIndex = -1;
- remainderSplitAmountActions.forEach(action => {
- const splitIndex = action.options.splitIndex;
- update.subtransactions[splitIndex].amount = amountPerRemainderSplit;
- remainingAmount -= amountPerRemainderSplit;
- lastNonFixedIndex = Math.max(lastNonFixedIndex, splitIndex);
- });
+ // The last remainder split will be adjusted for any leftovers from rounding.
+ newTransactions[lastNonFixedTransactionIndex].amount -=
+ getSplitRemainder(newTransactions);
+ }
- // The last non-fixed split will be adjusted for the remainder.
- update.subtransactions[lastNonFixedIndex].amount -= remainingAmount;
- }
- update = recalculateSplit(update);
- }
+ // The split index 0 (transaction index 1) is reserved for "Apply to all" actions.
+ // Remove that entry from the transaction list.
+ newTransactions.splice(1, 1);
+ return recalculateSplit(groupTransaction(newTransactions));
+}
+
+export function execActions(actions: Action[], transaction) {
+ const parentActions = actions.filter(action => !action.options?.splitIndex);
+ const childActions = actions.filter(action => action.options?.splitIndex);
+ const totalSplitCount =
+ actions.reduce(
+ (prev, cur) => Math.max(prev, cur.options?.splitIndex ?? 0),
+ 0,
+ ) + 1;
+
+ const nonSplitResult = execNonSplitActions(parentActions, transaction);
+ if (totalSplitCount === 1) {
+ // No splits, no need to do anything else.
+ return nonSplitResult;
}
- // The split index 0 is reserved for "Apply to all" actions.
- // Remove that entry from the subtransactions.
- update.subtransactions = update.subtransactions.slice(1);
+ if (nonSplitResult.is_child) {
+ // Rules with splits can't be applied to child transactions.
+ return nonSplitResult;
+ }
- return recalculateSplit(update);
+ return execSplitActions(childActions, nonSplitResult);
}
export class Rule {
diff --git a/upcoming-release-notes/3641.md b/upcoming-release-notes/3641.md
new file mode 100644
index 0000000000..4d0c1b8052
--- /dev/null
+++ b/upcoming-release-notes/3641.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [jfdoming]
+---
+
+Fix visual glitches with scheduled split transactions