- Server page: Configuration is a read view with an Edit popup; Update agent is a popup. - frp config: the file shows read-only; Edit opens it in a popup with Restart, the two-factor code and Save on the server (its confirmation unchanged). - Ports & defaults: install defaults, port range and central IP as a read view with an Edit popup; Mark as taken is a popup from the port list. - Install page (/installs/[id]): Clear public key is a popup with the two-factor code; the notes are a read view with an Edit popup; the page message is under the header. - Invoice: always the read view; Edit (draft, approved) opens a popup, so Approve no longer needs a save first. Void and Refund are popups instead of prompt(). - docs/POPUPS-PLAN.md done. Frontend only: no migration, no API changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
207 lines
14 KiB
TypeScript
207 lines
14 KiB
TypeScript
"use client";
|
||
|
||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||
import Link from "next/link";
|
||
import { useParams, useRouter } from "next/navigation";
|
||
import { Plus, Trash2, Upload } from "lucide-react";
|
||
import { api, errorText } from "@/lib/api";
|
||
import { ago, bytes, fmtDate } from "@/lib/format";
|
||
import { useServerPaged } from "@/lib/paging";
|
||
import { Field, Fields, FormError, Loading, Message, Modal, ModalButtons, PageMessage, PageTitle, Pager, ReadCard, useSubmit } from "@/components/ui";
|
||
import { PercentChart, ServersNav, StatusPill, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers";
|
||
import { FrpConfig, type FrpState } from "@/components/FrpConfig";
|
||
|
||
type Msg = { type: "ok" | "err"; text: string } | null;
|
||
type Detail = {
|
||
server: ServerSummary;
|
||
config: Record<string, string>;
|
||
processes: { name: string; church: string | null; product: string | null; status: string; memoryBytes: number; cpuPercent: number; restarts: number; uptimeSeconds: number }[];
|
||
stats: { at: string; cpuPercent: number; cpuPeak: number; ramUsedPercent: number; ramPeak: number; diskUsedPercent: number }[];
|
||
deployments: (Deployment & { customer: { id: string; name: string } })[];
|
||
jobs: Job[];
|
||
alerts: { id: string; type: string; level: string; message: string; createdAt: string; resolvedAt: string | null }[];
|
||
ports: { port: number; role: string; note: string | null; releasedAt: string | null }[];
|
||
frp: FrpState;
|
||
};
|
||
|
||
/** The settings a church server's jobs need (§5); others can be added. */
|
||
const SUGGESTED: { key: string; hint: string }[] = [
|
||
{ key: "TRUST_PROXY", hint: "Behind frp: loopback (lowercase; checked when saved)" },
|
||
{ key: "DB_HOST", hint: "The PostgreSQL server the sites use (default localhost)" },
|
||
{ key: "DB_PORT", hint: "Default 5432" },
|
||
{ key: "DB_ADMIN_URL", hint: "postgresql://admin:…@host/postgres: may create databases and roles. Blank: the local PostgreSQL via sudo -u postgres" },
|
||
];
|
||
|
||
/** The keys a church server's configuration shows: the suggested ones, then any others it has. */
|
||
const configKeys = (config: Record<string, string>) => [...new Set([...SUGGESTED.map(x => x.key), ...Object.keys(config)])];
|
||
|
||
/** Hub 2.17.0: the server's configuration, edited in a popup. */
|
||
function ConfigModal({ id, config, onClose, onSaved }: { id: string; config: Record<string, string>; onClose: () => void; onSaved: (text: string) => void }) {
|
||
const initial = useMemo<[string, string][]>(() => configKeys(config).map(k => [k, config[k] ?? (k === "TRUST_PROXY" ? "loopback" : "")]), [config]);
|
||
const [rows, setRows] = useState(initial);
|
||
const { busy, error, run } = useSubmit();
|
||
const set = (i: number, j: 0 | 1, v: string) => setRows(rows.map((r, n) => (n === i ? (j === 0 ? [v.toUpperCase(), r[1]] : [r[0], v]) : r)));
|
||
const save = (e: React.FormEvent) => {
|
||
e.preventDefault();
|
||
run(async () => {
|
||
await api(`/api/admin/servers/${id}/config`, { method: "PUT", body: { values: Object.fromEntries(rows.filter(r => r[0].trim())) } });
|
||
onSaved("Configuration saved. Jobs from now on carry it, sealed to this server's key.");
|
||
});
|
||
};
|
||
return (
|
||
<Modal title="Configuration" onClose={onClose} dirty={JSON.stringify(rows) !== JSON.stringify(initial)} wide>
|
||
<form onSubmit={save} className="space-y-3">
|
||
<p className="text-sm text-slate-500">Values ending in _URL, KEY, SECRET or PASSWORD show as dots: leave them to keep them.</p>
|
||
<div className="space-y-2">
|
||
{rows.map(([k, v], i) => (
|
||
<div key={i} className="grid gap-2 sm:grid-cols-[12rem_1fr_auto]">
|
||
<input className="input font-mono" value={k} onChange={e => set(i, 0, e.target.value)} placeholder="NAME" aria-label="Name" />
|
||
<input className="input font-mono" value={v} onChange={e => set(i, 1, e.target.value)} placeholder={SUGGESTED.find(x => x.key === k)?.hint || "value"} aria-label={`${k} value`} />
|
||
<button type="button" className="btn-secondary" onClick={() => setRows(rows.filter((_, n) => n !== i))} aria-label={`Remove ${k}`}><Trash2 className="h-4 w-4" /></button>
|
||
</div>
|
||
))}
|
||
</div>
|
||
<button type="button" className="btn-secondary" onClick={() => setRows([...rows, ["", ""]])}><Plus className="h-4 w-4" /> Add a setting</button>
|
||
<FormError error={error} />
|
||
<ModalButtons busy={busy} onCancel={onClose} />
|
||
</form>
|
||
</Modal>
|
||
);
|
||
}
|
||
|
||
/** Hub 2.17.0: Update agent in a popup; queuing it opens the job. */
|
||
function UpdateAgentModal({ current, onClose, queue }: { current: string | null; onClose: () => void; queue: (version: string) => Promise<void> }) {
|
||
const [version, setVersion] = useState("");
|
||
const { busy, error, run } = useSubmit();
|
||
return (
|
||
<Modal title="Update agent" onClose={onClose} dirty={version.trim() !== ""}>
|
||
<form onSubmit={e => { e.preventDefault(); run(() => queue(version.trim())); }} className="space-y-3">
|
||
<p className="text-sm text-slate-600">The agent here is {current || "an unknown version"}. The new version is queued as a job on this server.</p>
|
||
<div><label className="label" htmlFor="agent-version">Version</label><input id="agent-version" className="input font-mono" placeholder="agent@1.0.1" value={version} onChange={e => setVersion(e.target.value)} required /></div>
|
||
<FormError error={error} />
|
||
<ModalButtons busy={busy} onCancel={onClose} label="Update agent" busyLabel="Queuing…" />
|
||
</form>
|
||
</Modal>
|
||
);
|
||
}
|
||
|
||
export default function ServerPage() {
|
||
const { id } = useParams<{ id: string }>();
|
||
const router = useRouter();
|
||
const [d, setD] = useState<Detail | null>(null);
|
||
// Hub 2.6.0: every job on this server, a page at a time (it showed the last 25).
|
||
const jobsPaged = useServerPaged<Job>("/api/admin/jobs", { serverId: String(id) }, r => r.jobs as Job[], 20);
|
||
const [range, setRange] = useState<"24h" | "7d" | "90d">("24h");
|
||
const [msg, setMsg] = useState<Msg>(null);
|
||
// Hub 2.17.0: the popup that's open.
|
||
const [popup, setPopup] = useState<"config" | "agent" | null>(null);
|
||
|
||
const load = useCallback(() => api<Detail>(`/api/admin/servers/${id}?range=${range}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id, range]);
|
||
useEffect(() => { load(); }, [load]);
|
||
|
||
/** Queues a job and opens it; throws when the Hub refuses, for a popup to show. */
|
||
const queue = async (type: string, args: Record<string, unknown> = {}) => {
|
||
const r = await api<{ job: Job }>(`/api/admin/servers/${id}/jobs`, { method: "POST", body: { type, args } });
|
||
setMsg({ type: "ok", text: `Queued: the agent picks it up within 30 seconds.` });
|
||
router.push(`/jobs/${r.job.id}`);
|
||
};
|
||
const job = (type: string) => { setMsg(null); queue(type).catch(e => setMsg({ type: "err", text: errorText(e) })); };
|
||
const remove = async () => {
|
||
if (!d || !window.confirm(`Remove ${d.server.name} from the Hub? Its agent stops getting jobs. (Uninstall the agent on the server too.)`)) return;
|
||
try { await api(`/api/admin/servers/${id}`, { method: "DELETE" }); router.push("/servers"); } catch (e) { setMsg({ type: "err", text: errorText(e) }); }
|
||
};
|
||
|
||
if (!d) return <div><ServersNav active="/servers" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
|
||
const s = d.server;
|
||
return (
|
||
<div className="space-y-6">
|
||
<div>
|
||
<PageTitle title={s.name} subtitle={<>{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname} · agent {s.agentVersion} · last heard {ago(s.lastSeenAt)} <StatusPill status={s.busy ? "busy" : s.online ? "online" : "offline"} /></>} />
|
||
<ServersNav active="/servers" />
|
||
<PageMessage msg={msg} onClose={() => setMsg(null)} />
|
||
</div>
|
||
|
||
{!!d.alerts.filter(a => !a.resolvedAt).length && (
|
||
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
|
||
{d.alerts.filter(a => !a.resolvedAt).map(a => <div key={a.id}>⚠ {a.message} <span className="text-xs">(since {fmtDate(a.createdAt)})</span></div>)}
|
||
</div>
|
||
)}
|
||
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
{(["24h", "7d", "90d"] as const).map(r => <button key={r} className={range === r ? "btn-primary" : "btn-secondary"} onClick={() => setRange(r)}>{r === "24h" ? "24 hours" : r === "7d" ? "7 days" : "90 days"}</button>)}
|
||
</div>
|
||
<div className="grid gap-4 lg:grid-cols-2">
|
||
<PercentChart title="CPU" points={d.stats.map(p => ({ at: p.at, value: p.cpuPercent, peak: p.cpuPeak }))} />
|
||
<PercentChart title="RAM used" points={d.stats.map(p => ({ at: p.at, value: p.ramUsedPercent, peak: p.ramPeak }))} />
|
||
</div>
|
||
|
||
<div className="grid gap-4 md:grid-cols-3">
|
||
<div className="card text-sm">
|
||
<h2 className="font-medium">Resources now</h2>
|
||
<p className="mt-2">RAM {pct(s.ram?.usedPercent)} used, {bytes(s.ram?.availableBytes)} free of {bytes(s.ram?.totalBytes)}</p>
|
||
<p>CPU {pct(s.cpu?.percent)} · load {s.cpu?.load1?.toFixed(2)} on {s.cpu?.cores} cores</p>
|
||
{s.disk.map(x => <p key={x.mount}>Disk {x.mount}: {pct((x.usedBytes / Math.max(1, x.totalBytes)) * 100)} used, {bytes(x.freeBytes)} free</p>)}
|
||
</div>
|
||
<div className="card text-sm">
|
||
<h2 className="font-medium">Versions</h2>
|
||
<p className="mt-2">{s.versions?.os}</p>
|
||
<p>Node {s.versions?.node} · PostgreSQL {s.versions?.postgres || "–"} · frpc {s.versions?.frpc || "–"}</p>
|
||
{s.mode === "church" && <p>frpc {s.frpcRunning === null ? "unknown" : s.frpcRunning ? "running" : <b className="text-red-700">not running</b>}</p>}
|
||
{s.frpConfigPath !== undefined && <p>{s.mode === "central" ? "frps" : "frpc"} config: {s.frpConfigPath ? <span className="font-mono">{s.frpConfigPath}</span> : <b className="text-red-700">not found</b>}</p>}
|
||
{s.central && <p>proxy_bind_addr {s.central.proxyBindAddr || <b className="text-red-700">not set</b>}, allow_ports {s.central.allowPorts || "any"}</p>}
|
||
</div>
|
||
<div className="card space-y-2 text-sm">
|
||
<h2 className="font-medium">Actions</h2>
|
||
<button className="btn-secondary w-full" onClick={() => job("status")}>Check status and find installs</button>
|
||
<p className="text-xs text-slate-500">Asks the agent what's on the server. A site added there without the Hub (crosscode add, or by hand) is added to Installs and tied to its registration. It also runs by itself once a day when a registered site has no install record here.</p>
|
||
<button className="btn-secondary w-full" onClick={() => setPopup("agent")}><Upload className="h-4 w-4" /> Update agent…</button>
|
||
<button className="btn-danger w-full" onClick={remove}><Trash2 className="h-4 w-4" /> Remove server</button>
|
||
</div>
|
||
</div>
|
||
|
||
{s.mode === "church" && (
|
||
<ReadCard title="Configuration" onEdit={() => setPopup("config")}>
|
||
<p className="text-sm text-slate-500">The server layer of every install's .env here. Stored encrypted; sent only inside jobs, sealed to this server.</p>
|
||
<Fields>{configKeys(d.config).map(k => <Field key={k} label={k}>{d.config[k] ? <span className="break-all font-mono">{d.config[k]}</span> : null}</Field>)}</Fields>
|
||
</ReadCard>
|
||
)}
|
||
{popup === "config" && <ConfigModal id={s.id} config={d.config} onClose={() => setPopup(null)} onSaved={text => { setPopup(null); setMsg({ type: "ok", text }); load(); }} />}
|
||
{popup === "agent" && <UpdateAgentModal current={s.agentVersion} onClose={() => setPopup(null)} queue={version => queue("update-agent", { version })} />}
|
||
|
||
{d.frp && <FrpConfig serverId={s.id} agentVersion={s.agentVersion} frp={d.frp} onChange={m => { setMsg(m); load(); }} />}
|
||
|
||
{s.mode === "church" && (
|
||
<div className="card overflow-x-auto">
|
||
<h2 className="font-medium">Sites on this server</h2>
|
||
<table className="mt-3 w-full text-sm">
|
||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Church</th><th>Domain</th><th>Version</th><th>Ports (web, api)</th><th>Status</th></tr></thead>
|
||
<tbody>{d.deployments.map(x => (
|
||
<tr key={x.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${x.id}`}>{x.customer?.name} ({x.shortName})</Link></td><td>{x.domain}</td><td>{x.version || "–"}</td><td className="tabular-nums">{x.webPort}, {x.apiPort}</td><td><StatusPill status={x.status} /></td></tr>
|
||
))}</tbody>
|
||
</table>
|
||
{!d.deployments.length && <p className="mt-2 text-sm text-slate-500">None yet. <Link className="text-indigo-700 hover:underline" href="/servers/installs">New install</Link></p>}
|
||
</div>
|
||
)}
|
||
|
||
{s.mode === "church" && (
|
||
<div className="card overflow-x-auto">
|
||
<h2 className="font-medium">Processes (PM2)</h2>
|
||
<table className="mt-3 w-full text-sm tabular-nums">
|
||
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Name</th><th>Church</th><th>Status</th><th className="text-right">Memory</th><th className="text-right">CPU</th><th className="text-right">Restarts</th></tr></thead>
|
||
<tbody>{d.processes.map(p => <tr key={p.name} className="border-t"><td className="py-1.5">{p.name}</td><td>{p.church || "–"}</td><td>{p.status}</td><td className="text-right">{bytes(p.memoryBytes)}</td><td className="text-right">{Math.round(p.cpuPercent)}%</td><td className="text-right">{p.restarts}</td></tr>)}</tbody>
|
||
</table>
|
||
</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></tr></thead>
|
||
<tbody>{(jobsPaged.rows ?? d.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> <span className="text-xs text-slate-500">{String(j.args?.church || "")}</span></td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate pr-5 text-xs text-slate-500">{j.message}</td></tr>)}</tbody>
|
||
</table>
|
||
<Pager page={jobsPaged.page} pages={jobsPaged.pages} setPage={jobsPaged.setPage} total={jobsPaged.total} pageSize={jobsPaged.pageSize} />
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|