This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/components/admin/LicenceTab.tsx
T

295 lines
17 KiB
TypeScript

"use client";
import React, { useCallback, useEffect, useState } from "react";
import { KeyRound, RefreshCw, ShieldCheck, ShieldAlert, ArrowUpCircle, Undo2, BellOff, BellRing, Megaphone } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { errorMessage } from "@/lib/utils";
import { apiV2Data, apiV2Raw } from "@/lib/apiV2";
export type HubStatus = {
state: "active" | "grace" | "suspended" | "revoked" | "unlicensed";
readOnly: boolean;
daysLeft: number | null;
endsAt: string | null;
graceEndsAt: string | null;
licence: { customer: string; plan: string; status: string; licenceExpiresAt: string | null; graceDays: number; issuedAt: string; validUntil: string } | null;
connected: boolean;
keyConfigured: boolean;
hubUrl: string;
lastHeartbeatAt: string | null;
lastError: string | null;
version: string;
latestVersion: string | null;
updateAvailable: boolean;
urgentUpdate: boolean;
updateSnoozed: boolean;
releases: HubRelease[];
// `outdated`: a newer version than the one asked for is out (the request can be changed to it).
updateRequest: { requestedAt: string; version: string; outdated?: boolean } | null;
notices: HubNotice[];
};
export type HubRelease = { version: string; releasedAt: string | null; urgent: boolean; notes: string };
export type HubNotice = { id: string; level: "info" | "maintenance" | "warning"; title: string; message: string; startsAt: string | null; endsAt: string | null; updatedAt: string | null };
/** Release notes from the provider: lines starting with "- " are a list, the rest paragraphs. */
export function ReleaseNotes({ notes }: { notes: string }) {
const blocks: ({ list: false; text: string } | { list: true; items: string[] })[] = [];
for (const raw of notes.split(/\r?\n/)) {
const line = raw.trim();
if (!line) continue;
const item = /^[-*•]\s+(.*)$/.exec(line);
const last = blocks[blocks.length - 1];
if (item) {
if (last?.list) last.items.push(item[1]);
else blocks.push({ list: true, items: [item[1]] });
} else blocks.push({ list: false, text: line });
}
if (!blocks.length) return <p className="text-gray-400 italic">No details given.</p>;
return (
<div className="space-y-1.5 text-gray-700">
{blocks.map((b, i) => (b.list
? <ul key={i} className="list-disc pl-5 space-y-0.5">{b.items.map((t, j) => <li key={j}>{t}</li>)}</ul>
: <p key={i}>{b.text}</p>))}
</div>
);
}
const STATE: Record<HubStatus["state"], { label: string; tone: string; text: string }> = {
active: { label: "Active", tone: "bg-green-50 text-green-800 border-green-200", text: "Everything works." },
grace: { label: "Needs renewing", tone: "bg-amber-50 text-amber-900 border-amber-200", text: "Everything still works for now — renew before the grace period ends." },
suspended: { label: "Suspended", tone: "bg-red-50 text-red-800 border-red-200", text: "Read-only: events can't be created or edited, and no new registrations or payments. Tickets still scan and all data can be exported." },
revoked: { label: "Revoked", tone: "bg-red-50 text-red-800 border-red-200", text: "Read-only: events can't be created or edited, and no new registrations or payments. Tickets still scan and all data can be exported." },
unlicensed: { label: "No licence", tone: "bg-red-50 text-red-800 border-red-200", text: "Read-only until you connect a licence key: events can't be created or edited, and no new registrations or payments." },
};
const fmt = (d: string | null) => (d ? new Date(d).toLocaleString(undefined, { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500";
/** Enter a licence key and connect. Used in Site settings → Licence and the /setup wizard. */
export function ConnectForm({ token, onConnected, compact = false }: { token: string | null; onConnected: (s: HubStatus) => void; compact?: boolean }) {
const [key, setKey] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setError(null);
try {
onConnected(await (apiV2Data("post", "/hub/connect", { authToken: token, body: { licenceKey: key } }) as Promise<HubStatus>));
setKey("");
} catch (err) {
setError(errorMessage(err) || "Could not connect.");
} finally {
setBusy(false);
}
};
return (
<form onSubmit={submit} className="space-y-2">
<label className="block text-sm font-medium text-gray-700" htmlFor="licenceKey">Licence key</label>
<div className={`flex gap-2 ${compact ? "flex-col sm:flex-row" : ""}`}>
<input id="licenceKey" className={`${inputCls} font-mono uppercase`} placeholder="CEH-XXXX-XXXX-XXXX-XXXX" value={key} onChange={e => setKey(e.target.value)} required autoComplete="off" />
<button disabled={busy || !key.trim()} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50 whitespace-nowrap">
{busy ? "Connecting…" : "Connect"}
</button>
</div>
{error && <p className="text-sm text-red-700">{error}</p>}
</form>
);
}
/** Site settings → Licence: licence state, the Hub connection, and this site's version. */
export function LicenceTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [status, setStatus] = useState<HubStatus | null>(null);
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(async () => {
if (!token) return;
try { setStatus(await (apiV2Data("get", "/hub/status", { authToken: token }) as Promise<HubStatus>)); } catch (e) { setMsg({ type: "err", text: errorMessage(e) || "Could not load the licence." }); }
}, [token]);
useEffect(() => { if (active) load(); }, [active, load]);
const checkNow = async () => {
setBusy(true);
setMsg(null);
try {
setStatus(await (apiV2Data("post", "/hub/heartbeat", { authToken: token, body: {} }) as Promise<HubStatus>));
setMsg({ type: "ok", text: "Checked with the Hub." });
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "The Hub could not be reached." });
load();
} finally {
setBusy(false);
}
};
// Request, withdraw, "Not now" and "remind me again" all return the new status.
const updateAction = async (path: string, body: unknown, ok: string) => {
setBusy(true);
setMsg(null);
try {
setStatus(await apiV2Raw<HubStatus>("post", path, { authToken: token, body: body ?? {} }));
setMsg({ type: "ok", text: ok });
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "The Hub could not be reached." });
} finally {
setBusy(false);
}
};
const requestUpdate = () => updateAction("/hub/update-request", undefined, "Update requested. Your provider has been told and will update the site.");
// Same request again: the Hub moves the open request on to the latest version.
const changeRequest = () => updateAction("/hub/update-request", undefined, `Request changed to version ${status?.latestVersion}. Your provider has been told.`);
const withdrawRequest = () => {
if (!confirm("Withdraw the update request? Your provider is told not to update the site for now.")) return;
updateAction("/hub/update-request/cancel", undefined, "Update request withdrawn. Your provider has been told.");
};
const snooze = (on: boolean) => updateAction("/hub/update-snooze", { snooze: on }, on ? "Got it — no more reminders until the next version comes out." : "Update reminders are back on.");
if (!status) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-400">Loading…</p>;
const st = STATE[status.state];
return (
<div className="space-y-5">
<div>
<h2 className="text-lg font-semibold text-gray-900">Licence</h2>
<p className="text-sm text-gray-500">This site checks in with the Cross Events Hub 30 seconds after starting and every 15 minutes after that: version, health and totals only — never anyone&apos;s personal information.</p>
</div>
<div className={`border rounded-xl p-4 ${st.tone}`}>
<div className="flex items-center gap-2 font-semibold">
{status.state === "active" ? <ShieldCheck className="w-5 h-5" /> : <ShieldAlert className="w-5 h-5" />}
{st.label}
{status.state === "grace" && status.daysLeft != null && <span className="font-normal">— {status.daysLeft} day{status.daysLeft === 1 ? "" : "s"} left</span>}
</div>
<p className="text-sm mt-1">{st.text}</p>
</div>
{!status.keyConfigured && (
<p className="text-sm text-amber-800 bg-amber-50 border border-amber-200 rounded-lg p-3">
This version has no Hub key built in yet, so it can&apos;t check licences. Update Cross Events, or set HUB_PUBLIC_KEY on the server for testing.
</p>
)}
{status.licence && (
<dl className="grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm">
<div><dt className="text-gray-500">Licensed to</dt><dd className="font-medium">{status.licence.customer}</dd></div>
<div><dt className="text-gray-500">Plan</dt><dd className="capitalize">{status.licence.plan}</dd></div>
<div><dt className="text-gray-500">Licence ends</dt><dd>{status.licence.licenceExpiresAt ? fmt(status.licence.licenceExpiresAt) : "No end date"}</dd></div>
<div><dt className="text-gray-500">Grace period</dt><dd>{status.licence.graceDays} days</dd></div>
</dl>
)}
<div className="border rounded-xl p-4 space-y-3">
<div className="flex items-center gap-2 font-medium text-gray-900"><KeyRound className="w-4 h-4" /> Hub connection</div>
<dl className="grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm">
<div><dt className="text-gray-500">Hub</dt><dd className="break-all">{status.hubUrl}</dd></div>
<div><dt className="text-gray-500">Last check-in</dt><dd>{fmt(status.lastHeartbeatAt)}</dd></div>
</dl>
{status.lastError && <p className="text-xs text-red-700 break-words">Last problem: {status.lastError}</p>}
{status.connected && (
<button onClick={checkNow} disabled={busy} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm hover:bg-gray-50 disabled:opacity-50">
<RefreshCw className={`w-4 h-4 ${busy ? "animate-spin" : ""}`} /> Check now
</button>
)}
<div className="pt-2 border-t">
<p className="text-sm text-gray-600 mb-2">{status.connected ? "New licence key, or moved to a new address? Connect again:" : "Enter the licence key you received:"}</p>
<ConnectForm token={token} onConnected={s => { setStatus(s); setMsg({ type: "ok", text: "Connected to the Hub." }); }} />
</div>
</div>
<div className="border rounded-xl p-4 text-sm">
<div className="flex items-center gap-2 font-medium text-gray-900 mb-1"><ArrowUpCircle className="w-4 h-4" /> Version</div>
<p>This site runs Cross Events <strong>{status.version}</strong>.{status.latestVersion && !status.updateAvailable && " It's up to date."}</p>
{status.updateAvailable && (
<div className="mt-2 space-y-3">
{status.urgentUpdate && (
<p className="flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 p-3 text-red-800">
<ShieldAlert className="w-4 h-4 mt-0.5 shrink-0" />
<span>This update fixes a security problem or a serious bug. Please ask for it soon.</span>
</p>
)}
{status.updateRequest ? (
<div className="space-y-2" data-testid="update-request">
<div className="flex flex-wrap items-center gap-3">
<p className="text-gray-600">
You asked for version <strong>{status.updateRequest.version}</strong> on {fmt(status.updateRequest.requestedAt)} — your provider will install it.
</p>
{status.connected && (
<button onClick={withdrawRequest} disabled={busy} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm hover:bg-gray-50 disabled:opacity-50">
<Undo2 className="w-4 h-4" /> Withdraw request
</button>
)}
</div>
{status.updateRequest.outdated && (
<div className="flex flex-wrap items-center gap-3 rounded-lg border border-brand-200 bg-brand-50 p-3">
<p className="text-brand-800">Version <strong>{status.latestVersion}</strong> has come out since. Ask for it instead, and your provider installs that one.</p>
{status.connected && (
<button onClick={changeRequest} disabled={busy} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
<ArrowUpCircle className="w-4 h-4" /> {busy ? "Working…" : `Ask for ${status.latestVersion} instead`}
</button>
)}
</div>
)}
</div>
) : (
<div className="flex flex-wrap items-center gap-3">
<p className="text-brand-700">Version {status.latestVersion} is available.{status.updateSnoozed && <span className="text-gray-500"> You chose &quot;Not now&quot;, so there are no reminders until the next version.</span>}</p>
{status.connected && (
<button onClick={requestUpdate} disabled={busy} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
<ArrowUpCircle className="w-4 h-4" /> {busy ? "Working…" : "Request update"}
</button>
)}
{!status.urgentUpdate && (status.updateSnoozed ? (
<button onClick={() => snooze(false)} disabled={busy} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm hover:bg-gray-50 disabled:opacity-50">
<BellRing className="w-4 h-4" /> Remind me again
</button>
) : (
<button onClick={() => snooze(true)} disabled={busy} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm hover:bg-gray-50 disabled:opacity-50">
<BellOff className="w-4 h-4" /> Not now
</button>
))}
</div>
)}
{status.releases.length > 0 && (
<div className="border-t pt-3">
<h3 className="font-medium text-gray-900 mb-2">What&apos;s new</h3>
<div className="space-y-4">
{status.releases.map(r => (
<div key={r.version}>
<div className="flex flex-wrap items-center gap-2 mb-1">
<span className="font-semibold">{r.version}</span>
{r.urgent && <span className="inline-flex items-center gap-1 rounded-full bg-red-50 border border-red-200 px-2 py-0.5 text-xs font-medium text-red-700"><ShieldAlert className="w-3 h-3" /> Security or urgent fix</span>}
{r.releasedAt && <span className="text-xs text-gray-500">{new Date(r.releasedAt).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" })}</span>}
</div>
<ReleaseNotes notes={r.notes} />
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
{status.notices.length > 0 && (
<div className="border rounded-xl p-4 text-sm">
<div className="flex items-center gap-2 font-medium text-gray-900 mb-2"><Megaphone className="w-4 h-4" /> From your provider</div>
<div className="space-y-3">
{status.notices.map(n => (
<div key={n.id}>
<p className="font-medium">{n.title}</p>
<p className="text-gray-700 whitespace-pre-line">{n.message}</p>
{n.endsAt && <p className="text-xs text-gray-500 mt-0.5">Until {fmt(n.endsAt)}</p>}
</div>
))}
</div>
</div>
)}
{msg && <div className={`p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
</div>
);
}