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:
1 parent
fbdeea630a
commit
1bdcc57c2f
5 files changed
+66
-4
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -155,7 +155,7 @@ export function ConnectionActions({ itemId, broken, name }: { itemId: string; br
|
||||
<span className="flex items-center gap-2">
|
||||
{confirm ? (
|
||||
<>
|
||||
<span className="text-xs text-muted">Remove {name} and its transactions?</span>
|
||||
<span className="text-xs text-muted">Stop syncing {name}? Its accounts and history stay.</span>
|
||||
<button className="btn text-bad" onClick={remove} disabled={removing}>{removing ? "Removing..." : "Remove"}</button>
|
||||
<button className="btn" onClick={() => setConfirm(false)} disabled={removing}>Cancel</button>
|
||||
</>
|
||||
@@ -226,7 +226,7 @@ export function RemoveCopy({ itemId, name }: { itemId: string; name: string }) {
|
||||
}
|
||||
return confirm ? (
|
||||
<span className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-muted">Remove this copy of {name}? The other one keeps all your transactions.</span>
|
||||
<span className="text-muted">Remove this copy of {name}? Its history and your changes move to the other one.</span>
|
||||
<button className="btn text-bad" onClick={remove} disabled={busy}>{busy ? "Removing..." : "Remove copy"}</button>
|
||||
<button className="text-muted hover:text-ink" onClick={() => setConfirm(false)} disabled={busy}>Cancel</button>
|
||||
{err && <span className="text-bad">{err}</span>}
|
||||
|
||||
@@ -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");
|
||||
@@ -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<T extends Acct & { id: string; name?: string | null }>(leaving: T[], others: T[]) {
|
||||
const pool = [...others], twins = new Map<string, string>();
|
||||
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<string, string>();
|
||||
|
||||
@@ -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<MergeResult> {
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user