A local-first personal finance app
[AI] Fix category_group rule conditions never matching live transactions (#8587)
ReticentEclectic26352c32d692
diff --git a/packages/loot-core/src/server/transactions/transaction-rules.test.ts b/packages/loot-core/src/server/transactions/transaction-rules.test.tsindex 7892bbb64c..2f6b766d6a 100644--- a/packages/loot-core/src/server/transactions/transaction-rules.test.ts+++ b/packages/loot-core/src/server/transactions/transaction-rules.test.ts@@ -404,6 +404,96 @@ describe('Transaction rules', () => {});});+ test('category_group condition matches categories in that group (live)', async () => {+ await loadRules();+ const billsGroupId = await db.insertCategoryGroup({ name: 'Bills' });+ const electricId = await db.insertCategory({+ name: 'Electric',+ cat_group: billsGroupId,+ });++ await insertRule({+ stage: null,+ conditionsOp: 'and',+ conditions: [{ op: 'is', field: 'category_group', value: billsGroupId }],+ actions: [{ op: 'set', field: 'notes', value: 'bills-matched' }],+ });++ const transaction = await runRules({+ date: '2020-01-01',+ category: electricId,+ notes: '',+ });++ expect(transaction.notes).toBe('bills-matched');+ expect(transaction).not.toHaveProperty('category_group');+ });++ test('category_group condition does not match an unrelated group (live)', async () => {+ await loadRules();+ const billsGroupId = await db.insertCategoryGroup({ name: 'Bills' });+ const funGroupId = await db.insertCategoryGroup({ name: 'Fun' });+ const moviesId = await db.insertCategory({+ name: 'Movies',+ cat_group: funGroupId,+ });++ await insertRule({+ stage: null,+ conditionsOp: 'and',+ conditions: [{ op: 'is', field: 'category_group', value: billsGroupId }],+ actions: [{ op: 'set', field: 'notes', value: 'bills-matched' }],+ });++ const transaction = await runRules({+ date: '2020-01-01',+ category: moviesId,+ notes: '',+ });++ expect(transaction.notes).toBe('');+ expect(transaction).not.toHaveProperty('category_group');+ });++ test('category_group condition observes a category set earlier in the same rule chain (live)', async () => {+ await loadRules();+ const billsGroupId = await db.insertCategoryGroup({ name: 'Bills' });+ const electricId = await db.insertCategory({+ name: 'Electric',+ cat_group: billsGroupId,+ });+ await db.insertPayee({ id: 'power_co_id', name: 'Power Co' });++ // Runs first (pre stage): sets category based on payee. Nothing+ // about category_group is checked here.+ await insertRule({+ stage: 'pre',+ conditionsOp: 'and',+ conditions: [{ op: 'is', field: 'payee', value: 'power_co_id' }],+ actions: [{ op: 'set', field: 'category', value: electricId }],+ });++ // Runs after (post stage): checks category_group. This should see+ // the category the *first* rule just set, not whatever the+ // transaction started with.+ await insertRule({+ stage: 'post',+ conditionsOp: 'and',+ conditions: [{ op: 'is', field: 'category_group', value: billsGroupId }],+ actions: [{ op: 'set', field: 'notes', value: 'bills-matched' }],+ });++ const transaction = await runRules({+ date: '2020-01-01',+ payee: 'power_co_id',+ category: null,+ notes: '',+ });++ expect(transaction.category).toBe(electricId);+ expect(transaction.notes).toBe('bills-matched');+ });+test('transactions can be queried by rule', async () => {await loadRules();const account = await db.insertAccount({ name: 'bank' });diff --git a/packages/loot-core/src/server/transactions/transaction-rules.ts b/packages/loot-core/src/server/transactions/transaction-rules.tsindex 2f0f6d6543..843a986a40 100644--- a/packages/loot-core/src/server/transactions/transaction-rules.ts+++ b/packages/loot-core/src/server/transactions/transaction-rules.ts@@ -334,6 +334,7 @@ export async function runRules(}let finalTrans = await prepareTransactionForRules({ ...trans }, accountsMap);+ let lastCategoryIdForGroup: string | null = finalTrans.category ?? null;let scheduleRuleID = '';// Check if a schedule is attached to this transaction and if so get the rule ID attached to that schedule.@@ -371,6 +372,10 @@ export async function runRules(const changes = rules[i].execActions(finalTrans);finalTrans = Object.assign({}, finalTrans, changes);await resolvePayeeNameForRules(finalTrans);+ lastCategoryIdForGroup = await refreshCategoryGroupIfChanged(+ finalTrans,+ lastCategoryIdForGroup,+ );} else if (RuleIdsLinkedToSchedules.includes(rules[i].id)) {// skip all other rules that are linked to other schedules.continue;@@ -378,11 +383,19 @@ export async function runRules(// if a rule is not linked to a schedule, run it.finalTrans = rules[i].apply(finalTrans);await resolvePayeeNameForRules(finalTrans);+ lastCategoryIdForGroup = await refreshCategoryGroupIfChanged(+ finalTrans,+ lastCategoryIdForGroup,+ );}} else {// if there is no scheduleRuleID then just run all rules.finalTrans = rules[i].apply(finalTrans);await resolvePayeeNameForRules(finalTrans);+ lastCategoryIdForGroup = await refreshCategoryGroupIfChanged(+ finalTrans,+ lastCategoryIdForGroup,+ );}}@@ -989,6 +1002,8 @@ export type TransactionForRules = TransactionEntity & {balance?: number;_category_name?: string;_account_name?: string;+ /** The transaction's category's group id; see prepareTransactionForRules */+ category_group?: string;parent_amount?: number;/** Prefetched cent balances for BALANCE_OF("…") in rule formulas; cleared in finalize */_balanceOfPrefetched?: Map<string, number>;@@ -1095,6 +1110,16 @@ export async function prepareTransactionForRules(const category = await getCategory(trans.category);if (category) {r._category_name = category.name;++ // Populate the group id so a `category_group` rule condition can+ // actually match. Previously this was never set here, so+ // Condition.eval()'s `object['category_group']` lookup always+ // came back undefined and the condition silently never matched+ // during live rule application (import/manual entry). The+ // query/report path (conditionsToAQL) was unaffected, since it+ // maps the field to a real join (`category.group`) instead of+ // reading this property.+ r.category_group = category.cat_group;}}@@ -1120,6 +1145,35 @@ async function resolvePayeeNameForRules(}}+/**+ * `category_group` is only computed once, in prepareTransactionForRules,+ * before any rules have run. Since rules apply as a chain and an earlier+ * rule's action can change (or clear) `category`, a later rule's+ * `category_group` condition would otherwise read a stale group id left+ * over from before that change. Called after every rule application in+ * the runRules loop; only re-resolves the group when `category` has+ * actually changed since the last check, to avoid a database lookup on+ * every rule when category was untouched.+ */+async function refreshCategoryGroupIfChanged(+ trans: TransactionForRules,+ lastCategoryId: string | null,+): Promise<string | null> {+ const currentCategoryId = trans.category ?? null;+ if (currentCategoryId === lastCategoryId) {+ return lastCategoryId;+ }++ if (currentCategoryId) {+ const category = await getCategory(currentCategoryId);+ trans.category_group = category?.cat_group;+ } else {+ delete trans.category_group;+ }++ return currentCategoryId;+}+export async function finalizeTransactionForRules(trans: TransactionEntity | TransactionForRules,): Promise<TransactionEntity> {@@ -1132,6 +1186,13 @@ export async function finalizeTransactionForRules(delete trans.balance;}+ // Synthetic field used only for `category_group` condition matching;+ // never a real transaction column, so strip it before the+ // transaction is returned/persisted.+ if ('category_group' in trans) {+ delete trans.category_group;+ }+if ('_balanceOfPrefetched' in trans) {delete trans._balanceOfPrefetched;}diff --git a/upcoming-release-notes/fix-category-group-rule-matching.md b/upcoming-release-notes/fix-category-group-rule-matching.mdnew file mode 100644index 0000000000..7be2da4901--- /dev/null+++ b/upcoming-release-notes/fix-category-group-rule-matching.md@@ -0,0 +1,6 @@+---+category: Bugfixes+authors: [ReticentEclectic]+---++Rules and filters using "category group" as a condition now correctly match live transactions during import and manual entry.