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 <noreply@anthropic.com>
This commit is contained in:
MangaValkandClaude Opus 5.5 committed 2026-11-19 20:55:41 +01:00
1 parent 730d99d38b
commit c7298cf955
3 files changed
+61 -6

No files matched your search

+46 -5
View File
@@ -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<Rule, "id"> & { id?: string };
export const emptyRule = (x: Partial<Draft> = {}): 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<number> {
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<string, string[]>(); // patch as JSON -> row ids
for (const t of past) {
const p = applyRules((rest ?? []) as Rule[], t);
const patch: Record<string, unknown> = {};
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: <CategoryIcon icon={c.icon} color={c.color} size={26} /> }));
@@ -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
<p className="text-sm text-muted pb-1">First, set up how your rule finds transactions. Pick one or more.</p>
<Option icon={Pencil} label="Match on name" on={on.name} set={turn("name")}>
<input autoFocus value={d.match} onChange={(e) => setD({ ...d, match: e.target.value })} placeholder="Name contains, e.g. uber" aria-label="Name contains" className="select" />
{/* Text matches anywhere in a name: "ing" is also in Stichting, Payments and every ING IBAN. */}
{d.match.trim().length > 0 && d.match.trim().length <= 3 && (
<p className="text-xs text-bad">Short text also matches inside other words: &quot;{d.match.trim()}&quot; is in more names than you&apos;d think. Check the matches, or use a longer piece of the name.</p>
)}
</Option>
<Option icon={DollarSign} label="Match on amount" on={on.amount} set={turn("amount")}>
<div className="grid grid-cols-2 gap-3">
@@ -220,7 +258,10 @@ export function RuleDialog({ initial, cats, allTags, onClose, onDone }: { initia
{d.id && (
<div className="px-1 pt-2 text-sm">
{confirmDelete
? <span className="flex flex-wrap items-center gap-2"><span>Delete this rule? Past transactions keep their changes.</span><button type="button" onClick={remove} className="font-medium text-bad hover:opacity-70">Delete</button><button type="button" onClick={() => setConfirmDelete(false)} className="text-muted hover:text-ink">Cancel</button></span>
? <span className="flex flex-col gap-2">
<label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={undoPast} onChange={(e) => setUndoPast(e.target.checked)} className="size-4 accent-[var(--color-ink)]" />Also undo it on the past transactions it changed</label>
<span className="flex flex-wrap items-center gap-2"><span>Delete this rule?</span><button type="button" onClick={remove} disabled={busy} className="font-medium text-bad hover:opacity-70">{busy ? "Deleting..." : "Delete"}</button><button type="button" onClick={() => setConfirmDelete(false)} className="text-muted hover:text-ink">Cancel</button></span>
</span>
: <button type="button" onClick={() => setConfirmDelete(true)} className="text-muted underline underline-offset-2 hover:text-bad">Delete rule</button>}
</div>
)}
+12
View File
@@ -38,3 +38,15 @@ console.log("transfers ok");
assert.deepEqual(two.slice(0, 2), [{ id: "o1", key: "TRANSFER_OUT" }, { id: "i1", key: "TRANSFER_IN" }]);
}
console.log("own transfers ok");
// ING's own wording for its accounts, Dutch and English.
{
const r = (id: string, amount: number, name: string) => ({ id, date: "2026-10-01", amount, account_id: id, name, categoryKey: null });
const f = findOwnTransfers([
r("a", 100, "Transfer to current account NL24INGB0001234567"), r("b", -50, "Transfer from current account NL24INGB0001234567"),
r("c", 5000, "Naar Beleggingsrek. 15671748 Valutadatum: 26-08-2026"), r("d", 87.24, "Incasso ING creditcard Accountnr 210026951876 Periode juli"),
r("e", 36.93, "Naam: Alternate Nederland Omschrijving: 51312519073X"),
]);
assert.deepEqual(f.map((x) => x.id), ["a", "b", "c", "d"]);
}
console.log("ing phrases ok");
+3 -1
View File
@@ -33,7 +33,9 @@ export type OwnTransfer = { id: string; key: "TRANSFER_OUT" | "TRANSFER_IN" };
// Savings accounts at Dutch banks, by the name the other side carries: ING (Oranje) Spaarrekening, Doelspaarrekening,
// ABN AMRO Direct Sparen, Rabobank/ASN/SNS bonusrente and deposito accounts.
const SAVINGS = /spaarrekening|doelspaar|direct sparen|bonusrente|spaardeposito|vermogensspaar|spaarpot/i;
// Also ING's English savings export ("Transfer to current account NL..."), ING's investment account ("Naar
// Beleggingsrek."), and ING's monthly credit card collection ("Incasso ING creditcard Accountnr ...").
const SAVINGS = /spaarrekening|doelspaar|direct sparen|bonusrente|spaardeposito|vermogensspaar|spaarpot|beleggingsrek|transfer (to|from) (current|savings) account|incasso ing creditcard/i;
const open = (r: OwnRow) => r.categoryKey === null || r.categoryKey === "OTHER"; // a category the person chose stays
/** Pairs first (same amount out of one own account and into another within DAYS days, nearest date wins, each row used