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,108 @@
"use client";
import React, { useState } from "react";
import { api, errorText } from "@/lib/api";
type Settings = Record<string, string>;
type Msg = { type: "ok" | "err"; text: string } | null;
type Field = { key: string; label: string; hint?: string; type?: string; wide?: boolean };
const GROUPS: { title: string; intro?: string; fields: Field[] }[] = [
{
title: "Your business (printed on every document)",
fields: [
{ key: "business_name", label: "Business name" },
{ key: "business_owner", label: "Owner" },
{ key: "business_registration", label: "Registration (optional)", hint: "e.g. a CIPC number, if you have one." },
{ key: "business_address", label: "Address", wide: true },
{ key: "business_email", label: "Email", type: "email" },
{ key: "business_phone", label: "Phone" },
{ key: "business_website", label: "Website" },
{ key: "billing_reply_to", label: "Replies go to", type: "email", hint: "Blank: the business email." },
],
},
{
title: "Banking details (how churches pay)",
intro: "Shown under \"How to pay\" on invoices and statements. Until they're filled in, documents ask the church to contact you for them.",
fields: [
{ key: "bank_account_name", label: "Account name" },
{ key: "bank_name", label: "Bank" },
{ key: "bank_account_number", label: "Account number" },
{ key: "bank_branch_code", label: "Branch code" },
{ key: "bank_account_type", label: "Account type", hint: "e.g. Cheque, Business current" },
],
},
{
title: "Timing and numbering",
fields: [
{ key: "billing_draft_days", label: "Draft invoices this many days before", type: "number", hint: "Default 14. The draft is emailed to the alert email for approval." },
{ key: "billing_send_hour", label: "Send approved invoices from (hour, SA time)", type: "number", hint: "Default 8 (08:00) on the invoice date." },
{ key: "payment_terms_days", label: "Payment due after (days)", type: "number", hint: "Default 7." },
{ key: "invoice_prefix", label: "Invoice numbers start with", hint: "INV → INV-2026-0001" },
{ key: "receipt_prefix", label: "Receipt numbers start with", hint: "REC → REC-2026-0001" },
{ key: "change_prefix", label: "Licence change notices start with", hint: "LC → LC-2026-0001" },
{ key: "invoice_footer", label: "Line at the bottom of invoices", wide: true },
],
},
];
const KEYS = ["billing_enabled", "vat_registered", "vat_number", "vat_rate", ...GROUPS.flatMap(g => g.fields.map(f => f.key))];
/** Settings → Billing. */
export function BillingSettings({ settings, onSaved, setMsg }: { settings: Settings; onSaved: (s: Settings) => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState<Settings>(() => Object.fromEntries(KEYS.map(k => [k, settings[k] ?? ""])));
const set = (k: string, v: string) => setForm(f => ({ ...f, [k]: v }));
const vat = form.vat_registered === "true";
const save = async (e: React.FormEvent) => {
e.preventDefault();
if (vat && !form.vat_number.trim()) { setMsg({ type: "err", text: "Enter your VAT number before switching VAT on." }); return; }
try {
const r = await api<{ settings: Settings }>("/api/admin/settings", { method: "PUT", body: { settings: form } });
onSaved(r.settings);
setMsg({ type: "ok", text: "Billing settings saved." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<form onSubmit={save} className="space-y-6">
<div className="card space-y-3">
<label className="flex items-center gap-2 font-medium"><input type="checkbox" checked={form.billing_enabled === "true"} onChange={e => set("billing_enabled", e.target.checked ? "true" : "")} /> Automatic billing on</label>
<p className="text-sm text-slate-600">When it&apos;s on, invoices are drafted for billed licences, emailed to you for approval, and approved ones go out on their date. Off: nothing is drafted or sent automatically (you can still do it all by hand).</p>
</div>
<div className="card space-y-3">
<h2 className="font-semibold">VAT</h2>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={vat} onChange={e => set("vat_registered", e.target.checked ? "true" : "")} /> I&apos;m registered for VAT</label>
<p className="text-sm text-slate-600">
{vat
? "Prices are VAT-inclusive: totals stay the same, documents become tax invoices with your VAT number and show the VAT included. Only invoices made from now on change."
: "Not registered: documents are plain invoices with no VAT on them, as the law requires. When you register, tick this: your prices then include VAT, so churches pay the same."}
</p>
{vat && (
<div className="grid gap-3 sm:grid-cols-2">
<div><label className="label" htmlFor="vat_number">VAT number</label><input id="vat_number" className="input" value={form.vat_number} onChange={e => set("vat_number", e.target.value)} /></div>
<div><label className="label" htmlFor="vat_rate">VAT rate (%)</label><input id="vat_rate" type="number" className="input" value={form.vat_rate} onChange={e => set("vat_rate", e.target.value)} /></div>
</div>
)}
</div>
{GROUPS.map(g => (
<div key={g.title} className="card space-y-3">
<h2 className="font-semibold">{g.title}</h2>
{g.intro && <p className="text-sm text-slate-600">{g.intro}</p>}
<div className="grid gap-3 sm:grid-cols-2">
{g.fields.map(f => (
<div key={f.key} className={f.wide ? "sm:col-span-2" : ""}>
<label className="label" htmlFor={f.key}>{f.label}</label>
<input id={f.key} className="input" type={f.type || "text"} value={form[f.key] ?? ""} onChange={e => set(f.key, e.target.value)} />
{f.hint && <p className="mt-1 text-xs text-slate-500">{f.hint}</p>}
</div>
))}
</div>
</div>
))}
<button className="btn-primary">Save billing settings</button>
</form>
);
}
@@ -0,0 +1,253 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { FileText, Mail, Plus, Star } from "lucide-react";
import { api, errorText, openPdf } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { CYCLE, EMAIL_KIND, METHOD, StateBadge, centsFrom, day, money, randInput, todayYmd, type BillingCycle, type BillingEmail, type BillingTier, type Invoice, type LicenceChange, type Payment } from "@/lib/billing";
import { RecordPayment } from "./RecordPayment";
type Msg = { type: "ok" | "err"; text: string } | null;
type BillingLicence = { id: string; key: string; plan: string; status: string; billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null; customMonthlyCents: number | null; url: string | null; incomeBand: string | null };
type CustomerBillingData = {
id: string; name: string; billingEmail: string | null; billingAddress: string | null; founding: boolean; foundingSince: string | null; foundingNote: string | null;
sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[]; tiers: BillingTier[];
};
const yearAgo = () => { const d = new Date(`${todayYmd()}T00:00:00Z`); d.setUTCFullYear(d.getUTCFullYear() - 1); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); };
/** The tier a band ("R100 001–R150 000") falls in. */
function tierFor(tiers: BillingTier[], band: string | null) {
if (!band || band === "over R100 000") return null;
if (/^over /.test(band)) return tiers.find(t => t.upTo == null) || null;
const top = Number((band.split("–")[1] || "").replace(/[^\d]/g, ""));
return tiers.find(t => t.upTo == null || top <= t.upTo) || null;
}
/** One licence's billing set-up, and a notice of licence change for it. */
function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingLicence; tiers: BillingTier[]; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({
billingCycle: licence.billingCycle, billingStart: licence.billingStart || "", nextInvoiceDate: licence.nextInvoiceDate || "",
reviewDate: licence.reviewDate || "", custom: randInput(licence.customMonthlyCents),
});
const [change, setChange] = useState<{ toPlan: string; effectiveDate: string; price: string; reason: string } | null>(null);
const [busy, setBusy] = useState(false);
const suggested = tierFor(tiers, licence.incomeBand);
const tier = tiers.find(t => t.name === licence.plan);
const save = async () => {
setBusy(true);
try {
await api(`/api/admin/billing/licences/${licence.id}`, {
method: "PUT",
body: { billingCycle: form.billingCycle, billingStart: form.billingStart || null, nextInvoiceDate: form.nextInvoiceDate || null, reviewDate: form.reviewDate || null, customMonthlyCents: form.custom.trim() ? centsFrom(form.custom) : null },
});
setMsg({ type: "ok", text: form.billingCycle === "none" ? "Saved: this licence isn't billed." : "Billing saved. The next draft is made 14 days before the next invoice date." });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const sendChange = async (e: React.FormEvent) => {
e.preventDefault();
if (!change) return;
if (!confirm(`Email ${licence.plan} → ${change.toPlan} from ${day(change.effectiveDate)} to the church now?`)) return;
setBusy(true);
try {
const r = await api<{ change: LicenceChange; email: { ok: boolean; error: string | null } | null }>("/api/admin/billing/licence-changes", {
method: "POST", body: { licenceId: licence.id, toPlan: change.toPlan, effectiveDate: change.effectiveDate, reason: change.reason, toMonthlyCents: change.price.trim() ? centsFrom(change.price) : null },
});
setMsg({ type: r.email?.ok ? "ok" : "err", text: r.email?.ok ? `Notice ${r.change.number} sent. The tier changes on ${day(r.change.effectiveDate)}.` : `Notice ${r.change.number} recorded but not emailed: ${r.email?.error}` });
setChange(null);
onSaved();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); } finally { setBusy(false); }
};
return (
<div className="rounded-lg border border-slate-200 p-4">
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-2">
<div><code className="text-xs">{licence.key}</code>{licence.url && <span className="ml-2 text-xs text-slate-500">{licence.url.replace(/^https?:\/\//, "")}</span>}</div>
<div className="text-sm">
Tier <strong>{licence.plan}</strong>{licence.customMonthlyCents != null ? ` at ${money(licence.customMonthlyCents)}/month` : tier?.monthly != null ? ` (R${tier.monthly}/month)` : ""}
{licence.incomeBand && <span className="ml-2 text-xs text-slate-500">12-month income {licence.incomeBand}{suggested && suggested.name !== licence.plan ? ` → ${suggested.name} at the next review` : ""}</span>}
</div>
</div>
<div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-5">
<div>
<label className="label" htmlFor={`cycle-${licence.id}`}>Billing</label>
<select id={`cycle-${licence.id}`} className="input" value={form.billingCycle} onChange={e => setForm({ ...form, billingCycle: e.target.value as BillingCycle })}>
{(Object.keys(CYCLE) as BillingCycle[]).map(c => <option key={c} value={c}>{CYCLE[c]}</option>)}
</select>
</div>
<div><label className="label" htmlFor={`start-${licence.id}`}>Billing started</label><input id={`start-${licence.id}`} type="date" className="input" value={form.billingStart} onChange={e => setForm({ ...form, billingStart: e.target.value })} disabled={form.billingCycle === "none"} /></div>
<div><label className="label" htmlFor={`next-${licence.id}`}>Next invoice</label><input id={`next-${licence.id}`} type="date" className="input" value={form.nextInvoiceDate} onChange={e => setForm({ ...form, nextInvoiceDate: e.target.value })} disabled={form.billingCycle === "none"} /></div>
<div><label className="label" htmlFor={`review-${licence.id}`}>Next tier review</label><input id={`review-${licence.id}`} type="date" className="input" value={form.reviewDate} onChange={e => setForm({ ...form, reviewDate: e.target.value })} disabled={form.billingCycle === "none"} /></div>
<div><label className="label" htmlFor={`custom-${licence.id}`}>Custom price (R/month)</label><input id={`custom-${licence.id}`} className="input" inputMode="decimal" placeholder="Tier price" value={form.custom} onChange={e => setForm({ ...form, custom: e.target.value })} /></div>
</div>
<p className="mt-2 text-xs text-slate-500">Invoices are in advance: each covers the month (or year) starting on its date, on the same day of the month as billing started. Leave the next invoice and review blank to start from the billing date and review a year later. A custom price replaces the tier&apos;s (e.g. Network); founding churches get 35% off it.</p>
<div className="mt-3 flex flex-wrap gap-2">
<button className="btn-primary" onClick={save} disabled={busy}>Save billing</button>
{!change && <button className="btn-secondary" onClick={() => setChange({ toPlan: suggested && suggested.name !== licence.plan ? suggested.name : "", effectiveDate: licence.nextInvoiceDate || todayYmd(), price: "", reason: "" })}>Notice of licence change…</button>}
</div>
{change && (
<form onSubmit={sendChange} className="mt-4 space-y-3 rounded-lg bg-slate-50 p-3">
<div className="text-sm font-medium">Notice of licence change (emailed with a PDF)</div>
<div className="grid gap-3 sm:grid-cols-3">
<div>
<label className="label" htmlFor={`to-${licence.id}`}>New tier</label>
<select id={`to-${licence.id}`} className="input" value={change.toPlan} onChange={e => setChange({ ...change, toPlan: e.target.value })} required>
<option value="">Choose…</option>
{tiers.map(t => <option key={t.name} value={t.name} disabled={t.name === licence.plan}>{t.name}{t.monthly != null ? ` (R${t.monthly}/month)` : " (custom price)"}</option>)}
</select>
</div>
<div><label className="label" htmlFor={`eff-${licence.id}`}>Takes effect</label><input id={`eff-${licence.id}`} type="date" className="input" value={change.effectiveDate} onChange={e => setChange({ ...change, effectiveDate: e.target.value })} required /></div>
<div><label className="label" htmlFor={`price-${licence.id}`}>New price (R/month, for a custom price)</label><input id={`price-${licence.id}`} className="input" inputMode="decimal" placeholder="Tier price" value={change.price} onChange={e => setChange({ ...change, price: e.target.value })} /></div>
</div>
<div><label className="label" htmlFor={`why-${licence.id}`}>Why (printed on the notice)</label><input id={`why-${licence.id}`} className="input" value={change.reason} onChange={e => setChange({ ...change, reason: e.target.value })} placeholder="e.g. As agreed on our call." /></div>
<div className="flex gap-2"><button className="btn-primary" disabled={busy}>Send notice</button><button type="button" className="btn-secondary" onClick={() => setChange(null)}>Cancel</button></div>
</form>
)}
</div>
);
}
/** Customer page → Billing: founding, where invoices go, each licence's billing, statements, invoices, payments. */
export function CustomerBilling({ customerId }: { customerId: string }) {
const [c, setC] = useState<CustomerBillingData | null>(null);
const [form, setForm] = useState({ founding: false, foundingSince: "", foundingNote: "", billingEmail: "", billingAddress: "" });
const [stmt, setStmt] = useState({ from: yearAgo(), to: todayYmd(), email: "" });
const [paying, setPaying] = useState(false);
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => api<CustomerBillingData>(`/api/admin/billing/customers/${customerId}`).then(x => {
setC(x);
setForm({ founding: x.founding, foundingSince: x.foundingSince || "", foundingNote: x.foundingNote || "", billingEmail: x.billingEmail || "", billingAddress: x.billingAddress || "" });
}).catch(e => setMsg({ type: "err", text: errorText(e) })), [customerId]);
useEffect(() => { load(); }, [load]);
if (!c) return msg ? <div className="card text-sm text-red-700">{msg.text}</div> : null;
const saveDetails = async (e: React.FormEvent) => {
e.preventDefault();
try {
await api(`/api/admin/billing/customers/${customerId}`, { method: "PUT", body: { ...form, foundingSince: form.foundingSince || null } });
setMsg({ type: "ok", text: "Billing details saved. Drafts already made keep their price; recalculate them if needed." });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const emailStatement = async () => {
const to = stmt.email || c.sendsTo;
if (!confirm(`Email the statement (${day(stmt.from)} – ${day(stmt.to)}) to ${to}?`)) return;
try {
const r = await api<{ message: string }>(`/api/admin/billing/customers/${customerId}/statement/email`, { method: "POST", body: { from: stmt.from, to: stmt.to, email: stmt.email || undefined } });
setMsg({ type: "ok", text: r.message });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const pdf = (path: string) => openPdf(path).catch(e => setMsg({ type: "err", text: errorText(e) }));
return (
<section id="billing" className="mt-8 space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold">Billing</h2>
<div className="text-sm">{c.balanceCents > 0 ? <>Owing <strong>{money(c.balanceCents)}</strong></> : "Nothing owing"}</div>
</div>
{msg && <div role="status" className={`rounded-lg border p-3 text-sm ${msg.type === "ok" ? "border-green-200 bg-green-50 text-green-800" : "border-red-200 bg-red-50 text-red-800"}`}>{msg.text}</div>}
<div className="grid gap-4 lg:grid-cols-[1fr_2fr]">
<form onSubmit={saveDetails} className="card space-y-3 self-start">
<label className="flex items-center gap-2 font-medium"><input type="checkbox" checked={form.founding} onChange={e => setForm({ ...form, founding: e.target.checked, foundingSince: e.target.checked && !form.foundingSince ? todayYmd() : form.foundingSince })} /> <Star className="h-4 w-4 fill-amber-400 text-amber-400" /> Founding church (35% off)</label>
{form.founding && (
<div className="grid gap-3 sm:grid-cols-2">
<div><label className="label" htmlFor="f-since">Founding since</label><input id="f-since" type="date" className="input" value={form.foundingSince} onChange={e => setForm({ ...form, foundingSince: e.target.value })} /></div>
<div><label className="label" htmlFor="f-note">Note</label><input id="f-note" className="input" value={form.foundingNote} onChange={e => setForm({ ...form, foundingNote: e.target.value })} placeholder="e.g. Founding church 3 of 10" /></div>
</div>
)}
<div><label className="label" htmlFor="b-email">Billing email</label><input id="b-email" type="email" className="input" value={form.billingEmail} onChange={e => setForm({ ...form, billingEmail: e.target.value })} placeholder={c.sendsTo || ""} /><p className="mt-1 text-xs text-slate-500">Blank: the site&apos;s admin contact, then the customer&apos;s email. Now going to {c.sendsTo || "nobody (add one)"}.</p></div>
<div><label className="label" htmlFor="b-addr">Postal address (on invoices)</label><textarea id="b-addr" className="input" rows={2} value={form.billingAddress} onChange={e => setForm({ ...form, billingAddress: e.target.value })} /></div>
<button className="btn-secondary">Save billing details</button>
</form>
<div className="card space-y-3">
<h3 className="font-semibold">Licences</h3>
{c.licences.length === 0 ? <p className="text-sm text-slate-500">Generate a licence first.</p> : c.licences.map(l => <LicenceBilling key={`${l.id}-${l.plan}-${l.billingCycle}-${l.nextInvoiceDate}-${l.reviewDate}-${l.customMonthlyCents}`} licence={l} tiers={c.tiers} onSaved={load} setMsg={setMsg} />)}
</div>
</div>
<div className="card space-y-3">
<h3 className="font-semibold">Statement</h3>
<div className="flex flex-wrap items-end gap-3">
<div><label className="label" htmlFor="s-from">From</label><input id="s-from" type="date" className="input" value={stmt.from} onChange={e => setStmt({ ...stmt, from: e.target.value })} /></div>
<div><label className="label" htmlFor="s-to">To</label><input id="s-to" type="date" className="input" value={stmt.to} onChange={e => setStmt({ ...stmt, to: e.target.value })} /></div>
<div className="min-w-56 flex-1"><label className="label" htmlFor="s-email">Send to</label><input id="s-email" type="email" className="input" value={stmt.email} onChange={e => setStmt({ ...stmt, email: e.target.value })} placeholder={c.sendsTo || ""} /></div>
<button className="btn-secondary" onClick={() => pdf(`/api/admin/billing/customers/${customerId}/statement.pdf?from=${stmt.from}&to=${stmt.to}`)}><FileText className="h-4 w-4" /> Open PDF</button>
<button className="btn-primary" onClick={emailStatement}><Mail className="h-4 w-4" /> Email statement</button>
</div>
</div>
{paying && <RecordPayment customerId={customerId} onClose={() => setPaying(false)} onSaved={m => { setMsg(m); setPaying(false); load(); }} />}
<div className="card overflow-x-auto">
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
<h3 className="font-semibold">Invoices</h3>
<div className="flex gap-2"><Link className="btn-secondary" href={`/billing/invoices/new?customer=${customerId}`}><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>
</div>
{c.invoices.length === 0 ? <p className="text-sm text-slate-500">No invoices yet.</p> : (
<table className="w-full text-sm">
<thead className="text-left text-xs text-slate-500"><tr><th className="py-2">Invoice</th><th className="py-2">Date</th><th className="py-2">Tier</th><th className="py-2 text-right">Total</th><th className="py-2 text-right">Balance</th><th className="py-2">State</th></tr></thead>
<tbody>{c.invoices.map(i => (
<tr key={i.id} className="border-t border-slate-100">
<td className="py-2"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link></td>
<td className="py-2">{day(i.issueDate)}</td>
<td className="py-2">{i.plan || "One-off"}{i.planChange ? ` (from ${i.planChange.from})` : ""}</td>
<td className="py-2 text-right tabular-nums">{money(i.totalCents)}</td>
<td className="py-2 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>
<div className="grid gap-4 lg:grid-cols-2">
<div className="card text-sm">
<h3 className="mb-2 font-semibold">Payments</h3>
{c.payments.length === 0 ? <p className="text-slate-500">None yet.</p> : c.payments.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>
<div className="card text-sm">
<h3 className="mb-2 font-semibold">Notices of licence change</h3>
{c.licenceChanges.length === 0 ? <p className="text-slate-500">None yet.</p> : c.licenceChanges.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={() => api<{ message: string }>(`/api/admin/billing/licence-changes/${ch.id}/resend`, { method: "POST" }).then(r => { setMsg({ type: "ok", text: r.message }); load(); }).catch(e => setMsg({ type: "err", text: errorText(e) }))}>Send again</button>
</div>
</div>
))}
</div>
</div>
<div className="card text-sm">
<h3 className="mb-2 font-semibold">Billing emails</h3>
{c.emails.length === 0 ? <p className="text-slate-500">None yet.</p> : (
<table className="w-full">
<tbody>{c.emails.map(e => (
<tr key={e.id} className="border-t border-slate-100 first:border-0">
<td className="py-1.5 pr-3 whitespace-nowrap 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="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>
)}
</div>
</section>
);
}
@@ -0,0 +1,45 @@
"use client";
import React from "react";
import { Plus, Trash2 } from "lucide-react";
import { centsFrom, money, randInput, type Line } from "@/lib/billing";
/** A line as it's typed: the unit price as text in rand. */
export type EditLine = { description: string; quantity: string; unit: string };
export const toEdit = (lines: Line[]): EditLine[] => lines.map(l => ({ description: l.description, quantity: String(l.quantity), unit: randInput(l.unitCents) }));
export const fromEdit = (lines: EditLine[]) => lines
.filter(l => l.description.trim())
.map(l => ({ description: l.description.trim(), quantity: Number(l.quantity) || 1, unitCents: centsFrom(l.unit) ?? 0 }));
export const editTotal = (lines: EditLine[]) => fromEdit(lines).reduce((s, l) => s + Math.round(l.quantity * l.unitCents), 0);
/** Invoice lines: description, quantity and unit price (negative for a discount). */
export function LinesEditor({ lines, onChange }: { lines: EditLine[]; onChange: (lines: EditLine[]) => void }) {
const set = (i: number, patch: Partial<EditLine>) => onChange(lines.map((l, j) => (j === i ? { ...l, ...patch } : l)));
return (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="text-left text-xs text-slate-500"><tr><th className="pb-1">Description</th><th className="w-20 pb-1">Qty</th><th className="w-32 pb-1">Unit price (R)</th><th className="w-28 pb-1 text-right">Amount</th><th className="w-8" /></tr></thead>
<tbody>
{lines.map((l, i) => {
const amount = Math.round((Number(l.quantity) || 0) * (centsFrom(l.unit) ?? 0));
return (
<tr key={i}>
<td className="py-1 pr-2"><input aria-label={`Line ${i + 1} description`} className="input" value={l.description} onChange={e => set(i, { description: e.target.value })} /></td>
<td className="py-1 pr-2"><input aria-label={`Line ${i + 1} quantity`} className="input" inputMode="decimal" value={l.quantity} onChange={e => set(i, { quantity: e.target.value })} /></td>
<td className="py-1 pr-2"><input aria-label={`Line ${i + 1} unit price`} className="input" inputMode="decimal" value={l.unit} onChange={e => set(i, { unit: e.target.value })} /></td>
<td className="py-1 text-right tabular-nums">{money(amount)}</td>
<td className="py-1 pl-2"><button type="button" className="text-slate-400 hover:text-red-600" aria-label={`Remove line ${i + 1}`} onClick={() => onChange(lines.filter((_, j) => j !== i))}><Trash2 className="h-4 w-4" /></button></td>
</tr>
);
})}
</tbody>
</table>
<div className="mt-2 flex items-center justify-between">
<button type="button" className="btn-secondary" onClick={() => onChange([...lines, { description: "", quantity: "1", unit: "" }])}><Plus className="h-4 w-4" /> Add a line</button>
<div className="text-sm">Total <strong className="ml-2 tabular-nums">{money(editTotal(lines))}</strong></div>
</div>
<p className="mt-1 text-xs text-slate-500">Use a negative unit price for a discount.</p>
</div>
);
}
@@ -0,0 +1,101 @@
"use client";
import React, { useEffect, useState } from "react";
import { X } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { centsFrom, day, money, randInput, todayYmd, type Invoice } from "@/lib/billing";
type Msg = { type: "ok" | "err"; text: string };
/**
* Record money received: from which church, against which invoice (or on account), and the
* receipt emailed unless unticked. `customerId` / `invoice` fix the choice (customer and invoice pages).
*/
export function RecordPayment({ customers, customerId, invoice, onClose, onSaved }: {
customers?: { id: string; name: string }[];
customerId?: string;
invoice?: Invoice;
onClose: () => void;
onSaved: (msg: Msg) => void;
}) {
const [form, setForm] = useState({
customerId: invoice?.customerId || customerId || "",
invoiceId: invoice?.id || "",
amount: invoice ? randInput(Math.max(0, invoice.balanceCents)) : "",
paidOn: todayYmd(),
method: "eft",
reference: invoice?.number || "",
notes: "",
sendReceipt: true,
});
const [open, setOpen] = useState<Invoice[]>(invoice ? [invoice] : []);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// The church's invoices that still owe something.
useEffect(() => {
if (invoice || !form.customerId) return;
api<Invoice[]>(`/api/admin/billing/invoices?customerId=${form.customerId}&status=unpaid`).then(setOpen).catch(() => setOpen([]));
}, [form.customerId, invoice]);
const pickInvoice = (id: string) => {
const inv = open.find(i => i.id === id);
setForm(f => ({ ...f, invoiceId: id, amount: inv ? randInput(Math.max(0, inv.balanceCents)) : f.amount, reference: inv ? inv.number : f.reference }));
};
const save = async (e: React.FormEvent) => {
e.preventDefault();
const amountCents = centsFrom(form.amount);
if (!form.customerId) { setError("Choose the church."); return; }
if (amountCents == null || amountCents <= 0) { setError("Enter the amount received."); return; }
setBusy(true);
setError(null);
try {
const r = await api<{ payment: { receiptNumber: string }; receipt: { ok: boolean; error: string | null } | null }>("/api/admin/billing/payments", {
method: "POST",
body: { customerId: form.customerId, invoiceId: form.invoiceId || null, amountCents, paidOn: form.paidOn, method: form.method, reference: form.reference, notes: form.notes, sendReceipt: form.sendReceipt },
});
const receipt = r.receipt ? (r.receipt.ok ? " The receipt was emailed." : ` The receipt couldn't be emailed: ${r.receipt.error}`) : "";
onSaved({ type: r.receipt && !r.receipt.ok ? "err" : "ok", text: `Payment ${r.payment.receiptNumber} of ${money(amountCents)} recorded.${receipt}` });
} catch (err) { setError(errorText(err)); } finally { setBusy(false); }
};
return (
<form onSubmit={save} className="card space-y-3 border-indigo-200">
<div className="flex items-center justify-between"><h2 className="font-semibold">Record a payment</h2><button type="button" onClick={onClose} aria-label="Close" className="text-slate-400 hover:text-slate-700"><X className="h-4 w-4" /></button></div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{!invoice && !customerId && (
<div className="lg:col-span-2">
<label className="label" htmlFor="pay-customer">Church</label>
<select id="pay-customer" className="input" value={form.customerId} onChange={e => setForm({ ...form, customerId: e.target.value, invoiceId: "" })} required>
<option value="">Choose…</option>
{(customers || []).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
)}
{!invoice && (
<div className="lg:col-span-2">
<label className="label" htmlFor="pay-invoice">For invoice</label>
<select id="pay-invoice" className="input" value={form.invoiceId} onChange={e => pickInvoice(e.target.value)} disabled={!form.customerId}>
<option value="">On account (no invoice)</option>
{open.map(i => <option key={i.id} value={i.id}>{i.number}: {money(i.balanceCents)} owing, due {day(i.dueDate)}</option>)}
</select>
</div>
)}
<div><label className="label" htmlFor="pay-amount">Amount (R)</label><input id="pay-amount" className="input" inputMode="decimal" value={form.amount} onChange={e => setForm({ ...form, amount: e.target.value })} required /></div>
<div><label className="label" htmlFor="pay-date">Received on</label><input id="pay-date" type="date" className="input" value={form.paidOn} max={todayYmd()} onChange={e => setForm({ ...form, paidOn: e.target.value })} required /></div>
<div>
<label className="label" htmlFor="pay-method">Method</label>
<select id="pay-method" className="input" value={form.method} onChange={e => setForm({ ...form, method: e.target.value })}>
<option value="eft">EFT</option><option value="card">Card</option><option value="cash">Cash</option><option value="other">Other</option>
</select>
</div>
<div><label className="label" htmlFor="pay-ref">Their reference</label><input id="pay-ref" className="input" value={form.reference} onChange={e => setForm({ ...form, reference: e.target.value })} /></div>
<div className="sm:col-span-2 lg:col-span-4"><label className="label" htmlFor="pay-notes">Notes (printed on the receipt)</label><input id="pay-notes" className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} /></div>
</div>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.sendReceipt} onChange={e => setForm({ ...form, sendReceipt: e.target.checked })} /> Email the receipt (PDF) to the church</label>
{error && <p className="text-sm text-red-700">{error}</p>}
<div className="flex gap-2"><button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Record payment"}</button><button type="button" className="btn-secondary" onClick={onClose}>Cancel</button></div>
</form>
);
}