// Merging an imported (CSV) account into a linked one. The bank's own rows win from the day its history starts; older // imported rows move over, so the history stays complete. Edits on an imported row that the bank also has (same day, // same amount) carry over to the bank's row. Pure: `node src/lib/merge.test.ts` runs it. export type MergeRow = { id: string; date: string; amount: number; category_id?: string | null; custom_name?: string | null; note?: string | null; tags?: string[] | null; ignored?: boolean | null; /** Came from the bank link (false: imported or typed in). Only the bank's rows set where its history starts. */ fromBank?: boolean; }; export type Edit = Partial>; export type MergePlan = { start: string | null; move: string[]; drop: string[]; edits: { id: string; patch: Edit }[] }; /** What a person changed on a row: only those carry over, never the empty defaults. */ function editsOf(r: MergeRow): Edit { const e: Edit = {}; if (r.category_id) e.category_id = r.category_id; if (r.custom_name) e.custom_name = r.custom_name; if (r.note) e.note = r.note; if (r.tags?.length) e.tags = r.tags; if (r.ignored) e.ignored = true; return e; } // Only the bank's rows count on the target side: imported rows already moved there by a merge that stopped halfway // must not pull the start earlier, so running it again picks up where it stopped. export function planMerge(source: MergeRow[], target: MergeRow[]): MergePlan { const bank = target.filter((t) => t.fromBank !== false); const start = bank.reduce((m, r) => (m === null || r.date < m ? r.date : m), null); const move: string[] = [], drop: string[] = [], edits: MergePlan["edits"] = []; const unmatched = [...bank]; for (const r of [...source].sort((a, b) => a.date.localeCompare(b.date))) { if (start === null || r.date < start) { move.push(r.id); continue; } drop.push(r.id); // The same payment on the bank's side: same day and the same amount to the cent, each bank row used once. const i = unmatched.findIndex((t) => t.date === r.date && Math.abs(t.amount - r.amount) < 0.005); if (i < 0) continue; const [twin] = unmatched.splice(i, 1); const patch = editsOf(r); // The bank's row keeps anything it already has of its own, except a category: the imported one is what you chose. if (twin.custom_name) delete patch.custom_name; if (twin.note) delete patch.note; if (Object.keys(patch).length) edits.push({ id: twin.id, patch }); } return { start, move, drop, edits }; }