"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("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 = { 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 (

History

{VIEWS.map(([k, label]) => ( ))}
{view === "all" && } {view === "invoices" && } {view === "payments" && } {view === "notices" && } {view === "emails" && }
); } 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 = { invoice: "Invoice", payment: "Payment", notice: "Notice", email: "Email" }; const KIND_TONE: Record = { 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(() => [ ...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

Nothing yet.

; return ( <>
    {entries.map(e => (
  1. {day(e.at.slice(0, 10))} {KIND_LABEL[e.kind]}
  2. ))}
{b.emails.length >= 50 &&

Showing the last 50 billing emails.

} ); } function EntryText({ e }: { e: Entry }) { switch (e.kind) { case "invoice": { const i = e.item; return <>{i.number} {i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""}; } case "payment": { const p = e.item; return <>{p.receiptNumber} · {METHOD[p.method] || p.method}{p.invoice ? ` · ${p.invoice.number}` : " · on account"}{p.reference && p.reference !== p.invoice?.number ? ` · ${p.reference}` : ""}; } case "notice": { const ch = e.item; return <>{ch.number}: {ch.fromPlan} → {ch.toPlan} · from {day(ch.effectiveDate)}{ch.sentAt ? "" : " · not sent"}{ch.appliedAt ? " · in effect" : " · not yet in effect"}; } case "email": { const m = e.item; return <>{EMAIL_KIND[m.kind] || m.kind}: {m.subject} to {m.to}; } } } function EntryEnd({ e, pdf, resend }: { e: Entry; pdf: (p: string) => void; resend: (ch: LicenceChange) => void }) { switch (e.kind) { case "invoice": return <>{money(e.item.totalCents)}; case "payment": return <>{money(e.item.amountCents)}; case "notice": return <>; case "email": return {e.item.error ? `Failed: ${e.item.error}` : "Sent"}; } } // 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>; const CUSTOMER_PAYMENT_SORT = { received: { get: p => p.paidOn }, amount: { get: p => p.amountCents }, receipt: { get: p => p.receiptNumber }, } satisfies Record>; export function InvoiceList({ invoices: all }: { invoices: Invoice[] }) { const invoices = useSort(all, CUSTOMER_INVOICE_SORT, { key: "date", dir: "desc" }, "customer-invoices"); if (!all.length) return

No invoices yet.

; return (
InvoiceDateTierTotalBalanceState{invoices.rows.map(i => ( ))}
{i.number} {day(i.issueDate)} {i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""} {money(i.totalCents)} {i.status === "sent" ? money(i.balanceCents) : "—"}
); } 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

None yet.

; return (
{all.length > 1 &&
} {payments.rows.map(p => (
{p.receiptNumber} · {day(p.paidOn)}
{METHOD[p.method] || p.method}{p.invoice ? ` · ${p.invoice.number}` : " · on account"}{p.reference && p.reference !== p.invoice?.number ? ` · ${p.reference}` : ""}
{money(p.amountCents)}
))}
); } export function NoticeList({ changes, pdf, resend }: { changes: LicenceChange[]; pdf: (p: string) => void; resend: (ch: LicenceChange) => void }) { if (!changes.length) return

None yet.

; return (
{changes.map(ch => (
{ch.number}: {ch.fromPlan} → {ch.toPlan}
from {day(ch.effectiveDate)} · {ch.sentAt ? `sent ${fmtDate(ch.sentAt, false)}` : "not sent"}{ch.appliedAt ? " · in effect" : " · not yet in effect"}
))}
); } export function EmailLog({ emails }: { emails: BillingEmail[] }) { if (!emails.length) return

None yet.

; return (
{emails.map(e => ( ))}
{fmtDate(e.sentAt)} {EMAIL_KIND[e.kind] || e.kind} {e.subject}
to {e.to}
{e.error ? `Failed: ${e.error}` : "Sent"}
{emails.length >= 50 &&

Showing the last 50.

}
); }