A local-first personal finance app
[AI] Sync `set amount` rule actions when a schedule's amount is edited (#8266)
Zannis Kalampoukisbe289446cc6d
diff --git a/packages/loot-core/src/server/schedules/app.test.ts b/packages/loot-core/src/server/schedules/app.test.tsindex 5d73fd2984..47e97f402d 100644--- a/packages/loot-core/src/server/schedules/app.test.ts+++ b/packages/loot-core/src/server/schedules/app.test.ts@@ -810,5 +810,66 @@ describe('schedule app', () => {await schedulesApp.stopServices();}});++ it('keeps a `set amount` action in sync when the amount is edited', async () => {+ MockDate.set(new Date(2016, 11, 31, 12));+ schedulesApp.startServices();++ try {+ const accountId = await db.insertAccount({+ name: 'Checking',+ offbudget: 0,+ closed: 0,+ });++ const id = await createSchedule({+ schedule: { posts_transaction: true },+ conditions: [+ { op: 'is', field: 'account', value: accountId },+ { op: 'is', field: 'amount', value: -6000 },+ { op: 'is', field: 'date', value: '2016-12-31' },+ ],+ });++ // Some schedules have a rule that also *sets* the amount (e.g. a rule+ // customized via "Edit as rule"). Posting runs the rule, so the action+ // value must track the amount condition.+ const { data: ruleId } = await aqlQuery(+ q('schedules').filter({ id }).calculate('rule'),+ );+ const ruleRow = await db.first<Pick<db.DbRule, 'actions'>>(+ 'SELECT actions FROM rules WHERE id = ?',+ [ruleId],+ );+ await updateRule({+ id: ruleId,+ actions: [+ { op: 'set', field: 'amount', value: -6000 },+ ...JSON.parse(ruleRow.actions),+ ],+ });++ // Edit the amount in the schedule editor (condition only).+ await updateSchedule({+ schedule: { id },+ conditions: [+ { op: 'is', field: 'account', value: accountId },+ { op: 'is', field: 'date', value: '2016-12-31' },+ { op: 'is', field: 'amount', value: -8000 },+ ],+ });++ await advanceSchedulesService(true);++ const { data: transactions } = await aqlQuery(+ q('transactions').filter({ schedule: id }).select(['amount']),+ );++ expect(transactions.map(({ amount }) => amount)).toEqual([-8000]);+ } finally {+ MockDate.reset();+ await schedulesApp.stopServices();+ }+ });});});diff --git a/packages/loot-core/src/server/schedules/app.ts b/packages/loot-core/src/server/schedules/app.tsindex d77c8f4fc3..1947e5d479 100644--- a/packages/loot-core/src/server/schedules/app.ts+++ b/packages/loot-core/src/server/schedules/app.ts@@ -33,7 +33,11 @@ import {getStatus,recurConfigToRSchedule,} from '#shared/schedules';-import type { RuleConditionEntity, ScheduleEntity } from '#types/models';+import type {+ RuleActionEntity,+ RuleConditionEntity,+ ScheduleEntity,+} from '#types/models';import { findSchedules } from './find-schedules';@@ -119,6 +123,53 @@ export function updateConditions(conditions, newConditions) {return updated.concat(added);}+// Keep a rule's actions in sync with its (edited) schedule conditions.+//+// A schedule's amount lives in the rule's amount *condition*, but a rule can+// also carry a plain `set amount` *action* (e.g. when customized via "Edit as+// rule"). Posting a scheduled transaction runs the rule, so a stale action+// would revert the posted amount to the old value, ignoring the edited+// amount. Keep such actions in sync with the amount condition.+//+// Only plain `set amount` actions are rewritten:+// - Templated/formula actions (`options.template`/`options.formula`) compute+// their own value, so they're left untouched.+// - `set-split-amount` actions have a different `op` and so are excluded by+// the `action.op === 'set'` check below.+//+// Returns `null` when nothing changed, so callers can avoid a redundant write.+function updateActions(+ conditions: RuleConditionEntity[],+ actions: RuleActionEntity[],+): RuleActionEntity[] | null {+ const { amount: amountCond } = extractScheduleConds(conditions);+ if (amountCond === null) {+ return null;+ }++ // Mirrors how `_amount` resolves: a deleted/empty amount condition value+ // yields 0, so the action is synced to 0 too, keeping it consistent with+ // the amount the schedule actually posts.+ const amount = getScheduledAmount(amountCond.value);++ let changed = false;+ const updated = actions.map(action => {+ if (+ action.op === 'set' &&+ action.field === 'amount' &&+ !action.options?.template &&+ !action.options?.formula &&+ action.value !== amount+ ) {+ changed = true;+ return { ...action, value: amount };+ }+ return action;+ });++ return changed ? updated : null;+}+export async function getRuleForSchedule(id: string | null): Promise<Rule> {if (id == null) {throw new Error('Schedule not attached to a rule');@@ -362,7 +413,13 @@ export async function updateSchedule({const oldConditions = rule.serialize().conditions;const newConditions = updateConditions(oldConditions, conditions);- await updateRule({ id: rule.id, conditions: newConditions });+ const newActions = updateActions(newConditions, rule.serialize().actions);++ await updateRule({+ id: rule.id,+ conditions: newConditions,+ ...(newActions ? { actions: newActions } : {}),+ });// Annoyingly, sometimes it has `type` and sometimes it doesn'tconst stripType = ({ type: _type, ...fields }) => fields;diff --git a/upcoming-release-notes/8266.md b/upcoming-release-notes/8266.mdnew file mode 100644index 0000000000..8122694e17--- /dev/null+++ b/upcoming-release-notes/8266.md@@ -0,0 +1,6 @@+---+category: Bugfixes+authors: [zannis]+---++Fixed editing a schedule's amount not updating a `set amount` action on its rule, which caused auto-posted transactions to keep using the old amount.