Files
events-hub/frontend/src/app/(hub)/customers/[id]/page.tsx
T
joshuaandClaude Opus 5.5 219b08538f Billing tiers on the install page, plan picker on licences (1.6.2)
- Install page shows the 12-month event-income band (Cross Events 2.0.2+),
  the tier it falls in with its price and founding price, and flags a
  licence whose plan is a different tier.
- Licence card: Plan picker (Trial or Seed to Network).
- Protocol doc: 14 income bands and eventIncome12m.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:18:02 +02:00

189 lines
10 KiB
TypeScript

"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ArrowLeft, Copy, KeyRound } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { PLANS } from "@/lib/tiers";
import type { Customer, Licence, LicenceStatus } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
const dateInput = (d: string | null) => (d ? d.slice(0, 10) : "");
/** One licence: its key, and the settings that go into the next token the install receives. */
function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({
status: licence.status,
plan: licence.plan,
expiresAt: dateInput(licence.expiresAt),
graceDays: String(licence.graceDays),
aiRand: String(licence.aiMonthlyCapCents / 100),
aiMarkup: licence.aiMarkupPercent == null ? "" : String(licence.aiMarkupPercent),
notes: licence.notes || "",
});
const [busy, setBusy] = useState(false);
const save = async () => {
if (form.status !== licence.status && form.status !== "active" && !confirm(`${form.status === "revoked" ? "Revoke" : "Suspend"} this licence? The site becomes read-only after its next heartbeat (tickets still scan, data can still be exported).`)) return;
setBusy(true);
try {
await api(`/api/admin/licences/${licence.id}`, {
method: "PUT",
body: {
status: form.status,
plan: form.plan,
// End of the chosen day, South African time.
expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null,
graceDays: form.graceDays,
aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100),
aiMarkupPercent: form.aiMarkup.trim() === "" ? null : form.aiMarkup,
notes: form.notes,
},
});
setMsg({ type: "ok", text: "Licence saved. The site picks it up with its next heartbeat (within 15 minutes)." });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
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" });
setMsg({ type: "ok", text: "Released." });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<div className="card space-y-3">
<div className="flex flex-wrap items-center gap-2">
<KeyRound className="h-4 w-4 text-slate-400" />
<code className="text-sm font-semibold tracking-wide">{licence.key}</code>
<button className="text-xs text-indigo-600 hover:underline" onClick={() => navigator.clipboard?.writeText(licence.key)} aria-label="Copy key"><Copy className="inline h-3.5 w-3.5" /> Copy</button>
<span className="ml-auto"><Badge value={licence.status} /></span>
</div>
<div className="text-sm text-slate-600">
{licence.install
? <>Used by <Link href={`/installs/${licence.install.id}`} className="text-indigo-600 hover:underline">{licence.install.url}</Link> · last heartbeat {ago(licence.install.lastHeartbeatAt)}</>
: "Not used yet — enter this key in the church's Cross Events setup (or Site settings → Licence)."}
</div>
<div className="grid gap-3 sm:grid-cols-6">
<div>
<label className="label" htmlFor={`plan-${licence.id}`}>Plan</label>
<select id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })}>
{!PLANS.includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
{PLANS.map(p => <option key={p} value={p}>{p}</option>)}
</select>
<p className="mt-1 text-xs text-slate-500">Shown on the church&apos;s Licence page. Founding discount: note it below.</p>
</div>
<div>
<label className="label">Status</label>
<select className="input" value={form.status} onChange={e => setForm({ ...form, status: e.target.value as LicenceStatus })}>
<option value="active">Active</option>
<option value="suspended">Suspended</option>
<option value="revoked">Revoked</option>
</select>
</div>
<div>
<label className="label">Expires</label>
<input type="date" className="input" value={form.expiresAt} onChange={e => setForm({ ...form, expiresAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{form.expiresAt ? "" : "No end date"}</p>
</div>
<div>
<label className="label">Grace (days)</label>
<input type="number" min={0} max={90} className="input" value={form.graceDays} onChange={e => setForm({ ...form, graceDays: e.target.value })} />
</div>
<div>
<label className="label">AI cap (R / month)</label>
<input type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">0 = off (no AI buttons). Counted in charged rand.</p>
</div>
<div>
<label className="label" htmlFor={`markup-${licence.id}`}>AI markup (%)</label>
<input id={`markup-${licence.id}`} type="number" min={0} max={500} step="1" className="input" placeholder="Default" value={form.aiMarkup} onChange={e => setForm({ ...form, aiMarkup: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">Blank uses the default (Settings → AI).</p>
</div>
</div>
<div>
<label className="label">Notes</label>
<input className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="e.g. founding church, paid annually, invoice #123" />
</div>
<div className="flex flex-wrap gap-2">
<button className="btn-primary" onClick={save} disabled={busy}>{busy ? "Saving…" : "Save licence"}</button>
{licence.install && <button className="btn-danger" onClick={release}>Release from site</button>}
<span className="self-center text-xs text-slate-400">Created {fmtDate(licence.createdAt, false)}</span>
</div>
</div>
);
}
export default function CustomerPage() {
const { id } = useParams<{ id: string }>();
const [c, setC] = useState<Customer | null>(null);
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "" });
const [newLicence, setNewLicence] = useState({ expiresAt: "", graceDays: "14" });
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => api<Customer>(`/api/admin/customers/${id}`).then(x => {
setC(x);
setForm({ name: x.name, contactName: x.contactName || "", email: x.email || "", phone: x.phone || "", notes: x.notes || "" });
}).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => { load(); }, [load]);
if (!c) return msg ? <Message msg={msg} /> : <Loading />;
const saveDetails = async (e: React.FormEvent) => {
e.preventDefault();
try {
await api(`/api/admin/customers/${id}`, { method: "PUT", body: form });
setMsg({ type: "ok", text: "Saved." });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const generate = async (e: React.FormEvent) => {
e.preventDefault();
try {
const l = await api<Licence>(`/api/admin/customers/${id}/licences`, {
method: "POST",
body: { expiresAt: newLicence.expiresAt ? `${newLicence.expiresAt}T23:59:59+02:00` : null, graceDays: newLicence.graceDays },
});
setMsg({ type: "ok", text: `Licence ${l.key} created. Send it to the church for their setup.` });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<Link href="/customers" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Customers</Link>
<PageTitle title={c.name} subtitle={`Customer since ${fmtDate(c.createdAt, false)}`} />
<div className="mb-4"><Message msg={msg} /></div>
<div className="grid gap-6 lg:grid-cols-[1fr_2fr]">
<form onSubmit={saveDetails} className="card space-y-3 self-start">
<h2 className="font-semibold">Details</h2>
<div><label className="label">Name</label><input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required /></div>
<div><label className="label">Contact person</label><input className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<div><label className="label">Email</label><input type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
<div><label className="label">Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div><label className="label">Notes</label><textarea className="input" rows={4} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Plan, billing, anything worth remembering" /></div>
<button className="btn-secondary">Save details</button>
</form>
<div className="space-y-4">
<h2 className="font-semibold">Licences</h2>
{c.licences.map(l => <LicenceCard key={`${l.id}-${l.status}-${l.expiresAt}`} licence={l} onSaved={load} setMsg={setMsg} />)}
<form onSubmit={generate} className="card flex flex-wrap items-end gap-3">
<div><label className="label">Expires (optional)</label><input type="date" className="input" value={newLicence.expiresAt} onChange={e => setNewLicence({ ...newLicence, expiresAt: e.target.value })} /></div>
<div><label className="label">Grace (days)</label><input type="number" min={0} max={90} className="input w-24" value={newLicence.graceDays} onChange={e => setNewLicence({ ...newLicence, graceDays: e.target.value })} /></div>
<button className="btn-primary"><KeyRound className="h-4 w-4" /> Generate licence</button>
</form>
</div>
</div>
</>
);
}