diff --git a/CHANGELOG.md b/CHANGELOG.md index 4adfa22..0572d65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,27 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.15.0] - 2026-11-23 + +Frontend only: no migration, no API changes. + +### Changed + +- **An install's page is a header and tabs**, like the customer page. The header shows the church, + product and status, with tiles for the site (and whether it has registered), version, server, + ports and last heartbeat. Below are **Jobs**, **Settings (.env)** and **Exports** (when there are + any); the tab is in the address (`?tab=settings`). +- **Every action is a popup.** Schedule update (the header's button, or the Version tile), move + onto the monorepo, mark as a demo site / load demo data, uninstall, remove from the Hub and + remove the record open over the page, the rare and destructive ones from the ⋯ menu. Each asks + before discarding what you've typed, and shows its error by its button. The confirmations + (type the short name, two-factor code, the final "are you sure") are unchanged. +- **Settings (.env) shows the values; Edit opens one file in a popup** to change, remove or add + variables, then save and restart (or rebuild). +- **Banners for what needs attention**: not registered yet, no heartbeat for a day (with Remove + from the Hub), and an uninstall already planned for this install (with a link to its job). +- One message under the header for the whole page, shared with the customer page. + ## [2.14.0] - 2026-11-23 Frontend only: no migration, no API changes. diff --git a/backend/package-lock.json b/backend/package-lock.json index b56adeb..f5fa15f 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-backend", - "version": "2.14.0", + "version": "2.15.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "2.14.0", + "version": "2.15.0", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", diff --git a/backend/package.json b/backend/package.json index 86a0712..90412c8 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "2.14.0", + "version": "2.15.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 9614a13..be33128 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "2.14.0", + "version": "2.15.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "2.14.0", + "version": "2.15.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index d84c66e..c017ed4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.14.0", + "version": "2.15.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/customers/[id]/page.tsx b/frontend/src/app/(hub)/customers/[id]/page.tsx index bf0502f..cd2c094 100644 --- a/frontend/src/app/(hub)/customers/[id]/page.tsx +++ b/frontend/src/app/(hub)/customers/[id]/page.tsx @@ -3,11 +3,11 @@ import React, { useCallback, useEffect, useState } from "react"; import Link from "next/link"; import { useParams } from "next/navigation"; -import { KeyRound, X } from "lucide-react"; +import { KeyRound } from "lucide-react"; import { api, errorText } from "@/lib/api"; import { PRODUCTS, byProduct } from "@/lib/products"; import type { Customer } from "@/lib/types"; -import { Loading, Message, Tabs } from "@/components/ui"; +import { Loading, Message, PageMessage, Tabs } from "@/components/ui"; import { RecordPayment } from "@/components/billing/RecordPayment"; import { OneOffInvoice } from "@/components/billing/OneOffInvoice"; import { CustomerHeader, type HeaderAction } from "@/components/customer/CustomerHeader"; @@ -70,13 +70,6 @@ export default function CustomerPage() { window.history.replaceState(null, "", t === "overview" ? window.location.pathname : `?tab=${t}`); }; - // An "ok" message fades after a while; an error stays until it's closed or replaced. - useEffect(() => { - if (msg?.type !== "ok") return; - const t = setTimeout(() => setMsg(m => (m === msg ? null : m)), 12000); - return () => clearTimeout(t); - }, [msg]); - /** Every card and popup reports here: close the popup, show the message, reload. */ const done: Done = m => { setPopup(null); setMsg(m); load(); }; const close = () => setPopup(null); @@ -101,12 +94,7 @@ export default function CustomerPage() { <> 0} onAction={onAction} onArchive={setArchivedState} /> - {msg && ( -
- - -
- )} + setMsg(null)} /> diff --git a/frontend/src/app/(hub)/servers/installs/[id]/page.tsx b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx index 42a637c..a4c4619 100644 --- a/frontend/src/app/(hub)/servers/installs/[id]/page.tsx +++ b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx @@ -3,37 +3,29 @@ 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 { api, errorText } from "@/lib/api"; +import { 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"; +import { Loading, Message, PageMessage, Tabs } from "@/components/ui"; +import { ServersNav, type Job } from "@/components/servers"; import { EnvPanel } from "@/components/EnvPanel"; +import { InstallHeader, type InstallAction } from "@/components/install/InstallHeader"; +import { ExportsCard, JobsCard } from "@/components/install/JobsCard"; +import { UpdateModal } from "@/components/install/UpdateModal"; +import { AdoptModal } from "@/components/install/AdoptModal"; +import { DemoModal } from "@/components/install/DemoModal"; +import { UninstallModal } from "@/components/install/UninstallModal"; +import { RemoveModal } from "@/components/install/RemoveModal"; +import { post, productName, running, uninstallPlan, withWarnings, type Detail, type Done, type Msg } from "@/components/install/shared"; -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; - /** 2.12.0: no heartbeat for 24 hours, so it can be removed from the Hub. */ - stale: { since: string | null; stale: boolean }; - /** 2.12.0: what an uninstall removes: this product only (agent 1.5.0+), or the whole church. */ - uninstall: { - onlyThisProduct: boolean; minAgent: string; others: { id: string; product: string; domain: string; status: string }[]; - /** The church's uninstalls not run yet; `products` null: the whole church. `joinable`: this one can still be added to it. */ - pending: { jobId: string; notBefore: string; products: string[] | null; joinable: boolean }[]; - /** Every other product is being uninstalled: this one takes the whole church with it. */ - lastProduct: boolean; - }; -}; +type Tab = "jobs" | "settings" | "exports"; +type Popup = Exclude | null; -const productName = (p: string) => PRODUCT_NAMES[p as keyof typeof PRODUCT_NAMES] || p; - -const H = 60 * 60 * 1000; - -/** One install on a server: proxy, updates, adopt, uninstall (§7–9). */ +/** + * One install on a server (§7–9). Hub 2.15.0: a header with the status and tiles, then Jobs, + * Settings (.env) and Exports as tabs; every update, move, demo, uninstall and removal is a popup. + */ export default function DeploymentPage() { const { id } = useParams<{ id: string }>(); const router = useRouter(); @@ -41,16 +33,11 @@ export default function DeploymentPage() { const [d, setD] = useState(null); const [msg, setMsg] = useState(warn ? { type: "err", text: warn } : null); const [problems, setProblems] = useState([]); - 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 [forget, setForget] = useState(""); - // 2.12.0: with another product's uninstall pending, join it (the default) or a time of its own. - const [joining, setJoining] = useState(true); - const [releases, setReleases] = useState([]); - // Hub 2.6.0: every job of this install, a page at a time (it showed the last 50). + const [tab, setTab] = useState("jobs"); + const [popup, setPopup] = useState(null); + + // Hub 2.6.0: every job of this install, a page at a time. const jobsPaged = useServerPaged("/api/admin/jobs", { deploymentId: String(id) }, r => r.jobs as Job[], 20); const load = useCallback(() => { jobsPaged.reload(); @@ -60,256 +47,108 @@ export default function DeploymentPage() { useEffect(() => { load(); }, [load]); useEffect(() => { api("/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. + // The tab is in the address (?tab=settings), so a reload or a shared link opens it. + useEffect(() => { + const q = new URLSearchParams(window.location.search).get("tab"); + if (q === "settings" || q === "exports") setTab(q); + }, []); + const openTab = (t: Tab) => { + setTab(t); + const q = new URLSearchParams(window.location.search); + if (t === "jobs") q.delete("tab"); else q.set("tab", t); + const s = q.toString(); + window.history.replaceState(null, "", s ? `?${s}` : window.location.pathname); + }; + + /** Every popup and card reports here: close the popup, show the message, reload. */ + const done: Done = m => { setPopup(null); setMsg(m); load(); }; + const close = () => setPopup(null); + + // 2.7.1: the page's own buttons (proxy done, cancel a job, not a demo) are off from a click until the Hub answers. const [busy, setBusy] = useState(false); - const withBusy = async (fn: () => Promise) => { + const act = async (fn: () => Promise) => { if (busy) return; setBusy(true); - try { - await fn(); - } finally { - setBusy(false); - } - }; - const act = async (path: string, body: Record, ok: string): Promise => { - if (busy && !body.confirmLive) return; - setBusy(true); - try { - await doAct(path, body, ok); - } finally { - setBusy(false); - } - }; - const doAct = async (path: string, body: Record, ok: string): Promise => { - 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) }); } - }; - - const removeFromHub = () => withBusy(removeFromHubNow); - const removeFromHubNow = async () => { - if (!d || !window.confirm(`Remove ${d.deployment.domain} from the Hub? Nothing runs on the server: use this only when the site is already gone from it.`)) return; - setMsg(null); - try { - await api(`/api/admin/deployments/${id}/forget`, { method: "POST", body: { confirm: forget } }); - router.push("/servers/installs"); - } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + try { done(await fn()); } catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); } }; if (!d) return
{msg ? : }
; const x = d.deployment; - const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H; - const plan = d.uninstall; - const othersStaying = plan.others.filter(o => o.status !== "uninstalling"); - // Accounts goes last: the church's other products sign in through it. - const accountsInUse = x.product === "accounts" && othersStaying.length > 0; - const wholeChurch = !plan.onlyThisProduct && plan.others.length > 0; - // 2.12.0: the church's uninstalls not run yet (by product), and the one this could join. - const pendingRuns = plan.pending.filter(p => p.products); - const joinable = pendingRuns.find(p => p.joinable) || null; - const lastNow = plan.onlyThisProduct && plan.lastProduct; + const plan = uninstallPlan(d); + const hasEnv = ["events", "accounts"].includes(x.product) && running(x); + const tabs: { key: Tab; label: string }[] = [ + { key: "jobs", label: "Jobs" }, + ...(hasEnv ? [{ key: "settings" as const, label: "Settings (.env)" }] : []), + ...(x.exports.length ? [{ key: "exports" as const, label: `Exports (${x.exports.length})` }] : []), + ]; + const shown = tabs.some(t => t.key === tab) ? tab : "jobs"; + + const proxyDone = () => act(async () => { + const r = await api<{ live: boolean; problems: string[] }>(`/api/admin/deployments/${id}/proxy-done`, { method: "POST" }); + setProblems(r.problems); + return r.live ? { type: "ok", text: "Live. The site admin got the welcome email." } : { type: "err", text: "The site isn't answering as expected yet:" }; + }); + const cancelJob = (j: Job) => act(async () => { + const r = await post(`/api/admin/jobs/${j.id}/cancel`); + return { type: "ok", text: withWarnings("Cancelled; the church was told.", r) }; + }); + const onAction = (a: InstallAction) => { + if (a === "undemo") { + if (!window.confirm(`${x.shortName} won't be a demo site any more: its data can't be replaced from the Hub then.`)) return; + act(async () => { await post(`/api/admin/deployments/${x.id}/demo`, { isDemo: false }); return { type: "ok", text: "No longer a demo site." }; }); + } else setPopup(a); + }; return ( -
-
- {x.domain} · on {x.server.name} · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} } /> - - - {/* Hub 2.6.0: whether the site has registered with the Hub (its banners, licence and heartbeats need it). */} -

- {x.install - ? <>Registered site: {x.install.url}, last heartbeat {x.install.lastHeartbeatAt ? ago(x.install.lastHeartbeatAt) : "never"}. - : The site hasn'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't happen, check its HUB_URL and HUB_LICENCE_KEY.} -

- {!!problems.length &&
    {problems.map(p =>
  • {p}
  • )}
} + <> + + + + { setMsg(null); setProblems([]); }} /> + {!!problems.length &&
    {problems.map(p =>
  • {p}
  • )}
} + +
+ {/* Hub 2.6.0: the site registers with the Hub itself; its banners, licence and heartbeats need it. */} + {!x.install && running(x) && ( +

The site hasn'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't happen, check its HUB_URL and HUB_LICENCE_KEY.

+ )} + {/* Hub 2.12.0: gone from its server without the Hub (uninstalled by hand, server rebuilt …)? */} + {d.stale.stale && ( +
+ No heartbeat since {d.stale.since ? fmtDate(d.stale.since) : "it was made"}. If the site is gone from {x.server.name}, remove it from the Hub; if it's still there, uninstall it. + +
+ )} + {plan.planned && ( +

+ Uninstall planned for {fmtDate(plan.planned.notBefore)}{plan.planned.products ? (plan.planned.products.length > 1 ? `, with ${plan.planned.products.filter(p => p !== x.product).map(productName).join(" and ")}` : "") : ": the whole church"}.{" "} + See the job to cancel it. +

+ )} + {(x.status === "waiting_for_proxy" || x.status === "installing") && ( +
+

Set up the site in FastPanel

+
{d.fastPanel}
+
+ + {x.status === "installing" &&

Waiting for the install to finish (see its job under Jobs).

} +
+
+ )}
- {(x.status === "waiting_for_proxy" || x.status === "installing") && ( -
-

Set up the site in FastPanel

-
{d.fastPanel}
- - {x.status === "installing" &&

Waiting for the install to finish (see its job below).

} -
- )} - - {x.status === "live" && ( -
{ 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."); }}> -

Schedule an update

-
- - -
- {upd.emergency && upd.asap - ?
When

As soon as possible: the agent starts within a minute.

- :
setUpd({ ...upd, at: e.target.value })} />

At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.

} - - {upd.emergency && <> -
- When the emergency update runs - - -
-
setUpd({ ...upd, reason: e.target.value })} />
-
setUpd({ ...upd, totp: e.target.value })} />
- } -
-
- )} - - {x.status === "live" && x.install?.version?.startsWith("2.1.") && ( -
{ 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."); }}> -

Move onto the monorepo (crosscode adopt)

-

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 crosscode adopt {x.shortName} --undo.

-
setAdopt({ ...adopt, eventsDir: e.target.value })} />
-
setAdopt({ ...adopt, address: e.target.value })} />
-
setAdopt({ ...adopt, version: e.target.value })} />
-
setAdopt({ ...adopt, at: e.target.value })} />
-
-
- )} - - {/* Hub 2.8.0: the install's .env, and changing it with a restart. */} - {["events", "accounts"].includes(x.product) && ["live", "waiting_for_proxy"].includes(x.status) && } - - {x.product === "events" && ["live", "waiting_for_proxy"].includes(x.status) && ( -
-

Demo site

- {!x.isDemo ? ( -
{ e.preventDefault(); act(`/api/admin/deployments/${x.id}/demo`, { isDemo: true, confirm: demo.markConfirm }, "Marked as a demo site."); }}> -

A demo site's data can be replaced with demo data from here. Only mark sites used for showing Cross Events, never a church's real site.

-
setDemo({ ...demo, markConfirm: e.target.value })} />
- -
- ) : ( - <> -
{ 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."); }}> -

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.

-
- -
-
setDemo({ ...demo, confirm: e.target.value })} />
- -
- - - )} -
- )} - -
-

Jobs

- - - {(jobsPaged.rows ?? x.jobs).map(j => ( - - - - - - ))} -
JobWhenStatusResult
{j.type}{j.emergency && emergency}{fmtDate(j.notBefore)}{j.message}{["queued", "scheduled"].includes(j.status) && }
- + +
+ {shown === "jobs" && } + {shown === "settings" && } + {shown === "exports" && }
- {!!x.exports.length && ( -
-

Exports

- {x.exports.map(e =>

{e.id}: {bytes(e.bytes)}, {e.deletedAt ? `deleted ${fmtDate(e.deletedAt)}` : `until ${fmtDate(e.expiresAt)}`}{e.downloadedAt ? `, downloaded ${fmtDate(e.downloadedAt)}` : ", not downloaded yet"}

)} -
- )} - - {d.canRemoveRecord && ( -
-

Remove the record

-

This install failed and the server already removed what it made, so there's nothing to export or uninstall. Removing the record frees the short name.

- -
- )} - - {/* Hub 2.12.0: gone from its server without the Hub (uninstalled by hand, server rebuilt …). */} - {d.stale.stale && ( -
{ e.preventDefault(); removeFromHub(); }}> -
-

Remove from the Hub

-

No heartbeat since {d.stale.since ? `${fmtDate(d.stale.since)} (${ago(d.stale.since)})` : "it was made"}. If the site is no longer on {x.server.name} (uninstalled by hand, or the server was rebuilt), remove it here: nothing runs on the server, what was planned for it is cancelled, its ports are freed after 30 days and its licence's heartbeats are refused. If it's still there, uninstall it instead.

-
-
setForget(e.target.value)} />
- -
- )} - - {["live", "waiting_for_proxy"].includes(x.status) && ( -
{ - e.preventDefault(); - const together = joining && joinable; - const when = together ? fmtDate(together.notBefore) : un.at.replace("T", " "); - if (!window.confirm(`Uninstall ${productName(x.product)} of ${x.shortName} on ${when}${together ? `, together with ${together.products!.map(productName).join(" and ")}` : ""}?${lastNow ? ` It's the church's last product here, so the whole church goes.` : ""} The church gets its data first.`)) return; - act(`/api/admin/deployments/${x.id}/uninstall`, { at: together ? undefined : fromInput(un.at), totp: un.totp, confirm: un.confirm, ...(pendingRuns.length ? { join: !!together, joinJobId: together ? together.jobId : undefined } : {}) }, - together ? "Added to that uninstall: one export and one uninstall for both. The site admin was emailed and sees a banner." : "Uninstall planned: the site admin was emailed and sees a banner. The export runs first."); - }}> -

Uninstall {productName(x.product)}

-

At the time: {productName(x.product)}'s data is exported (encrypted; the link goes to the site admin), then {x.domain}, its tunnels and database are removed. The final backup stays on the server for 30 days.{plan.onlyThisProduct && plan.others.length > 0 && !plan.lastProduct && <> The church keeps {plan.others.map(o => `${productName(o.product)} (${o.domain})`).join(" and ")}.}

- {/* Hub 2.12.0: another product of the church is already planned for uninstall. */} - {plan.onlyThisProduct && pendingRuns.length > 0 && ( -
- {pendingRuns.map(p => `${p.products!.map(productName).join(" and ")} on ${fmtDate(p.notBefore)}`).join("; ")}: already planned for uninstall - - -
- )} - {plan.onlyThisProduct && plan.lastProduct && !pendingRuns.length &&

This is the church's last product here: the uninstall removes the whole church (its folder and app user).

} - {wholeChurch &&

The agent on {x.server.name} is {x.server.agentVersion || "an unknown version"}: it can only remove the whole church, with {plan.others.map(o => productName(o.product)).join(" and ")}. Update the agent to {plan.minAgent} or later first.

} - {accountsInUse &&

{othersStaying.map(o => productName(o.product)).join(" and ")} signs in through Accounts: uninstall {othersStaying.length === 1 ? "it" : "them"} first, then Accounts (at the same time or later).

} - {joining && joinable - ?
When

{fmtDate(joinable.notBefore)}, with {joinable.products!.map(productName).join(" and ")}

- :
setUn({ ...un, at: e.target.value })} />
} -
setUn({ ...un, confirm: e.target.value })} />
-
setUn({ ...un, totp: e.target.value })} />
-
-
- )} -
+ {popup === "update" && } + {popup === "adopt" && } + {popup === "demo" && } + {popup === "uninstall" && } + {(popup === "record" || popup === "forget") && router.push("/servers/installs")} />} + ); } diff --git a/frontend/src/components/EnvPanel.tsx b/frontend/src/components/EnvPanel.tsx index b66975d..e9fb0e6 100644 --- a/frontend/src/components/EnvPanel.tsx +++ b/frontend/src/components/EnvPanel.tsx @@ -2,14 +2,16 @@ import React, { useCallback, useEffect, useMemo, useState } from "react"; import Link from "next/link"; +import { Pencil } from "lucide-react"; import { api, errorText } from "@/lib/api"; import { ago, fmtDate } from "@/lib/format"; -import { Message } from "@/components/ui"; +import { FormError, Message, Modal } from "@/components/ui"; /** * An install's .env (Hub 2.8.0, agent 1.3.0): what's in it (secrets only as set or not), changing * plain values, then a restart (or a rebuild for the frontend's file). The server keeps a copy of * the file and puts it back when the site doesn't start again with the new values. + * Hub 2.15.0: the page shows the values; each file's changes are made in a popup. */ type Variable = { name: string; value: string | null; secret: boolean; set: boolean; layer: string | null; description: string | null; editable: boolean }; @@ -37,18 +39,30 @@ const FILE_NOTE: Record = { "frontend/.env.production": "Next.js builds these values in: saving rebuilds the frontend (a few minutes), then restarts it.", }; -export function EnvPanel({ deploymentId, product }: { deploymentId: string; product: string }) { - const [state, setState] = useState(null); - const [msg, setMsg] = useState(null); - const [busy, setBusy] = useState(false); - // Edits per file: changed values, names to remove, and new variables. - const [edits, setEdits] = useState>>({}); - const [removed, setRemoved] = useState>({}); - const [added, setAdded] = useState>({}); - const [restart, setRestart] = useState(true); - const [showAll, setShowAll] = useState(false); +/** A variable's value as text: secrets only as set or not. */ +function ValueText({ v }: { v: Variable }) { + if (v.secret) return {v.set ? "•••••••• (secret, set)" : "secret, not set"}; + if (!v.set) return not set; + return {v.value}{!v.editable && made by the server}; +} - const load = useCallback(() => api(`/api/admin/deployments/${deploymentId}/env`).then(setState).catch(e => setMsg({ type: "err", text: errorText(e) })), [deploymentId]); +function VarName({ v }: { v: Variable }) { + return ( + <> +
{v.name}
+ {(v.description || v.layer) &&
{[v.layer, v.description].filter(Boolean).join(" · ")}
} + + ); +} + +export function EnvPanel({ deploymentId, product, onMessage }: { deploymentId: string; product: string; onMessage: (m: Msg) => void }) { + const [state, setState] = useState(null); + const [loadError, setLoadError] = useState(null); + const [busy, setBusy] = useState(false); + const [showAll, setShowAll] = useState(false); + const [editing, setEditing] = useState(null); + + const load = useCallback(() => api(`/api/admin/deployments/${deploymentId}/env`).then(s => { setState(s); setLoadError(null); }).catch(e => setLoadError(errorText(e))), [deploymentId]); useEffect(() => { load(); }, [load]); // While the agent has a job of ours, look again every few seconds. const waiting = !!state?.pending.length; @@ -58,46 +72,16 @@ export function EnvPanel({ deploymentId, product }: { deploymentId: string; prod return () => clearInterval(t); }, [waiting, load]); - const run = async (fn: () => Promise) => { + const read = async () => { if (busy) return; setBusy(true); - setMsg(null); - try { await fn(); } catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); } + try { + await api(`/api/admin/deployments/${deploymentId}/env/read`, { method: "POST" }); + onMessage({ type: "ok", text: "Asked the agent: the values show here within a minute." }); + await load(); + } catch (e) { onMessage({ type: "err", text: errorText(e) }); } finally { setBusy(false); } }; - const read = () => run(async () => { - await api(`/api/admin/deployments/${deploymentId}/env/read`, { method: "POST" }); - setMsg({ type: "ok", text: "Asked the agent: the values show here within a minute." }); - await load(); - }); - - const changesFor = (file: string) => { - const set: Record = { ...(edits[file] || {}) }; - const a = added[file]; - if (a?.name.trim()) set[a.name.trim()] = a.value; - return { set, unset: removed[file] || [] }; - }; - - const save = (file: string) => run(async () => { - const { set, unset } = changesFor(file); - const names = [...Object.keys(set), ...unset]; - if (!names.length) return; - const bad = names.find(n => !NAME.test(n)); - if (bad) throw new Error(`${bad} isn't a variable name (A-Z, 0-9 and _, starting with a letter).`); - const secret = names.find(n => SECRET.test(n)); - if (secret) throw new Error(`${secret} looks like a secret: change it on the server, not from the Hub.`); - const rebuild = file.startsWith("frontend/"); - const lines = [...Object.entries(set).map(([k, v]) => ` ${k}=${v}`), ...unset.map(n => ` remove ${n}`)].join("\n"); - const then = rebuild ? "The frontend is then rebuilt and restarted (the site is slow or unavailable for a few minutes)." : restart ? "The backend is then restarted (a few seconds)." : "Nothing is restarted: the new values apply at the next restart."; - if (!window.confirm(`Change ${file} on the server?\n\n${lines}\n\n${then} If it doesn't start again, the file is put back as it was.`)) return; - await api(`/api/admin/deployments/${deploymentId}/env`, { method: "POST", body: { file, set, unset, restart: rebuild || restart } }); - setEdits(e => ({ ...e, [file]: {} })); - setRemoved(r => ({ ...r, [file]: [] })); - setAdded(a => ({ ...a, [file]: { name: "", value: "" } })); - setMsg({ type: "ok", text: "Queued: the agent changes the file at its next poll. This panel updates when it's done." }); - await load(); - }); - const addresses = useMemo(() => { const names = ADDRESSES[product] || []; const out: { file: string; v: Variable }[] = []; @@ -105,133 +89,183 @@ export function EnvPanel({ deploymentId, product }: { deploymentId: string; prod return out; }, [state, product]); - if (!state) return

Settings (.env)

{msg ?
:

Loading…

}
; - if (!state.supported) return null; + if (!state) return
{loadError ? :

Loading…

}
; + if (!state.supported) return
The agent on this server can't read the .env files yet: it needs agent {state.minAgent} or later.
; const pendingRead = state.pending.find(p => p.type === "env-read"); const pendingSet = state.pending.find(p => p.type === "env-set"); + const editFile = state.env?.files.find(f => f.file === editing) || null; return ( -
-
-
-

Settings (.env)

-

- The values in this install's .env files on the server. Secrets (passwords, keys, the database) are never sent to the Hub: only whether they're set. - Needs agent {state.minAgent} or later. -

+
+
+
+
+

Settings (.env)

+

+ The values in this install's .env files on the server. Secrets (passwords, keys, the database) are never sent to the Hub: only whether they're set. +

+
+
- -
- - {pendingSet &&

A change is {pendingSet.status === "delivered" ? "being made on the server now" : "waiting for the agent"} (job).

} - {state.lastSet && !pendingSet && state.lastSet.status !== "succeeded" && ( -

- The last change ({fmtDate(state.lastSet.finishedAt)}) {state.lastSet.status === "rolled_back" ? "was put back: the site didn't start with it" : `didn't go through (${state.lastSet.status.replace(/_/g, " ")})`}. - {state.lastSet.message ? ` ${state.lastSet.message}` : ""} See the job. -

- )} + {loadError && } + {pendingSet &&

A change is {pendingSet.status === "delivered" ? "being made on the server now" : "waiting for the agent"} (job).

} + {state.lastSet && !pendingSet && state.lastSet.status !== "succeeded" && ( +

+ The last change ({fmtDate(state.lastSet.finishedAt)}) {state.lastSet.status === "rolled_back" ? "was put back: the site didn't start with it" : `didn't go through (${state.lastSet.status.replace(/_/g, " ")})`}. + {state.lastSet.message ? ` ${state.lastSet.message}` : ""} See the job. +

+ )} + {!state.env && !pendingRead &&

Not read yet. “Read from the server” asks the agent for them.

} + {state.env &&

Read {ago(state.env.readAt)} ({fmtDate(state.env.readAt)}){state.readJobId && <> · job}.

} - {!state.env && !pendingRead &&

Not read yet. “Read from the server” asks the agent for them.

} + {!!addresses.length && ( +
+

Addresses

+
+ {addresses.map(({ file, v }) => ( + +
{v.name}({file.split("/")[0]})
+
{v.set ? v.value : not set}
+
+ ))} +
+

Change them in the files below. The site's address on the Hub ({product}) and in FastPanel doesn't change with them.

+
+ )} - {state.env && ( - <> -

Read {ago(state.env.readAt)} ({fmtDate(state.env.readAt)}){state.readJobId && <> · job}.

+ {state.env && } + - {!!addresses.length && ( -
-

Addresses

-
- {addresses.map(({ file, v }) => ( - -
{v.name}({file.split("/")[0]})
-
{v.set ? v.value : not set}
-
- ))} -
-

Change them in the files below. The site's address on the Hub ({product}) and in FastPanel doesn't change with them.

+ {state.env?.files.map(f => { + const rows = f.variables.filter(v => showAll || v.set); + return ( +
+
+
+

{f.file}{!f.exists && missing on the server}

+

{FILE_NOTE[f.file]}

+
+
- )} - - - - {state.env.files.map(f => { - const fileEdits = edits[f.file] || {}; - const fileRemoved = removed[f.file] || []; - const a = added[f.file] || { name: "", value: "" }; - const { set, unset } = changesFor(f.file); - const count = Object.keys(set).length + unset.length; - const rebuild = f.file.startsWith("frontend/"); - const rows = f.variables.filter(v => showAll || v.set || v.name in fileEdits); - return ( -
{ e.preventDefault(); save(f.file); }}> -
-

{f.file}{!f.exists && missing on the server}

- {FILE_NOTE[f.file]} -
+ {rows.length === 0 + ?

No variables set.

+ : (
- - - {rows.map(v => { - const isRemoved = fileRemoved.includes(v.name); - const value = v.name in fileEdits ? fileEdits[v.name] : (v.value ?? ""); - const changed = v.name in fileEdits && fileEdits[v.name] !== (v.value ?? ""); - return ( - - - - - - ); - })} - - - + + {rows.map(v => ( + + + - + ))}
NameValueRemove
-
{v.name}
- {(v.description || v.layer) &&
{[v.layer, v.description].filter(Boolean).join(" · ")}
} -
- {v.secret ? ( - {v.set ? "•••••••• (secret, set)" : "secret, not set"} - ) : v.editable ? ( - { - const next = e.target.value; - setEdits(x => { - const fe = { ...(x[f.file] || {}) }; - if (next === (v.value ?? "")) delete fe[v.name]; else fe[v.name] = next; - return { ...x, [f.file]: fe }; - }); - }} /> - ) : ( - {v.value}made by the server - )} - - {v.editable && v.set && ( - - )} -
setAdded(x => ({ ...x, [f.file]: { ...a, name: e.target.value.toUpperCase() } }))} /> setAdded(x => ({ ...x, [f.file]: { ...a, value: e.target.value } }))} />
NameValue
-
- - {!rebuild && } - {!!count && } -
-
- ); - })} - + )} +
+ ); + })} + + {editFile && ( + setEditing(null)} + onSaved={() => { setEditing(null); onMessage({ type: "ok", text: "Queued: the agent changes the file at its next poll. The Settings tab updates when it's done." }); load(); }} /> )}
); } + +/** Change one .env file: edit values, remove some, add one; then restart (or rebuild) to apply it. */ +function EnvFileModal({ deploymentId, f, onClose, onSaved }: { deploymentId: string; f: EnvFile; onClose: () => void; onSaved: () => void }) { + const [edits, setEdits] = useState>({}); + const [removed, setRemoved] = useState([]); + const [added, setAdded] = useState({ name: "", value: "" }); + const [restart, setRestart] = useState(true); + const [showAll, setShowAll] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const set: Record = { ...edits }; + if (added.name.trim()) set[added.name.trim()] = added.value; + const unset = removed; + const count = Object.keys(set).length + unset.length; + const rebuild = f.file.startsWith("frontend/"); + const rows = f.variables.filter(v => showAll || v.set || v.name in edits); + + const save = async (e: React.FormEvent) => { + e.preventDefault(); + if (busy || !count) return; + setError(null); + const names = [...Object.keys(set), ...unset]; + const bad = names.find(n => !NAME.test(n)); + if (bad) return setError(`${bad} isn't a variable name (A-Z, 0-9 and _, starting with a letter).`); + const secret = names.find(n => SECRET.test(n)); + if (secret) return setError(`${secret} looks like a secret: change it on the server, not from the Hub.`); + const lines = [...Object.entries(set).map(([k, v]) => ` ${k}=${v}`), ...unset.map(n => ` remove ${n}`)].join("\n"); + const then = rebuild ? "The frontend is then rebuilt and restarted (the site is slow or unavailable for a few minutes)." : restart ? "The backend is then restarted (a few seconds)." : "Nothing is restarted: the new values apply at the next restart."; + if (!window.confirm(`Change ${f.file} on the server?\n\n${lines}\n\n${then} If it doesn't start again, the file is put back as it was.`)) return; + setBusy(true); + try { + await api(`/api/admin/deployments/${deploymentId}/env`, { method: "POST", body: { file: f.file, set, unset, restart: rebuild || restart } }); + onSaved(); + } catch (err) { setError(errorText(err)); } finally { setBusy(false); } + }; + + return ( + {f.file}} onClose={onClose} wide dirty={count > 0}> +
+

{FILE_NOTE[f.file]}

+ +
+ + + + {rows.map(v => { + const isRemoved = removed.includes(v.name); + const value = v.name in edits ? edits[v.name] : (v.value ?? ""); + const isChanged = v.name in edits && edits[v.name] !== (v.value ?? ""); + return ( + + + + + + ); + })} + + + + + +
NameValueRemove
+ {v.editable && !v.secret ? ( + { + const next = e.target.value; + setEdits(x => { + const fe = { ...x }; + if (next === (v.value ?? "")) delete fe[v.name]; else fe[v.name] = next; + return fe; + }); + }} /> + ) : } + + {v.editable && v.set && ( + + )} +
setAdded({ ...added, name: e.target.value.toUpperCase() })} /> setAdded({ ...added, value: e.target.value })} />
+
+ {!rebuild && } + +
+ + +
+ +
+ ); +} diff --git a/frontend/src/components/customer/ReadCard.tsx b/frontend/src/components/customer/ReadCard.tsx index f2cfc4a..419b520 100644 --- a/frontend/src/components/customer/ReadCard.tsx +++ b/frontend/src/components/customer/ReadCard.tsx @@ -34,11 +34,13 @@ export function Fields({ children }: { children: React.ReactNode }) { return
{children}
; } -/** Save and Cancel at the foot of a popup form. */ -export function ModalButtons({ busy, onCancel, label = "Save" }: { busy: boolean; onCancel: () => void; label?: string }) { +/** Save and Cancel at the foot of a popup form. `danger` for what can't be undone (Hub 2.15.0). */ +export function ModalButtons({ busy, onCancel, label = "Save", busyLabel = "Saving…", danger, disabled }: { + busy: boolean; onCancel: () => void; label?: string; busyLabel?: string; danger?: boolean; disabled?: boolean; +}) { return (
- +
); diff --git a/frontend/src/components/install/AdoptModal.tsx b/frontend/src/components/install/AdoptModal.tsx new file mode 100644 index 0000000..b7b1fb4 --- /dev/null +++ b/frontend/src/components/install/AdoptModal.tsx @@ -0,0 +1,39 @@ +"use client"; + +import React, { useState } from "react"; +import { FormError, Modal } from "@/components/ui"; +import { fromInput, toInput } from "@/components/servers"; +import { ModalButtons } from "@/components/customer/ReadCard"; +import { H, changed, post, useSubmit, withWarnings, type Done, type Install } from "./shared"; + +/** Move an old (2.1.x) Events install onto the monorepo: `crosscode adopt` at a planned time. */ +export function AdoptModal({ x, onClose, onDone }: { x: Install; onClose: () => void; onDone: Done }) { + const [form0] = useState(() => ({ eventsDir: "", version: "", address: "", at: toInput(new Date(Date.now() + 5 * H)) })); + const [adopt, setAdopt] = useState(form0); + const { busy, error, run } = useSubmit(); + const eventsSub = x.domain.startsWith("events."); + + const save = (e: React.FormEvent) => { + e.preventDefault(); + run(async () => { + const r = await post(`/api/admin/deployments/${x.id}/adopt`, { eventsDir: adopt.eventsDir, version: adopt.version || undefined, address: adopt.address || undefined, at: fromInput(adopt.at) }); + onDone({ type: "ok", text: withWarnings("Adopt planned. The site admin was emailed.", r) }); + }); + }; + + return ( + +
+

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 crosscode adopt {x.shortName} --undo.

+
+
setAdopt({ ...adopt, eventsDir: e.target.value })} />
+
setAdopt({ ...adopt, address: e.target.value })} />
+
setAdopt({ ...adopt, version: e.target.value })} />
+
setAdopt({ ...adopt, at: e.target.value })} />
+
+ + + +
+ ); +} diff --git a/frontend/src/components/install/DemoModal.tsx b/frontend/src/components/install/DemoModal.tsx new file mode 100644 index 0000000..5424869 --- /dev/null +++ b/frontend/src/components/install/DemoModal.tsx @@ -0,0 +1,74 @@ +"use client"; + +import React, { useState } from "react"; +import { FormError, Modal } from "@/components/ui"; +import { ModalButtons } from "@/components/customer/ReadCard"; +import { post, useSubmit, withWarnings, type Done, type Install } from "./shared"; + +const PROFILES = [ + { key: "small", label: "Small church: the essentials" }, + { key: "events", label: "Events and conferences" }, + { key: "ministry", label: "Weekly ministry: courses, kids, volunteers" }, + { key: "multicampus", label: "Three campuses" }, +]; + +/** + * An Events site used for showing Cross Events: mark it as a demo site, or (once it is one) replace + * its data with a demo set. Unmarking is a menu item on the page. + */ +export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => void; onDone: Done }) { + const [profile, setProfile] = useState("events"); + const [confirmName, setConfirmName] = useState(""); + const { busy, error, run } = useSubmit(); + const typed = confirmName === x.shortName; + + const mark = (e: React.FormEvent) => { + e.preventDefault(); + run(async () => { + const r = await post(`/api/admin/deployments/${x.id}/demo`, { isDemo: true, confirm: confirmName }); + onDone({ type: "ok", text: withWarnings("Marked as a demo site.", r) }); + }); + }; + const seed = (e: React.FormEvent) => { + e.preventDefault(); + if (!window.confirm(`Replace ALL of ${x.shortName}'s data with the "${profile}" demo? A backup is taken first; one admin account is kept.`)) return; + run(async () => { + const r = await post(`/api/admin/deployments/${x.id}/seed-demo`, { profile, confirm: confirmName }); + onDone({ type: "ok", text: withWarnings("Queued: the agent loads the demo data on its next poll (see Jobs). You get an email when it's done.", r) }); + }); + }; + + const confirmField = ( +
setConfirmName(e.target.value)} />
+ ); + + if (!x.isDemo) return ( + +
+

A demo site's data can be replaced with demo data from the Hub. Only mark sites used for showing Cross Events, never a church's real site.

+ {confirmField} + + + +
+ ); + + return ( + +
+

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.

+
+
+ + +
+ {confirmField} +
+ + + +
+ ); +} diff --git a/frontend/src/components/install/InstallHeader.tsx b/frontend/src/components/install/InstallHeader.tsx new file mode 100644 index 0000000..8836188 --- /dev/null +++ b/frontend/src/components/install/InstallHeader.tsx @@ -0,0 +1,70 @@ +"use client"; + +import React from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { ArrowLeft, RefreshCw } from "lucide-react"; +import { ago } from "@/lib/format"; +import { Menu, Stat } from "@/components/ui"; +import { StatusPill } from "@/components/servers"; +import { productName, running, type Detail } from "./shared"; + +/** What the header's buttons, menu and tiles open. */ +export type InstallAction = "update" | "adopt" | "demo" | "undemo" | "uninstall" | "record" | "forget"; + +/** + * Hub 2.15.0: always at the top of an install's page: which church and product, its status, the + * everyday action (an update) and the rare ones in the ⋯ menu, and tiles for where it runs. + */ +export function InstallHeader({ d, onAction }: { d: Detail; onAction: (a: InstallAction) => void }) { + const router = useRouter(); + const x = d.deployment; + const live = x.status === "live"; + const version = x.install?.version || x.version; + const heard = x.install?.lastHeartbeatAt || null; + + return ( +
+ Installs +
+
+

+ {x.customer?.name} ({x.shortName}) + + {x.isDemo && Demo site} +

+

+ {productName(x.product)} · {x.customer ? customer : "customer"} +

+
+
+ {live && } + onAction("adopt") }, + x.product === "events" && running(x) && (x.isDemo + ? { label: "Load demo data…", onClick: () => onAction("demo") } + : { label: "Mark as a demo site…", onClick: () => onAction("demo") }), + x.product === "events" && running(x) && x.isDemo && { label: "It isn't a demo site any more", onClick: () => onAction("undemo") }, + running(x) && { label: `Uninstall ${productName(x.product)}…`, onClick: () => onAction("uninstall"), danger: true }, + d.stale.stale && { label: "Remove from the Hub…", onClick: () => onAction("forget"), danger: true }, + d.canRemoveRecord && { label: "Remove the record…", onClick: () => onAction("record"), danger: true }, + ]} /> +
+
+ +
+ {x.domain}} + tone={x.install ? undefined : "amber"} + sub={x.install ? {x.install.url} : "Not registered with the Hub yet"} /> + onAction("update") : undefined} + sub={live ? "Schedule an update" : undefined} /> + router.push(`/servers/${x.serverId}`)} + sub={`agent ${x.server.agentVersion || "unknown"}`} /> + + +
+
+ ); +} diff --git a/frontend/src/components/install/JobsCard.tsx b/frontend/src/components/install/JobsCard.tsx new file mode 100644 index 0000000..a6608c9 --- /dev/null +++ b/frontend/src/components/install/JobsCard.tsx @@ -0,0 +1,56 @@ +"use client"; + +import React from "react"; +import Link from "next/link"; +import { bytes, fmtDate } from "@/lib/format"; +import { Pager } from "@/components/ui"; +import { StatusPill, type Job } from "@/components/servers"; +import type { useServerPaged } from "@/lib/paging"; +import type { Export } from "./shared"; + +/** Hub 2.6.0: every job of this install, a page at a time; a job not run yet can be cancelled. */ +export function JobsCard({ paged, fallback, busy, onCancel }: { + paged: ReturnType>; fallback: Job[]; busy: boolean; onCancel: (j: Job) => void; +}) { + const rows = paged.rows ?? fallback; + return ( +
+ {rows.length === 0 + ?

No jobs yet.

+ : ( + + + {rows.map(j => ( + + + + + + + + ))} +
JobWhenStatusResultActions
{j.type}{j.emergency && emergency}{fmtDate(j.notBefore)}{j.message}{["queued", "scheduled"].includes(j.status) && }
+ )} + +
+ ); +} + +/** The church's data exports (made before an uninstall), and whether they've been downloaded. */ +export function ExportsCard({ exports }: { exports: Export[] }) { + return ( +
+ + + {exports.map(e => ( + + + + + + + ))} +
ExportSizeKept untilDownloaded
{e.id}{bytes(e.bytes)}{e.deletedAt ? Deleted {fmtDate(e.deletedAt)} : fmtDate(e.expiresAt)}{e.downloadedAt ? fmtDate(e.downloadedAt) : Not yet}
+
+ ); +} diff --git a/frontend/src/components/install/RemoveModal.tsx b/frontend/src/components/install/RemoveModal.tsx new file mode 100644 index 0000000..c644049 --- /dev/null +++ b/frontend/src/components/install/RemoveModal.tsx @@ -0,0 +1,47 @@ +"use client"; + +import React, { useState } from "react"; +import { api } from "@/lib/api"; +import { ago, fmtDate } from "@/lib/format"; +import { FormError, Modal } from "@/components/ui"; +import { ModalButtons } from "@/components/customer/ReadCard"; +import { useSubmit, type Detail, type Install } from "./shared"; + +export type RemoveKind = "record" | "forget"; + +/** + * Take an install off the Hub without running anything on its server: + * - "record": its install failed and the server already cleaned up (frees the short name); + * - "forget" (2.12.0): no heartbeat for a day, and the site is gone from the server by other means. + */ +export function RemoveModal({ kind, x, stale, onClose, onRemoved }: { kind: RemoveKind; x: Install; stale: Detail["stale"]; onClose: () => void; onRemoved: () => void }) { + const [typed, setTyped] = useState(""); + const { busy, error, run } = useSubmit(); + const record = kind === "record"; + + const save = (e: React.FormEvent) => { + e.preventDefault(); + const sure = record + ? `Remove the record of ${x.shortName}? Its install failed, so nothing of it is on the server.` + : `Remove ${x.domain} from the Hub? Nothing runs on the server: use this only when the site is already gone from it.`; + if (!window.confirm(sure)) return; + run(async () => { + if (record) await api(`/api/admin/deployments/${x.id}`, { method: "DELETE" }); + else await api(`/api/admin/deployments/${x.id}/forget`, { method: "POST", body: { confirm: typed } }); + onRemoved(); + }); + }; + + return ( + +
+ {record + ?

This install failed and the server already removed what it made, so there's nothing to export or uninstall. Removing the record frees the short name.

+ :

No heartbeat since {stale.since ? `${fmtDate(stale.since)} (${ago(stale.since)})` : "it was made"}. If the site is no longer on {x.server.name} (uninstalled by hand, or the server was rebuilt), remove it here: nothing runs on the server, what was planned for it is cancelled, its ports are freed after 30 days and its licence's heartbeats are refused. If it's still there, uninstall it instead.

} + {!record &&
setTyped(e.target.value)} />
} + + + +
+ ); +} diff --git a/frontend/src/components/install/UninstallModal.tsx b/frontend/src/components/install/UninstallModal.tsx new file mode 100644 index 0000000..8f22802 --- /dev/null +++ b/frontend/src/components/install/UninstallModal.tsx @@ -0,0 +1,75 @@ +"use client"; + +import React, { useState } from "react"; +import { fmtDate } from "@/lib/format"; +import { FormError, Modal } from "@/components/ui"; +import { fromInput, toInput } from "@/components/servers"; +import { ModalButtons } from "@/components/customer/ReadCard"; +import { H, post, productName, useSubmit, withWarnings, type Done, type Install, type UninstallPlan } from "./shared"; + +/** + * Plan an uninstall of one product (2.12.0): the church's data is exported first, then the site + * is removed. With another product of the church already planned, join that run (the default) or + * pick a time of its own. + */ +export function UninstallModal({ x, plan, onClose, onDone }: { x: Install; plan: UninstallPlan; onClose: () => void; onDone: Done }) { + const [at0] = useState(() => toInput(new Date(Date.now() + 7 * 24 * H))); + const [un, setUn] = useState({ at: at0, totp: "", confirm: "" }); + const [joining, setJoining] = useState(true); + const { busy, error, run } = useSubmit(); + const { joinable, pendingRuns, lastNow, wholeChurch, accountsInUse, othersStaying } = plan; + const together = joining && joinable ? joinable : null; + + const save = (e: React.FormEvent) => { + e.preventDefault(); + const when = together ? fmtDate(together.notBefore) : un.at.replace("T", " "); + if (!window.confirm(`Uninstall ${productName(x.product)} of ${x.shortName} on ${when}${together ? `, together with ${together.products!.map(productName).join(" and ")}` : ""}?${lastNow ? ` It's the church's last product here, so the whole church goes.` : ""} The church gets its data first.`)) return; + run(async () => { + const r = await post(`/api/admin/deployments/${x.id}/uninstall`, { at: together ? undefined : fromInput(un.at), totp: un.totp, confirm: un.confirm, ...(pendingRuns.length ? { join: !!together, joinJobId: together ? together.jobId : undefined } : {}) }); + onDone({ type: "ok", text: withWarnings(together ? "Added to that uninstall: one export and one uninstall for both. The site admin was emailed and sees a banner." : "Uninstall planned: the site admin was emailed and sees a banner. The export runs first.", r) }); + }); + }; + + const blocked = wholeChurch || accountsInUse; + return ( + +
+

+ At the time: {productName(x.product)}'s data is exported (encrypted; the link goes to the site admin), then {x.domain}, its tunnels and database are removed. The final backup stays on the server for 30 days. + {plan.onlyThisProduct && plan.others.length > 0 && !plan.lastProduct && <> The church keeps {plan.others.map(o => `${productName(o.product)} (${o.domain})`).join(" and ")}.} +

+ + {/* What stops it: say so first, before any fields. */} + {wholeChurch &&

The agent on {x.server.name} is {x.server.agentVersion || "an unknown version"}: it can only remove the whole church, with {plan.others.map(o => productName(o.product)).join(" and ")}. Update the agent to {plan.minAgent} or later first.

} + {accountsInUse &&

{othersStaying.map(o => productName(o.product)).join(" and ")} signs in through Accounts: uninstall {othersStaying.length === 1 ? "it" : "them"} first, then Accounts (at the same time or later).

} + + {/* Another product of the church is already planned for uninstall. */} + {plan.onlyThisProduct && pendingRuns.length > 0 && ( +
+ {pendingRuns.map(p => `${p.products!.map(productName).join(" and ")} on ${fmtDate(p.notBefore)}`).join("; ")}: already planned for uninstall + + +
+ )} + {lastNow && !pendingRuns.length &&

This is the church's last product here: the uninstall removes the whole church (its folder and app user).

} + +
+ {together + ?
When

{fmtDate(together.notBefore)}, with {together.products!.map(productName).join(" and ")}

+ :
setUn({ ...un, at: e.target.value })} />
} +
setUn({ ...un, confirm: e.target.value })} />
+
setUn({ ...un, totp: e.target.value })} />
+
+ + + + +
+ ); +} diff --git a/frontend/src/components/install/UpdateModal.tsx b/frontend/src/components/install/UpdateModal.tsx new file mode 100644 index 0000000..896d2e3 --- /dev/null +++ b/frontend/src/components/install/UpdateModal.tsx @@ -0,0 +1,73 @@ +"use client"; + +import React, { useState } from "react"; +import type { Release } from "@/lib/types"; +import { PRODUCT_NAMES } from "@/lib/products"; +import { FormError, Modal } from "@/components/ui"; +import { fromInput, toInput } from "@/components/servers"; +import { ModalButtons } from "@/components/customer/ReadCard"; +import { H, changed, post, productName, useSubmit, withWarnings, type Done, type Install } from "./shared"; + +/** + * Schedule an update of one install: at a time at least 4 hours away (the church gets notice), or + * an emergency with a reason and a two-factor code, at least 15 minutes away or as soon as possible. + */ +export function UpdateModal({ x, releases, onClose, onDone }: { x: Install; releases: Release[]; onClose: () => void; onDone: Done }) { + const [form0] = useState(() => ({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, asap: true, reason: "", totp: "" })); + const [upd, setUpd] = useState(form0); + const { busy, error, run } = useSubmit(); + const asap = upd.emergency && upd.asap; + const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H; + const mine = releases.filter(r => r.product === x.product); + + const save = (e: React.FormEvent) => { + e.preventDefault(); + run(async () => { + const r = await post("/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 }); + onDone({ type: "ok", text: withWarnings(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.", r) }); + }); + }; + + return ( + +
+
+
+ + +

Now on {x.install?.version || x.version || "an unknown version"}.

+
+ {asap + ?
When

As soon as possible: the agent starts within a minute.

+ :
+ + setUpd({ ...upd, at: e.target.value })} /> +

At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.

+
} +
+ + + + {upd.emergency && ( +
+
+ When the emergency update runs + + +
+
+
setUpd({ ...upd, reason: e.target.value })} />
+
setUpd({ ...upd, totp: e.target.value })} />
+
+
+ )} + + + + +
+ ); +} diff --git a/frontend/src/components/install/shared.ts b/frontend/src/components/install/shared.ts new file mode 100644 index 0000000..fe7a80c --- /dev/null +++ b/frontend/src/components/install/shared.ts @@ -0,0 +1,95 @@ +"use client"; + +import { useRef, useState } from "react"; +import { api, ApiError, errorText } from "@/lib/api"; +import { PRODUCT_NAMES } from "@/lib/products"; +import type { Deployment, Job, ServerSummary } from "@/components/servers"; + +// Hub 2.15.0: what the install page loads once and passes to its cards and popups. + +export type { Msg, Done } from "@/components/customer/shared"; +export { changed } from "@/components/customer/shared"; + +export type Export = { id: string; bytes: number; expiresAt: string; downloadedAt: string | null; deletedAt: string | null }; + +export type Detail = { + deployment: Deployment & { server: ServerSummary; jobs: Job[]; exports: Export[]; install: { version: string | null; url: string; lastHeartbeatAt: string | null } | null }; + fastPanel: string; + canRemoveRecord: boolean; + /** 2.12.0: no heartbeat for 24 hours, so it can be removed from the Hub. */ + stale: { since: string | null; stale: boolean }; + /** 2.12.0: what an uninstall removes: this product only (agent 1.5.0+), or the whole church. */ + uninstall: { + onlyThisProduct: boolean; minAgent: string; others: { id: string; product: string; domain: string; status: string }[]; + /** The church's uninstalls not run yet; `products` null: the whole church. `joinable`: this one can still be added to it. */ + pending: { jobId: string; notBefore: string; products: string[] | null; joinable: boolean }[]; + /** Every other product is being uninstalled: this one takes the whole church with it. */ + lastProduct: boolean; + }; +}; +export type Install = Detail["deployment"]; + +export const productName = (p: string) => PRODUCT_NAMES[p as keyof typeof PRODUCT_NAMES] || p; + +export const H = 60 * 60 * 1000; + +/** The statuses an install can be changed in (its .env, demo data, an uninstall). */ +export const running = (x: Install) => ["live", "waiting_for_proxy"].includes(x.status); + +/** + * A POST to the Hub. Hub 2.7.0: when an event is on the site now, the Hub refuses with LIVE_EVENT: + * ask once more and send it again with confirmLive. + */ +export async function post(path: string, body: Record = {}): Promise { + try { + return await api(path, { method: "POST", body }); + } catch (e) { + if (e instanceof ApiError && e.code === "LIVE_EVENT" && !body.confirmLive && window.confirm(e.message)) return post(path, { ...body, confirmLive: true }); + throw e; + } +} + +/** A success message with the Hub's warnings after it. */ +export const withWarnings = (ok: string, r?: { warnings?: string[] } | null) => `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}`; + +/** + * 2.7.1: one click is one job: `run` does nothing while the last one hasn't answered. A thrown + * error lands in `error`, for the popup to show by its button. + */ +export function useSubmit() { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const inFlight = useRef(false); + const run = async (fn: () => Promise) => { + if (inFlight.current) return; + inFlight.current = true; + setBusy(true); + setError(null); + try { await fn(); } catch (e) { setError(errorText(e)); } finally { inFlight.current = false; setBusy(false); } + }; + return { busy, error, run }; +} + +/** 2.12.0: what an uninstall of this install takes with it, and what stops it. */ +export function uninstallPlan(d: Detail) { + const x = d.deployment; + const plan = d.uninstall; + const othersStaying = plan.others.filter(o => o.status !== "uninstalling"); + // The church's uninstalls not run yet (by product), and the one this could join. + const pendingRuns = plan.pending.filter(p => p.products); + const joinable = pendingRuns.find(p => p.joinable) || null; + return { + ...plan, + othersStaying, + pendingRuns, + joinable, + // Accounts goes last: the church's other products sign in through it. + accountsInUse: x.product === "accounts" && othersStaying.length > 0, + // An agent before minAgent can only remove the whole church, with its other products. + wholeChurch: !plan.onlyThisProduct && plan.others.length > 0, + lastNow: plan.onlyThisProduct && plan.lastProduct, + /** An uninstall already planned that takes this install: its own, or the whole church's. */ + planned: plan.pending.find(p => !p.products || p.products.includes(x.product)) || null, + }; +} +export type UninstallPlan = ReturnType; diff --git a/frontend/src/components/ui.tsx b/frontend/src/components/ui.tsx index fe5c406..d2b1e9a 100644 --- a/frontend/src/components/ui.tsx +++ b/frontend/src/components/ui.tsx @@ -143,6 +143,27 @@ export function Modal({ title, onClose, dirty = false, wide = false, children }: ); } +/** + * The one message under a page's header (Hub 2.14.0, shared in 2.15.0): it stays in view while you + * scroll, an "ok" fades after a while, an error stays until it's closed or replaced. + */ +export function PageMessage({ msg, onClose }: { msg: { type: "ok" | "err"; text: string } | null; onClose: () => void }) { + const close = React.useRef(onClose); + close.current = onClose; + React.useEffect(() => { + if (msg?.type !== "ok") return; + const t = setTimeout(() => close.current(), 12000); + return () => clearTimeout(t); + }, [msg]); + if (!msg) return null; + return ( +
+ + +
+ ); +} + /** The error of a form in a popup, next to its Save button. */ export function FormError({ error }: { error: string | null }) { return error ?

{error}

: null;