"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?:\/\//, "")}}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.
Generate a licence first.
: c.licences.map(l =>No invoices yet.
: (| Invoice | Date | Tier | Total | Balance | State |
|---|---|---|---|---|---|
| {i.number} | {day(i.issueDate)} | {i.plan || "One-off"}{i.planChange ? ` (from ${i.planChange.from})` : ""} | {money(i.totalCents)} | {i.status === "sent" ? money(i.balanceCents) : "—"} |
None yet.
: c.payments.map(p => (None yet.
: c.licenceChanges.map(ch => (None yet.
: (| {fmtDate(e.sentAt)} | {EMAIL_KIND[e.kind] || e.kind} | {e.subject} to {e.to} |
{e.error ? `Failed: ${e.error}` : "Sent"} |