"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; }; 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 (
setForm({ ...form, billingStart: e.target.value })} disabled={off} />
setForm({ ...form, nextInvoiceDate: e.target.value })} disabled={off} />
setForm({ ...form, reviewDate: e.target.value })} disabled={off} />

One invoice covers all the church'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't charged yet from the billing date; a product added later starts after its free month.

); } type AddressType = "own_domain" | "crosscode" | "included"; const ADDRESS_OPTIONS: Record = { 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: ".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 (
setForm({ ...form, domain: e.target.value })} placeholder={form.addressType === "crosscode" ? "hopefamily.crosscode.co.za" : "hopefamily.co.za"} />
{form.addressType !== "own_domain" &&
setForm({ ...form, custom: e.target.value })} />
} {form.addressType === "included" &&
setForm({ ...form, domainRenewsOn: e.target.value })} />
}

{ADDRESS_OPTIONS[form.addressType].help} Charged once per invoice for all the church's products, never discounted.{form.addressType === "included" ? " You're emailed 30 days before the renewal date." : ""}

{due &&

{c.domain || "The domain"} is due for renewal on {day(c.domainRenewsOn)}.

}
{c.addressType === "included" && c.domainRenewsOn && }
); } /** 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 (
{name} {licence.key} Free: comes with the church's other products, never invoiced.
); } 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 (
{name} {licence.key}{licence.url && {licence.url.replace(/^https?:\/\//, "")}}
{licence.product === "website" ? "Website" : <>Tier {licence.plan}} {licence.customMonthlyCents != null ? ` at ${money(licence.customMonthlyCents)}/month` : tier?.monthly != null ? ` (R${tier.monthly}/month)` : ""} {reportText(licence)}{suggested && suggested.name !== licence.plan ? ` → ${suggested.name} at the next review` : ""}
setForm({ ...form, billedFrom: e.target.value })} />

{licence.billedUntil ? `Invoiced up to ${day(licence.billedUntil)}.` : "Not invoiced yet."} Blank: not charged (e.g. a trial).

setForm({ ...form, custom: e.target.value })} />

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's (e.g. Network); founding churches get 35% off it.

{plans.length > 1 && !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." />
)}
); } /** The next invoice as it would be drafted now: nothing is saved. */ function NextInvoice({ customerId, version }: { customerId: string; version: string }) { const [p, setP] = useState(null); const [err, setErr] = useState(null); useEffect(() => { api(`/api/admin/billing/customers/${customerId}/preview`).then(setP).catch(e => setErr(errorText(e))); }, [customerId, version]); if (err) return

{err}

; if (!p) return null; if (!p.billed) return

Not billed: set the billing up above to see the next invoice.

; if (p.empty) return

Nothing to charge for the period from {day(p.invoice.periodStart)}: no product is charged yet.

; const inv = p.invoice; return (

For {day(inv.periodStart)} – {day(inv.periodEnd)}, drafted 14 days before {day(inv.issueDate)}. As it stands today (prices, founding, what each product reports):

{inv.lines.map((l, i) => ( ))}
{l.description}{l.quantity !== 1 ? · {l.quantity} × {money(l.unitCents)} : null} {money(l.amountCents)}
Total{money(inv.totalCents)}
{inv.planChanges.length > 0 &&

At this review: {inv.planChanges.map(pc => `${PRODUCT_NAMES[pc.product || "events"]} ${pc.from} → ${pc.to}`).join(", ")}.

} {inv.warnings.length > 0 &&
    {inv.warnings.map(w =>
  • {w}
  • )}
}
); } /** 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 })} placeholder={c.sendsTo || "accounts@church.org"} />

Invoices, statements and receipts go to every address here. Blank: the site's admin contact, then the customer's email. Now going to {c.sendsTo || "nobody (add one)"}.