Hub 2.0 step 4: billing per customer

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 16:18:23 +02:00
co-authored by Claude Opus 5.5
parent 937c1fa38e
commit 7478e84e9d
21 changed files with 1081 additions and 316 deletions
@@ -10,6 +10,7 @@ import { Loading, Message, PageTitle } from "@/components/ui";
import { EMAIL_KIND, METHOD, StateBadge, day, money, todayYmd, type BillingEmail, type Invoice, type LicenceChange } from "@/lib/billing";
import { LinesEditor, editTotal, fromEdit, toEdit, type EditLine } from "@/components/billing/LinesEditor";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { PRODUCT_NAMES } from "@/lib/products";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = Invoice & { licenceChanges: LicenceChange[]; emails: BillingEmail[] };
@@ -102,8 +103,9 @@ function InvoiceDetail({ id }: { id: string }) {
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 changes = inv.planChanges.map(pc => `${PRODUCT_NAMES[pc.product || "events"]}: ${pc.from} → ${pc.to}`).join(", ");
if (!confirm(`Approve ${inv.number}? It goes to ${inv.recipientEmail} ${when}.${changes ? `\n\nThe church is also sent a notice of licence change for each tier change (${changes}) now.` : ""}`)) return;
act("approve", "approve", {}, r => `Approved. It goes out ${when}.${r.notice ? (r.notice.email?.ok ? ` The notice of licence change ${r.notice.change.number}${inv.planChanges.length > 1 ? " (and the others)" : ""} was emailed.` : ` The notice ${r.notice.change.number} couldn't be emailed: ${r.notice.email?.error}`) : ""}`);
};
const voidIt = () => {
const reason = prompt(`Void ${inv.number}? It stays on record, marked void. Why (printed on it)?`, "");
@@ -111,11 +113,12 @@ function InvoiceDetail({ id }: { id: string }) {
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;
const many = inv.planChanges.length > 1;
if (!confirm(`Remove the tier change${many ? "s" : ""} from this invoice? The tier${many ? "s stay" : " stays"} as ${many ? "they are" : "it is"}${inv.licenceId ? "; then press Recalculate to price it at that tier" : ", and the draft is priced at them again"}.`)) return;
setBusy("drop");
try {
await api(`/api/admin/billing/invoices/${id}`, { method: "PUT", body: { dropPlanChange: true } });
setMsg({ type: "ok", text: "Tier change removed. Press Recalculate to price it at the current tier." });
setMsg({ type: "ok", text: inv.licenceId ? "Tier change removed. Press Recalculate to price it at the current tier." : `Tier change${many ? "s" : ""} removed, and the draft repriced.` });
await load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(null); }
};
@@ -141,7 +144,7 @@ function InvoiceDetail({ id }: { id: string }) {
<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 === "draft" && inv.periodStart && inv.cycle !== "none" && <button className="btn-secondary" onClick={() => act("recalc", "recalculate", {}, () => "Recalculated from the church's products, prices and founding status as they are now.")} disabled={!!busy}><RefreshCw className="h-4 w-4" /> Recalculate</button>}
{inv.status === "approved" && <button className="btn-primary" onClick={() => confirm(`Send ${inv.number} to ${inv.recipientEmail} now?`) && act("send", "send", {}, () => `Sent to ${inv.recipientEmail}.`)} disabled={!!busy}><Send className="h-4 w-4" /> {busy === "send" ? "Sending…" : "Send now"}</button>}
{inv.status === "approved" && <button className="btn-secondary" onClick={() => act("unapprove", "unapprove", {}, () => "Back to draft: it won't go out until you approve it again.")} disabled={!!busy}><Undo2 className="h-4 w-4" /> Back to draft</button>}
{inv.status === "sent" && inv.balanceCents > 0 && <button className="btn-primary" onClick={() => setPaying(true)}>Record payment</button>}
@@ -157,10 +160,18 @@ function InvoiceDetail({ id }: { id: string }) {
<ul className="list-disc space-y-0.5 pl-5">{inv.warnings.map(w => <li key={w}>{w}</li>)}</ul>
</div>
)}
{inv.planChange && (
{inv.planChanges.length > 0 && (
<div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-sky-200 bg-sky-50 p-3 text-sm text-sky-900">
<div><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>
{inv.planChanges.map(pc => (
<div key={`${pc.product}-${pc.to}`}>
<strong>Annual review, {PRODUCT_NAMES[pc.product || "events"]}: {pc.from} → {pc.to}</strong>
{pc.band ? ` (${pc.product === "app" ? "active members" : "12-month event income"} ${pc.band})` : ""}
</div>
))}
<div className="mt-1">{inv.status === "draft" ? `Approving sends the church a notice of licence change for each straight away; the tier${inv.planChanges.length > 1 ? "s change" : " changes"} when this invoice goes out.` : inv.status === "approved" ? "The notices were sent; the tiers change when this invoice goes out." : ""}</div>
</div>
{inv.status === "draft" && <button className="btn-secondary" onClick={dropChange} disabled={!!busy}>Keep the tier{inv.planChanges.length > 1 ? "s" : ""}</button>}
</div>
)}
+17 -8
View File
@@ -6,15 +6,18 @@ 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 { CYCLE, METHOD, StateBadge, day, money, todayYmd, type BillingCycle, type Invoice, type Payment } from "@/lib/billing";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
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 }[];
// Hub 2.0: the schedule is the church's, for all its products.
billingCycle: BillingCycle; nextInvoiceDate: string | null; reviewDate: string | null;
licences: { id: string; key: string; product: Product; plan: string; status: string; billable: boolean; billedFrom: string | null; customMonthlyCents: number | null; url: string | null }[];
};
type Tab = "invoices" | "payments" | "churches";
const TABS: { key: Tab; label: string }[] = [
@@ -126,7 +129,7 @@ export default function BillingPage() {
<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"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link>{i.planChanges.map(pc => <div key={`${pc.product}-${pc.to}`} className="text-xs text-amber-700">{pc.product && pc.product !== "events" ? `${PRODUCT_NAMES[pc.product]}: ` : ""}{pc.from} → {pc.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>
@@ -167,10 +170,10 @@ export default function BillingPage() {
{tab === "churches" && (!accounts ? <Loading /> : (
<>
<p className="mb-3 text-sm text-slate-600">{founding} founding church{founding === 1 ? "" : "es"}. Founding churches pay the founding price (35% less) on every tier for as long as they stay. Set billing up for each licence on the church&apos;s page.</p>
<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 on the church&apos;s page: one invoice covers all its products.</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>
<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">Products</th><th className="p-3">Billing</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">
@@ -179,10 +182,16 @@ export default function BillingPage() {
<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 className="p-3">{a.licences.filter(l => l.billable).length === 0 ? <span className="text-slate-400">No product licence</span> : [...a.licences].filter(l => l.billable).sort(byProduct).map(l => (
<div key={l.id}>
{PRODUCT_NAMES[l.product]}: {l.plan}{l.customMonthlyCents != null ? ` (${money(l.customMonthlyCents)}/month)` : ""}
{l.status !== "active" ? <span className="text-red-600"> · {l.status}</span> : !l.billedFrom ? <span className="text-slate-400"> · not charged</span> : l.billedFrom > todayYmd() ? <span className="text-xs text-slate-500"> · from {day(l.billedFrom)}</span> : null}
</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">
<span className={a.billingCycle === "none" ? "text-slate-400" : ""}>{CYCLE[a.billingCycle]}</span>
{a.billingCycle !== "none" && <div className="text-xs text-slate-500">next {day(a.nextInvoiceDate)}{a.reviewDate ? ` · review ${day(a.reviewDate)}` : ""}</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>
))}
@@ -6,7 +6,7 @@ import { useParams } from "next/navigation";
import { ArrowLeft, Copy, KeyRound } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { PLANS } from "@/lib/tiers";
import { PLANS_BY_PRODUCT } from "@/lib/tiers";
import { KEY_WHERE, PRODUCTS, PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
import type { Customer, Licence, LicenceStatus } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
@@ -76,15 +76,13 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
<div className="grid gap-3 sm:grid-cols-6">
<div>
<label className="label" htmlFor={`plan-${licence.id}`}>Plan</label>
{licence.product === "events" ? (
<select id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })}>
{!PLANS.includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
{PLANS.map(p => <option key={p} value={p}>{p}</option>)}
</select>
) : licence.product === "accounts" ? (
{licence.product === "accounts" ? (
<input id={`plan-${licence.id}`} className="input" value="Included" disabled />
) : (
<input id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })} />
<select id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })}>
{!PLANS_BY_PRODUCT[licence.product].includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
{PLANS_BY_PRODUCT[licence.product].map(p => <option key={p} value={p}>{p}</option>)}
</select>
)}
<p className="mt-1 text-xs text-slate-500">
{licence.product === "accounts"
@@ -5,45 +5,103 @@ 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 { CYCLE, EMAIL_KIND, METHOD, StateBadge, centsFrom, day, money, randInput, todayYmd, type BillingCycle, type BillingEmail, type Invoice, type LicenceChange, type Line, type Payment, type PlanChange } from "@/lib/billing";
import { PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
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 };
/** A plan of a product: the Events tiers have an income ceiling (upTo), the App tiers a member band. */
type Plan = { name: string; monthly: number | null; founding: number | null; upTo?: number | null; band?: string };
type BillingLicence = {
id: string; key: string; product: Product; plan: string; status: string; customMonthlyCents: number | null;
billedFrom: string | null; billedUntil: string | null; billable: boolean; url: string | null;
incomeBand?: string | null; activeMembers?: string | null; storage?: { usedBytes: number; includedBytes: number } | 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[];
billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null;
sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[];
plans: Record<Product, Plan[]>;
};
type Preview = { billed: false } | { billed: true; empty: boolean; invoice: { periodStart: string; periodEnd: string; issueDate: string; lines: Line[]; totalCents: number; warnings: string[]; planChanges: PlanChange[] } };
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); };
const gb = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
/** 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;
/** The tier a product's report points to: an Events income band ("R100 001–R150 000") or an App member band. */
function suggestedTier(licence: BillingLicence, plans: Plan[]) {
if (licence.product === "app") return plans.find(p => p.band && p.band === licence.activeMembers) || null;
const band = licence.incomeBand;
if (licence.product !== "events" || !band || band === "over R100 000") return null;
if (/^over /.test(band)) return plans.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;
return plans.find(t => t.upTo == null || top <= (t.upTo ?? Infinity)) || 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),
});
/** What the product reports that its price depends on. */
function reportText(l: BillingLicence) {
if (l.product === "events") return l.incomeBand ? `12-month event income ${l.incomeBand}` : "No event income reported yet";
if (l.product === "app") return l.activeMembers ? `${l.activeMembers} active members (90 days)` : "No active members reported yet";
if (l.product === "website") return l.storage ? `${gb(l.storage.usedBytes)} of ${gb(l.storage.includedBytes)} storage used` : "No storage reported yet";
return "";
}
/** The church's billing schedule: one for all its products. */
function Schedule({ c, onSaved, setMsg }: { c: CustomerBillingData; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({ billingCycle: c.billingCycle, billingStart: c.billingStart || "", nextInvoiceDate: c.nextInvoiceDate || "", reviewDate: c.reviewDate || "" });
const [busy, setBusy] = useState(false);
const off = form.billingCycle === "none";
const save = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
try {
await api(`/api/admin/billing/customers/${c.id}`, { method: "PUT", body: { billingCycle: form.billingCycle, billingStart: form.billingStart || null, nextInvoiceDate: form.nextInvoiceDate || null, reviewDate: form.reviewDate || null } });
setMsg({ type: "ok", text: off ? "Saved: this church isn't billed." : "Billing saved. The next draft, for all the church's products, is made 14 days before the next invoice date." });
onSaved();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); } finally { setBusy(false); }
};
return (
<form onSubmit={save} className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<div>
<label className="label" htmlFor="cycle">Billing</label>
<select id="cycle" className="input" value={form.billingCycle} onChange={e => setForm({ ...form, billingCycle: e.target.value as BillingCycle })}>
{(Object.keys(CYCLE) as BillingCycle[]).map(k => <option key={k} value={k}>{CYCLE[k]}</option>)}
</select>
</div>
<div><label className="label" htmlFor="start">Billing started</label><input id="start" type="date" className="input" value={form.billingStart} onChange={e => setForm({ ...form, billingStart: e.target.value })} disabled={off} /></div>
<div><label className="label" htmlFor="next">Next invoice</label><input id="next" type="date" className="input" value={form.nextInvoiceDate} onChange={e => setForm({ ...form, nextInvoiceDate: e.target.value })} disabled={off} /></div>
<div><label className="label" htmlFor="review">Next tier review</label><input id="review" type="date" className="input" value={form.reviewDate} onChange={e => setForm({ ...form, reviewDate: e.target.value })} disabled={off} /></div>
</div>
<p className="text-xs text-slate-500">One invoice covers all the church&apos;s products, in advance, 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. Starting billing charges the products that aren&apos;t charged yet from the billing date; a product added later starts after its free month.</p>
<button className="btn-primary" disabled={busy}>Save billing</button>
</form>
);
}
/** One licence's billing: when it's charged from, a custom price, and a notice of licence change. */
function LicenceBilling({ licence, plans, nextInvoiceDate, onSaved, setMsg }: { licence: BillingLicence; plans: Plan[]; nextInvoiceDate: string | null; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({ billedFrom: licence.billedFrom || "", 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 suggested = suggestedTier(licence, plans);
const tier = plans.find(t => t.name === licence.plan);
const name = PRODUCT_NAMES[licence.product];
if (!licence.billable) {
return (
<div className="rounded-lg border border-slate-200 p-4 text-sm">
<span className="font-medium">{name}</span> <code className="ml-2 text-xs">{licence.key}</code>
<span className="ml-2 text-slate-500">Free: comes with the church&apos;s other products, never invoiced.</span>
</div>
);
}
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." });
await api(`/api/admin/billing/licences/${licence.id}`, { method: "PUT", body: { billedFrom: form.billedFrom || null, customMonthlyCents: form.custom.trim() ? centsFrom(form.custom) : null } });
setMsg({ type: "ok", text: form.billedFrom ? `${name}: charged from ${day(form.billedFrom)}.` : `${name}: not charged.` });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
@@ -51,7 +109,7 @@ function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingL
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;
if (!confirm(`Email ${name}: ${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", {
@@ -66,28 +124,25 @@ function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingL
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><span className="font-medium">{name}</span> <code className="ml-2 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>}
{licence.product === "website" ? "Website" : <>Tier <strong>{licence.plan}</strong></>}
{licence.customMonthlyCents != null ? ` at ${money(licence.customMonthlyCents)}/month` : tier?.monthly != null ? ` (R${tier.monthly}/month)` : ""}
<span className="ml-2 text-xs text-slate-500">{reportText(licence)}{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 className="grid gap-3 sm:grid-cols-3">
<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>
<label className="label" htmlFor={`from-${licence.id}`}>Charged from</label>
<input id={`from-${licence.id}`} type="date" className="input" value={form.billedFrom} onChange={e => setForm({ ...form, billedFrom: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{licence.billedUntil ? `Invoiced up to ${day(licence.billedUntil)}.` : "Not invoiced yet."} Blank: not charged (e.g. a trial).</p>
</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>
<p className="mt-2 text-xs text-slate-500">A product that starts part-way through a period is charged by the day up to the next period. 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>}
<button className="btn-primary" onClick={save} disabled={busy}>Save</button>
{plans.length > 1 && !change && <button className="btn-secondary" onClick={() => setChange({ toPlan: suggested && suggested.name !== licence.plan ? suggested.name : "", effectiveDate: 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">
@@ -97,7 +152,7 @@ function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingL
<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>)}
{plans.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>
@@ -111,6 +166,38 @@ function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingL
);
}
/** The next invoice as it would be drafted now: nothing is saved. */
function NextInvoice({ customerId, version }: { customerId: string; version: string }) {
const [p, setP] = useState<Preview | null>(null);
const [err, setErr] = useState<string | null>(null);
useEffect(() => {
api<Preview>(`/api/admin/billing/customers/${customerId}/preview`).then(setP).catch(e => setErr(errorText(e)));
}, [customerId, version]);
if (err) return <p className="text-sm text-red-700">{err}</p>;
if (!p) return null;
if (!p.billed) return <p className="text-sm text-slate-500">Not billed: set the billing up above to see the next invoice.</p>;
if (p.empty) return <p className="text-sm text-slate-500">Nothing to charge for the period from {day(p.invoice.periodStart)}: no product is charged yet.</p>;
const inv = p.invoice;
return (
<div className="space-y-2 text-sm">
<p className="text-slate-600">For {day(inv.periodStart)} – {day(inv.periodEnd)}, drafted 14 days before {day(inv.issueDate)}. As it stands today (prices, founding, what each product reports):</p>
<table className="w-full">
<tbody>
{inv.lines.map((l, i) => (
<tr key={i} className="border-t border-slate-100 first:border-0">
<td className="py-1.5 pr-3">{l.description}{l.quantity !== 1 ? <span className="text-xs text-slate-500"> · {l.quantity} × {money(l.unitCents)}</span> : null}</td>
<td className={`py-1.5 text-right tabular-nums ${l.amountCents < 0 ? "text-green-700" : ""}`}>{money(l.amountCents)}</td>
</tr>
))}
<tr className="border-t border-slate-300 font-semibold"><td className="py-1.5">Total</td><td className="py-1.5 text-right tabular-nums">{money(inv.totalCents)}</td></tr>
</tbody>
</table>
{inv.planChanges.length > 0 && <p className="text-sky-800">At this review: {inv.planChanges.map(pc => `${PRODUCT_NAMES[pc.product || "events"]} ${pc.from} → ${pc.to}`).join(", ")}.</p>}
{inv.warnings.length > 0 && <ul className="list-disc pl-5 text-amber-800">{inv.warnings.map(w => <li key={w}>{w}</li>)}</ul>}
</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);
@@ -168,9 +255,21 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
<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 className="space-y-4">
<div className="card space-y-3">
<h3 className="font-semibold">Billing schedule</h3>
<Schedule key={`${c.billingCycle}-${c.billingStart}-${c.nextInvoiceDate}-${c.reviewDate}`} c={c} onSaved={load} setMsg={setMsg} />
</div>
<div className="card space-y-3">
<h3 className="font-semibold">Products</h3>
{c.licences.length === 0 ? <p className="text-sm text-slate-500">Generate a licence first.</p> : [...c.licences].filter(l => l.status !== "revoked").sort(byProduct).map(l => (
<LicenceBilling key={`${l.id}-${l.plan}-${l.billedFrom}-${l.billedUntil}-${l.customMonthlyCents}`} licence={l} plans={c.plans[l.product] || []} nextInvoiceDate={c.nextInvoiceDate} onSaved={load} setMsg={setMsg} />
))}
</div>
<div className="card space-y-3">
<h3 className="font-semibold">Next invoice</h3>
<NextInvoice customerId={customerId} version={JSON.stringify([c.founding, c.billingCycle, c.nextInvoiceDate, c.licences.map(l => [l.plan, l.billedFrom, l.billedUntil, l.customMonthlyCents, l.status])])} />
</div>
</div>
</div>
@@ -199,7 +298,7 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
<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">{i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""}</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>
+8 -3
View File
@@ -1,4 +1,5 @@
import React from "react";
import type { Product } from "./products";
// Billing (1.7.0): the shapes the billing API returns, and how they're shown.
@@ -6,7 +7,8 @@ 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 };
/** A tier change at the annual review (Hub 2.0: one per product). */
export type PlanChange = { licenceId?: string | null; product?: Product; 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 = {
@@ -18,13 +20,16 @@ export type Payment = {
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;
plan: string | null; incomeBand: string | null; reviewed: boolean; founding: boolean;
/** The tier changes on this invoice (the API reads Hub 1.7's single change as a list of one). */
planChanges: PlanChange[];
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;
/** Before Hub 2.0 an invoice was for one licence; from 2.0 it's for the customer (null). */
licence?: { id: string; key: string; product: Product; plan: string; installUrl: string | null } | null;
};
export type LicenceChange = {
+31
View File
@@ -19,6 +19,37 @@ export const TIERS: Tier[] = [
/** Licence plans offered on a licence: the tiers, plus a trial. */
export const PLANS = ["Trial", ...TIERS.map(t => t.name)];
// Hub 2.0: the other products' prices (ROADMAP-v3 §10), the same as backend/src/utils/billing/tiers.js.
/** Church Website: one price, 5 GB of uploads included. */
export const WEBSITE_PLAN = { name: "Website", monthly: 99, founding: 64 };
export type AppTier = { name: string; band: string; monthly: number | null; founding: number | null };
/** Church App tiers, on active members in the last 90 days. */
export const APP_TIERS: AppTier[] = [
{ name: "Mustard Seed", band: "0–100", monthly: 99, founding: 64 },
{ name: "Small Group", band: "101–300", monthly: 249, founding: 162 },
{ name: "Congregation", band: "301–750", monthly: 399, founding: 259 },
{ name: "Gathering", band: "751–2 000", monthly: 649, founding: 422 },
{ name: "Multitude", band: "2 001–5 000", monthly: 999, founding: 649 },
{ name: "Network", band: "over 5 000", monthly: null, founding: null },
];
/** Plans offered on a licence, per product (Accounts has none: it's free). */
export const PLANS_BY_PRODUCT = {
events: PLANS,
website: [WEBSITE_PLAN.name],
app: ["Trial", ...APP_TIERS.map(t => t.name)],
accounts: [] as string[],
};
/** Extra website storage: R20 a month per 5 GB above the 5 GB included. Never discounted. */
export const STORAGE_ADDON = { includedGb: 5, stepGb: 5, monthly: 20 };
/** Bundles: % off the products (not add-ons) by how many are billed. */
export const BUNDLE_PERCENT: Record<number, number> = { 2: 15, 3: 25 };
/** The highest rand amount in a band label ("R100 001–R150 000" → 150000; "over R10 000 000" → Infinity). */
function bandTop(band: string): number | null {
if (/^over /i.test(band)) return Infinity;