"use client"; import { Ban, NotebookPen, Trash2, Wand2, X } from "lucide-react"; import { useRouter } from "next/navigation"; import { useRef, useState } from "react"; import { Dropdown } from "@/components/Dropdown"; import { CategoryIcon } from "@/components/Icons"; import { Merchant } from "@/components/Merchant"; import { Modal } from "@/components/Modal"; import { categoryOptions, emptyRule, RuleDialog, type Draft } from "@/components/RuleForm"; import { TagButton, TagChip, TagEditor } from "@/components/Tags"; import { toast } from "@/components/Toast"; import type { Category, Txn } from "@/lib/data"; import { displayName } from "@/lib/format"; import { createClient } from "@/utils/supabase/client"; import { useMoney } from "@/components/Money"; type Patch = Partial> & { checked_at?: string }; export function TxnRow({ t, cats, allTags = [], to }: { t: Txn; cats: Category[]; allTags?: string[]; to?: string }) { const { dayLabel, dateLabel, signed } = useMoney(); const router = useRouter(); const [ignored, setIgnored] = useState(t.ignored); const [noteOpen, setNoteOpen] = useState(!!t.note); const [catId, setCatId] = useState(t.category_id ?? ""); const [sheet, setSheet] = useState(false); const [rule, setRule] = useState(null); const [tags, setTags] = useState(t.tags ?? []); const actions = useRef(null); const name = displayName(t); // A partner's shared row is read-only here: RLS lets you see it, not change it. const mine = !t.account?.owner_label; const cat = cats.find((c) => c.id === catId); const label = (id: string) => cats.find((c) => c.id === id)?.label ?? "Uncategorized"; const options = [{ value: "", label: "Uncategorized", icon: }, ...categoryOptions(cats)]; // A new rule starts from this merchant ("Uber", not "UBER *TRIP 8812") and the category it has now. const newRule = (category_id = catId) => setRule(emptyRule({ match: t.merchant_name ?? t.name, category_id: category_id || null })); const ruleLink = ( ); // Optimistic: the screen and the toast change at once, the write runs behind it, and a failure puts it back. // Only edits that change totals re-render the page from the server. RLS blocks with 0 rows, not an error. function save(patch: Patch, rollback: () => void, refresh = false) { createClient().from("transactions").update(patch).eq("id", t.id).select("id").then(({ data, error }) => { if (error || !data?.length) { rollback(); toast("Couldn't save that. Try again."); } else if (refresh) router.refresh(); }); } function setCategory(next: string) { const prev = catId; setCatId(next); // A category picked by hand is a checked one: "Is this right?" stops asking about it (checked_at, 0023). save({ category_id: next || null, checked_at: new Date().toISOString() }, () => setCatId(prev)); toast( `${name} moved to ${label(next)}`, () => { setCatId(prev); save({ category_id: prev || null }, () => setCatId(next)); }, next ? { label: "Always", run: () => newRule(next) } : undefined, ); } function saveTags(next: string[]) { const prev = tags; setTags(next); save({ tags: next }, () => setTags(prev)); toast(next.length ? `Tags saved for ${name}` : `Tags removed from ${name}`, () => { setTags(prev); save({ tags: prev }, () => setTags(next)); }); } async function remove() { const { data, error } = await createClient().from("transactions").delete().eq("id", t.id).select("id"); if (error || !data?.length) return toast("Couldn't delete that."); setSheet(false); toast(`${name} deleted`); router.refresh(); } function toggleIgnore() { const next = !ignored; setIgnored(next); save({ ignored: next }, () => setIgnored(!next), true); toast(next ? `${name} hidden from totals` : `${name} counted again`, () => { setIgnored(!next); save({ ignored: !next }, () => setIgnored(next), true); }); } // On narrow layouts the category and action columns are hidden, so tapping the row opens a sheet instead. const narrow = () => !!actions.current && getComputedStyle(actions.current).display === "none"; return ( narrow() && !(e.target as HTMLElement).closest("input,button,select") && setSheet(true)} className={`row-hover border-b border-line last:border-0 ${ignored ? "text-muted" : ""}`} > {dateLabel(t.date, { month: "numeric", day: "numeric" })}
{name}
{to &&
To {to}
} {(t.pending || t.manual) &&
{t.pending ? "Pending" : mine ? "Added by you" : `Added by ${t.account?.owner_label}`}
} {!!tags.length &&
{tags.map((g) => )}
} {!mine && t.note &&
{t.note}
} {mine && noteOpen && ( e.target.value !== (t.note ?? "") && (save({ note: e.target.value || null }, () => {}), toast("Note saved"))} className="mt-1 text-xs border-b border-line focus:border-ink w-56 bg-transparent" /> )}
{mine ? (o.value === catId ? { ...o, icon: } : o))} onChange={setCategory} searchable footer={ruleLink} /> : {label(catId)}} {rule && setRule(null)} onDone={(msg) => { setRule(null); toast(msg); router.refresh(); }} />} {mine &&
{t.manual && }
} {signed(t.amount, t.currency)} {sheet && renderSheet()} ); // A plain render function, not a component, so the inputs keep focus across re-renders. function renderSheet() { return ( setSheet(false)} sheet className="space-y-5">
{name}
{dayLabel(t.date)}{t.account ? ` ยท ${t.account.name}${t.account.owner_label ? ` (${t.account.owner_label})` : ""}` : ""}
{signed(t.amount, t.currency)}
{mine ? ( <>
Category
Tags
{t.manual && } ) : (
{label(catId)}
{!!tags.length &&
{tags.map((g) => )}
} {t.note &&

{t.note}

}

Shared by {t.account?.owner_label}. Only they can edit it.

)}
); } }