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:
2026-11-03 13:42:45 +02:00
co-authored by Claude Opus 5.5
parent cc7d62690b
commit 6fce0fe90e
33 changed files with 3579 additions and 53 deletions
@@ -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&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.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} />;
}
+197
View File
@@ -0,0 +1,197 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { FileText, Play, Plus, Star } from "lucide-react";
import { api, errorText, openPdf } from "@/lib/api";
import { matches, usePaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager, SearchInput, Stat, Tabs } from "@/components/ui";
import { CYCLE, METHOD, StateBadge, day, money, type BillingCycle, type Invoice, type Payment } from "@/lib/billing";
import { RecordPayment } from "@/components/billing/RecordPayment";
type Msg = { type: "ok" | "err"; text: string } | null;
type Overview = { drafts: number; approved: number; owingCents: number; overdueCents: number; overdue: number; receivedThisMonthCents: number };
type Account = {
id: string; name: string; founding: boolean; foundingSince: string | null; foundingNote: string | null; billingEmail: string | null;
balanceCents: number; overdue: number;
licences: { id: string; key: string; plan: string; status: string; billingCycle: BillingCycle; nextInvoiceDate: string | null; reviewDate: string | null; customMonthlyCents: number | null; url: string | null }[];
};
type Tab = "invoices" | "payments" | "churches";
const TABS: { key: Tab; label: string }[] = [
{ key: "invoices", label: "Invoices" },
{ key: "payments", label: "Payments" },
{ key: "churches", label: "Churches and founding" },
];
const FILTERS = [
["", "All invoices"], ["draft", "Waiting for approval"], ["approved", "Approved, not sent yet"], ["unpaid", "Owing"],
["overdue", "Overdue"], ["paid", "Paid"], ["void", "Void"],
] as const;
/** Billing: invoices (drafted automatically, approved here), payments and receipts, churches and founding status. */
export default function BillingPage() {
const [tab, setTab] = useState<Tab>("invoices");
const [overview, setOverview] = useState<Overview | null>(null);
const [invoices, setInvoices] = useState<Invoice[] | null>(null);
const [payments, setPayments] = useState<Payment[] | null>(null);
const [accounts, setAccounts] = useState<Account[] | null>(null);
const [filter, setFilter] = useState("");
const [query, setQuery] = useState("");
const [msg, setMsg] = useState<Msg>(null);
const [running, setRunning] = useState(false);
const [paying, setPaying] = useState(false);
const loadOverview = useCallback(() => api<Overview>("/api/admin/billing/overview").then(setOverview).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
const loadInvoices = useCallback(() => api<Invoice[]>(`/api/admin/billing/invoices${filter ? `?status=${filter}` : ""}`).then(setInvoices).catch(e => setMsg({ type: "err", text: errorText(e) })), [filter]);
const loadPayments = useCallback(() => api<Payment[]>("/api/admin/billing/payments").then(setPayments).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
const loadAccounts = useCallback(() => api<Account[]>("/api/admin/billing/customers").then(setAccounts).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
useEffect(() => {
const fromHash = window.location.hash.slice(1);
if (TABS.some(t => t.key === fromHash)) setTab(fromHash as Tab);
const f = new URLSearchParams(window.location.search).get("status");
if (f && FILTERS.some(([k]) => k === f)) setFilter(f);
loadOverview();
}, [loadOverview]);
useEffect(() => { if (tab === "invoices") loadInvoices(); }, [tab, loadInvoices]);
useEffect(() => { if (tab === "payments" || paying) { loadPayments(); loadAccounts(); } }, [tab, paying, loadPayments, loadAccounts]);
useEffect(() => { if (tab === "churches") loadAccounts(); }, [tab, loadAccounts]);
const openTab = (t: Tab) => { setTab(t); setQuery(""); window.history.replaceState(null, "", `#${t}`); };
const run = async () => {
setRunning(true);
try {
const r = await api<{ drafted: number; sent: number; reminded: number; applied: number }>("/api/admin/billing/run", { method: "POST" });
setMsg({ type: "ok", text: `Billing run: ${r.drafted} drafted, ${r.sent} sent, ${r.applied} tier change${r.applied === 1 ? "" : "s"} applied.` });
loadOverview(); loadInvoices();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setRunning(false); }
};
const toggleFounding = async (a: Account) => {
try {
await api(`/api/admin/billing/customers/${a.id}`, { method: "PUT", body: { founding: !a.founding } });
setMsg({ type: "ok", text: a.founding ? `${a.name} is no longer a founding church. Drafts already made keep their price; recalculate them if needed.` : `${a.name} is now a founding church: 35% off from the next draft.` });
loadAccounts();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const shownInvoices = useMemo(() => (invoices || []).filter(i => matches(query, i.number, i.customer?.name, i.plan, i.recipientEmail)), [invoices, query]);
const shownPayments = useMemo(() => (payments || []).filter(p => matches(query, p.receiptNumber, p.customer?.name, p.reference, p.invoice?.number)), [payments, query]);
const shownAccounts = useMemo(() => (accounts || []).filter(a => matches(query, a.name, a.billingEmail, ...a.licences.map(l => l.plan))), [accounts, query]);
const invPaged = usePaged(shownInvoices, `${query}|${filter}`, 25);
const payPaged = usePaged(shownPayments, query, 25);
const founding = (accounts || []).filter(a => a.founding).length;
return (
<>
<PageTitle
title="Billing"
subtitle="Invoices are drafted 14 days before their date and emailed to you to approve; approved ones go out on their date."
actions={<>
<button className="btn-secondary" onClick={run} disabled={running}><Play className="h-4 w-4" /> {running ? "Running…" : "Run billing now"}</button>
<Link className="btn-secondary" href="/billing/invoices/new"><Plus className="h-4 w-4" /> One-off invoice</Link>
<button className="btn-primary" onClick={() => setPaying(true)}><Plus className="h-4 w-4" /> Record payment</button>
</>}
/>
<div className="mb-4"><Message msg={msg} /></div>
{overview && (
<div className="mb-6 grid grid-cols-2 gap-3 lg:grid-cols-5">
<button type="button" className="text-left" onClick={() => { setFilter("draft"); openTab("invoices"); }}><Stat label="Waiting for approval" value={overview.drafts} tone={overview.drafts ? "amber" : undefined} /></button>
<button type="button" className="text-left" onClick={() => { setFilter("approved"); openTab("invoices"); }}><Stat label="Approved, to go out" value={overview.approved} /></button>
<button type="button" className="text-left" onClick={() => { setFilter("unpaid"); openTab("invoices"); }}><Stat label="Owing" value={money(overview.owingCents)} /></button>
<button type="button" className="text-left" onClick={() => { setFilter("overdue"); openTab("invoices"); }}><Stat label={`Overdue (${overview.overdue})`} value={money(overview.overdueCents)} tone={overview.overdue ? "red" : undefined} /></button>
<Stat label="Received this month" value={money(overview.receivedThisMonthCents)} tone="green" />
</div>
)}
{paying && accounts && (
<div className="mb-6"><RecordPayment customers={accounts.map(a => ({ id: a.id, name: a.name }))} onClose={() => setPaying(false)} onSaved={(m) => { setMsg(m); setPaying(false); loadOverview(); loadPayments(); loadInvoices(); }} /></div>
)}
<Tabs tabs={TABS} active={tab} onChange={openTab} />
<div className="mt-4 mb-3 flex flex-wrap items-center gap-3">
<SearchInput value={query} onChange={setQuery} placeholder={tab === "payments" ? "Search receipts, churches, references" : tab === "churches" ? "Search churches" : "Search invoices, churches"} className="w-72 max-w-full" />
{tab === "invoices" && (
<select className="input w-auto" value={filter} onChange={e => { setFilter(e.target.value); window.history.replaceState(null, "", `${e.target.value ? `?status=${e.target.value}` : "?"}#invoices`); }} aria-label="Show">
{FILTERS.map(([k, label]) => <option key={k} value={k}>{label}</option>)}
</select>
)}
</div>
{tab === "invoices" && (!invoices ? <Loading /> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Invoice</th><th className="p-3">Church</th><th className="p-3">Date</th><th className="p-3 text-right">Total</th><th className="p-3 text-right">Balance</th><th className="p-3">State</th><th className="p-3" /></tr></thead>
<tbody>
{invPaged.rows.map(i => (
<tr key={i.id} className="border-t border-slate-100">
<td className="p-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link>{i.planChange && <div className="text-xs text-amber-700">{i.planChange.from} → {i.planChange.to}</div>}{i.warnings.length > 0 && i.status === "draft" && <div className="text-xs text-amber-700">Check {i.warnings.length === 1 ? "1 note" : `${i.warnings.length} notes`}</div>}</td>
<td className="p-3">{i.customer?.name}{i.customer?.founding && <Star className="ml-1 inline h-3.5 w-3.5 fill-amber-400 text-amber-400" aria-label="Founding church" />}<div className="text-xs text-slate-500">{i.plan || "One-off"}</div></td>
<td className="p-3 whitespace-nowrap">{day(i.issueDate)}<div className="text-xs text-slate-500">due {day(i.dueDate)}</div></td>
<td className="p-3 text-right tabular-nums">{money(i.totalCents)}</td>
<td className="p-3 text-right tabular-nums">{i.status === "sent" ? money(i.balanceCents) : "—"}</td>
<td className="p-3"><StateBadge state={i.state} short /></td>
<td className="p-3 text-right"><button className="text-slate-500 hover:text-indigo-700" title="Open the PDF" onClick={() => openPdf(`/api/admin/billing/invoices/${i.id}/pdf`).catch(e => setMsg({ type: "err", text: errorText(e) }))}><FileText className="h-4 w-4" /></button></td>
</tr>
))}
{shownInvoices.length === 0 && <tr><td colSpan={7} className="p-6 text-center text-slate-500">No invoices{filter || query ? " match" : " yet. Set up billing on a customer's licence and the drafts appear here 14 days before each invoice date"}.</td></tr>}
</tbody>
</table>
<div className="p-3"><Pager {...invPaged} /></div>
</div>
))}
{tab === "payments" && (!payments ? <Loading /> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Receipt</th><th className="p-3">Church</th><th className="p-3">Received</th><th className="p-3">For</th><th className="p-3 text-right">Amount</th><th className="p-3">Receipt sent</th><th className="p-3" /></tr></thead>
<tbody>
{payPaged.rows.map(p => (
<tr key={p.id} className="border-t border-slate-100">
<td className="p-3 font-medium">{p.receiptNumber}<div className="text-xs text-slate-500">{METHOD[p.method] || p.method}{p.reference ? ` · ${p.reference}` : ""}</div></td>
<td className="p-3"><Link className="hover:underline" href={`/customers/${p.customerId}#billing`}>{p.customer?.name}</Link></td>
<td className="p-3 whitespace-nowrap">{day(p.paidOn)}</td>
<td className="p-3">{p.invoice ? <Link className="text-indigo-700 hover:underline" href={`/billing/invoices/${p.invoice.id}`}>{p.invoice.number}</Link> : "On account"}</td>
<td className="p-3 text-right tabular-nums">{money(p.amountCents)}</td>
<td className="p-3 text-slate-600">{p.receiptSentAt ? day(p.receiptSentAt) : "Not sent"}</td>
<td className="p-3 text-right"><button className="text-slate-500 hover:text-indigo-700" title="Open the receipt" onClick={() => openPdf(`/api/admin/billing/payments/${p.id}/pdf`).catch(e => setMsg({ type: "err", text: errorText(e) }))}><FileText className="h-4 w-4" /></button></td>
</tr>
))}
{shownPayments.length === 0 && <tr><td colSpan={7} className="p-6 text-center text-slate-500">No payments{query ? " match" : " recorded yet"}.</td></tr>}
</tbody>
</table>
<div className="p-3"><Pager {...payPaged} /></div>
</div>
))}
{tab === "churches" && (!accounts ? <Loading /> : (
<>
<p className="mb-3 text-sm text-slate-600">{founding} founding church{founding === 1 ? "" : "es"}. Founding churches pay the founding price (35% less) on every tier for as long as they stay. Set billing up for each licence on the church&apos;s page.</p>
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Church</th><th className="p-3">Founding</th><th className="p-3">Tier and billing</th><th className="p-3">Next invoice</th><th className="p-3 text-right">Owing</th></tr></thead>
<tbody>
{shownAccounts.map(a => (
<tr key={a.id} className="border-t border-slate-100 align-top">
<td className="p-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/customers/${a.id}#billing`}>{a.name}</Link><div className="text-xs text-slate-500">{a.billingEmail || ""}</div></td>
<td className="p-3">
<label className="inline-flex items-center gap-2"><input type="checkbox" checked={a.founding} onChange={() => toggleFounding(a)} /> {a.founding ? "Founding" : "No"}</label>
{a.founding && <div className="text-xs text-slate-500">{a.foundingSince ? `since ${day(a.foundingSince)}` : ""}{a.foundingNote ? ` · ${a.foundingNote}` : ""}</div>}
</td>
<td className="p-3">{a.licences.length === 0 ? <span className="text-slate-400">No licence</span> : a.licences.map(l => (
<div key={l.id}>{l.plan}{l.customMonthlyCents != null ? ` (${money(l.customMonthlyCents)}/month)` : ""} · <span className={l.billingCycle === "none" ? "text-slate-400" : ""}>{CYCLE[l.billingCycle]}</span>{l.status !== "active" && <span className="text-red-600"> · {l.status}</span>}</div>
))}</td>
<td className="p-3">{a.licences.filter(l => l.billingCycle !== "none").map(l => <div key={l.id}>{day(l.nextInvoiceDate)}{l.reviewDate && <span className="text-xs text-slate-500"> · review {day(l.reviewDate)}</span>}</div>)}</td>
<td className={`p-3 text-right tabular-nums ${a.overdue ? "text-red-700" : ""}`}>{a.balanceCents ? money(a.balanceCents) : "—"}{a.overdue > 0 && <div className="text-xs">{a.overdue} overdue</div>}</td>
</tr>
))}
{shownAccounts.length === 0 && <tr><td colSpan={5} className="p-6 text-center text-slate-500">No churches{query ? " match" : " yet"}.</td></tr>}
</tbody>
</table>
</div>
</>
))}
</>
);
}
@@ -9,6 +9,7 @@ import { ago, fmtDate } from "@/lib/format";
import { PLANS } from "@/lib/tiers";
import type { Customer, Licence, LicenceStatus } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
import { CustomerBilling } from "@/components/billing/CustomerBilling";
type Msg = { type: "ok" | "err"; text: string } | null;
const dateInput = (d: string | null) => (d ? d.slice(0, 10) : "");
@@ -77,7 +78,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
{!PLANS.includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
{PLANS.map(p => <option key={p} value={p}>{p}</option>)}
</select>
<p className="mt-1 text-xs text-slate-500">Shown on the church&apos;s Licence page. Founding discount: note it below.</p>
<p className="mt-1 text-xs text-slate-500">Shown on the church&apos;s Licence page. Billing and founding status are under Billing below.</p>
</div>
<div>
<label className="label">Status</label>
@@ -109,7 +110,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
</div>
<div>
<label className="label">Notes</label>
<input className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="e.g. founding church, paid annually, invoice #123" />
<input className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Anything worth remembering about this licence" />
</div>
<div className="flex flex-wrap gap-2">
<button className="btn-primary" onClick={save} disabled={busy}>{busy ? "Saving…" : "Save licence"}</button>
@@ -183,6 +184,8 @@ export default function CustomerPage() {
</form>
</div>
</div>
<CustomerBilling key={c.licences.map(l => `${l.id}-${l.status}`).join()} customerId={id} />
</>
);
}
+2 -1
View File
@@ -3,7 +3,7 @@
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone } from "lucide-react";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone, Receipt } from "lucide-react";
import { api, getToken, setToken } from "@/lib/api";
import { Logo } from "@/components/ui";
@@ -12,6 +12,7 @@ type Me = { id: string; name: string; email: string };
const NAV = [
{ href: "/", label: "Installs", icon: LayoutDashboard },
{ href: "/customers", label: "Customers", icon: Building2 },
{ href: "/billing", label: "Billing", icon: Receipt },
{ href: "/alerts", label: "Alerts", icon: BellRing },
{ href: "/releases", label: "Releases", icon: Rocket },
{ href: "/notices", label: "Notices", icon: Megaphone },
+4 -1
View File
@@ -7,6 +7,7 @@ import { fmtDate, rand, randFine } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import type { AiInstallUse } from "@/lib/types";
import { Loading, Message, PageTitle, Pager, SearchInput, Tabs } from "@/components/ui";
import { BillingSettings } from "@/components/billing/BillingSettings";
type Settings = Record<string, string>;
type AuditRow = { id: string; action: string; target: string | null; metadata: unknown; createdAt: string; actor: { name: string } | null };
@@ -21,10 +22,11 @@ const FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "licence_expiry_warning_days", label: "Warn about licence expiry (days before)", hint: "Default 14.", type: "number" },
];
type Tab = "alerts" | "email" | "ai" | "security" | "audit";
type Tab = "alerts" | "email" | "billing" | "ai" | "security" | "audit";
const TABS: { key: Tab; label: string }[] = [
{ key: "alerts", label: "Alerts" },
{ key: "email", label: "Email" },
{ key: "billing", label: "Billing" },
{ key: "ai", label: "AI" },
{ key: "security", label: "Login and security" },
{ key: "audit", label: "Audit log" },
@@ -301,6 +303,7 @@ export default function SettingsPage() {
</form>
)}
{tab === "billing" && <BillingSettings settings={settings} onSaved={setSettings} setMsg={setMsg} />}
{tab === "ai" && <AiTab settings={settings} models={aiModels} onSaved={setSettings} setMsg={setMsg} />}
{tab === "security" && (