Files
events-hub/frontend/src/app/(hub)/servers/installs/page.tsx
T
joshuaandClaude Opus 5.5 3a00271a02 Hub 2.12.0: one product uninstalled at a time, stale installs removed, customers archived
- Uninstalls name the product (agent 1.5.0); a whole-church uninstall marks every product
  of the church on that server removed. Older agents are refused while the church has others.
- A second product's uninstall joins one already planned (one export and one uninstall) or
  gets its own time; the last product removes the whole church. Accounts goes last.
- Remove an install from the Hub after 24 hours without a heartbeat (POST .../forget).
- Archive and restore customers (migration 20261123090000_customer_archive).
- Several addresses for a customer's email and billing email, with a + button.
- Statements show R0 invoices' amounts. Vendors contracts 1.16.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:17:35 +02:00

175 lines
14 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, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Link2, Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import { Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
import { ServersNav, StatusPill, pct, shownStatus, type Deployment, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Customer = { id: string; name: string; domain?: string | null };
type InstallRow = { id: string; name: string; url: string; customer: { id: string; name: string } | null; version: string | null };
const emptyNew = { product: "events", customerId: "", serverId: "", shortName: "", domain: "", accountsDomain: "", timezone: "", adminName: "", adminEmail: "", version: "" };
const emptyLink = { installId: "", serverId: "", shortName: "", webPort: "", apiPort: "" };
/** Installs on servers: New install (§7) and linking existing installs (§14). */
export default function InstallsPage() {
const router = useRouter();
const [list, setList] = useState<Deployment[] | null>(null);
// Hub 2.6.0: which product each install is, a filter for it, a search, and a page at a time.
const [product, setProduct] = useState("");
const [query, setQuery] = useState("");
const shown = useMemo(() => (list || []).filter(d => (!product || d.product === product) && matches(query, d.customer?.name, d.shortName, d.domain, d.server?.name)), [list, product, query]);
const paged = usePaged(shown, `${product}|${query}`);
const [srv, setSrv] = useState<ServerSummary[]>([]);
const [customers, setCustomers] = useState<Customer[]>([]);
const [installs, setInstalls] = useState<InstallRow[]>([]);
const [mode, setMode] = useState<"none" | "new" | "link">("none");
const [form, setForm] = useState(emptyNew);
const [link, setLink] = useState(emptyLink);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(() => {
api<{ deployments: Deployment[] }>("/api/admin/deployments").then(r => setList(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setSrv(r.servers.filter(s => s.mode === "church"))).catch(() => {});
}, []);
useEffect(() => { load(); }, [load]);
useEffect(() => {
if (mode === "new" && !customers.length) api<Customer[]>("/api/admin/customers").then(setCustomers).catch(() => {});
if (mode === "link" && !installs.length) api<InstallRow[]>("/api/admin/installs").then(setInstalls).catch(() => {});
}, [mode, customers.length, installs.length]);
const submitNew = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setMsg(null);
try {
const r = await api<{ deployment: Deployment; warnings: string[]; checkingPorts?: boolean; alsoInstalling?: { product: string; domain: string; version: string } }>("/api/admin/deployments", { method: "POST", body: { ...form, version: form.version || undefined, accountsDomain: form.accountsDomain || undefined } });
// Hub 2.5.0: Cross Events 3.x for a church without Accounts installs Accounts first.
const notes = [
// Hub 2.11.0: the ports are checked on the central server and this one first.
...(r.checkingPorts ? ["The ports are being checked on the central server and this server first; the install starts on ports free on both (about a minute)."] : []),
...(r.alsoInstalling ? [`Accounts ${r.alsoInstalling.version} is installed first at ${r.alsoInstalling.domain}; Cross Events follows when it has finished.`] : []),
...r.warnings,
];
router.push(`/servers/installs/${r.deployment.id}${notes.length ? `?warn=${encodeURIComponent(notes.join(" "))}` : ""}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setBusy(false);
};
const submitLink = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setMsg(null);
try {
const r = await api<{ deployment: Deployment }>("/api/admin/deployments/link", { method: "POST", body: link });
router.push(`/servers/installs/${r.deployment.id}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setBusy(false);
};
const f = (k: keyof typeof emptyNew) => ({ value: form[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setForm({ ...form, [k]: e.target.value }) });
const l = (k: keyof typeof emptyLink) => ({ value: link[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setLink({ ...link, [k]: e.target.value }) });
return (
<div>
<PageTitle title="Installs on servers" subtitle="Sites the Hub installs, updates and uninstalls through each server's agent."
actions={<div className="flex gap-2"><button className="btn-secondary" onClick={() => setMode("link")}><Link2 className="h-4 w-4" /> Link existing</button><button className="btn-primary" onClick={() => setMode("new")}><Plus className="h-4 w-4" /> New install</button></div>} />
<ServersNav active="/servers/installs" />
<Message msg={msg} />
{mode === "new" && (
<form onSubmit={submitNew} className="card mb-6 grid gap-3 md:grid-cols-2">
<h2 className="font-medium md:col-span-2">New install</h2>
<div className="md:col-span-2">
<label className="label" htmlFor="n-product">Product</label>
<select id="n-product" className="input" {...f("product")}>
<option value="events">Cross Events</option>
<option value="accounts">Accounts (the church&apos;s sign-in)</option>
</select>
<p className="mt-1 text-xs text-slate-500">
{form.product === "accounts"
? "Install Accounts before the Website, the App or Cross Events 3.0. Use the church's short name to add it next to its Events on the same server."
: "A church that already has a product here keeps its short name: the new one is added next to it on the same server."}
</p>
</div>
<div><label className="label" htmlFor="n-cust">Customer</label><select id="n-cust" className="input" required {...f("customerId")}><option value="">Choose…</option>{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select></div>
<div><label className="label" htmlFor="n-short">Short name</label><input id="n-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...f("shortName")} /><p className="mt-1 text-xs text-slate-500">Folders, database and tunnels: a-z, 0-9 and -.</p></div>
<div><label className="label" htmlFor="n-domain">Domain</label><input id="n-domain" className="input" required placeholder={form.product === "accounts" ? "accounts.hope.co.za" : "events.hope.co.za"} {...f("domain")} /></div>
{form.product === "events" && (
<div><label className="label" htmlFor="n-acc">Accounts domain</label><input id="n-acc" className="input" placeholder={form.domain ? form.domain.replace(/^[^.]+./, "accounts.") : "accounts.hope.co.za"} {...f("accountsDomain")} /><p className="mt-1 text-xs text-slate-500">Cross Events 3 signs in through the church&apos;s Accounts: a church without it gets it installed first, here.</p></div>
)}
<div><label className="label" htmlFor="n-tz">Time zone</label><input id="n-tz" className="input" placeholder="Africa/Johannesburg" {...f("timezone")} /></div>
<div><label className="label" htmlFor="n-an">Site admin name</label><input id="n-an" className="input" {...f("adminName")} /></div>
<div><label className="label" htmlFor="n-ae">Site admin email</label><input id="n-ae" type="email" className="input" {...f("adminEmail")} /><p className="mt-1 text-xs text-slate-500">Gets the welcome email and update notices.</p></div>
<div className="md:col-span-2">
<span className="label">Server</span>
<div className="grid gap-2 md:grid-cols-2">
{srv.map(s => {
const low = (s.ram?.availableBytes ?? 0) < 1.5 * 1024 ** 3;
return (
<label key={s.id} className={`flex cursor-pointer gap-2 rounded-lg border p-3 text-sm ${form.serverId === s.id ? "border-indigo-500 bg-indigo-50" : "border-slate-200"}`}>
<input type="radio" name="server" value={s.id} checked={form.serverId === s.id} onChange={() => setForm({ ...form, serverId: s.id })} disabled={!s.online} />
<span>
<span className="font-medium">{s.name}</span> <StatusPill status={s.busy ? "busy" : s.online ? "online" : "offline"} />
<span className="block text-xs text-slate-500">RAM free {s.ram ? `${(s.ram.availableBytes / 1024 ** 3).toFixed(1)} GB` : "?"} · CPU day avg {pct(s.lastDay?.cpuAvg)} · disk {pct(s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0))} · {s.deployments ?? 0} site(s)</span>
{low && <span className="block text-xs font-medium text-amber-800">Not recommended: under 1.5 GB RAM free</span>}
</span>
</label>
);
})}
</div>
</div>
<div><label className="label" htmlFor="n-ver">Release</label><input id="n-ver" className="input" placeholder="latest" {...f("version")} /></div>
<div className="flex items-end gap-2 md:col-span-2">
<button className="btn-primary" disabled={busy || !form.serverId}>{busy ? "Starting…" : "Install"}</button>
<button type="button" className="btn-secondary" onClick={() => setMode("none")}>Cancel</button>
<p className="text-xs text-slate-500">The Hub makes the licence, picks two ports, and the agent installs within a minute. You get the report and the FastPanel steps by email.</p>
</div>
</form>
)}
{mode === "link" && (
<form onSubmit={submitLink} className="card mb-6 grid gap-3 md:grid-cols-2">
<h2 className="font-medium md:col-span-2">Link an install that&apos;s already on a server</h2>
<p className="text-sm text-slate-500 md:col-span-2">For sites installed by hand or moved with <code>crosscode adopt</code>. Nothing on the server changes; the Hub records the server, folder name and ports (see the server&apos;s church.env and frpc.ini).</p>
<div><label className="label" htmlFor="l-inst">Install</label><select id="l-inst" className="input" required {...l("installId")}><option value="">Choose…</option>{installs.map(i => <option key={i.id} value={i.id}>{i.customer?.name || i.name} ({i.url})</option>)}</select></div>
<div><label className="label" htmlFor="l-srv">Server</label><select id="l-srv" className="input" required {...l("serverId")}><option value="">Choose…</option>{srv.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</select></div>
<div><label className="label" htmlFor="l-short">Short name</label><input id="l-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...l("shortName")} /><p className="mt-1 text-xs text-slate-500">Just the name, not a path: its folder is /var/www/sites/&lt;name&gt;. A site still in an old folder (/var/www/hope-events) gets that name when you move it onto the monorepo.</p></div>
<div className="grid grid-cols-2 gap-2">
<div><label className="label" htmlFor="l-web">Web port</label><input id="l-web" className="input" required inputMode="numeric" {...l("webPort")} /></div>
<div><label className="label" htmlFor="l-api">API port</label><input id="l-api" className="input" required inputMode="numeric" {...l("apiPort")} /></div>
</div>
<div className="flex gap-2 md:col-span-2"><button className="btn-primary" disabled={busy}>Link</button><button type="button" className="btn-secondary" onClick={() => setMode("none")}>Cancel</button></div>
</form>
)}
{!list ? <Loading /> : (
<div className="card overflow-x-auto p-0">
<div className="flex flex-wrap gap-2 p-4">
<select className="input w-48" aria-label="Product" value={product} onChange={e => setProduct(e.target.value)}>
<option value="">Every product</option>
<option value="events">{PRODUCT_NAMES.events}</option>
<option value="accounts">{PRODUCT_NAMES.accounts}</option>
</select>
<SearchInput className="w-full sm:w-72" value={query} onChange={setQuery} placeholder="Search a church, domain or server" />
</div>
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="px-4 py-1">Church</th><th>Product</th><th>Domain</th><th>Server</th><th>Version</th><th>Last heartbeat</th><th>Status</th></tr></thead>
<tbody>{paged.rows.map(d => (
<tr key={d.id} className="border-t"><td className="px-4 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${d.id}`}>{d.customer?.name} ({d.shortName})</Link>{d.isDemo && <span className="ml-1 rounded bg-sky-100 px-1.5 text-xs text-sky-800">demo</span>}</td><td>{PRODUCT_NAMES[d.product as keyof typeof PRODUCT_NAMES] || d.product}</td><td>{d.domain}</td><td>{d.server?.name}</td><td>{d.install?.version || d.version || "–"}</td><td>{d.installId ? ago(d.install?.lastHeartbeatAt) : <span className="text-amber-800">not registered</span>}</td><td><StatusPill status={shownStatus(d)} /></td></tr>
))}</tbody>
</table>
{!list.length ? <p className="px-4 py-3 text-sm text-slate-500">No installs on servers yet.</p> : !shown.length && <p className="px-4 py-3 text-sm text-slate-500">No installs match.</p>}
<Pager {...paged} />
</div>
)}
</div>
);
}