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:
1 parent
514b2aac77
commit
8e830dc422
3 files changed
+156
No files matched your search
@@ -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 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user