The account editor of an imported account gets a Merge into section: pick the linked account, see what moves and what the bank already has, then merge. Tested in the stack: older rows move, overlap counts once, edits carry over, and the next sync leaves it alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
142 lines
7.8 KiB
TypeScript
142 lines
7.8 KiB
TypeScript
"use client";
|
|
|
|
import { Pencil, X } from "lucide-react";
|
|
import { useRouter } from "next/navigation";
|
|
import { useState } from "react";
|
|
import { Dropdown } from "@/components/Dropdown";
|
|
import { Modal } from "@/components/Modal";
|
|
import { toast } from "@/components/Toast";
|
|
import { plural } from "@/lib/format";
|
|
import { createClient } from "@/utils/supabase/client";
|
|
|
|
const KINDS = [
|
|
{ value: "depository", label: "Bank account (checking or savings)" },
|
|
{ value: "credit", label: "Credit card" },
|
|
{ value: "loan", label: "Loan" },
|
|
{ value: "investment", label: "Investment" },
|
|
{ value: "other", label: "Something else (cash, a car, a home)" },
|
|
];
|
|
|
|
// Rename an account, say what kind it is, or delete it. The kind decides where it counts: a credit card's balance is a
|
|
// debt and its purchases are spending on the card. Linked accounts come back on the next sync, so only accounts you
|
|
// added or imported can be deleted; a linked one is hidden instead, or its bank removed under Connections.
|
|
type Preview = { start: string | null; moved: number; replaced: number; edits: number };
|
|
const day = (d: string) => new Date(`${d}T12:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" });
|
|
|
|
export function AccountEdit({ id, name, bankName, type, manual, targets = [] }: { id: string; name: string; bankName: string; type: string; manual: boolean; targets?: { id: string; label: string }[] }) {
|
|
const router = useRouter();
|
|
const [open, setOpen] = useState(false);
|
|
const [label, setLabel] = useState(name);
|
|
const [kind, setKind] = useState(type);
|
|
const [busy, setBusy] = useState(false);
|
|
const [confirm, setConfirm] = useState(false);
|
|
const [err, setErr] = useState("");
|
|
// Merge this imported account into a linked one (api/accounts/merge): pick it, see what happens, then confirm.
|
|
const [into, setInto] = useState("");
|
|
const [preview, setPreview] = useState<Preview | null>(null);
|
|
const close = () => { setOpen(false); setConfirm(false); setErr(""); setInto(""); setPreview(null); };
|
|
const merge = (target: string, dry: boolean) =>
|
|
fetch("/api/accounts/merge", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ from: id, into: target, preview: dry }) })
|
|
.then(async (r) => ({ ok: r.ok, body: (await r.json().catch(() => ({}))) as Preview & { error?: string } }));
|
|
async function pick(target: string) {
|
|
setInto(target);
|
|
setPreview(null);
|
|
setErr("");
|
|
const { ok, body } = await merge(target, true);
|
|
if (!ok) return setErr(body.error ?? "Couldn't check that. Try again.");
|
|
setPreview(body);
|
|
}
|
|
async function doMerge() {
|
|
setBusy(true);
|
|
const { ok, body } = await merge(into, false);
|
|
setBusy(false);
|
|
if (!ok) return setErr(body.error ?? "Couldn't merge them. Try again.");
|
|
close();
|
|
toast(`Merged ${name}`);
|
|
router.refresh();
|
|
}
|
|
|
|
async function save(e: React.FormEvent) {
|
|
e.preventDefault();
|
|
setBusy(true);
|
|
const patch: Record<string, unknown> = { custom_name: label.trim() && label.trim() !== bankName ? label.trim() : null };
|
|
if (kind !== type) patch.type_override = kind;
|
|
// RLS blocks with 0 rows, not an error.
|
|
const { data, error } = await createClient().from("accounts").update(patch).eq("id", id).select("id");
|
|
setBusy(false);
|
|
if (error || !data?.length) return setErr(/type_override/.test(error?.message ?? "") ? "This needs a database update. Open Setup to run it." : "Couldn't save that. Try again.");
|
|
close();
|
|
toast("Saved");
|
|
router.refresh();
|
|
}
|
|
|
|
async function remove() {
|
|
setBusy(true);
|
|
const { data, error } = await createClient().from("accounts").delete().eq("id", id).select("id");
|
|
setBusy(false);
|
|
if (error || !data?.length) return setErr("Couldn't delete it. Try again.");
|
|
close();
|
|
toast(`Deleted ${name}`);
|
|
router.refresh();
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<button onClick={() => setOpen(true)} aria-label={`Edit ${name}`} title="Edit" className="size-8 grid place-items-center rounded-full text-muted hover:text-ink hover:bg-[var(--hover-strong)] shrink-0">
|
|
<Pencil size={15} />
|
|
</button>
|
|
{open && (
|
|
<Modal label={`Edit ${name}`} onClose={close}>
|
|
<form onSubmit={save} className="p-6 space-y-5">
|
|
<div className="flex items-center justify-between">
|
|
<div className="card-title">Edit account</div>
|
|
<button type="button" aria-label="Close" onClick={close} className="p-2 -mr-2 rounded-full hover:bg-[var(--hover)]"><X size={18} /></button>
|
|
</div>
|
|
<label className="block space-y-1.5">
|
|
<span className="text-sm font-medium">Name</span>
|
|
<input data-autofocus value={label} onChange={(e) => setLabel(e.target.value)} placeholder={bankName} className="select" />
|
|
</label>
|
|
<div className="space-y-1.5">
|
|
<span className="block text-sm font-medium">What kind of account is it?</span>
|
|
<Dropdown label="Kind of account" placeholder="Choose a kind" value={kind} onChange={setKind} options={KINDS} />
|
|
<p className="text-xs text-muted">A credit card's balance counts as money you owe. A bank account's counts as money you have.</p>
|
|
</div>
|
|
{err && <p className="text-sm text-bad">{err}</p>}
|
|
<button disabled={busy} className="btn-primary w-full !py-2.5">{busy && !confirm ? "Saving..." : "Save"}</button>
|
|
<div className="border-t border-line pt-4 text-sm">
|
|
{!manual ? (
|
|
<p className="text-muted">This account comes from your bank, so it comes back on the next sync. To stop counting it, use the switch next to it. To remove the whole bank, use Remove under Connections.</p>
|
|
) : confirm ? (
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<span className="text-muted">Delete it and all its transactions? This can't be undone.</span>
|
|
<button type="button" className="btn text-bad" disabled={busy} onClick={remove}>{busy ? "Deleting..." : "Delete"}</button>
|
|
<button type="button" className="text-muted hover:text-ink" disabled={busy} onClick={() => setConfirm(false)}>Cancel</button>
|
|
</div>
|
|
) : (
|
|
<button type="button" className="text-bad underline underline-offset-2" onClick={() => setConfirm(true)}>Delete this account</button>
|
|
)}
|
|
</div>
|
|
{manual && !!targets.length && (
|
|
<div className="border-t border-line pt-4 space-y-2 text-sm">
|
|
<span className="block font-medium">Merge into a linked account</span>
|
|
<p className="text-xs text-muted">For a statement you imported before linking the same account. Where both have the same days, they count twice until you merge.</p>
|
|
<Dropdown label="Merge into" placeholder="Choose the linked account" value={into} onChange={pick} options={targets.map((t) => ({ value: t.id, label: t.label }))} />
|
|
{preview && (
|
|
<>
|
|
<p className="text-muted">
|
|
{preview.start
|
|
? <>Moves {plural(preview.moved, "transaction")} from before {day(preview.start)}. From then on it keeps the bank's own and drops {plural(preview.replaced, "imported one")}{preview.edits ? <> (your changes on {preview.edits} carry over)</> : null}. Then {name} is removed.</>
|
|
: <>Moves all {plural(preview.moved, "transaction")}, then {name} is removed.</>}
|
|
</p>
|
|
<button type="button" className="btn-primary" disabled={busy} onClick={doMerge}>{busy ? "Merging..." : "Merge"}</button>
|
|
</>
|
|
)}
|
|
</div>
|
|
)}
|
|
</form>
|
|
</Modal>
|
|
)}
|
|
</>
|
|
);
|
|
}
|