import "server-only"; import type { SupabaseClient } from "@supabase/supabase-js"; import { planMerge, type MergeRow } from "@/lib/merge"; // Merge an imported account into another of the person's accounts (lib/merge.ts decides what moves). Used by the // Accounts page (api/accounts/merge) and the MCP tools. db: a client that can write the user's rows. const COLS = "id, date, amount, category_id, custom_name, note, tags, ignored, plaid_transaction_id"; async function rowsOf(db: SupabaseClient, 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 = (xs: T[], n = 200) => Array.from({ length: Math.ceil(xs.length / n) }, (_, i) => xs.slice(i * n, i * n + n)); export type MergeResult = { error?: string; status?: number; start?: string | null; moved?: number; replaced?: number; edits?: number; ok?: boolean }; export async function mergeAccounts(db: SupabaseClient, userId: string, from: string, into: string, preview: boolean): Promise { if (!from || !into || from === into) return { error: "Pick the account to merge into.", status: 400 }; const { data: accts } = await db.from("accounts").select("id, manual").eq("user_id", userId).in("id", [from, into]); 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 }; 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; for (const e of plan.edits) { const { error } = await db.from("transactions").update(e.patch).eq("id", e.id).eq("user_id", userId); if (error) throw error; } for (const ids of chunks(plan.move)) { const { error } = await db.from("transactions").update({ account_id: into }).eq("user_id", userId).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", userId).eq("account_id", from); await db.from("recurring").update({ account_id: into }).eq("user_id", userId).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", userId); if (error) throw error; return { ok: true, ...counts }; }