From 1bdcc57c2f971dfa2ab16d94ad35d3927dafbc01 Mon Sep 17 00:00:00 2001 From: MangaValk Date: Sat, 21 Nov 2026 16:04:27 +0100 Subject: [PATCH] Keep accounts and history when a connection is removed Removing a bank connection deleted its accounts and transactions through the cascade, so a relink or "Remove this copy" could wipe years of history and every edit. Now an account that another connection also has folds into that one (older rows move, edits carry over), and any other account stays as an account added by hand. Test banks still go entirely. Co-Authored-By: Claude Opus 5.5 --- src/app/api/plaid/remove/route.ts | 38 ++++++++++++++++++++++++++++++- src/components/PlaidButtons.tsx | 4 ++-- src/lib/links.test.ts | 9 +++++++- src/lib/links.ts | 12 ++++++++++ src/lib/merge-run.ts | 7 ++++++ 5 files changed, 66 insertions(+), 4 deletions(-) diff --git a/src/app/api/plaid/remove/route.ts b/src/app/api/plaid/remove/route.ts index 97619be..8ffcf31 100644 --- a/src/app/api/plaid/remove/route.ts +++ b/src/app/api/plaid/remove/route.ts @@ -1,9 +1,16 @@ import { NextResponse } from "next/server"; +import { twinAccounts } from "@/lib/links"; +import { foldInto } from "@/lib/merge-run"; import { revokeItem } from "@/lib/plaid"; import { createAdminClient } from "@/utils/supabase/admin"; import { createClient } from "@/utils/supabase/server"; -// Removes a bank connection: revokes it at Plaid, then deletes the item (its accounts, transactions and holdings cascade). +type Acct = { id: string; item_id: string | null; name: string | null; mask: string | null; type: string | null }; + +// Removes a bank connection: revokes it at the provider, then deletes the connection. Its accounts and their history +// stay. An account that another connection also has (linked twice, or linked again) folds into that one: older rows +// move over and your categories and names carry over. Any other account stays as an account added by hand, no longer +// syncing. Only a test bank's accounts and transactions go with it, because test data never stays next to real banks. export async function POST(request: Request) { const supabase = await createClient(); const { data: { user } } = await supabase.auth.getUser(); @@ -15,7 +22,36 @@ export async function POST(request: Request) { if (!item) return NextResponse.json({ error: "Connection not found" }, { status: 404 }); if (!(await revokeItem(item)).ok) return NextResponse.json({ error: "Plaid couldn't remove this connection. Try again in a moment." }, { status: 502 }); + if (!item.access_token?.startsWith("access-sandbox-")) { + try { + await keepAccounts(db, user.id, item.id); + } catch (e) { + console.error("[broke] remove, keeping accounts:", e instanceof Error ? e.message : JSON.stringify(e)); + return NextResponse.json({ error: "Couldn't keep this connection's accounts, so nothing was removed. Try again." }, { status: 500 }); + } + } const { error } = await db.from("plaid_items").delete().eq("id", item.id); if (error) return NextResponse.json({ error: "Couldn't remove this connection." }, { status: 500 }); return NextResponse.json({ ok: true }); } + +async function keepAccounts(db: ReturnType, userId: string, itemId: string) { + const { data, error } = await db.from("accounts").select("id, item_id, name, mask, type").eq("user_id", userId).not("item_id", "is", null); + if (error) throw error; + const all = (data ?? []) as Acct[]; + const leaving = all.filter((a) => a.item_id === itemId); + const twins = twinAccounts(leaving, all.filter((a) => a.item_id !== itemId)); + for (const a of leaving) { + const twin = twins.get(a.id); + if (twin) { + await foldInto(db, userId, a.id, twin); + continue; + } + // No twin: unlink it. Its rows lose the bank's ids, so linking the bank again adds the bank's rows fresh and + // Accounts can merge this one into the new account like an imported statement. + const rows = await db.from("transactions").update({ plaid_transaction_id: null }).eq("user_id", userId).eq("account_id", a.id); + if (rows.error) throw rows.error; + const acct = await db.from("accounts").update({ item_id: null, plaid_account_id: null, manual: true }).eq("id", a.id).eq("user_id", userId); + if (acct.error) throw acct.error; + } +} diff --git a/src/components/PlaidButtons.tsx b/src/components/PlaidButtons.tsx index ee9b891..2a0a1f3 100644 --- a/src/components/PlaidButtons.tsx +++ b/src/components/PlaidButtons.tsx @@ -155,7 +155,7 @@ export function ConnectionActions({ itemId, broken, name }: { itemId: string; br {confirm ? ( <> - Remove {name} and its transactions? + Stop syncing {name}? Its accounts and history stay. @@ -226,7 +226,7 @@ export function RemoveCopy({ itemId, name }: { itemId: string; name: string }) { } return confirm ? ( - Remove this copy of {name}? The other one keeps all your transactions. + Remove this copy of {name}? Its history and your changes move to the other one. {err && {err}} diff --git a/src/lib/links.test.ts b/src/lib/links.test.ts index 3f770ce..19118a1 100644 --- a/src/lib/links.test.ts +++ b/src/lib/links.test.ts @@ -1,6 +1,6 @@ // Run: node src/lib/links.test.ts import assert from "node:assert/strict"; -import { duplicateItems, sameAccounts } from "./links.ts"; +import { duplicateItems, sameAccounts, twinAccounts } from "./links.ts"; const wf = [{ mask: "8640", type: "depository" }, { mask: "4381", type: "credit" }]; assert.equal(sameAccounts(wf, wf), true); @@ -17,4 +17,11 @@ const items = [ { id: "co3", institution_id: "ins_128026", created_at: "2026-10-29T15:40", accounts: [{ mask: "7777", type: "credit" }] }, ]; assert.deepEqual([...duplicateItems(items)], [["wf2", "wf1"], ["co2", "co1"]]); + +// Removing a connection: its accounts find their twins on the connection that stays. +const leaving = [{ id: "a1", mask: "5339", type: "depository" }, { id: "a2", mask: null, type: "depository", name: "Savings" }, { id: "a3", mask: "1111", type: "credit" }]; +const staying = [{ id: "b1", mask: "5339", type: "depository" }, { id: "b2", mask: null, type: "depository", name: "Savings" }, { id: "b3", mask: "1111", type: "depository" }]; +assert.deepEqual([...twinAccounts(leaving, staying)], [["a1", "b1"], ["a2", "b2"]], "a3 has no twin: another type"); +assert.deepEqual([...twinAccounts([leaving[0], { ...leaving[0], id: "a4" }], staying)], [["a1", "b1"]], "each twin used once"); +assert.deepEqual([...twinAccounts([{ id: "a5", mask: null, type: "depository", name: null }], [{ id: "b5", mask: null, type: "depository", name: null }])], [], "no digits and no name: can't tell"); console.log("links ok"); diff --git a/src/lib/links.ts b/src/lib/links.ts index 8e8b456..3ee8fcf 100644 --- a/src/lib/links.ts +++ b/src/lib/links.ts @@ -13,6 +13,18 @@ export function sameAccounts(next: Acct[], existing: Acct[]) { return masked.every((a) => have.has(a.mask)); } +/** The same account on another connection, for a connection that is being removed: same type and last four digits, + * or, without digits, the same type and name. Each other account is used once. */ +export function twinAccounts(leaving: T[], others: T[]) { + const pool = [...others], twins = new Map(); + const same = (a: T, b: T) => (a.type ?? "") === (b.type ?? "") && (a.mask ? a.mask === b.mask : !b.mask && !!a.name && a.name === b.name); + for (const a of leaving) { + const i = pool.findIndex((b) => same(a, b)); + if (i >= 0) twins.set(a.id, pool.splice(i, 1)[0].id); + } + return twins; +} + /** Connections that copy an earlier one at the same bank: id -> the earlier connection's id. */ export function duplicateItems(items: { id: string; institution_id: string | null; created_at: string; accounts: Acct[] }[]) { const copies = new Map(); diff --git a/src/lib/merge-run.ts b/src/lib/merge-run.ts index 552bae0..1af4829 100644 --- a/src/lib/merge-run.ts +++ b/src/lib/merge-run.ts @@ -24,6 +24,13 @@ export async function mergeAccounts(db: SupabaseClient, userId: string, from: st const src = accts?.find((a) => a.id === from), dst = accts?.find((a) => a.id === into); if (!src || !dst) return { error: "Account not found.", status: 404 }; if (!src.manual) return { error: "Only an imported account can be merged into another.", status: 400 }; + return foldInto(db, userId, from, into, preview); +} + +/** Moves one account's history into another: older rows move, the overlap the target already has goes, edits carry + * over. Then the source account is deleted. Also used when a connection is removed and the same account stays on + * another connection (api/plaid/remove), so nothing typed or chosen there is lost. */ +export async function foldInto(db: SupabaseClient, userId: string, from: string, into: string, preview = false): Promise { const plan = planMerge(await rowsOf(db, userId, from), await rowsOf(db, userId, into)); const counts = { start: plan.start, moved: plan.move.length, replaced: plan.drop.length, edits: plan.edits.length }; if (preview) return counts;