Hub 2.24.0: update everything at a church to latest

A customer's Sites card has "Update everything to latest": every product
that's behind, in one batch (Accounts first, one at a time, stopping at the
first failure), scheduled or as an emergency, planned whole or not at all.
Later products keep Accounts at the version the batch updates it to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 08:20:21 +02:00
co-authored by Claude Opus 5.5
parent 6ccf492810
commit 2f2e7138ba
11 changed files with 314 additions and 19 deletions
+25
View File
@@ -5,6 +5,31 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.24.0] - 2026-11-27
No migration; no API is removed.
### Added
- **Update everything at a church to latest** (customer → Overview → Sites → "Update everything
to latest"). The popup lists each product with its version and its latest release, and which are
already on it. One click plans every product that's behind in one batch, one at a time:
Accounts first, then Cross Events, the Church Website and the App, stopping at the first failure
(the rest are told it's postponed). It can be planned like any update, at least 4 hours ahead, or
as an emergency with a reason and a two-factor code, at least 15 minutes ahead or as soon as
possible. Each product is checked as its own update would be, all before anything is made, so
it's planned whole or not at all. A product with an update already planned or running, or that
isn't live, stops it and is named. Each site's admin gets the usual email and banner.
`GET /api/admin/customers/:id/update-plan`, `POST /api/admin/customers/:id/update-all`
(audit `church_update_scheduled` / `emergency_church_update_scheduled`).
### Changed
- `scheduleUpdate` takes internal options for a church update: requirements met by a product
earlier in the same batch count as met, and a later product's deploy keeps Accounts at the
version the batch updates it to (before, it would have pinned the version Accounts ran when it
was planned, undoing the update before it).
## [2.23.1] - 2026-11-26
No migration; no API is removed.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "2.23.1",
"version": "2.24.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.23.1",
"version": "2.24.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.23.1",
"version": "2.24.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
+11
View File
@@ -293,6 +293,17 @@ router.post('/updates', wrap(async (req, res) => {
res.status(201).json(out);
}));
// Hub 2.24.0: a whole church (customer) to the latest release of each product, in one batch.
router.get('/customers/:id/update-plan', wrap(async (req, res) => {
res.json({ products: await jobs.churchUpdatePlan(req.params.id) });
}));
router.post('/customers/:id/update-all', wrap(async (req, res) => {
const out = await jobs.scheduleChurchUpdate(req.params.id, req.body || {}, req.admin);
await audit(req, req.body?.emergency ? 'emergency_church_update_scheduled' : 'church_update_scheduled', out.batchId, { customerId: req.params.id, updates: out.updates, at: req.body?.asap ? 'as soon as possible' : req.body?.at, reason: req.body?.reason || null, ...(req.body?.confirmLive ? { duringLiveEvent: true } : {}) });
res.status(201).json(out);
}));
// ─── Jobs ─────────────────────────────────────────────────────────────────────
// Hub 2.6.0: paged (?page, ?pageSize), with filters for every status (succeeded too), a job type,
+89 -8
View File
@@ -1139,8 +1139,10 @@ function scheduleWarnings(at, deployment) {
* - otherwise: the version it runs, so it isn't changed
* Returns { version: 'accounts@x' | null, install: { domain, release } | null, note }.
*/
async function accountsPlan(d, release, accountsRelease) {
async function accountsPlan(d, release, accountsRelease, upcomingAccounts = null) {
if (d.product === 'accounts') return { version: null, install: null, note: null };
// Hub 2.24.0: Accounts is updated earlier in the same church update, so this deploy keeps it there.
if (upcomingAccounts) return { version: `accounts@${upcomingAccounts}`, install: null, note: null };
const acc = await prisma.deployment.findFirst({ where: { shortName: d.shortName, product: 'accounts', status: { notIn: ['removed', 'failed'] } }, include: { install: true } });
const running = acc ? (acc.install?.version || acc.version || null) : null;
const releases = await prisma.release.findMany({ where: { product: d.product } });
@@ -1172,7 +1174,15 @@ async function liveAt(d, now = new Date()) {
return { eventsNow: Number(live.eventsNow) || 0, checkInsLastHour: Number(live.checkInsLastHour) || 0 };
}
async function scheduleUpdate({ deploymentIds, product: wanted = null, version, at, emergency = false, asap = false, confirmLive = false, reason = null, totp = null }, admin, now = new Date()) {
/**
* `opts` (Hub 2.24.0, never from a request): for a whole church's update (scheduleChurchUpdate).
* upcoming { product: version } updated earlier in the same batch: their requirements count as met
* batch { id, order } shared by every product's jobs; only the batch's first job is queued
* dryRun every check, nothing made
* totpChecked the two-factor code was checked once already
*/
async function scheduleUpdate({ deploymentIds, product: wanted = null, version, at, emergency = false, asap = false, confirmLive = false, reason = null, totp = null }, admin, now = new Date(), opts = {}) {
const upcoming = opts.upcoming || {};
// Hub 2.7.0: an emergency update can run as soon as possible (the agent's next poll, within a
// minute) instead of at a time at least 15 minutes away (decision 30, changed 2026-11-19).
if (asap && !emergency) throw fail(400, 'BAD_REQUEST', 'Only an emergency update runs as soon as possible.');
@@ -1180,7 +1190,7 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
if (Number.isNaN(when.getTime())) throw fail(400, 'BAD_REQUEST', 'Pick a time.');
if (emergency) {
if (!reason || !String(reason).trim()) throw fail(400, 'BAD_REQUEST', 'An emergency update needs a reason (it goes in the email and banner).');
requireTotp(admin, totp);
if (!opts.totpChecked) requireTotp(admin, totp);
if (!asap && when - now < EMERGENCY_MIN_MINUTES * MIN) throw fail(400, 'TOO_SOON', `An emergency update at a time needs at least ${EMERGENCY_MIN_MINUTES} minutes' notice (or choose as soon as possible).`);
} else if (when - now < SCHEDULE_MIN_HOURS * HOUR) {
throw fail(400, 'TOO_SOON', `Updates are planned at least ${SCHEDULE_MIN_HOURS} hours ahead (or as an emergency update).`);
@@ -1222,7 +1232,8 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', `${d.shortName}'s server was removed.`);
if (d.install) {
// Accounts is handled below (kept, updated, or installed first); anything else must be met.
const unmet = (await unmetRequirementsFor(d.install, release.version)).filter(u => u.product !== 'accounts');
const unmet = (await unmetRequirementsFor(d.install, release.version))
.filter(u => u.product !== 'accounts' && !(upcoming[u.product] && compareVersions(upcoming[u.product], u.version) >= 0));
if (unmet.length) throw fail(409, 'REQUIREMENT_NOT_MET', `${d.shortName}: ${release.version} needs ${unmet.map(u => `${u.product} ${u.version}`).join(', ')} first.`);
}
const missing = await missingFor(product, release.version, servers.serverConfig(d.server), await servers.installDefaults());
@@ -1230,19 +1241,23 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
const invalid = invalidFor(servers.serverConfig(d.server), await servers.installDefaults());
if (invalid.length) throw fail(409, 'CONFIG_INVALID', `${d.shortName}: fix ${d.server.name}'s configuration first. ${invalid.join(' ')}`);
warnings.push(...scheduleWarnings(when, d));
const plan = await accountsPlan(d, release, accountsRelease);
const plan = await accountsPlan(d, release, accountsRelease, upcoming.accounts || null);
if (plan.install) await preflight(d.server, 'accounts', plan.install.release.version, now);
if (plan.note) warnings.push(plan.note);
plans.set(d.id, plan);
}
if (opts.dryRun) return { jobs: [], batchId: null, warnings: [...new Set(warnings)] };
const installsFirst = [...plans.values()].filter(p => p.install).length;
const batchId = deployments.length + installsFirst > 1 ? servers.newId('batch') : null;
const batchId = opts.batch ? opts.batch.id : deployments.length + installsFirst > 1 ? servers.newId('batch') : null;
const name = PRODUCT_NAMES[product];
const jobs = [];
let order = 0;
for (const d of deployments) {
const plan = plans.get(d.id);
const next = () => ({ batchId, batchOrder: batchId ? order : null, status: !batchId || order++ === 0 ? 'queued' : 'scheduled' });
const next = () => {
if (opts.batch) { const o = opts.batch.order++; return { batchId, batchOrder: o, status: o === 0 ? 'queued' : 'scheduled' }; }
return { batchId, batchOrder: batchId ? order : null, status: !batchId || order++ === 0 ? 'queued' : 'scheduled' };
};
if (plan.install) {
// The church's Accounts, installed just before its update (a licence, ports, an add-product job).
const acc = await prisma.$transaction(async tx => {
@@ -1287,6 +1302,72 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
return { jobs, batchId, warnings: [...new Set(warnings)] };
}
/**
* Hub 2.24.0: a church's products and their latest releases, for "Update everything to latest".
* In update order (Accounts first: the others sign in through it). `behind`: a newer release
* exists; `ready`: it's behind, live, and has no update planned or running (else `why` says).
*/
async function churchUpdatePlan(customerId) {
const deployments = await prisma.deployment.findMany({ where: { customerId, status: { notIn: ['removed', 'failed'] } }, include: { install: true } });
deployments.sort((a, b) => PRODUCT_ORDER.indexOf(a.product) - PRODUCT_ORDER.indexOf(b.product) || a.domain.localeCompare(b.domain));
const latest = {};
const out = [];
for (const d of deployments) {
if (!(d.product in latest)) {
const releases = await prisma.release.findMany({ where: { product: d.product } });
latest[d.product] = releases.sort((a, b) => compareVersions(b.version, a.version))[0]?.version || null;
}
const to = latest[d.product];
const current = d.install?.version || d.version || null;
const pending = await prisma.job.findFirst({ where: { deploymentId: d.id, type: 'deploy', status: { in: ['scheduled', 'queued', 'delivered'] } } });
const behind = !!to && (!current || compareVersions(current, to) < 0);
let why = null;
if (!behind) why = to ? 'On the latest release.' : 'No releases yet.';
else if (d.status !== 'live') why = `Not live (${d.status}).`;
else if (pending) why = pending.status === 'delivered' ? 'An update is running.' : `An update is planned for ${sast(pending.notBefore)}.`;
out.push({ id: d.id, product: d.product, shortName: d.shortName, domain: d.domain, status: d.status, current, latest: to, behind, ready: behind && !why, why });
}
return out;
}
/**
* Hub 2.24.0: every product of a church that's behind, to its latest release, in one batch: one
* at a time from `at` (or as soon as possible for an emergency), Accounts first, stopping at the
* first failure. Each product is checked as its own update would be, all before anything is made,
* so it's planned whole or not at all. Each site gets its email and banner as for its own update.
*/
async function scheduleChurchUpdate(customerId, { at, emergency = false, asap = false, confirmLive = false, reason = null, totp = null }, admin, now = new Date()) {
const plan = await churchUpdatePlan(customerId);
if (!plan.length) throw fail(404, 'NOT_FOUND', 'This customer has nothing installed.');
const blocked = plan.filter(p => p.behind && !p.ready);
if (blocked.length) throw fail(409, 'NOT_READY', blocked.map(p => `${PRODUCT_NAMES[p.product]} (${p.domain}): ${p.why}`).join(' '));
const todo = plan.filter(p => p.ready);
if (!todo.length) throw fail(409, 'UP_TO_DATE', 'Everything at this church is on its latest release already.');
// Checked once here (the per-product checks below are told it was); the reason first, as scheduleUpdate does.
if (emergency) {
if (!reason || !String(reason).trim()) throw fail(400, 'BAD_REQUEST', 'An emergency update needs a reason (it goes in the email and banner).');
requireTotp(admin, totp);
}
const input = p => ({ deploymentIds: [p.id], product: p.product, version: p.latest, at, emergency, asap, confirmLive, reason });
// Every product checked in update order, each counting the ones before it as done.
const upcoming = {};
for (const p of todo) {
await scheduleUpdate(input(p), admin, now, { upcoming: { ...upcoming }, dryRun: true, totpChecked: true });
upcoming[p.product] = p.latest;
}
const batch = { id: servers.newId('batch'), order: 0 };
const made = [];
const warnings = [];
const done = {};
for (const p of todo) {
const r = await scheduleUpdate(input(p), admin, now, { upcoming: { ...done }, batch, totpChecked: true });
made.push(...r.jobs);
warnings.push(...r.warnings);
done[p.product] = p.latest;
}
return { jobs: made, batchId: batch.id, warnings: [...new Set(warnings)], updates: todo.map(p => ({ product: p.product, domain: p.domain, from: p.current, to: p.latest })) };
}
/** Cancel a job that hasn't been handed out yet; the church is told and the banner ends. */
async function cancelJob(jobId, admin, now = new Date()) {
const job = await prisma.job.findUnique({ where: { id: jobId }, include: { deployment: { include: { install: true } } } });
@@ -1684,7 +1765,7 @@ async function setEnv(deploymentId, { file, set, unset, restart }, admin, now =
module.exports = {
readEnv, setEnv, envState, readFrp, writeFrp, listFrpcTunnels, portsProbed, probeServers, PROBE_SPARE,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, churchUpdatePlan, scheduleChurchUpdate,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, staleness, forgetStale, uninstallPlan, STALE_MS, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
fastPanelText, fastPanelSteps, notesBlocks, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
+74
View File
@@ -1236,3 +1236,77 @@ describe('frps allow_ports and port labels (Hub 2.20.0)', () => {
expect((await db.serverAlert.findFirst({ where: { serverId: central.id, type: 'allow_ports' } })).resolvedAt).toEqual(NOW);
});
});
describe('a whole church to latest in one go (2.24.0)', () => {
const at = () => new Date(NOW.getTime() + 5 * H);
async function church() {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.release.create({ data: { id: 'r30', product: 'events', version: '3.0.0', notes: '- Accounts', requires: [{ product: 'accounts', version: '1.1.0' }], releasedAt: NOW } });
await db.release.create({ data: { id: 'ra10', product: 'accounts', version: '1.0.0', releasedAt: NOW } });
await db.release.create({ data: { id: 'ra11', product: 'accounts', version: '1.1.0', releasedAt: NOW } });
await db.release.create({ data: { id: 'rw10', product: 'website', version: '1.0.0', releasedAt: NOW } });
const dep = (id, product, version, port) => db.deployment.create({ data: { id, serverId: server.id, customerId: 'cust-1', product, shortName: 'hope', domain: `${product}.hope.co.za`, webPort: port, apiPort: port + 1, status: 'live', version } });
const ev = await dep('ev-hope', 'events', '2.4.0', 22000);
const acc = await dep('acc-hope', 'accounts', '1.0.0', 22010);
const web = await dep('web-hope', 'website', '1.0.0', 22020);
return { server, ev, acc, web };
}
test('the plan lists every product in update order, Accounts first, and says which are behind', async () => {
await church();
const plan = await jobs.churchUpdatePlan('cust-1');
expect(plan.map(p => [p.product, p.current, p.latest, p.ready])).toEqual([
['accounts', '1.0.0', '1.1.0', true], ['events', '2.4.0', '3.0.0', true], ['website', '1.0.0', '1.0.0', false],
]);
expect(plan[2].why).toBe('On the latest release.');
});
test('one batch: Accounts first, then Events, which keeps the new Accounts; up to date products are left alone', async () => {
const { server } = await church();
const out = await jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW);
expect(out.batchId).toMatch(/^batch_/);
expect(out.jobs.map(j => [j.deploymentId, j.status, j.batchOrder, j.batchId])).toEqual([
['acc-hope', 'queued', 0, out.batchId], ['ev-hope', 'scheduled', 1, out.batchId],
]);
expect(out.jobs[0].args.versions).toEqual(['accounts@1.1.0']);
// Not accounts@1.0.0: that would undo the update just before it.
expect(out.jobs[1].args.versions).toEqual(['accounts@1.1.0', 'events@3.0.0']);
expect(out.updates).toEqual([
{ product: 'accounts', domain: 'accounts.hope.co.za', from: '1.0.0', to: '1.1.0' },
{ product: 'events', domain: 'events.hope.co.za', from: '2.4.0', to: '3.0.0' },
]);
// The batch runs on: Accounts succeeds, so Events is queued.
const poll = when => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.0.0', mode: 'church', runningJobId: null }, when);
const first = (await poll(at())).jobs[0];
expect(first.id).toBe(out.jobs[0].id);
await jobs.receiveReport(server, signedReport(first, 'succeeded'), at());
expect((await db.job.findUnique({ where: { id: out.jobs[1].id } })).status).toBe('queued');
// Everything is planned now: a second click is refused.
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_READY' });
});
test('planned whole or not at all, and refused when there is nothing to update', async () => {
const { ev } = await church();
await jobs.scheduleUpdate({ deploymentIds: [ev.id], version: '2.4.0', at: at() }, admin, NOW).catch(() => null);
const { jobs: [planned] } = await jobs.scheduleUpdate({ deploymentIds: ['acc-hope'], version: '1.1.0', at: at() }, admin, NOW);
const before = await db.job.count();
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'NOT_READY', message: expect.stringContaining('Accounts (accounts.hope.co.za): An update is planned') });
expect(await db.job.count()).toBe(before);
expect(planned.status).toBe('queued');
await db.deployment.update({ where: { id: 'ev-hope' }, data: { version: '3.0.0' } });
await db.deployment.update({ where: { id: 'acc-hope' }, data: { version: '1.1.0' } });
await db.job.update({ where: { id: planned.id }, data: { status: 'cancelled' } });
await expect(jobs.scheduleChurchUpdate('cust-1', { at: at() }, admin, NOW)).rejects.toMatchObject({ code: 'UP_TO_DATE' });
});
test('an emergency runs as soon as possible, with a reason and one two-factor code', async () => {
await church();
await expect(jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, reason: 'Security fix', totp: '000000' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_TOTP' });
await expect(jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ message: expect.stringContaining('reason') });
const out = await jobs.scheduleChurchUpdate('cust-1', { emergency: true, asap: true, reason: 'Security fix', totp: totpNow() }, admin, NOW);
expect(out.jobs.map(j => [j.emergency, j.reason, j.status])).toEqual([[true, 'Security fix', 'queued'], [true, 'Security fix', 'scheduled']]);
expect(out.jobs[0].notBefore).toEqual(NOW);
});
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.23.1",
"version": "2.24.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.23.1",
"version": "2.24.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.23.1",
"version": "2.24.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
@@ -16,6 +16,7 @@ import { ScheduleCard, ScheduleModal } from "@/components/customer/ScheduleCard"
import { AddressCard, AddressModal } from "@/components/customer/AddressCard";
import { AiCard, AiModal } from "@/components/customer/AiCard";
import { SitesCard } from "@/components/customer/SitesCard";
import { ChurchUpdateModal } from "@/components/customer/ChurchUpdateModal";
import { ProductCard } from "@/components/customer/ProductCard";
import { AddProductModal } from "@/components/customer/AddProductModal";
import { NextInvoiceModal } from "@/components/customer/NextInvoice";
@@ -29,7 +30,7 @@ const TABS: { key: Tab; label: string }[] = [
{ key: "products", label: "Products" },
{ key: "invoices", label: "Invoices and payments" },
];
type Popup = Exclude<HeaderAction, "history"> | "schedule" | null;
type Popup = Exclude<HeaderAction, "history"> | "schedule" | "update" | null;
/** The tab in the address (?tab=products); the old #billing link opens Invoices and payments. */
function tabFromUrl(): Tab {
@@ -103,7 +104,7 @@ export default function CustomerPage() {
<div className="grid gap-4 lg:grid-cols-2">
<div className="space-y-4">
{b && <DetailsCard c={c} b={b} onDone={done} />}
<SitesCard c={c} />
<SitesCard c={c} onUpdateAll={() => setPopup("update")} />
</div>
<div className="space-y-4">
{b && <ScheduleCard b={b} onEdit={() => setPopup("schedule")} />}
@@ -144,6 +145,7 @@ export default function CustomerPage() {
{popup === "schedule" && b && <ScheduleModal b={b} onClose={close} onDone={done} />}
{popup === "address" && b && <AddressModal b={b} onClose={close} onDone={done} />}
{popup === "ai" && <AiModal c={c} onClose={close} onDone={done} />}
{popup === "update" && <ChurchUpdateModal customerId={id} name={c.name} onClose={close} onDone={done} />}
</>
);
}
@@ -0,0 +1,97 @@
"use client";
import React, { useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { PRODUCT_NAMES } from "@/lib/products";
import { FormError, Loading, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { fromInput, toInput } from "@/components/servers";
import { H, changed, post, withWarnings } from "@/components/install/shared";
import type { Done } from "./shared";
type PlanRow = { id: string; product: keyof typeof PRODUCT_NAMES; domain: string; current: string | null; latest: string | null; behind: boolean; ready: boolean; why: string | null };
/**
* Hub 2.24.0: every product of a church to its latest release, in one batch (Accounts first, one
* at a time, stopping at the first failure). Planned like one install's update: at a time at least
* 4 hours away, or an emergency with a reason and a two-factor code, at least 15 minutes away or
* as soon as possible. Each site's admin is emailed and sees a banner.
*/
export function ChurchUpdateModal({ customerId, name, onClose, onDone }: { customerId: string; name: string; onClose: () => void; onDone: Done }) {
const [plan, setPlan] = useState<PlanRow[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [form0] = useState(() => ({ at: toInput(new Date(Date.now() + 5 * H)), emergency: false, asap: true, reason: "", totp: "" }));
const [f, setF] = useState(form0);
const { busy, error, run } = useSubmit();
useEffect(() => {
api<{ products: PlanRow[] }>(`/api/admin/customers/${customerId}/update-plan`).then(r => setPlan(r.products)).catch(e => setLoadError(errorText(e)));
}, [customerId]);
const asap = f.emergency && f.asap;
const minAt = f.emergency ? 15 * 60 * 1000 : 4 * H;
const todo = plan?.filter(p => p.ready) || [];
const blocked = plan?.filter(p => p.behind && !p.ready) || [];
const save = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await post<{ warnings: string[]; updates: unknown[] }>(`/api/admin/customers/${customerId}/update-all`, { at: asap ? undefined : fromInput(f.at), asap, emergency: f.emergency, reason: f.reason || null, totp: f.totp || null });
const n = r.updates.length;
onDone({ type: "ok", text: withWarnings(`${n} product${n === 1 ? "" : "s"} ${asap ? "updating now, one at a time" : "planned, one after the other"}. Each site's admin was emailed and sees a banner.`, r) });
});
};
return (
<Modal title={`Update everything at ${name} to latest`} onClose={onClose} dirty={changed(f, form0)} wide>
{!plan ? (loadError ? <FormError error={loadError} /> : <Loading />) : (
<form onSubmit={save} className="space-y-4">
<ul className="divide-y divide-slate-100 rounded-lg border border-slate-200 text-sm">
{plan.map(p => (
<li key={p.id} className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5 px-3 py-2">
<span className="min-w-0"><span className="font-medium">{PRODUCT_NAMES[p.product] || p.product}</span> <span className="break-all text-slate-500">{p.domain}</span></span>
{p.ready
? <span className="font-medium text-indigo-700">{p.current || "unknown"} → {p.latest}</span>
: <span className={p.behind ? "text-amber-700" : "text-slate-500"}>{p.current || "unknown"} · {p.why}</span>}
</li>
))}
</ul>
{blocked.length > 0 && <p role="alert" className="text-sm text-amber-800">Some products can&apos;t be updated now (see above). Wait for, or cancel, their update first: nothing is planned until every product that&apos;s behind can be.</p>}
{todo.length === 0 && blocked.length === 0 && <p className="text-sm text-slate-600">Everything is on its latest release already.</p>}
{todo.length > 0 && blocked.length === 0 && (
<>
<p className="text-sm text-slate-600">One at a time, in this order{todo.length > 1 ? `, starting ${asap ? "now" : "at the time below"}` : ""}. If one fails, the rest wait and their admins are told it&apos;s postponed.</p>
{asap
? <div><span className="label">When</span><p className="mt-2 text-sm">As soon as possible: the agent starts within a minute.</p></div>
: <div>
<label className="label" htmlFor="cu-at">When</label>
<input id="cu-at" type="datetime-local" className="input sm:w-64" value={f.at} min={toInput(new Date(Date.now() + minAt))} onChange={e => setF({ ...f, at: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">At least {f.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.</p>
</div>}
<label className="flex items-start gap-2 text-sm"><input type="checkbox" className="mt-1" checked={f.emergency} onChange={e => setF({ ...f, emergency: e.target.checked })} /> <span>Emergency (security fix or broken release): a reason and your two-factor code</span></label>
{f.emergency && (
<div className="space-y-3 rounded-lg border border-red-200 bg-red-50/40 p-3">
<fieldset className="flex flex-wrap gap-4 text-sm">
<legend className="sr-only">When the emergency update runs</legend>
<label className="flex items-center gap-2"><input type="radio" name="cu-when" checked={f.asap} onChange={() => setF({ ...f, asap: true })} /> As soon as possible (within a minute)</label>
<label className="flex items-center gap-2"><input type="radio" name="cu-when" checked={!f.asap} onChange={() => setF({ ...f, asap: false })} /> At a time, at least 15 minutes away</label>
</fieldset>
<div className="grid gap-3 sm:grid-cols-2">
<div><label className="label" htmlFor="cu-r">Reason (shown to the church)</label><input id="cu-r" className="input" required value={f.reason} onChange={e => setF({ ...f, reason: e.target.value })} /></div>
<div><label className="label" htmlFor="cu-t">Two-factor code</label><input id="cu-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={f.totp} onChange={e => setF({ ...f, totp: e.target.value })} /></div>
</div>
</div>
)}
</>
)}
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} danger={f.emergency} disabled={todo.length === 0 || blocked.length > 0}
label={asap ? `Update ${todo.length === 1 ? "it" : `all ${todo.length}`} now` : `Schedule ${todo.length === 1 ? "the update" : `${todo.length} updates`}`} />
</form>
)}
</Modal>
);
}
@@ -1,15 +1,20 @@
import React from "react";
import Link from "next/link";
import { RefreshCw } from "lucide-react";
import { ago } from "@/lib/format";
import { PRODUCT_NAMES, byProduct } from "@/lib/products";
import type { Customer } from "@/lib/types";
import { ReadCard } from "@/components/ui";
/** The church's sites: where each product runs and when it last checked in. */
export function SitesCard({ c }: { c: Customer }) {
/**
* The church's sites: where each product runs and when it last checked in. Hub 2.24.0: "Update
* everything to latest" plans each product's latest release (ChurchUpdateModal).
*/
export function SitesCard({ c, onUpdateAll }: { c: Customer; onUpdateAll?: () => void }) {
const sites = [...c.installs].sort((a, b) => (a.releasedAt ? 1 : 0) - (b.releasedAt ? 1 : 0) || byProduct(a, b));
const live = sites.some(s => !s.releasedAt);
return (
<ReadCard title="Sites">
<ReadCard title="Sites" actions={live && onUpdateAll ? <button type="button" className="btn-secondary px-2.5 py-1.5" onClick={onUpdateAll}><RefreshCw className="h-3.5 w-3.5" /> Update everything to latest</button> : null}>
{sites.length === 0 ? <p className="text-sm text-slate-500">No site has registered yet: enter a product&apos;s licence key in its setup.</p> : (
<ul className="divide-y divide-slate-100 text-sm">
{sites.map(s => (