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 <noreply@anthropic.com>
This commit is contained in:
MangaValkandClaude Opus 5.5 committed 2026-11-21 16:04:27 +01:00
1 parent fbdeea630a
commit 1bdcc57c2f
5 files changed
+66 -4

No files matched your search

+37 -1
View File
@@ -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<typeof createAdminClient>, 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;
}
}