Billing: invoices, approval, receipts, statements, licence changes (1.7.0)
- Invoices drafted 14 days before each licence's invoice date and emailed to the alert email for approval; approved ones go out on their date from 08:00 SA time. Drafts can be edited, recalculated, sent early, put back to draft or voided; one-off invoices too. - Annual tier review from the 12-month event-income band; approving a tier change emails a notice of licence change, applied when the invoice goes out. Notices can also be sent by hand. - Founding churches (35% off as its own line), payments with receipts, statements for any dates. - Every billing email is styled HTML with a PDF (invoice / tax invoice, receipt, statement, licence change) and logged per customer. - Settings -> Billing: business and bank details, VAT (off: plain invoices; on: VAT-inclusive tax invoices), timing and numbering. - Migration 20261103111645_invoicing; pdfkit 0.17.2; tests/billing.test.js; scripts/sample-billing-pdfs.js. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,264 @@
|
||||
"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";
|
||||
|
||||
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)}`;
|
||||
if (!confirm(`Approve ${inv.number}? It goes to ${inv.recipientEmail} ${when}.${inv.planChange ? `\n\nThe church is also sent a notice of licence change (${inv.planChange.from} → ${inv.planChange.to}) 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} 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 () => {
|
||||
if (!confirm("Remove the tier change from this invoice? The tier stays as it is; then press Recalculate to price it at that tier.")) return;
|
||||
setBusy("drop");
|
||||
try {
|
||||
await api(`/api/admin/billing/invoices/${id}`, { method: "PUT", body: { dropPlanChange: true } });
|
||||
setMsg({ type: "ok", text: "Tier change removed. Press Recalculate to price it at the current tier." });
|
||||
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.licenceId && inv.periodStart && <button className="btn-secondary" onClick={() => act("recalc", "recalculate", {}, () => "Recalculated from the licence 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'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.planChange && (
|
||||
<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><strong>Annual review: {inv.planChange.from} → {inv.planChange.to}</strong>{inv.planChange.band ? ` (12-month event income ${inv.planChange.band})` : ""}. {inv.status === "draft" ? "Approving sends the church a notice of licence change straight away; the tier changes when this invoice goes out." : inv.status === "approved" ? "The notice was sent; the tier changes when this invoice goes out." : ""}</div>
|
||||
{inv.status === "draft" && <button className="btn-secondary" onClick={dropChange} disabled={!!busy}>Keep the tier</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} />;
|
||||
}
|
||||
Reference in New Issue
Block a user