Files
events-hub/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx
T
joshuaandClaude Opus 5.5 7478e84e9d Hub 2.0 step 4: billing per customer
- One invoice per customer per period for all its products; the schedule
  moves from Licence to Customer (migration copies it, so billing carries
  on unchanged); licences get billedFrom / billedUntil
- Website (R99, 5 GB) and App (on active members) prices next to the
  Events tiers; founding prices per product, then bundles (15% two, 25%
  three); extra website storage R20 per 5 GB, never discounted
- A product added to a billed customer starts after its free month; days
  before its first full period are prorated, never charged twice
- Annual review per product (Events income, App members), one notice of
  licence change per product; invoices, PDFs and emails name products
- Customer page: schedule, per-product billing, next-invoice preview
- Invoices from before 2.0 kept as they were (still recalculable)

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

276 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { AlertTriangle, ArrowLeft, Check, FileText, RefreshCw, Send, Star, Undo2, XCircle } from "lucide-react";
import { api, errorText, openPdf } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { EMAIL_KIND, METHOD, StateBadge, day, money, todayYmd, type BillingEmail, type Invoice, type LicenceChange } from "@/lib/billing";
import { LinesEditor, editTotal, fromEdit, toEdit, type EditLine } from "@/components/billing/LinesEditor";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { PRODUCT_NAMES } from "@/lib/products";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = Invoice & { licenceChanges: LicenceChange[]; emails: BillingEmail[] };
/** A one-off invoice (standby support, set-up…), made as a draft. */
function NewInvoice() {
const router = useRouter();
const [customers, setCustomers] = useState<{ id: string; name: string }[]>([]);
const [form, setForm] = useState({ customerId: "", issueDate: todayYmd(), notes: "" });
const [lines, setLines] = useState<EditLine[]>([{ description: "", quantity: "1", unit: "" }]);
const [msg, setMsg] = useState<Msg>(null);
useEffect(() => {
api<{ id: string; name: string }[]>("/api/admin/billing/customers").then(setCustomers).catch(e => setMsg({ type: "err", text: errorText(e) }));
const c = new URLSearchParams(window.location.search).get("customer");
if (c) setForm(f => ({ ...f, customerId: c }));
}, []);
const save = async (e: React.FormEvent) => {
e.preventDefault();
try {
const inv = await api<Invoice>("/api/admin/billing/invoices", { method: "POST", body: { ...form, lines: fromEdit(lines) } });
router.replace(`/billing/invoices/${inv.id}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<Link href="/billing" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Billing</Link>
<PageTitle title="One-off invoice" subtitle="For anything outside the licence, like standby support for a big event. It's made as a draft for you to approve." />
<div className="mb-4"><Message msg={msg} /></div>
<form onSubmit={save} className="card max-w-3xl space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="new-customer">Church</label>
<select id="new-customer" className="input" value={form.customerId} onChange={e => setForm({ ...form, customerId: e.target.value })} required>
<option value="">Choose…</option>
{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div><label className="label" htmlFor="new-date">Invoice date (it goes out on this day once approved)</label><input id="new-date" type="date" className="input" value={form.issueDate} onChange={e => setForm({ ...form, issueDate: e.target.value })} required /></div>
</div>
<LinesEditor lines={lines} onChange={setLines} />
<div><label className="label" htmlFor="new-notes">Notes (printed on the invoice)</label><textarea id="new-notes" className="input" rows={2} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} /></div>
<button className="btn-primary" disabled={editTotal(lines) === 0 && !fromEdit(lines).length}>Create draft</button>
</form>
</>
);
}
function InvoiceDetail({ id }: { id: string }) {
const [inv, setInv] = useState<Detail | null>(null);
const [form, setForm] = useState({ issueDate: "", dueDate: "", recipientEmail: "", notes: "" });
const [lines, setLines] = useState<EditLine[]>([]);
const [dirty, setDirty] = useState(false);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState<string | null>(null);
const [paying, setPaying] = useState(false);
const load = useCallback(() => api<Detail>(`/api/admin/billing/invoices/${id}`).then(x => {
setInv(x);
setForm({ issueDate: x.issueDate, dueDate: x.dueDate, recipientEmail: x.recipientEmail || "", notes: x.notes || "" });
setLines(toEdit(x.lines));
setDirty(false);
}).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => { load(); }, [load]);
if (!inv) return msg ? <Message msg={msg} /> : <Loading />;
const editable = inv.status === "draft" || inv.status === "approved";
const act = async (name: string, path: string, body?: unknown, ok?: (r: { invoice?: Invoice; notice?: { change: LicenceChange; email: { ok: boolean; error: string | null } | null } | null; message?: string }) => string) => {
setBusy(name);
setMsg(null);
try {
const r = await api<{ invoice?: Invoice; notice?: { change: LicenceChange; email: { ok: boolean; error: string | null } | null } | null; message?: string }>(`/api/admin/billing/invoices/${id}/${path}`, { method: "POST", body: body ?? {} });
setMsg({ type: "ok", text: ok ? ok(r) : r.message || "Done." });
await load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(null); }
};
const save = async () => {
setBusy("save");
try {
await api(`/api/admin/billing/invoices/${id}`, { method: "PUT", body: { ...form, lines: fromEdit(lines) } });
setMsg({ type: "ok", text: inv.status === "approved" ? "Saved. It's still approved and goes out on its date." : "Saved." });
await load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(null); }
};
const approve = () => {
if (dirty) { setMsg({ type: "err", text: "Save your changes first." }); return; }
const when = inv.issueDate <= todayYmd() ? "within the next 15 minutes (its date has come)" : `on ${day(inv.issueDate)}`;
const changes = inv.planChanges.map(pc => `${PRODUCT_NAMES[pc.product || "events"]}: ${pc.from} → ${pc.to}`).join(", ");
if (!confirm(`Approve ${inv.number}? It goes to ${inv.recipientEmail} ${when}.${changes ? `\n\nThe church is also sent a notice of licence change for each tier change (${changes}) now.` : ""}`)) return;
act("approve", "approve", {}, r => `Approved. It goes out ${when}.${r.notice ? (r.notice.email?.ok ? ` The notice of licence change ${r.notice.change.number}${inv.planChanges.length > 1 ? " (and the others)" : ""} was emailed.` : ` The notice ${r.notice.change.number} couldn't be emailed: ${r.notice.email?.error}`) : ""}`);
};
const voidIt = () => {
const reason = prompt(`Void ${inv.number}? It stays on record, marked void. Why (printed on it)?`, "");
if (reason === null) return;
act("void", "void", { reason }, () => `${inv.number} is void.`);
};
const dropChange = async () => {
const many = inv.planChanges.length > 1;
if (!confirm(`Remove the tier change${many ? "s" : ""} from this invoice? The tier${many ? "s stay" : " stays"} as ${many ? "they are" : "it is"}${inv.licenceId ? "; then press Recalculate to price it at that tier" : ", and the draft is priced at them again"}.`)) return;
setBusy("drop");
try {
await api(`/api/admin/billing/invoices/${id}`, { method: "PUT", body: { dropPlanChange: true } });
setMsg({ type: "ok", text: inv.licenceId ? "Tier change removed. Press Recalculate to price it at the current tier." : `Tier change${many ? "s" : ""} removed, and the draft repriced.` });
await load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(null); }
};
const pdf = (path: string) => openPdf(path).catch(e => setMsg({ type: "err", text: errorText(e) }));
const paymentAction = async (pid: string, what: "resend" | "delete") => {
if (what === "delete" && !confirm("Remove this payment? Its receipt number won't be used again.")) return;
try {
const r = await api<{ message: string }>(`/api/admin/billing/payments/${pid}${what === "resend" ? "/resend" : ""}`, { method: what === "resend" ? "POST" : "DELETE" });
setMsg({ type: "ok", text: r.message });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<>
<Link href="/billing" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Billing</Link>
<PageTitle
title={`Invoice ${inv.number}`}
subtitle={<><Link className="text-indigo-600 hover:underline" href={`/customers/${inv.customerId}#billing`}>{inv.customer?.name}</Link>{inv.customer?.founding && <span className="ml-2 inline-flex items-center gap-1 text-amber-700"><Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" /> founding church</span>}</>}
actions={<StateBadge state={inv.state} />}
/>
<div className="mb-4"><Message msg={msg} /></div>
<div className="mb-4 flex flex-wrap gap-2">
{inv.status === "draft" && <button className="btn-primary" onClick={approve} disabled={!!busy}><Check className="h-4 w-4" /> {busy === "approve" ? "Approving…" : "Approve"}</button>}
{inv.status === "draft" && inv.periodStart && inv.cycle !== "none" && <button className="btn-secondary" onClick={() => act("recalc", "recalculate", {}, () => "Recalculated from the church's products, prices and founding status as they are now.")} disabled={!!busy}><RefreshCw className="h-4 w-4" /> Recalculate</button>}
{inv.status === "approved" && <button className="btn-primary" onClick={() => confirm(`Send ${inv.number} to ${inv.recipientEmail} now?`) && act("send", "send", {}, () => `Sent to ${inv.recipientEmail}.`)} disabled={!!busy}><Send className="h-4 w-4" /> {busy === "send" ? "Sending…" : "Send now"}</button>}
{inv.status === "approved" && <button className="btn-secondary" onClick={() => act("unapprove", "unapprove", {}, () => "Back to draft: it won't go out until you approve it again.")} disabled={!!busy}><Undo2 className="h-4 w-4" /> Back to draft</button>}
{inv.status === "sent" && inv.balanceCents > 0 && <button className="btn-primary" onClick={() => setPaying(true)}>Record payment</button>}
{inv.status === "sent" && <button className="btn-secondary" onClick={() => act("resend", "resend")} disabled={!!busy}><Send className="h-4 w-4" /> Send again</button>}
<button className="btn-secondary" onClick={() => pdf(`/api/admin/billing/invoices/${id}/pdf`)}><FileText className="h-4 w-4" /> {editable ? "Preview PDF" : "PDF"}</button>
{inv.status !== "void" && inv.payments.length === 0 && <button className="btn-danger" onClick={voidIt} disabled={!!busy}><XCircle className="h-4 w-4" /> Void</button>}
</div>
{inv.sendError && <div className="mb-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">The last attempt to send it failed: {inv.sendError}. It&apos;s tried again every 15 minutes.</div>}
{inv.warnings.length > 0 && editable && (
<div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
<div className="mb-1 flex items-center gap-1.5 font-medium"><AlertTriangle className="h-4 w-4" /> Check before approving</div>
<ul className="list-disc space-y-0.5 pl-5">{inv.warnings.map(w => <li key={w}>{w}</li>)}</ul>
</div>
)}
{inv.planChanges.length > 0 && (
<div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-sky-200 bg-sky-50 p-3 text-sm text-sky-900">
<div>
{inv.planChanges.map(pc => (
<div key={`${pc.product}-${pc.to}`}>
<strong>Annual review, {PRODUCT_NAMES[pc.product || "events"]}: {pc.from} → {pc.to}</strong>
{pc.band ? ` (${pc.product === "app" ? "active members" : "12-month event income"} ${pc.band})` : ""}
</div>
))}
<div className="mt-1">{inv.status === "draft" ? `Approving sends the church a notice of licence change for each straight away; the tier${inv.planChanges.length > 1 ? "s change" : " changes"} when this invoice goes out.` : inv.status === "approved" ? "The notices were sent; the tiers change when this invoice goes out." : ""}</div>
</div>
{inv.status === "draft" && <button className="btn-secondary" onClick={dropChange} disabled={!!busy}>Keep the tier{inv.planChanges.length > 1 ? "s" : ""}</button>}
</div>
)}
{paying && <div className="mb-4"><RecordPayment invoice={inv} onClose={() => setPaying(false)} onSaved={m => { setMsg(m); setPaying(false); load(); }} /></div>}
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
<div className="card space-y-4">
{editable ? (
<>
<div className="grid gap-3 sm:grid-cols-3">
<div><label className="label" htmlFor="inv-date">Date (goes out)</label><input id="inv-date" type="date" className="input" value={form.issueDate} onChange={e => { setForm({ ...form, issueDate: e.target.value }); setDirty(true); }} /></div>
<div><label className="label" htmlFor="inv-due">Due</label><input id="inv-due" type="date" className="input" value={form.dueDate} onChange={e => { setForm({ ...form, dueDate: e.target.value }); setDirty(true); }} /></div>
<div><label className="label" htmlFor="inv-to">Send to</label><input id="inv-to" type="email" className="input" value={form.recipientEmail} onChange={e => { setForm({ ...form, recipientEmail: e.target.value }); setDirty(true); }} /></div>
</div>
<LinesEditor lines={lines} onChange={l => { setLines(l); setDirty(true); }} />
<div><label className="label" htmlFor="inv-notes">Notes (printed on the invoice)</label><textarea id="inv-notes" className="input" rows={2} value={form.notes} onChange={e => { setForm({ ...form, notes: e.target.value }); setDirty(true); }} /></div>
<button className="btn-primary" onClick={save} disabled={!dirty || !!busy}>{busy === "save" ? "Saving…" : "Save changes"}</button>
</>
) : (
<>
<table className="w-full text-sm">
<thead className="text-left text-xs text-slate-500"><tr><th className="pb-2">Description</th><th className="pb-2 text-right">Qty</th><th className="pb-2 text-right">Unit</th><th className="pb-2 text-right">Amount</th></tr></thead>
<tbody>{inv.lines.map((l, i) => <tr key={i} className="border-t border-slate-100"><td className="py-2">{l.description}</td><td className="py-2 text-right">{l.quantity}</td><td className="py-2 text-right tabular-nums">{money(l.unitCents)}</td><td className="py-2 text-right tabular-nums">{money(l.amountCents)}</td></tr>)}</tbody>
</table>
<div className="ml-auto max-w-xs space-y-1 text-sm">
{inv.vatCents > 0 && <div className="flex justify-between text-slate-500"><span>Includes VAT</span><span className="tabular-nums">{money(inv.vatCents)}</span></div>}
<div className="flex justify-between font-semibold"><span>Total</span><span className="tabular-nums">{money(inv.totalCents)}</span></div>
{inv.status === "sent" && <><div className="flex justify-between text-green-700"><span>Paid</span><span className="tabular-nums">{money(inv.paidCents)}</span></div><div className="flex justify-between font-semibold"><span>Balance</span><span className="tabular-nums">{money(inv.balanceCents)}</span></div></>}
</div>
{inv.notes && <p className="text-sm text-slate-600">Notes: {inv.notes}</p>}
{inv.voidReason && <p className="text-sm text-slate-600">Void: {inv.voidReason}</p>}
</>
)}
</div>
<div className="space-y-4">
<div className="card space-y-1.5 text-sm">
<h2 className="mb-1 font-semibold">About it</h2>
<Row k="Date" v={day(inv.issueDate)} />
<Row k="Due" v={day(inv.dueDate)} />
{inv.periodStart && <Row k="Period" v={`${day(inv.periodStart)} – ${day(inv.periodEnd)}`} />}
<Row k="Tier" v={inv.plan || "One-off"} />
{inv.reviewed && <Row k="12-month income" v={inv.incomeBand || "not reported"} />}
<Row k="Sends to" v={inv.recipientEmail || "—"} />
{inv.licence?.installUrl && <Row k="Site" v={inv.licence.installUrl.replace(/^https?:\/\//, "")} />}
{inv.approvalEmailedAt && <Row k="Approval emailed" v={fmtDate(inv.approvalEmailedAt)} />}
{inv.approvedAt && <Row k="Approved" v={fmtDate(inv.approvedAt)} />}
{inv.sentAt && <Row k="Sent" v={fmtDate(inv.sentAt)} />}
</div>
{inv.payments.length > 0 && (
<div className="card text-sm">
<h2 className="mb-2 font-semibold">Payments</h2>
{inv.payments.map(p => (
<div key={p.id} className="border-t border-slate-100 py-2 first:border-0">
<div className="flex justify-between"><span>{p.receiptNumber} · {day(p.paidOn)}</span><strong className="tabular-nums">{money(p.amountCents)}</strong></div>
<div className="text-xs text-slate-500">{METHOD[p.method] || p.method}{p.reference && p.reference !== inv.number ? ` · ${p.reference}` : ""}{p.receiptSentAt ? " · receipt sent" : ""}</div>
<div className="mt-1 flex gap-3 text-xs">
<button className="text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/payments/${p.id}/pdf`)}>Receipt</button>
<button className="text-indigo-700 hover:underline" onClick={() => paymentAction(p.id, "resend")}>Email receipt</button>
<button className="text-red-700 hover:underline" onClick={() => paymentAction(p.id, "delete")}>Remove</button>
</div>
</div>
))}
</div>
)}
{inv.licenceChanges.length > 0 && (
<div className="card text-sm">
<h2 className="mb-2 font-semibold">Notice of licence change</h2>
{inv.licenceChanges.map(c => (
<div key={c.id}>
{c.number}: {c.fromPlan} → {c.toPlan} from {day(c.effectiveDate)}
<div className="text-xs text-slate-500">{c.sentAt ? `Sent ${fmtDate(c.sentAt)}` : "Not sent"}{c.appliedAt ? " · in effect" : ""}</div>
<button className="text-xs text-indigo-700 hover:underline" onClick={() => pdf(`/api/admin/billing/licence-changes/${c.id}/pdf`)}>Open the notice</button>
</div>
))}
</div>
)}
<div className="card text-sm">
<h2 className="mb-2 font-semibold">Emails</h2>
{inv.emails.length === 0 ? <p className="text-slate-500">None yet.</p> : inv.emails.map(e => (
<div key={e.id} className="border-t border-slate-100 py-1.5 first:border-0">
<div>{EMAIL_KIND[e.kind] || e.kind} → {e.to}</div>
<div className={`text-xs ${e.error ? "text-red-700" : "text-slate-500"}`}>{fmtDate(e.sentAt)}{e.error ? ` · failed: ${e.error}` : ""}</div>
</div>
))}
</div>
</div>
</div>
</>
);
}
const Row = ({ k, v }: { k: string; v: React.ReactNode }) => <div className="flex justify-between gap-3"><span className="text-slate-500">{k}</span><span className="text-right">{v}</span></div>;
export default function InvoicePage() {
const { id } = useParams<{ id: string }>();
return id === "new" ? <NewInvoice /> : <InvoiceDetail id={id} />;
}