Files
events-hub/frontend/src/app/(hub)/servers/installs/[id]/page.tsx
T
joshuaandClaude Opus 5.5 dab6fbcff6 Hub 2.7.1: one click is one update
Buttons are off from the click until the Hub answers (the Updates page and
every action on an install's page); the server refuses a second update for
an install with one planned or running (ALREADY_PLANNED). Test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:15:58 +02:00

240 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { api, ApiError, errorText } from "@/lib/api";
import { ago, bytes, fmtDate } from "@/lib/format";
import { useServerPaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import type { Release } from "@/lib/types";
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = {
deployment: Deployment & { server: ServerSummary; jobs: Job[]; exports: { id: string; bytes: number; expiresAt: string; downloadedAt: string | null; deletedAt: string | null }[]; install: { version: string | null; url: string; lastHeartbeatAt: string | null } | null };
fastPanel: string;
canRemoveRecord: boolean;
};
const H = 60 * 60 * 1000;
/** One install on a server: proxy, updates, adopt, uninstall (§7–9). */
export default function DeploymentPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const warn = useSearchParams().get("warn");
const [d, setD] = useState<Detail | null>(null);
const [msg, setMsg] = useState<Msg>(warn ? { type: "err", text: warn } : null);
const [problems, setProblems] = useState<string[]>([]);
const [upd, setUpd] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, asap: true, reason: "", totp: "" });
const [adopt, setAdopt] = useState({ eventsDir: "", version: "", address: "", at: toInput(new Date(Date.now() + 5 * H)) });
const [un, setUn] = useState({ at: toInput(new Date(Date.now() + 7 * 24 * H)), totp: "", confirm: "" });
const [demo, setDemo] = useState({ profile: "events", confirm: "", markConfirm: "" });
const [releases, setReleases] = useState<Release[]>([]);
// Hub 2.6.0: every job of this install, a page at a time (it showed the last 50).
const jobsPaged = useServerPaged<Job>("/api/admin/jobs", { deploymentId: String(id) }, r => r.jobs as Job[], 20);
const load = useCallback(() => {
jobsPaged.reload();
return api<Detail>(`/api/admin/deployments/${id}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) }));
// eslint-disable-next-line react-hooks/exhaustive-deps -- reload is a fresh function each render
}, [id]);
useEffect(() => { load(); }, [load]);
useEffect(() => { api<Release[]>("/api/admin/releases").then(setReleases).catch(() => {}); }, []);
// 2.7.1: every button here is off from a click until the Hub answers, so one click is one job.
const [busy, setBusy] = useState(false);
const withBusy = async (fn: () => Promise<void>) => {
if (busy) return;
setBusy(true);
try {
await fn();
} finally {
setBusy(false);
}
};
const act = async (path: string, body: Record<string, unknown>, ok: string): Promise<void> => {
if (busy && !body.confirmLive) return;
setBusy(true);
try {
await doAct(path, body, ok);
} finally {
setBusy(false);
}
};
const doAct = async (path: string, body: Record<string, unknown>, ok: string): Promise<void> => {
setMsg(null);
try {
const r = await api<{ warnings?: string[] }>(path, { method: "POST", body });
setMsg({ type: "ok", text: `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}` });
load();
} catch (e) {
// Hub 2.7.0: an event is on there now: ask once more, then go ahead.
if (e instanceof ApiError && e.code === "LIVE_EVENT" && !body.confirmLive && window.confirm(e.message)) return doAct(path, { ...body, confirmLive: true }, ok);
setMsg({ type: "err", text: errorText(e) });
}
};
const proxyDone = () => withBusy(proxyDoneNow);
const proxyDoneNow = async () => {
setMsg(null);
try {
const r = await api<{ live: boolean; problems: string[] }>(`/api/admin/deployments/${id}/proxy-done`, { method: "POST" });
setProblems(r.problems);
setMsg(r.live ? { type: "ok", text: "Live. The site admin got the welcome email." } : { type: "err", text: "The site isn't answering as expected yet:" });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const removeRecord = () => withBusy(removeRecordNow);
const removeRecordNow = async () => {
if (!d || !window.confirm(`Remove the record of ${d.deployment.shortName}? Its install failed, so nothing of it is on the server.`)) return;
setMsg(null);
try {
await api(`/api/admin/deployments/${id}`, { method: "DELETE" });
router.push("/servers/installs");
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
if (!d) return <div><ServersNav active="/servers/installs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const x = d.deployment;
const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H;
return (
<div className="space-y-6">
<div>
<PageTitle title={`${x.customer?.name} (${x.shortName})`} subtitle={<>{x.domain} · on <Link className="text-indigo-700 hover:underline" href={`/servers/${x.serverId}`}>{x.server.name}</Link> · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} <StatusPill status={x.status} /></>} />
<ServersNav active="/servers/installs" />
<Message msg={msg} />
{/* Hub 2.6.0: whether the site has registered with the Hub (its banners, licence and heartbeats need it). */}
<p className="mt-2 text-sm text-slate-600">
{x.install
? <>Registered site: <a className="text-indigo-700 hover:underline" href={x.install.url} target="_blank" rel="noreferrer">{x.install.url}</a>, last heartbeat {x.install.lastHeartbeatAt ? ago(x.install.lastHeartbeatAt) : "never"}.</>
: <span className="text-amber-800">The site hasn&apos;t registered with the Hub yet. It registers by itself with its licence key when it starts, and is tied to this record at its first heartbeat; if that doesn&apos;t happen, check its HUB_URL and HUB_LICENCE_KEY.</span>}
</p>
{!!problems.length && <ul className="mt-2 list-disc pl-6 text-sm text-red-800">{problems.map(p => <li key={p}>{p}</li>)}</ul>}
</div>
{(x.status === "waiting_for_proxy" || x.status === "installing") && (
<div className="card">
<h2 className="font-medium">Set up the site in FastPanel</h2>
<pre className="mt-3 overflow-x-auto whitespace-pre-wrap rounded-lg bg-slate-50 p-3 text-xs">{d.fastPanel}</pre>
<button className="btn-primary mt-3" disabled={x.status !== "waiting_for_proxy" || busy} onClick={proxyDone}>Proxy done</button>
{x.status === "installing" && <p className="mt-2 text-xs text-slate-500">Waiting for the install to finish (see its job below).</p>}
</div>
)}
{x.status === "live" && (
<form className="card grid gap-3 md:grid-cols-2" onSubmit={e => { e.preventDefault(); const asap = upd.emergency && upd.asap; act("/api/admin/updates", { deploymentIds: [x.id], product: x.product, version: upd.version || undefined, at: asap ? undefined : fromInput(upd.at), asap, emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null }, asap ? "Started: the agent picks it up within a minute. The site admin was emailed and sees a banner." : "Planned. The site admin was emailed and sees a banner."); }}>
<h2 className="font-medium md:col-span-2">Schedule an update</h2>
<div>
<label className="label" htmlFor="u-v">{PRODUCT_NAMES[x.product as keyof typeof PRODUCT_NAMES] || x.product} release</label>
<select id="u-v" className="input" value={upd.version} onChange={e => setUpd({ ...upd, version: e.target.value })}>
<option value="">Latest</option>
{releases.filter(r => r.product === x.product).map(r => <option key={r.id} value={r.version}>{r.version}{r.latest ? " (latest)" : ""}{r.requires?.length ? ` · needs ${r.requires.map(q => `${PRODUCT_NAMES[q.product]} ${q.version}`).join(", ")}` : ""}</option>)}
</select>
</div>
{upd.emergency && upd.asap
? <div><span className="label">When</span><p className="mt-2 text-sm">As soon as possible: the agent starts within a minute.</p></div>
: <div><label className="label" htmlFor="u-at">When</label><input id="u-at" type="datetime-local" className="input" value={upd.at} min={toInput(new Date(Date.now() + minAt))} onChange={e => setUpd({ ...upd, at: e.target.value })} /><p className="mt-1 text-xs text-slate-500">At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.</p></div>}
<label className="flex items-center gap-2 text-sm md:col-span-2"><input type="checkbox" checked={upd.emergency} onChange={e => setUpd({ ...upd, emergency: e.target.checked })} /> Emergency (security fix or broken release): a reason and your two-factor code</label>
{upd.emergency && <>
<fieldset className="md:col-span-2 flex flex-wrap gap-4 text-sm">
<legend className="sr-only">When the emergency update runs</legend>
<label className="flex items-center gap-2"><input type="radio" name="u-when" checked={upd.asap} onChange={() => setUpd({ ...upd, asap: true })} /> As soon as possible (within a minute)</label>
<label className="flex items-center gap-2"><input type="radio" name="u-when" checked={!upd.asap} onChange={() => setUpd({ ...upd, asap: false })} /> At a time, at least 15 minutes away</label>
</fieldset>
<div><label className="label" htmlFor="u-r">Reason (shown to the church)</label><input id="u-r" className="input" required value={upd.reason} onChange={e => setUpd({ ...upd, reason: e.target.value })} /></div>
<div><label className="label" htmlFor="u-t">Two-factor code</label><input id="u-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={upd.totp} onChange={e => setUpd({ ...upd, totp: e.target.value })} /></div>
</>}
<div className="md:col-span-2"><button className="btn-primary" disabled={busy} aria-busy={busy}>{busy ? "Working…" : upd.emergency && upd.asap ? "Update now" : "Schedule"}</button></div>
</form>
)}
{x.status === "live" && x.install?.version?.startsWith("2.1.") && (
<form className="card grid gap-3 md:grid-cols-3" onSubmit={e => { e.preventDefault(); act(`/api/admin/deployments/${x.id}/adopt`, { eventsDir: adopt.eventsDir, version: adopt.version || undefined, address: adopt.address || undefined, at: fromInput(adopt.at) }, "Adopt planned. The site admin was emailed."); }}>
<h2 className="font-medium md:col-span-3">Move onto the monorepo (crosscode adopt)</h2>
<p className="text-sm text-slate-500 md:col-span-3">Moves the site from its old folder to /var/www/sites/{x.shortName}/events. Same database, uploads, .env and ports; the old folder is kept 14 days for <code>crosscode adopt {x.shortName} --undo</code>.</p>
<div><label className="label" htmlFor="a-d">The old install&apos;s folder</label><input id="a-d" className="input font-mono" required placeholder="/var/www/hope-events" value={adopt.eventsDir} onChange={e => setAdopt({ ...adopt, eventsDir: e.target.value })} /></div>
<div><label className="label" htmlFor="a-a">The church&apos;s address</label><input id="a-a" className="input" required={!x.domain.startsWith("events.")} placeholder={x.domain.startsWith("events.") ? x.domain.slice("events.".length) : "hope.co.za"} value={adopt.address} onChange={e => setAdopt({ ...adopt, address: e.target.value })} /></div>
<div><label className="label" htmlFor="a-v">Release</label><input id="a-v" className="input" placeholder="latest" value={adopt.version} onChange={e => setAdopt({ ...adopt, version: e.target.value })} /></div>
<div><label className="label" htmlFor="a-at">When</label><input id="a-at" type="datetime-local" className="input" value={adopt.at} onChange={e => setAdopt({ ...adopt, at: e.target.value })} /></div>
<div className="md:col-span-3"><button className="btn-primary" disabled={busy}>Plan the move</button></div>
</form>
)}
{x.product === "events" && ["live", "waiting_for_proxy"].includes(x.status) && (
<div className="card space-y-3">
<h2 className="font-medium">Demo site</h2>
{!x.isDemo ? (
<form className="grid gap-3 md:grid-cols-[1fr_auto] md:items-end" onSubmit={e => { e.preventDefault(); act(`/api/admin/deployments/${x.id}/demo`, { isDemo: true, confirm: demo.markConfirm }, "Marked as a demo site."); }}>
<p className="text-sm text-slate-500 md:col-span-2">A demo site&apos;s data can be replaced with demo data from here. Only mark sites used for showing Cross Events, never a church&apos;s real site.</p>
<div><label className="label" htmlFor="d-m">Type {x.shortName}</label><input id="d-m" className="input" value={demo.markConfirm} onChange={e => setDemo({ ...demo, markConfirm: e.target.value })} /></div>
<button className="btn-secondary" disabled={demo.markConfirm !== x.shortName || busy}>Mark as a demo site</button>
</form>
) : (
<>
<form className="grid gap-3 md:grid-cols-3 md:items-end" onSubmit={e => { e.preventDefault(); if (window.confirm(`Replace ALL of ${x.shortName}'s data with the "${demo.profile}" demo? A backup is taken first; one admin account is kept.`)) act(`/api/admin/deployments/${x.id}/seed-demo`, { profile: demo.profile, confirm: demo.confirm }, "Queued: the agent loads the demo data on its next poll (see Jobs below). You get an email when it's done."); }}>
<p className="text-sm text-slate-500 md:col-span-3">Replaces everything (events, people, payments) with a demo set, keeping the site settings and {x.adminEmail || "the site's first admin"}. Demo logins use the password Demo@1234.</p>
<div><label className="label" htmlFor="d-p">Demo</label>
<select id="d-p" className="input" value={demo.profile} onChange={e => setDemo({ ...demo, profile: e.target.value })}>
<option value="small">Small church: the essentials</option>
<option value="events">Events and conferences</option>
<option value="ministry">Weekly ministry: courses, kids, volunteers</option>
<option value="multicampus">Three campuses</option>
</select>
</div>
<div><label className="label" htmlFor="d-c">Type {x.shortName}</label><input id="d-c" className="input" value={demo.confirm} onChange={e => setDemo({ ...demo, confirm: e.target.value })} /></div>
<button className="btn-danger" disabled={demo.confirm !== x.shortName || busy}>Load demo data</button>
</form>
<button type="button" className="text-sm text-slate-500 underline" onClick={() => act(`/api/admin/deployments/${x.id}/demo`, { isDemo: false }, "No longer a demo site.")}>It isn&apos;t a demo site any more</button>
</>
)}
</div>
)}
<div className="card overflow-x-auto p-0">
<h2 className="px-5 pt-5 font-medium">Jobs</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="px-5 py-1">Job</th><th>When</th><th>Status</th><th>Result</th><th /></tr></thead>
<tbody>{(jobsPaged.rows ?? x.jobs).map(j => (
<tr key={j.id} className="border-t">
<td className="px-5 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td>
<td className="pr-5">{["queued", "scheduled"].includes(j.status) && <button className="btn-secondary px-2 py-1 text-xs" disabled={busy} onClick={() => act(`/api/admin/jobs/${j.id}/cancel`, {}, "Cancelled; the church was told.")}>Cancel</button>}</td>
</tr>
))}</tbody>
</table>
<Pager page={jobsPaged.page} pages={jobsPaged.pages} setPage={jobsPaged.setPage} total={jobsPaged.total} pageSize={jobsPaged.pageSize} />
</div>
{!!x.exports.length && (
<div className="card text-sm">
<h2 className="font-medium">Exports</h2>
{x.exports.map(e => <p key={e.id} className="mt-2">{e.id}: {bytes(e.bytes)}, {e.deletedAt ? `deleted ${fmtDate(e.deletedAt)}` : `until ${fmtDate(e.expiresAt)}`}{e.downloadedAt ? `, downloaded ${fmtDate(e.downloadedAt)}` : ", not downloaded yet"}</p>)}
</div>
)}
{d.canRemoveRecord && (
<div className="card border-red-200">
<h2 className="font-medium text-red-800">Remove the record</h2>
<p className="mt-1 text-sm text-slate-500">This install failed and the server already removed what it made, so there&apos;s nothing to export or uninstall. Removing the record frees the short name.</p>
<button className="btn-danger mt-3" disabled={busy} onClick={removeRecord}>Remove the record</button>
</div>
)}
{["live", "waiting_for_proxy"].includes(x.status) && (
<form className="card grid gap-3 border-red-200 md:grid-cols-3" onSubmit={e => { e.preventDefault(); if (window.confirm(`Uninstall ${x.shortName} on ${un.at.replace("T", " ")}? The church gets its data first.`)) act(`/api/admin/deployments/${x.id}/uninstall`, { at: fromInput(un.at), totp: un.totp, confirm: un.confirm }, "Uninstall planned: the site admin was emailed and sees a banner. The export runs first."); }}>
<h2 className="font-medium text-red-800 md:col-span-3">Uninstall</h2>
<p className="text-sm text-slate-500 md:col-span-3">At the time: the church&apos;s data is exported (encrypted; the link goes to the site admin), then the site, its tunnels and database are removed. The final backup stays on the server for 30 days.</p>
<div><label className="label" htmlFor="x-at">When</label><input id="x-at" type="datetime-local" className="input" value={un.at} onChange={e => setUn({ ...un, at: e.target.value })} /></div>
<div><label className="label" htmlFor="x-c">Type {x.shortName}</label><input id="x-c" className="input" required value={un.confirm} onChange={e => setUn({ ...un, confirm: e.target.value })} /></div>
<div><label className="label" htmlFor="x-t">Two-factor code</label><input id="x-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={un.totp} onChange={e => setUn({ ...un, totp: e.target.value })} /></div>
<div className="md:col-span-3"><button className="btn-danger" disabled={un.confirm !== x.shortName || busy}>Plan the uninstall</button></div>
</form>
)}
</div>
);
}