"use client"; import React, { useState } from "react"; import Link from "next/link"; import { Copy, KeyRound, Pencil } from "lucide-react"; import { api, errorText } from "@/lib/api"; import { centsFrom, day, money, randInput, todayYmd, type LicenceChange } from "@/lib/billing"; import { ago, fmtDate } from "@/lib/format"; import { KEY_WHERE, PRODUCT_NAMES } from "@/lib/products"; import { PLANS_BY_PRODUCT } from "@/lib/tiers"; import type { Licence, LicenceStatus } from "@/lib/types"; import { Badge, FormError, Menu, Modal, ModalButtons } from "@/components/ui"; import { changed, dateInput, endOfDay, reportText, suggestedTier, type BillingLicence, type Done, type Plan } from "./shared"; const HEARTBEAT = "The site picks it up with its next heartbeat (within 15 minutes)."; /** * Hub 2.14.0: one card per product, joining what used to be two: the licence (tier, expiry, grace, * notes) and its billing (charged from, custom price). Suspend, revoke and release are in the ⋯ menu. */ export function ProductCard({ licence, billing, plans, nextInvoiceDate, onDone }: { licence: Licence; billing: BillingLicence | undefined; plans: Plan[]; nextInvoiceDate: string | null; onDone: Done; }) { const [open, setOpen] = useState<"edit" | "notice" | null>(null); const name = PRODUCT_NAMES[licence.product]; const revoked = licence.status === "revoked"; const billed = !!billing?.billable && !revoked; const tier = plans.find(t => t.name === licence.plan); const suggested = billing && billed ? suggestedTier(billing, plans) : null; const done: Done = m => { setOpen(null); onDone(m); }; const setStatus = async (status: LicenceStatus) => { const text = status === "active" ? `Reactivate this ${name} licence?` : `${status === "revoked" ? "Revoke" : "Suspend"} this ${name} licence? The site becomes read-only after its next heartbeat (tickets still scan, data can still be exported).`; if (!confirm(text)) return; try { await api(`/api/admin/licences/${licence.id}`, { method: "PUT", body: { status } }); onDone({ type: "ok", text: `${name}: ${status === "active" ? "active again" : status}. ${HEARTBEAT}` }); } catch (e) { onDone({ type: "err", text: errorText(e) }); } }; const release = async () => { if (!confirm("Release this licence from its site? The site's heartbeats are refused from now on, and the key can be registered again from a new address.")) return; try { await api(`/api/admin/licences/${licence.id}/release`, { method: "POST" }); onDone({ type: "ok", text: `${name}: released from ${licence.install?.url}.` }); } catch (e) { onDone({ type: "err", text: errorText(e) }); } }; const price = billing?.customMonthlyCents != null ? `${money(billing.customMonthlyCents)}/month (custom)` : tier?.monthly != null ? `R${tier.monthly}/month` : null; const facts = licence.product === "accounts" ? ["Free: comes with the church's other products"] : [ licence.product === "website" ? "Website" : `Tier ${licence.plan}`, price, billed ? (billing?.billedFrom ? `charged from ${day(billing.billedFrom)}` : "not charged") : null, ]; facts.push(licence.expiresAt ? `expires ${fmtDate(licence.expiresAt, false)}` : "expires never", `grace ${licence.graceDays} days`); return (

{name}

{licence.key}

{licence.install ? <>{licence.install.url.replace(/^https?:\/\//, "")} · heartbeat {ago(licence.install.lastHeartbeatAt)} : revoked ? "Not in use." : `Not used yet: enter this key in ${KEY_WHERE[licence.product]}.`}

{facts.filter(Boolean).join(" · ")}

{billed && billing && (

{reportText(billing)}{suggested && suggested.name !== licence.plan ? ` → ${suggested.name} at the next review` : ""} {billing.billedUntil ? ` · invoiced up to ${day(billing.billedUntil)}` : billing.billedFrom ? " · not invoiced yet" : ""}

)} {licence.notes &&

{licence.notes}

}
Created {fmtDate(licence.createdAt, false)} {billed && plans.length > 1 && } setStatus("active") }, licence.status === "active" && { label: "Suspend…", onClick: () => setStatus("suspended"), danger: true }, !revoked && { label: "Revoke…", onClick: () => setStatus("revoked"), danger: true }, !!licence.install && { label: "Release from site…", onClick: release, danger: true }, ]} />
{open === "edit" && setOpen(null)} onDone={done} />} {open === "notice" && billing && ( setOpen(null)} onDone={done} /> )}
); } /** One popup, one Save: the licence fields and the billing fields, each sent only if changed. */ function EditProduct({ licence, billing, onClose, onDone }: { licence: Licence; billing: BillingLicence | undefined; onClose: () => void; onDone: Done }) { const lic0 = { plan: licence.plan, expiresAt: dateInput(licence.expiresAt), graceDays: String(licence.graceDays), notes: licence.notes || "" }; const bill0 = { billedFrom: billing?.billedFrom || "", custom: randInput(billing?.customMonthlyCents) }; const [lic, setLic] = useState(lic0); const [bill, setBill] = useState(bill0); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const name = PRODUCT_NAMES[licence.product]; const plans = PLANS_BY_PRODUCT[licence.product]; const licChanged = changed(lic, lic0); const billChanged = !!billing && changed(bill, bill0); const save = async (e: React.FormEvent) => { e.preventDefault(); if (!licChanged && !billChanged) { onClose(); return; } setBusy(true); setError(null); try { const said: string[] = []; if (licChanged) { await api(`/api/admin/licences/${licence.id}`, { method: "PUT", body: { plan: lic.plan, expiresAt: endOfDay(lic.expiresAt), graceDays: lic.graceDays, notes: lic.notes } }); said.push(`Licence saved. ${HEARTBEAT}`); } if (billChanged && billing) { await api(`/api/admin/billing/licences/${billing.id}`, { method: "PUT", body: { billedFrom: bill.billedFrom || null, customMonthlyCents: bill.custom.trim() ? centsFrom(bill.custom) : null } }); said.push(bill.billedFrom ? `Charged from ${day(bill.billedFrom)}.` : "Not charged."); } onDone({ type: "ok", text: `${name}: ${said.join(" ")}` }); } catch (err) { setError(errorText(err)); } finally { setBusy(false); } }; return (

Licence

{licence.product === "accounts" ? ( ) : ( )}
setLic({ ...lic, expiresAt: e.target.value })} />

{lic.expiresAt ? "" : "No end date"}

setLic({ ...lic, graceDays: e.target.value })} />

{licence.product === "accounts" ? "Free: comes with the church's other products." : "The tier is shown on the church's Licence page and priced on its invoices."}

setLic({ ...lic, notes: e.target.value })} placeholder="Anything worth remembering about this licence" />
{billing && (

Billing

setBill({ ...bill, billedFrom: e.target.value })} />

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

setBill({ ...bill, 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.

)}
); } /** A notice of licence change, emailed to the church with a PDF. */ function NoticeModal({ licence, plans, initialPlan, nextInvoiceDate, onClose, onDone }: { licence: BillingLicence; plans: Plan[]; initialPlan: string; nextInvoiceDate: string | null; onClose: () => void; onDone: Done; }) { const form0 = { toPlan: initialPlan, effectiveDate: nextInvoiceDate || todayYmd(), price: "", reason: "" }; const [change, setChange] = useState(form0); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const name = PRODUCT_NAMES[licence.product]; const send = async (e: React.FormEvent) => { e.preventDefault(); if (!confirm(`Email ${name}: ${licence.plan} → ${change.toPlan} from ${day(change.effectiveDate)} to the church now?`)) return; setBusy(true); setError(null); 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 }, }); onDone({ 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}` }); } catch (err) { setError(errorText(err)); } finally { setBusy(false); } }; return (

Now on {licence.plan}. The notice is emailed to the church with a PDF; the tier changes on the date it takes effect.

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." />
); }