Merge an imported account into a linked one (server side, no button yet)

POST /api/accounts/merge {from, into, preview}. Older imported rows move over; from
the day the bank's history starts the bank's rows win, and edits on matching rows
carry over. Safe to run again after stopping halfway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
MangaValkandClaude Opus 5.5 committed 2026-11-19 17:35:49 +01:00
1 parent 514b2aac77
commit 8e830dc422
3 files changed
+156

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
import { NextResponse } from "next/server";
import { planMerge, type MergeRow } from "@/lib/merge";
import { sameOrigin } from "@/lib/setup";
import { createAdminClient } from "@/utils/supabase/admin";
import { createClient } from "@/utils/supabase/server";
// Merge an imported account into another of the person's accounts (usually the one their bank link made).
// preview: true only counts. Both accounts must be theirs, and only an imported (manual) one can be merged away:
// a linked account would come back on the next sync.
const COLS = "id, date, amount, category_id, custom_name, note, tags, ignored, plaid_transaction_id";
async function rowsOf(db: ReturnType<typeof createAdminClient>, userId: string, accountId: string) {
const out: MergeRow[] = [];
for (let from = 0; ; from += 1000) {
const { data, error } = await db.from("transactions").select(COLS).eq("user_id", userId).eq("account_id", accountId).order("date").range(from, from + 999);
if (error) throw error;
out.push(...(data ?? []).map(({ plaid_transaction_id, ...r }) => ({ ...r, fromBank: !!plaid_transaction_id }) as MergeRow));
if ((data ?? []).length < 1000) return out;
}
}
const chunks = <T,>(xs: T[], n = 200) => Array.from({ length: Math.ceil(xs.length / n) }, (_, i) => xs.slice(i * n, i * n + n));
export async function POST(request: Request) {
const { data: { user } } = await (await createClient()).auth.getUser();
if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 });
if (!sameOrigin(request)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const { from, into, preview } = (await request.json().catch(() => ({}))) as { from?: string; into?: string; preview?: boolean };
if (!from || !into || from === into) return NextResponse.json({ error: "Pick the account to merge into." }, { status: 400 });
const db = createAdminClient();
const { data: accts } = await db.from("accounts").select("id, manual").eq("user_id", user.id).in("id", [from, into]);
const src = accts?.find((a) => a.id === from), dst = accts?.find((a) => a.id === into);
if (!src || !dst) return NextResponse.json({ error: "Account not found." }, { status: 404 });
if (!src.manual) return NextResponse.json({ error: "Only an imported account can be merged into another." }, { status: 400 });
try {
const plan = planMerge(await rowsOf(db, user.id, from), await rowsOf(db, user.id, into));
const counts = { start: plan.start, moved: plan.move.length, replaced: plan.drop.length, edits: plan.edits.length };
if (preview) return NextResponse.json(counts);
for (const e of plan.edits) {
const { error } = await db.from("transactions").update(e.patch).eq("id", e.id).eq("user_id", user.id);
if (error) throw error;
}
for (const ids of chunks(plan.move)) {
const { error } = await db.from("transactions").update({ account_id: into }).eq("user_id", user.id).in("id", ids);
if (error) throw error;
}
// Rules and repeating charges that point at the imported account now point at the one it went into.
await db.from("rules").update({ account_id: into }).eq("user_id", user.id).eq("account_id", from);
await db.from("recurring").update({ account_id: into }).eq("user_id", user.id).eq("account_id", from);
// What's left on the imported account is the overlap the bank already has. Deleting the account takes it along.
const { error } = await db.from("accounts").delete().eq("id", from).eq("user_id", user.id);
if (error) throw error;
return NextResponse.json({ ok: true, ...counts });
} catch (e) {
console.error("[broke] merge accounts:", e instanceof Error ? e.message : e);
return NextResponse.json({ error: "Couldn't finish the merge. Try again: it picks up where it stopped." }, { status: 500 });
}
}
+41
View File
@@ -0,0 +1,41 @@
// node src/lib/merge.test.ts
import assert from "node:assert/strict";
import { planMerge } from "./merge.ts";
// The bank's history starts on 1 Nov. Older imported rows move; from 1 Nov the bank's rows are kept.
const csv = [
{ id: "c1", date: "2026-10-20", amount: 30, category_id: "food" },
{ id: "c2", date: "2026-11-02", amount: 42.17, category_id: "groceries", custom_name: "Boodschappen", tags: ["home"] },
{ id: "c3", date: "2026-11-02", amount: 42.17 }, // a second identical payment that day
{ id: "c4", date: "2026-11-05", amount: 9.99, note: "only in the export" },
];
const bank = [
{ id: "b1", date: "2026-11-01", amount: 5 },
{ id: "b2", date: "2026-11-02", amount: 42.17 },
{ id: "b3", date: "2026-11-02", amount: 42.17, custom_name: "Kept" },
];
const p = planMerge(csv, bank);
assert.equal(p.start, "2026-11-01");
assert.deepEqual(p.move, ["c1"]);
assert.deepEqual(p.drop.sort(), ["c2", "c3", "c4"]);
// c2's edits go to the first matching bank row; c3 has none; c4 has no twin, so its note goes with it.
assert.deepEqual(p.edits, [{ id: "b2", patch: { category_id: "groceries", custom_name: "Boodschappen", tags: ["home"] } }]);
// A bank row's own name stays; only what it lacks is filled in.
assert.deepEqual(planMerge([{ id: "c", date: "2026-11-02", amount: 1, custom_name: "Mine", category_id: "x" }], [{ id: "b", date: "2026-11-02", amount: 1, custom_name: "Bank's" }]).edits, [{ id: "b", patch: { category_id: "x" } }]);
// Nothing on the linked side yet: everything moves, nothing is dropped.
assert.deepEqual(planMerge(csv, []), { start: null, move: ["c1", "c2", "c3", "c4"], drop: [], edits: [] });
console.log("merge ok");
// Run again after stopping halfway: a row already moved over (not from the bank) doesn't move the start earlier.
{
const again = planMerge(
[{ id: "c-old2", date: "2026-10-21", amount: 7 }, { id: "c-new", date: "2026-11-03", amount: 2 }],
[{ id: "c-old1", date: "2026-10-20", amount: 30, fromBank: false }, { id: "b", date: "2026-11-01", amount: 5, fromBank: true }],
);
assert.equal(again.start, "2026-11-01");
assert.deepEqual(again.move, ["c-old2"]);
assert.deepEqual(again.drop, ["c-new"]);
}
console.log("merge rerun ok");
+55
View File
@@ -0,0 +1,55 @@
// Merging an imported (CSV) account into a linked one. The bank's own rows win from the day its history starts; older
// imported rows move over, so the history stays complete. Edits on an imported row that the bank also has (same day,
// same amount) carry over to the bank's row. Pure: `node src/lib/merge.test.ts` runs it.
export type MergeRow = {
id: string;
date: string;
amount: number;
category_id?: string | null;
custom_name?: string | null;
note?: string | null;
tags?: string[] | null;
ignored?: boolean | null;
/** Came from the bank link (false: imported or typed in). Only the bank's rows set where its history starts. */
fromBank?: boolean;
};
export type Edit = Partial<Pick<MergeRow, "category_id" | "custom_name" | "note" | "tags" | "ignored">>;
export type MergePlan = { start: string | null; move: string[]; drop: string[]; edits: { id: string; patch: Edit }[] };
/** What a person changed on a row: only those carry over, never the empty defaults. */
function editsOf(r: MergeRow): Edit {
const e: Edit = {};
if (r.category_id) e.category_id = r.category_id;
if (r.custom_name) e.custom_name = r.custom_name;
if (r.note) e.note = r.note;
if (r.tags?.length) e.tags = r.tags;
if (r.ignored) e.ignored = true;
return e;
}
// Only the bank's rows count on the target side: imported rows already moved there by a merge that stopped halfway
// must not pull the start earlier, so running it again picks up where it stopped.
export function planMerge(source: MergeRow[], target: MergeRow[]): MergePlan {
const bank = target.filter((t) => t.fromBank !== false);
const start = bank.reduce<string | null>((m, r) => (m === null || r.date < m ? r.date : m), null);
const move: string[] = [], drop: string[] = [], edits: MergePlan["edits"] = [];
const unmatched = [...bank];
for (const r of [...source].sort((a, b) => a.date.localeCompare(b.date))) {
if (start === null || r.date < start) {
move.push(r.id);
continue;
}
drop.push(r.id);
// The same payment on the bank's side: same day and the same amount to the cent, each bank row used once.
const i = unmatched.findIndex((t) => t.date === r.date && Math.abs(t.amount - r.amount) < 0.005);
if (i < 0) continue;
const [twin] = unmatched.splice(i, 1);
const patch = editsOf(r);
// The bank's row keeps anything it already has of its own, except a category: the imported one is what you chose.
if (twin.custom_name) delete patch.custom_name;
if (twin.note) delete patch.note;
if (Object.keys(patch).length) edits.push({ id: twin.id, patch });
}
return { start, move, drop, edits };
}