"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 (
{licence.key}{licence.url && {licence.url.replace(/^https?:\/\//, "")}}
Tier {licence.plan}{licence.customMonthlyCents != null ? ` at ${money(licence.customMonthlyCents)}/month` : tier?.monthly != null ? ` (R${tier.monthly}/month)` : ""} {licence.incomeBand && 12-month income {licence.incomeBand}{suggested && suggested.name !== licence.plan ? ` → ${suggested.name} at the next review` : ""}}
setForm({ ...form, billingStart: e.target.value })} disabled={form.billingCycle === "none"} />
setForm({ ...form, nextInvoiceDate: e.target.value })} disabled={form.billingCycle === "none"} />
setForm({ ...form, reviewDate: e.target.value })} disabled={form.billingCycle === "none"} />
setForm({ ...form, custom: e.target.value })} />

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.

{!change && }
{change && (
Notice of licence change (emailed with a PDF)
setChange({ ...change, effectiveDate: e.target.value })} required />
setChange({ ...change, price: e.target.value })} />
setChange({ ...change, reason: e.target.value })} placeholder="e.g. As agreed on our call." />
)}
); } /** Customer page → Billing: founding, where invoices go, each licence's billing, statements, invoices, payments. */ export function CustomerBilling({ customerId }: { customerId: string }) { const [c, setC] = useState(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(null); const load = useCallback(() => api(`/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 ?
{msg.text}
: 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 (

Billing

{c.balanceCents > 0 ? <>Owing {money(c.balanceCents)} : "Nothing owing"}
{msg &&
{msg.text}
}
{form.founding && (
setForm({ ...form, foundingSince: e.target.value })} />
setForm({ ...form, foundingNote: e.target.value })} placeholder="e.g. Founding church 3 of 10" />
)}
setForm({ ...form, billingEmail: e.target.value })} placeholder={c.sendsTo || ""} />

Blank: the site's admin contact, then the customer's email. Now going to {c.sendsTo || "nobody (add one)"}.