Hub 2.14.0: customer page as a summary and tabs, popups for every edit
- Customer page: header tiles (products, owing, next invoice, address, AI) and three tabs (Overview, Products, Invoices and payments), the tab in the URL; #billing links open Invoices and payments and Billing's links use ?tab=invoices. - Every add or edit is a popup (new Modal in components/ui.tsx: Esc / click outside, asks before discarding changes, focus kept inside, full screen on a phone). The page shows only read views. Record payment is a popup on Billing and the invoice page too. - One card per product: licence and billing fields in one Edit with one Save (each endpoint called only if its fields changed); suspend/revoke/reactivate/release in a ⋯ menu. Contact and billing details edited together. One page-level message. - History as one timeline with a filter; each kind on its own keeps its sortable table. - CustomerBilling.tsx split into components/customer/; plan in docs/CUSTOMER-PAGE-PLAN.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
"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 } from "@/components/ui";
|
||||
import { ModalButtons } from "./ReadCard";
|
||||
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 (
|
||||
<article className={`card space-y-2 ${revoked ? "bg-slate-50 opacity-80" : ""}`}>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<KeyRound className="h-4 w-4 text-slate-400" />
|
||||
<h3 className="font-semibold">{name}</h3>
|
||||
<code className="text-sm font-semibold tracking-wide">{licence.key}</code>
|
||||
<button type="button" className="text-xs text-indigo-600 hover:underline" onClick={() => navigator.clipboard?.writeText(licence.key)} aria-label={`Copy the ${name} key`}><Copy className="inline h-3.5 w-3.5" /> Copy</button>
|
||||
<span className="ml-auto"><Badge value={licence.status} /></span>
|
||||
</div>
|
||||
<p className="text-sm text-slate-600">
|
||||
{licence.install
|
||||
? <><Link href={`/installs/${licence.install.id}`} className="break-all text-indigo-700 hover:underline">{licence.install.url.replace(/^https?:\/\//, "")}</Link> · heartbeat {ago(licence.install.lastHeartbeatAt)}</>
|
||||
: revoked ? "Not in use." : `Not used yet: enter this key in ${KEY_WHERE[licence.product]}.`}
|
||||
</p>
|
||||
<p className="text-sm">{facts.filter(Boolean).join(" · ")}</p>
|
||||
{billed && billing && (
|
||||
<p className="text-xs text-slate-500">
|
||||
{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" : ""}
|
||||
</p>
|
||||
)}
|
||||
{licence.notes && <p className="text-sm italic text-slate-600">{licence.notes}</p>}
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 pt-1">
|
||||
<span className="mr-auto text-xs text-slate-400">Created {fmtDate(licence.createdAt, false)}</span>
|
||||
{billed && plans.length > 1 && <button type="button" className="btn-secondary" onClick={() => setOpen("notice")}>Notice of change…</button>}
|
||||
<button type="button" className="btn-secondary" onClick={() => setOpen("edit")}><Pencil className="h-3.5 w-3.5" /> Edit</button>
|
||||
<Menu label={`More actions for ${name}`} items={[
|
||||
licence.status !== "active" && { label: "Reactivate", onClick: () => 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 },
|
||||
]} />
|
||||
</div>
|
||||
{open === "edit" && <EditProduct licence={licence} billing={billed ? billing : undefined} onClose={() => setOpen(null)} onDone={done} />}
|
||||
{open === "notice" && billing && (
|
||||
<NoticeModal licence={billing} plans={plans} initialPlan={suggested && suggested.name !== licence.plan ? suggested.name : ""} nextInvoiceDate={nextInvoiceDate} onClose={() => setOpen(null)} onDone={done} />
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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<string | null>(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 (
|
||||
<Modal title={`Edit ${name}`} onClose={onClose} dirty={licChanged || billChanged}>
|
||||
<form onSubmit={save} className="space-y-4">
|
||||
<section className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-slate-700">Licence</h3>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="label" htmlFor="p-plan">Tier</label>
|
||||
{licence.product === "accounts" ? (
|
||||
<input id="p-plan" className="input" value="Included" disabled />
|
||||
) : (
|
||||
<select id="p-plan" className="input" value={lic.plan} onChange={e => setLic({ ...lic, plan: e.target.value })}>
|
||||
{!plans.includes(lic.plan) && <option value={lic.plan}>{lic.plan}</option>}
|
||||
{plans.map(p => <option key={p} value={p}>{p}</option>)}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label className="label" htmlFor="p-exp">Expires</label>
|
||||
<input id="p-exp" type="date" className="input" value={lic.expiresAt} onChange={e => setLic({ ...lic, expiresAt: e.target.value })} />
|
||||
<p className="mt-1 text-xs text-slate-500">{lic.expiresAt ? "" : "No end date"}</p>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="p-grace">Grace (days)</label><input id="p-grace" type="number" min={0} max={90} className="input" value={lic.graceDays} onChange={e => setLic({ ...lic, graceDays: e.target.value })} /></div>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">{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."}</p>
|
||||
<div><label className="label" htmlFor="p-notes">Notes</label><input id="p-notes" className="input" value={lic.notes} onChange={e => setLic({ ...lic, notes: e.target.value })} placeholder="Anything worth remembering about this licence" /></div>
|
||||
</section>
|
||||
|
||||
{billing && (
|
||||
<section className="space-y-3 border-t border-slate-200 pt-4">
|
||||
<h3 className="text-sm font-semibold text-slate-700">Billing</h3>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label" htmlFor="p-from">Charged from</label>
|
||||
<input id="p-from" type="date" className="input" value={bill.billedFrom} onChange={e => setBill({ ...bill, billedFrom: e.target.value })} />
|
||||
<p className="mt-1 text-xs text-slate-500">{billing.billedUntil ? `Invoiced up to ${day(billing.billedUntil)}.` : "Not invoiced yet."} Blank: not charged (e.g. a trial).</p>
|
||||
</div>
|
||||
<div><label className="label" htmlFor="p-custom">Custom price (R/month)</label><input id="p-custom" className="input" inputMode="decimal" placeholder="Tier price" value={bill.custom} onChange={e => setBill({ ...bill, custom: e.target.value })} /></div>
|
||||
</div>
|
||||
<p className="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's (e.g. Network); founding churches get 35% off it.</p>
|
||||
</section>
|
||||
)}
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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<string | null>(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 (
|
||||
<Modal title={`${name}: notice of licence change`} onClose={onClose} dirty={changed(change, form0)}>
|
||||
<form onSubmit={send} className="space-y-3">
|
||||
<p className="text-sm text-slate-600">Now on <strong>{licence.plan}</strong>. The notice is emailed to the church with a PDF; the tier changes on the date it takes effect.</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label" htmlFor="n-to">New tier</label>
|
||||
<select id="n-to" 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="n-eff">Takes effect</label><input id="n-eff" type="date" className="input" value={change.effectiveDate} onChange={e => setChange({ ...change, effectiveDate: e.target.value })} required /></div>
|
||||
<div className="sm:col-span-2"><label className="label" htmlFor="n-price">New price (R/month, for a custom price)</label><input id="n-price" 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="n-why">Why (printed on the notice)</label><input id="n-why" className="input" value={change.reason} onChange={e => setChange({ ...change, reason: e.target.value })} placeholder="e.g. As agreed on our call." /></div>
|
||||
<FormError error={error} />
|
||||
<ModalButtons busy={busy} onCancel={onClose} label="Send notice" />
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user