From c7298cf9551d2e743ce43d7d82d336be524d6d17 Mon Sep 17 00:00:00 2001 From: MangaValk Date: Thu, 19 Nov 2026 20:55:41 +0100 Subject: [PATCH] Rules: undo a rule on past transactions when deleting it; warn about short text Deleting a rule can now take back what it did: rows it changed get what the other rules say (or Other / no category), then own transfers are looked for again. A rule's text matches anywhere in a name, so 1-3 letters ("ing": also Stichting, Payments, every ING IBAN) gets a warning. Transfers: also ING's English savings export ("Transfer to/from current account"), "Naar Beleggingsrek." and "Incasso ING creditcard". Co-Authored-By: Claude Opus 5.5 --- src/components/RuleForm.tsx | 51 +++++++++++++++++++++++++++++++++---- src/lib/transfers.test.ts | 12 +++++++++ src/lib/transfers.ts | 4 ++- 3 files changed, 61 insertions(+), 6 deletions(-) diff --git a/src/components/RuleForm.tsx b/src/components/RuleForm.tsx index 2ba01f3..6df2cae 100644 --- a/src/components/RuleForm.tsx +++ b/src/components/RuleForm.tsx @@ -10,13 +10,13 @@ import { useMoney } from "@/components/Money"; import { TagEditor } from "@/components/Tags"; import type { Category } from "@/lib/data"; import { displayName, plural } from "@/lib/format"; -import { findsSomething, matches, mergeTags, type Rule } from "@/lib/rules"; +import { applyRules, findsSomething, matches, mergeTags, RULE_COLS, type Rule } from "@/lib/rules"; import { createClient } from "@/utils/supabase/client"; export type Draft = Omit & { id?: string }; export const emptyRule = (x: Partial = {}): Draft => ({ match: "", amount_min: null, amount_max: null, account_id: null, day_from: null, day_to: null, category_id: null, rename: null, ignore: null, add_tags: null, ...x }); -type Match = { id: string; date: string; name: string; merchant_name: string | null; custom_name: string | null; logo_url: string | null; amount: number; currency: string | null; account_id: string; tags: string[] | null }; +type Match = { id: string; date: string; name: string; merchant_name: string | null; custom_name: string | null; logo_url: string | null; amount: number; currency: string | null; account_id: string; tags: string[] | null; category_id?: string | null; ignored?: boolean }; // Past transactions the rule matches, newest first. Name and account filter in Postgres, the rest here. export async function pastMatches(d: Draft) { @@ -29,7 +29,7 @@ export async function pastMatches(d: Draft) { // ponytail: a rule with no name pages through every own row; fine for a personal ledger, an RPC if it gets slow. const rows: Match[] = []; for (let from = 0; ; from += 1000) { - let q = db.from("transactions").select("id, date, name, merchant_name, custom_name, logo_url, amount, currency, account_id, tags").eq("user_id", uid); + let q = db.from("transactions").select("id, date, name, merchant_name, custom_name, logo_url, amount, currency, account_id, tags, category_id, ignored").eq("user_id", uid); if (s) q = q.or(`name.ilike.%${s}%,merchant_name.ilike.%${s}%`); if (d.account_id) q = q.eq("account_id", d.account_id); const { data } = await q.order("date", { ascending: false }).order("id").range(from, from + 999); @@ -61,6 +61,35 @@ export async function saveRule(d: Draft, applyPast: boolean): Promise<{ error?: return { updated: ids.length }; } +/** Takes back what a rule did to past transactions, before it's deleted: rows it still matches and that still carry its + * category, name or hiding get what the other rules say instead (or nothing: Other for money out). Tags stay. + * Then transfers between own accounts are looked for again, since rows without a category are open to that. */ +export async function undoRule(rule: Draft): Promise { + const db = createClient(); + const past = await pastMatches(rule); + const { data: rest } = await db.from("rules").select(RULE_COLS).neq("id", rule.id ?? "").order("created_at", { ascending: false }); + const { data: other } = await db.from("categories").select("id").is("user_id", null).eq("key", "OTHER").maybeSingle(); + const by = new Map(); // patch as JSON -> row ids + for (const t of past) { + const p = applyRules((rest ?? []) as Rule[], t); + const patch: Record = {}; + if (rule.category_id && t.category_id === rule.category_id) patch.category_id = p.category_id ?? (t.amount > 0 ? other?.id ?? null : null); + if (rule.rename && t.custom_name === rule.rename) patch.custom_name = p.custom_name ?? null; + if (rule.ignore != null && t.ignored === rule.ignore) patch.ignored = p.ignored ?? false; + if (!Object.keys(patch).length) continue; + const k = JSON.stringify(patch); + by.set(k, [...(by.get(k) ?? []), t.id]); + } + let n = 0; + for (const [k, ids] of by) + for (let i = 0; i < ids.length; i += 200) { + const { error } = await db.from("transactions").update(JSON.parse(k)).in("id", ids.slice(i, i + 200)); + if (!error) n += Math.min(200, ids.length - i); + } + await fetch("/api/transfers/find", { method: "POST" }).catch(() => null); + return n; +} + export const categoryOptions = (cats: Category[]) => cats.map((c) => ({ value: c.id, label: c.label, icon: })); @@ -149,10 +178,15 @@ export function RuleDialog({ initial, cats, allTags, onClose, onDone }: { initia onDone(r.updated ? `Rule saved. Updated ${plural(r.updated, "past transaction")}.` : "Rule saved."); } + const [undoPast, setUndoPast] = useState(true); async function remove() { + setBusy(true); + // Undo first, while the rule still exists to say which rows it changed; the saved rule, not unsaved edits. + const undone = undoPast ? await undoRule({ ...initial, id: d.id }) : 0; const { error } = await createClient().from("rules").delete().eq("id", d.id!); + setBusy(false); if (error) return setErr("Couldn't delete the rule."); - onDone("Rule deleted. Past transactions keep their changes."); + onDone(undoPast ? `Rule deleted. Took it back on ${plural(undone, "past transaction")}.` : "Rule deleted. Past transactions keep their changes."); } // Until the count for these settings lands, say so instead of showing 0 (or the last count). @@ -178,6 +212,10 @@ export function RuleDialog({ initial, cats, allTags, onClose, onDone }: { initia

First, set up how your rule finds transactions. Pick one or more.