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:
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "events-hub-frontend",
|
||||
"version": "1.6.2",
|
||||
"version": "1.7.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "events-hub-frontend",
|
||||
"version": "1.6.2",
|
||||
"version": "1.7.0",
|
||||
"dependencies": {
|
||||
"lucide-react": "^0.536.0",
|
||||
"next": "^15.5.24",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "events-hub-frontend",
|
||||
"version": "1.6.2",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3200",
|
||||
|
||||
@@ -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} />;
|
||||
}
|
||||
@@ -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'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's Licence page. Founding discount: note it below.</p>
|
||||
<p className="mt-1 text-xs text-slate-500">Shown on the church'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} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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" && (
|
||||
|
||||
@@ -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'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'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'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's admin contact, then the customer'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>
|
||||
);
|
||||
}
|
||||
@@ -40,3 +40,24 @@ export async function api<T = unknown>(path: string, options: { method?: string;
|
||||
}
|
||||
|
||||
export const errorText = (e: unknown, fallback = "Something went wrong.") => (e instanceof Error && e.message) || fallback;
|
||||
|
||||
/** Opens a PDF from the API (which needs the session token) in a new tab. */
|
||||
export async function openPdf(path: string) {
|
||||
// Open the tab first, while the click still counts as the user's: browsers block it after an await.
|
||||
const tab = window.open("", "_blank");
|
||||
try {
|
||||
const token = getToken();
|
||||
const res = await fetch(`${API_URL}${path}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
throw new ApiError(data?.message || `Request failed (${res.status})`, res.status, data?.code);
|
||||
}
|
||||
const url = URL.createObjectURL(await res.blob());
|
||||
if (tab) tab.location.href = url;
|
||||
else window.location.href = url;
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
} catch (e) {
|
||||
tab?.close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import React from "react";
|
||||
|
||||
// Billing (1.7.0): the shapes the billing API returns, and how they're shown.
|
||||
|
||||
export type InvoiceStatus = "draft" | "approved" | "sent" | "void";
|
||||
export type InvoiceState = InvoiceStatus | "unpaid" | "part_paid" | "overdue" | "paid";
|
||||
export type BillingCycle = "none" | "monthly" | "yearly";
|
||||
export type Line = { description: string; quantity: number; unitCents: number; amountCents: number };
|
||||
export type PlanChange = { from: string; to: string; fromMonthlyCents: number | null; toMonthlyCents: number | null; band?: string | null };
|
||||
export type BillingTier = { name: string; upTo: number | null; monthly: number | null; founding: number | null };
|
||||
|
||||
export type Payment = {
|
||||
id: string; receiptNumber: string; customerId: string; invoiceId: string | null; amountCents: number; paidOn: string;
|
||||
method: string; reference: string | null; notes: string | null; receiptSentAt: string | null; createdAt: string;
|
||||
invoice?: { id: string; number: string } | null; customer?: { id: string; name: string };
|
||||
};
|
||||
|
||||
export type Invoice = {
|
||||
id: string; number: string; customerId: string; licenceId: string | null; status: InvoiceStatus; state: InvoiceState;
|
||||
issueDate: string; dueDate: string; periodStart: string | null; periodEnd: string | null; cycle: BillingCycle;
|
||||
plan: string | null; incomeBand: string | null; reviewed: boolean; founding: boolean; planChange: PlanChange | null;
|
||||
lines: Line[]; totalCents: number; vatCents: number; paidCents: number; balanceCents: number;
|
||||
notes: string | null; warnings: string[]; recipientEmail: string | null;
|
||||
approvedAt: string | null; approvalEmailedAt: string | null; sentAt: string | null; sendError: string | null; voidedAt: string | null; voidReason: string | null;
|
||||
createdAt: string; payments: Payment[];
|
||||
customer?: { id: string; name: string; founding: boolean };
|
||||
licence?: { id: string; key: string; plan: string; billingCycle: BillingCycle; installUrl: string | null } | null;
|
||||
};
|
||||
|
||||
export type LicenceChange = {
|
||||
id: string; number: string; fromPlan: string; toPlan: string; fromMonthlyCents: number | null; toMonthlyCents: number | null;
|
||||
effectiveDate: string; reason: string | null; incomeBand: string | null; appliedAt: string | null; sentAt: string | null; invoiceId: string | null; createdAt: string;
|
||||
};
|
||||
|
||||
export type BillingEmail = { id: string; kind: string; to: string; subject: string; error: string | null; sentAt: string };
|
||||
|
||||
/** R1 350.00 */
|
||||
export function money(cents: number | null | undefined) {
|
||||
if (cents == null) return "—";
|
||||
const neg = cents < 0;
|
||||
const [r, c] = (Math.abs(Math.round(cents)) / 100).toFixed(2).split(".");
|
||||
return `${neg ? "-" : ""}R${r.replace(/\B(?=(\d{3})+(?!\d))/g, " ")}.${c}`;
|
||||
}
|
||||
|
||||
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
/** "1 Dec 2026" from "2026-12-01". */
|
||||
export function day(d: string | null | undefined) {
|
||||
if (!d) return "—";
|
||||
const [y, m, dd] = d.slice(0, 10).split("-").map(Number);
|
||||
return `${dd} ${MONTHS[m - 1]} ${y}`;
|
||||
}
|
||||
/** Today in South Africa, "YYYY-MM-DD". */
|
||||
export const todayYmd = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Africa/Johannesburg", year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date());
|
||||
|
||||
export const STATE: Record<InvoiceState, { label: string; cls: string }> = {
|
||||
draft: { label: "Draft: needs approval", cls: "bg-amber-50 text-amber-800 border-amber-200" },
|
||||
approved: { label: "Approved: goes out on its date", cls: "bg-indigo-50 text-indigo-700 border-indigo-200" },
|
||||
sent: { label: "Sent", cls: "bg-slate-50 text-slate-700 border-slate-200" },
|
||||
unpaid: { label: "Unpaid", cls: "bg-sky-50 text-sky-800 border-sky-200" },
|
||||
part_paid: { label: "Part paid", cls: "bg-sky-50 text-sky-800 border-sky-200" },
|
||||
overdue: { label: "Overdue", cls: "bg-red-50 text-red-700 border-red-200" },
|
||||
paid: { label: "Paid", cls: "bg-green-50 text-green-700 border-green-200" },
|
||||
void: { label: "Void", cls: "bg-slate-100 text-slate-500 border-slate-200" },
|
||||
};
|
||||
|
||||
export function StateBadge({ state, short = false }: { state: InvoiceState; short?: boolean }) {
|
||||
const s = STATE[state];
|
||||
return <span className={`inline-block whitespace-nowrap rounded-full border px-2 py-0.5 text-xs font-medium ${s.cls}`}>{short ? s.label.split(":")[0] : s.label}</span>;
|
||||
}
|
||||
|
||||
export const CYCLE: Record<BillingCycle, string> = { none: "Not billed", monthly: "Monthly", yearly: "Yearly (2 months free)" };
|
||||
export const METHOD: Record<string, string> = { eft: "EFT", card: "Card", cash: "Cash", other: "Other" };
|
||||
export const EMAIL_KIND: Record<string, string> = { invoice: "Invoice", receipt: "Receipt", statement: "Statement", licence_change: "Licence change", approval: "Approval request (to you)", reminder: "Reminder (to you)" };
|
||||
|
||||
/** Rand typed into a form ("1350" or "1 350,50") → cents, or null. */
|
||||
export function centsFrom(v: string): number | null {
|
||||
const n = Number(String(v).replace(/[\sR]/g, "").replace(",", "."));
|
||||
return Number.isFinite(n) && String(v).trim() !== "" ? Math.round(n * 100) : null;
|
||||
}
|
||||
export const randInput = (cents: number | null | undefined) => (cents == null ? "" : (cents / 100).toFixed(2));
|
||||
Reference in New Issue
Block a user