Files
events-hub/frontend/src/components/billing/CustomerBilling.tsx
T
joshuaandClaude Opus 5.5 3a00271a02 Hub 2.12.0: one product uninstalled at a time, stale installs removed, customers archived
- Uninstalls name the product (agent 1.5.0); a whole-church uninstall marks every product
  of the church on that server removed. Older agents are refused while the church has others.
- A second product's uninstall joins one already planned (one export and one uninstall) or
  gets its own time; the last product removes the whole church. Accounts goes last.
- Remove an install from the Hub after 24 hours without a heartbeat (POST .../forget).
- Archive and restore customers (migration 20261123090000_customer_archive).
- Several addresses for a customer's email and billing email, with a + button.
- Statements show R0 invoices' amounts. Vendors contracts 1.16.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:17:35 +02:00

414 lines
32 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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 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";
import { EmailList } from "@/components/EmailList";
type Msg = { type: "ok" | "err"; text: 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;
billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null;
addressType: AddressType; domain: string | null; addressCustomCents: number | null; addressMonthlyCents: number; domainRenewsOn: 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 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 plans.find(t => t.upTo == null || top <= (t.upTo ?? Infinity)) || null;
}
/** 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>
);
}
type AddressType = "own_domain" | "crosscode" | "included";
const ADDRESS_OPTIONS: Record<AddressType, { label: string; price: string; help: string }> = {
own_domain: { label: "Own domain", price: "R0", help: "The church (or whoever manages its domain) adds the DNS records we send. We look after the certificates." },
crosscode: { label: "Cross Code address", price: "R10/month", help: "<church>.crosscode.co.za, with events., app. and so on in front. Free during a trial." },
included: { label: "Domain included", price: "R25/month", help: "A .co.za or .org.za registered in the church's name; we renew it and manage the DNS. Other endings at cost: set a custom price." },
};
/** The church's address: one for all its products, billed once per invoice and never discounted. */
function Address({ c, onSaved, setMsg }: { c: CustomerBillingData; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({ addressType: c.addressType, domain: c.domain || "", custom: randInput(c.addressCustomCents), domainRenewsOn: c.domainRenewsOn || "" });
const [busy, setBusy] = useState(false);
const save = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
try {
await api(`/api/admin/billing/customers/${c.id}`, { method: "PUT", body: { addressType: form.addressType, domain: form.domain || null, addressCustomCents: form.custom.trim() ? centsFrom(form.custom) : null, domainRenewsOn: form.domainRenewsOn || null } });
setMsg({ type: "ok", text: `Address saved: ${ADDRESS_OPTIONS[form.addressType].label}.` });
onSaved();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); } finally { setBusy(false); }
};
const renewed = async () => {
if (!confirm(`Mark ${c.domain || "the domain"} as renewed? The renewal date moves on a year.`)) return;
try {
const r = await api<{ message: string }>(`/api/admin/billing/customers/${c.id}/domain-renewed`, { method: "POST" });
setMsg({ type: "ok", text: r.message });
onSaved();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const due = c.addressType === "included" && c.domainRenewsOn && c.domainRenewsOn <= new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10);
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="addr-type">Address</label>
<select id="addr-type" className="input" value={form.addressType} onChange={e => setForm({ ...form, addressType: e.target.value as AddressType })}>
{(Object.keys(ADDRESS_OPTIONS) as AddressType[]).map(k => <option key={k} value={k}>{ADDRESS_OPTIONS[k].label} ({ADDRESS_OPTIONS[k].price})</option>)}
</select>
</div>
<div><label className="label" htmlFor="addr-domain">Domain</label><input id="addr-domain" className="input" value={form.domain} onChange={e => setForm({ ...form, domain: e.target.value })} placeholder={form.addressType === "crosscode" ? "hopefamily.crosscode.co.za" : "hopefamily.co.za"} /></div>
{form.addressType !== "own_domain" && <div><label className="label" htmlFor="addr-price">Custom price (R/month)</label><input id="addr-price" className="input" inputMode="decimal" placeholder={ADDRESS_OPTIONS[form.addressType].price} value={form.custom} onChange={e => setForm({ ...form, custom: e.target.value })} /></div>}
{form.addressType === "included" && <div><label className="label" htmlFor="addr-renews">Domain renews on</label><input id="addr-renews" type="date" className="input" value={form.domainRenewsOn} onChange={e => setForm({ ...form, domainRenewsOn: e.target.value })} /></div>}
</div>
<p className="text-xs text-slate-500">{ADDRESS_OPTIONS[form.addressType].help} Charged once per invoice for all the church&apos;s products, never discounted.{form.addressType === "included" ? " You're emailed 30 days before the renewal date." : ""}</p>
{due && <p className="rounded-lg bg-amber-50 p-2 text-sm text-amber-900">{c.domain || "The domain"} is due for renewal on {day(c.domainRenewsOn)}.</p>}
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>Save address</button>
{c.addressType === "included" && c.domainRenewsOn && <button type="button" className="btn-secondary" onClick={renewed}>Renewed</button>}
</div>
</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 = 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: { 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); }
};
const sendChange = async (e: React.FormEvent) => {
e.preventDefault();
if (!change) 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", {
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><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">
{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">
<div>
<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={`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">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</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">
<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>
{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>
<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>
);
}
/** 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);
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>
<EmailList id="b-email" label="Billing email" value={form.billingEmail} onChange={billingEmail => setForm({ ...form, billingEmail })} placeholder={c.sendsTo || "accounts@church.org"} />
<p className="mt-1 text-xs text-slate-500">Invoices, statements and receipts go to every address here. Blank: the site&apos;s admin contact, then the customer&apos;s email. Now going to {c.sendsTo || "nobody (add one)"}.</p>
</div>
<div><label className="label" htmlFor="b-addr">Postal address (on invoices)</label><textarea id="b-addr" className="input" rows={2} value={form.billingAddress} onChange={e => setForm({ ...form, billingAddress: e.target.value })} /></div>
<button className="btn-secondary">Save billing details</button>
</form>
<div className="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">Address</h3>
<Address key={`${c.addressType}-${c.domain}-${c.addressCustomCents}-${c.domainRenewsOn}`} 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.addressType, c.addressCustomCents, c.licences.map(l => [l.plan, l.billedFrom, l.billedUntil, l.customMonthlyCents, l.status])])} />
</div>
</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.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>
</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>
);
}