Files
events-hub/frontend/src/components/customer/History.tsx
T
joshuaandClaude Opus 5.5 590757e040 Hub 2.14.0: customer page as a summary and tabs, popups for every edit
- Customer page: header tiles (products, owing, next invoice, address, AI) and three
  tabs (Overview, Products, Invoices and payments), the tab in the URL; #billing links
  open Invoices and payments and Billing's links use ?tab=invoices.
- Every add or edit is a popup (new Modal in components/ui.tsx: Esc / click outside,
  asks before discarding changes, focus kept inside, full screen on a phone). The page
  shows only read views. Record payment is a popup on Billing and the invoice page too.
- One card per product: licence and billing fields in one Edit with one Save (each
  endpoint called only if its fields changed); suspend/revoke/reactivate/release in a
  ⋯ menu. Contact and billing details edited together. One page-level message.
- History as one timeline with a filter; each kind on its own keeps its sortable table.
- CustomerBilling.tsx split into components/customer/; plan in docs/CUSTOMER-PAGE-PLAN.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:14:05 +02:00

208 lines
13 KiB
TypeScript

"use client";
import React, { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { api, errorText, openPdf } from "@/lib/api";
import { EMAIL_KIND, METHOD, StateBadge, day, money, type BillingEmail, type Invoice, type LicenceChange, type Payment } from "@/lib/billing";
import { fmtDate } from "@/lib/format";
import { SortSelect, SortTh, useSort, type SortColumn } from "@/lib/sort";
import type { CustomerBillingData, Done } from "./shared";
type View = "all" | "invoices" | "payments" | "notices" | "emails";
const VIEWS: [View, string][] = [["all", "Everything"], ["invoices", "Invoices"], ["payments", "Payments"], ["notices", "Notices of licence change"], ["emails", "Billing emails"]];
const VIEW_KEY = "customer-history-view";
/**
* Hub 2.14.0: the church's invoices, payments, notices and billing emails. "Everything" is one
* timeline, newest first; each kind on its own is its table, sortable as before.
*/
export function History({ b, onDone }: { b: CustomerBillingData; onDone: Done }) {
const [view, setView] = useState<View>("all");
useEffect(() => {
try { const v = localStorage.getItem(VIEW_KEY); if (VIEWS.some(([k]) => k === v)) setView(v as View); } catch { /* not remembered */ }
}, []);
const pick = (v: View) => { setView(v); try { localStorage.setItem(VIEW_KEY, v); } catch { /* not remembered */ } };
const pdf = (path: string) => openPdf(path).catch(e => onDone({ type: "err", text: errorText(e) }));
const resend = (ch: LicenceChange) => api<{ message: string }>(`/api/admin/billing/licence-changes/${ch.id}/resend`, { method: "POST" })
.then(r => onDone({ type: "ok", text: r.message })).catch(e => onDone({ type: "err", text: errorText(e) }));
const count: Record<View, number> = { all: 0, invoices: b.invoices.length, payments: b.payments.length, notices: b.licenceChanges.length, emails: b.emails.length };
count.all = count.invoices + count.payments + count.notices + count.emails;
return (
<section className="card space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="font-semibold">History</h2>
<div role="group" aria-label="Show" className="flex flex-wrap gap-1">
{VIEWS.map(([k, label]) => (
<button key={k} type="button" aria-pressed={view === k} onClick={() => pick(k)}
className={`rounded-full px-3 py-1 text-xs ring-1 ring-inset ${view === k ? "bg-indigo-600 text-white ring-indigo-600" : "bg-white text-slate-600 ring-slate-300 hover:bg-slate-50"}`}>
{label} <span className={view === k ? "text-indigo-100" : "text-slate-400"}>{count[k]}</span>
</button>
))}
</div>
</div>
{view === "all" && <Timeline b={b} pdf={pdf} resend={resend} />}
{view === "invoices" && <InvoiceList invoices={b.invoices} />}
{view === "payments" && <PaymentList payments={b.payments} pdf={pdf} />}
{view === "notices" && <NoticeList changes={b.licenceChanges} pdf={pdf} resend={resend} />}
{view === "emails" && <EmailLog emails={b.emails} />}
</section>
);
}
type Entry =
| { kind: "invoice"; at: string; item: Invoice }
| { kind: "payment"; at: string; item: Payment }
| { kind: "notice"; at: string; item: LicenceChange }
| { kind: "email"; at: string; item: BillingEmail };
const KIND_LABEL: Record<Entry["kind"], string> = { invoice: "Invoice", payment: "Payment", notice: "Notice", email: "Email" };
const KIND_TONE: Record<Entry["kind"], string> = {
invoice: "bg-indigo-50 text-indigo-700", payment: "bg-green-50 text-green-700", notice: "bg-sky-50 text-sky-700", email: "bg-slate-100 text-slate-600",
};
/** Dates and times sort together: a bare date counts as midday South African time. */
const when = (d: string) => (d.length === 10 ? `${d}T10:00:00.000Z` : new Date(d).toISOString());
function Timeline({ b, pdf, resend }: { b: CustomerBillingData; pdf: (p: string) => void; resend: (ch: LicenceChange) => void }) {
const entries = useMemo<Entry[]>(() => [
...b.invoices.map(i => ({ kind: "invoice" as const, at: when(i.issueDate), item: i })),
...b.payments.map(p => ({ kind: "payment" as const, at: when(p.paidOn), item: p })),
...b.licenceChanges.map(ch => ({ kind: "notice" as const, at: when(ch.sentAt || ch.createdAt), item: ch })),
...b.emails.map(e => ({ kind: "email" as const, at: when(e.sentAt), item: e })),
].sort((x, y) => (x.at < y.at ? 1 : x.at > y.at ? -1 : 0)), [b]);
if (!entries.length) return <p className="text-sm text-slate-500">Nothing yet.</p>;
return (
<>
<ol className="divide-y divide-slate-100 text-sm">
{entries.map(e => (
<li key={`${e.kind}-${e.item.id}`} className="grid grid-cols-[5.5rem_1fr] gap-x-3 gap-y-1 py-2 sm:grid-cols-[6.5rem_4.5rem_1fr_auto] sm:items-baseline">
<span className="whitespace-nowrap text-slate-500">{day(e.at.slice(0, 10))}</span>
<span className={`w-fit rounded px-1.5 py-0.5 text-xs font-medium ${KIND_TONE[e.kind]}`}>{KIND_LABEL[e.kind]}</span>
<div className="col-span-2 min-w-0 sm:col-span-1"><EntryText e={e} /></div>
<div className="col-span-2 flex flex-wrap items-baseline justify-end gap-3 text-right sm:col-span-1"><EntryEnd e={e} pdf={pdf} resend={resend} /></div>
</li>
))}
</ol>
{b.emails.length >= 50 && <p className="text-xs text-slate-500">Showing the last 50 billing emails.</p>}
</>
);
}
function EntryText({ e }: { e: Entry }) {
switch (e.kind) {
case "invoice": {
const i = e.item;
return <><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link> <span className="text-slate-600">{i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""}</span></>;
}
case "payment": {
const p = e.item;
return <>{p.receiptNumber} <span className="text-slate-600">· {METHOD[p.method] || p.method}{p.invoice ? ` · ${p.invoice.number}` : " · on account"}{p.reference && p.reference !== p.invoice?.number ? ` · ${p.reference}` : ""}</span></>;
}
case "notice": {
const ch = e.item;
return <>{ch.number}: {ch.fromPlan} → {ch.toPlan} <span className="text-slate-600">· from {day(ch.effectiveDate)}{ch.sentAt ? "" : " · not sent"}{ch.appliedAt ? " · in effect" : " · not yet in effect"}</span></>;
}
case "email": {
const m = e.item;
return <>{EMAIL_KIND[m.kind] || m.kind}: {m.subject} <span className="break-all text-xs text-slate-500">to {m.to}</span></>;
}
}
}
function EntryEnd({ e, pdf, resend }: { e: Entry; pdf: (p: string) => void; resend: (ch: LicenceChange) => void }) {
switch (e.kind) {
case "invoice": return <><span className="tabular-nums">{money(e.item.totalCents)}</span><StateBadge state={e.item.state} short /></>;
case "payment": return <><strong className="tabular-nums text-green-700">{money(e.item.amountCents)}</strong><button className="text-xs text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/payments/${e.item.id}/pdf`)}>Receipt</button></>;
case "notice": return <><button className="text-xs text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/licence-changes/${e.item.id}/pdf`)}>PDF</button><button className="text-xs text-indigo-700 hover:underline" onClick={() => resend(e.item)}>Send again</button></>;
case "email": return <span className={`text-xs ${e.item.error ? "text-red-700" : "text-green-700"}`}>{e.item.error ? `Failed: ${e.item.error}` : "Sent"}</span>;
}
}
// Hub 2.13.0: how the church's invoices and payments can be sorted.
const CUSTOMER_INVOICE_SORT = {
number: { get: i => i.number, first: "desc" },
date: { get: i => i.issueDate, first: "desc" },
plan: { get: i => i.plan || "One-off" },
total: { get: i => i.totalCents, first: "desc" },
balance: { get: i => (i.status === "sent" ? i.balanceCents : null), first: "desc" },
state: { get: i => i.state },
} satisfies Record<string, SortColumn<Invoice>>;
const CUSTOMER_PAYMENT_SORT = {
received: { get: p => p.paidOn },
amount: { get: p => p.amountCents },
receipt: { get: p => p.receiptNumber },
} satisfies Record<string, SortColumn<Payment>>;
export function InvoiceList({ invoices: all }: { invoices: Invoice[] }) {
const invoices = useSort(all, CUSTOMER_INVOICE_SORT, { key: "date", dir: "desc" }, "customer-invoices");
if (!all.length) return <p className="text-sm text-slate-500">No invoices yet.</p>;
return (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="text-left text-xs text-slate-500"><tr><SortTh sort={invoices.sort} k="number" className="py-2 pr-3">Invoice</SortTh><SortTh sort={invoices.sort} k="date" className="py-2 pr-3">Date</SortTh><SortTh sort={invoices.sort} k="plan" className="py-2 pr-3">Tier</SortTh><SortTh sort={invoices.sort} k="total" className="py-2 pr-3" right>Total</SortTh><SortTh sort={invoices.sort} k="balance" className="py-2 pr-3" right>Balance</SortTh><SortTh sort={invoices.sort} k="state" className="py-2">State</SortTh></tr></thead>
<tbody>{invoices.rows.map(i => (
<tr key={i.id} className="border-t border-slate-100">
<td className="py-2 pr-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link></td>
<td className="whitespace-nowrap py-2 pr-3">{day(i.issueDate)}</td>
<td className="py-2 pr-3">{i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""}</td>
<td className="py-2 pr-3 text-right tabular-nums">{money(i.totalCents)}</td>
<td className="py-2 pr-3 text-right tabular-nums">{i.status === "sent" ? money(i.balanceCents) : "—"}</td>
<td className="py-2"><StateBadge state={i.state} short /></td>
</tr>
))}</tbody>
</table>
</div>
);
}
export function PaymentList({ payments: all, pdf }: { payments: Payment[]; pdf: (p: string) => void }) {
const payments = useSort(all, CUSTOMER_PAYMENT_SORT, { key: "received", dir: "desc" }, "customer-payments");
if (!all.length) return <p className="text-sm text-slate-500">None yet.</p>;
return (
<div className="text-sm">
{all.length > 1 && <div className="mb-1 flex justify-end"><SortSelect sort={payments.sort} options={[["received", "desc", "Newest first"], ["received", "asc", "Oldest first"], ["amount", "desc", "Largest first"], ["amount", "asc", "Smallest first"], ["receipt", "desc", "Receipt number"]]} /></div>}
{payments.rows.map(p => (
<div key={p.id} className="flex justify-between gap-3 border-t border-slate-100 py-2 first:border-0">
<div>{p.receiptNumber} · {day(p.paidOn)}<div className="text-xs text-slate-500">{METHOD[p.method] || p.method}{p.invoice ? ` · ${p.invoice.number}` : " · on account"}{p.reference && p.reference !== p.invoice?.number ? ` · ${p.reference}` : ""}</div></div>
<div className="text-right"><strong className="tabular-nums">{money(p.amountCents)}</strong><div><button className="text-xs text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/payments/${p.id}/pdf`)}>Receipt</button></div></div>
</div>
))}
</div>
);
}
export function NoticeList({ changes, pdf, resend }: { changes: LicenceChange[]; pdf: (p: string) => void; resend: (ch: LicenceChange) => void }) {
if (!changes.length) return <p className="text-sm text-slate-500">None yet.</p>;
return (
<div className="text-sm">
{changes.map(ch => (
<div key={ch.id} className="flex justify-between gap-3 border-t border-slate-100 py-2 first:border-0">
<div>{ch.number}: {ch.fromPlan} → {ch.toPlan}<div className="text-xs text-slate-500">from {day(ch.effectiveDate)} · {ch.sentAt ? `sent ${fmtDate(ch.sentAt, false)}` : "not sent"}{ch.appliedAt ? " · in effect" : " · not yet in effect"}</div></div>
<div className="flex shrink-0 gap-3 text-xs">
<button className="text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/licence-changes/${ch.id}/pdf`)}>PDF</button>
<button className="text-indigo-700 hover:underline" onClick={() => resend(ch)}>Send again</button>
</div>
</div>
))}
</div>
);
}
export function EmailLog({ emails }: { emails: BillingEmail[] }) {
if (!emails.length) return <p className="text-sm text-slate-500">None yet.</p>;
return (
<div className="overflow-x-auto text-sm">
<table className="w-full">
<tbody>{emails.map(e => (
<tr key={e.id} className="border-t border-slate-100 first:border-0">
<td className="whitespace-nowrap py-1.5 pr-3 text-slate-500">{fmtDate(e.sentAt)}</td>
<td className="py-1.5 pr-3">{EMAIL_KIND[e.kind] || e.kind}</td>
<td className="py-1.5 pr-3">{e.subject}<div className="break-all text-xs text-slate-500">to {e.to}</div></td>
<td className={`py-1.5 ${e.error ? "text-red-700" : "text-green-700"}`}>{e.error ? `Failed: ${e.error}` : "Sent"}</td>
</tr>
))}</tbody>
</table>
{emails.length >= 50 && <p className="mt-2 text-xs text-slate-500">Showing the last 50.</p>}
</div>
);
}