Hub 2.12.0: one product uninstalled at a time, stale installs removed, customers archived

- Uninstalls name the product (agent 1.5.0); a whole-church uninstall marks every product
  of the church on that server removed. Older agents are refused while the church has others.
- A second product's uninstall joins one already planned (one export and one uninstall) or
  gets its own time; the last product removes the whole church. Accounts goes last.
- Remove an install from the Hub after 24 hours without a heartbeat (POST .../forget).
- Archive and restore customers (migration 20261123090000_customer_archive).
- Several addresses for a customer's email and billing email, with a + button.
- Statements show R0 invoices' amounts. Vendors contracts 1.16.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 09:17:35 +02:00
co-authored by Claude Opus 5.5
parent f3bee827e5
commit 3a00271a02
25 changed files with 683 additions and 61 deletions
+40
View File
@@ -5,6 +5,46 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.12.0] - 2026-11-23
Needs agent 1.5.0 (`agent@1.5.0`) to uninstall one product of a church; vendors contracts 1.16.0.
Migration `20261123090000_customer_archive` (one column on `Customer`).
### Fixed
- **Uninstalling one product removed the whole church, and the Hub didn't know.** The uninstall
job named only the church, so the agent removed every product of it; the Hub marked only the
one install removed, showed the other as live, and its own uninstall later failed. Now the
export and uninstall name the product (agent 1.5.0). A report of a whole-church uninstall (no
products, or the script saying nothing is left) marks every product of the church on that
server removed, frees their ports, refuses their licences' heartbeats and cancels what was
still planned for them. With an older agent, uninstalling one product of a church with others
is refused (update the agent first).
### Added
- **A second product while another is being uninstalled.** The uninstall form asks: add it to
that run (one export and one uninstall for both, at that time; at least 4 hours away, so the
church gets notice) or give it its own time. The last product to go removes the whole church
(its folder and app user) when it runs; the form says so beforehand and the email afterwards.
Accounts goes last: refused while the church's other products stay, and not planned before
their uninstall. A failed or cancelled run puts every product it named back to live.
- **Remove a stale install from the Hub.** An install without a heartbeat for 24 hours shows as
"No heartbeat" and gets "Remove from the Hub" (type its short name): for a site already gone
from its server (uninstalled by hand, server rebuilt). Nothing runs on the server. New:
`POST /api/admin/deployments/:id/forget`.
- **Archive customers.** Archive or restore on the customer's page; archived customers are left
out of the list, pickers and the dashboard count, and listed under Customers → Archived
(`GET /api/admin/customers?archived=1`). Not while it still has installs on a server, sites
sending heartbeats, or billing on.
- **Several email addresses** for a customer's email and billing email, with a + button. Invoices,
statements and receipts go to every billing address. Stored as one comma-separated value, so
no migration.
### Changed
- Statements show an R0 invoice's amount (R0.00) instead of a blank.
## [2.11.0] - 2026-11-21
Needs agent 1.4.0 on the servers (`agent@1.4.0`) for the new parts; vendors contracts 1.15.0.
+6 -6
View File
@@ -1,16 +1,16 @@
{
"name": "events-hub-backend",
"version": "2.11.0",
"version": "2.12.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.11.0",
"version": "2.12.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.15.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.16.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -609,9 +609,9 @@
"license": "MIT"
},
"node_modules/@crosscode/contracts": {
"version": "1.15.0",
"resolved": "file:vendor/crosscode-contracts-1.15.0.tgz",
"integrity": "sha512-NZI53pUP1SpYcWRwH3OeGSvwmf9+v5EPkSG2hwPnhCPUsKYnCHLW/aUCJUHKAB+oQRnJ6SRGR2kxEEnc/8OD+A==",
"version": "1.16.0",
"resolved": "file:vendor/crosscode-contracts-1.16.0.tgz",
"integrity": "sha512-pqqrBS6stQquM+NUW22pb8Z6g4w7HG4fPZozZgp1FC79eT/0/V6VjrmFUcsIasF+RVgl6oug2Spxbq0cx6FUuw==",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.11.0",
"version": "2.12.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
@@ -20,7 +20,7 @@
},
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.15.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.16.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -0,0 +1,3 @@
-- Hub 2.12.0: an archived customer is left out of the customer list (and pickers) until it's
-- restored; its records, invoices and history stay.
ALTER TABLE "Customer" ADD COLUMN "archivedAt" TIMESTAMP(3);
+2
View File
@@ -67,6 +67,8 @@ model Customer {
// the Hub default (Settings → AI).
aiMonthlyCapCents Int @default(0)
aiMarkupPercent Int?
// Hub 2.12.0: archived (left out of the customer list until restored). Nothing else changes.
archivedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
+41 -2
View File
@@ -21,6 +21,7 @@ const { parseRepoUrl, syncReleases, releaseSources, cleanSources } = require('..
const ai = require('../utils/ai');
const { AI_MODELS } = require('../utils/aiModels');
const { requireTotp } = require('../utils/jobs');
const { emailList } = require('../utils/emails');
const router = express.Router();
router.use(protect);
@@ -73,7 +74,7 @@ router.get('/dashboard', wrap(async (req, res) => {
const churches = churchesOf(installs);
const rows = installs.map(i => summary(i, settings, latest, new Date(), churches.get(i.customerId)));
const [customers, licences, openAlerts, billed, sentInvoices] = await Promise.all([
prisma.customer.count(),
prisma.customer.count({ where: { archivedAt: null } }),
prisma.licence.groupBy({ by: ['product', 'status'], _count: { _all: true } }),
prisma.installEvent.count({ where: { resolvedAt: null, level: { not: 'info' } } }),
prisma.customer.findMany({ where: { billingCycle: { not: 'none' } }, include: { licences: { include: { install: true } } } }),
@@ -113,8 +114,11 @@ router.get('/dashboard', wrap(async (req, res) => {
// ─── Customers ────────────────────────────────────────────────────────────────
// Hub 2.12.0: archived customers only with ?archived=1 (and only them).
router.get('/customers', wrap(async (req, res) => {
const archived = req.query.archived === '1' || req.query.archived === 'true';
const customers = await prisma.customer.findMany({
where: { archivedAt: archived ? { not: null } : null },
orderBy: { name: 'asc' },
include: { licences: { select: { id: true, product: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, product: true, url: true, lastHeartbeatAt: true } } },
});
@@ -123,7 +127,9 @@ router.get('/customers', wrap(async (req, res) => {
function customerData(body, { partial = false } = {}) {
const data = {};
for (const f of ['name', 'contactName', 'email', 'phone', 'notes']) if (body?.[f] !== undefined) data[f] = text(body[f], f === 'notes' ? 5000 : 200);
for (const f of ['name', 'contactName', 'phone', 'notes']) if (body?.[f] !== undefined) data[f] = text(body[f], f === 'notes' ? 5000 : 200);
// Hub 2.12.0: one or more addresses (a list, or one value with commas).
if (body?.email !== undefined) data.email = emailList(body.email);
// AI (Hub 2.0: the church's, for all its installs): the monthly cap and an optional markup.
if (body?.aiMonthlyCapCents !== undefined) {
const n = parseInt(body.aiMonthlyCapCents, 10);
@@ -163,6 +169,39 @@ router.put('/customers/:id', wrap(async (req, res) => {
res.json(customer);
}));
/**
* Hub 2.12.0: archive a customer (left out of the list and pickers) or restore it. Not while it
* still has something running or is billed: those would disappear from view.
*/
async function archiveBlockers(customerId) {
const [onServers, sites, customer] = await Promise.all([
prisma.deployment.count({ where: { customerId, status: { notIn: ['removed', 'failed'] } } }),
prisma.install.count({ where: { customerId, releasedAt: null } }),
prisma.customer.findUnique({ where: { id: customerId } }),
]);
const out = [];
if (onServers) out.push(`${onServers} install${onServers === 1 ? ' is' : 's are'} still on a server (uninstall ${onServers === 1 ? 'it' : 'them'}, or remove ${onServers === 1 ? 'it' : 'them'} from the Hub once stale)`);
else if (sites) out.push(`${sites} site${sites === 1 ? '' : 's'} still send${sites === 1 ? 's' : ''} heartbeats (release the licence first)`);
if (customer && customer.billingCycle !== 'none') out.push('it\'s still billed (set billing to "not invoiced" first)');
return out;
}
router.post('/customers/:id/archive', wrap(async (req, res) => {
const customer = await prisma.customer.findUnique({ where: { id: req.params.id } });
if (!customer) throw bad('Customer not found', 404);
const blockers = await archiveBlockers(customer.id);
if (blockers.length) throw bad(`${customer.name} can't be archived yet: ${blockers.join('; ')}.`, 409);
const updated = await prisma.customer.update({ where: { id: customer.id }, data: { archivedAt: customer.archivedAt || new Date() } });
await audit(req, 'customer_archived', customer.id, { name: customer.name });
res.json(updated);
}));
router.post('/customers/:id/restore', wrap(async (req, res) => {
const customer = await prisma.customer.update({ where: { id: req.params.id }, data: { archivedAt: null } }).catch(() => { throw bad('Customer not found', 404); });
await audit(req, 'customer_restored', customer.id, { name: customer.name });
res.json(customer);
}));
// ─── Licences ─────────────────────────────────────────────────────────────────
function licenceData(body, { partial = false } = {}) {
+6 -4
View File
@@ -15,6 +15,7 @@ const { ymd, day, today } = require('../utils/billing/dates');
const { TIERS, PLANS, BUNDLE_PERCENT, STORAGE, ADDRESS } = require('../utils/billing/tiers');
const { addMonths } = require('../utils/billing/dates');
const { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
const { emailList } = require('../utils/emails');
const router = express.Router();
router.use(protect);
@@ -298,9 +299,8 @@ router.put('/customers/:id', wrap(async (req, res) => {
if (b.foundingNote !== undefined) data.foundingNote = text(b.foundingNote, 500);
if (b.billingAddress !== undefined) data.billingAddress = text(b.billingAddress, 500);
if (b.billingEmail !== undefined) {
const e = text(b.billingEmail, 200);
if (e && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) throw bad('That email address doesn\'t look right.');
data.billingEmail = e;
// Hub 2.12.0: invoices, statements and receipts go to every address in the list.
data.billingEmail = emailList(b.billingEmail);
}
// The schedule (Hub 2.0: per customer, for all its products).
if (b.billingCycle !== undefined) {
@@ -359,7 +359,9 @@ router.get('/customers/:id/statement', wrap(async (req, res) => {
router.get('/customers/:id/statement.pdf', wrap(async (req, res) => sendPdf(res, await billing.statementPdfFor(req.params.id, req.query.from, req.query.to))));
router.post('/customers/:id/statement/email', emailLimiter, wrap(async (req, res) => {
const out = await billing.emailStatement(req.params.id, req.body || {});
const body = req.body || {};
// Hub 2.12.0: an override can name several addresses too.
const out = await billing.emailStatement(req.params.id, { ...body, email: body.email ? emailList(body.email) : undefined });
await audit(req, 'statement_sent', req.params.id, { to: out.to, from: out.statement.from, until: out.statement.to });
res.json({ message: `Statement sent to ${out.to}.` });
}));
+10 -2
View File
@@ -198,7 +198,15 @@ router.post('/deployments/link', wrap(async (req, res) => {
router.get('/deployments/:id', wrap(async (req, res) => {
const d = await prisma.deployment.findUnique({ where: { id: req.params.id }, include: { server: true, customer: { select: { id: true, name: true } }, install: true, jobs: { orderBy: { createdAt: 'desc' }, take: 50 }, exports: { select: { id: true, bytes: true, expiresAt: true, downloadedAt: true, deletedAt: true, createdAt: true } } } });
if (!d) throw bad('Not found.', 404);
res.json({ deployment: { ...d, server: serverSummary(d.server) }, fastPanel: await jobs.fastPanelText(d), canRemoveRecord: await jobs.neverInstalled(d) });
res.json({ deployment: { ...d, server: serverSummary(d.server) }, fastPanel: await jobs.fastPanelText(d), canRemoveRecord: await jobs.neverInstalled(d), stale: jobs.staleness(d), uninstall: await jobs.uninstallPlan(d) });
}));
// Hub 2.12.0: an install that's no longer on its server (no heartbeat for 24 hours), removed from
// the Hub only: nothing runs on the server.
router.post('/deployments/:id/forget', wrap(async (req, res) => {
const d = await jobs.forgetStale(req.params.id, { confirm: req.body?.confirm });
await audit(req, 'install_removed_from_hub', d.id, { shortName: d.shortName, product: d.product, server: d.serverId, lastHeardAt: jobs.staleness(d).since });
res.json({ ok: true });
}));
// A failed install's record (nothing of it is on the server, so there's nothing to uninstall).
@@ -252,7 +260,7 @@ router.post('/deployments/:id/seed-demo', wrap(async (req, res) => {
}));
router.post('/deployments/:id/uninstall', wrap(async (req, res) => {
const out = await jobs.scheduleUninstall({ deploymentId: req.params.id, at: req.body?.at, totp: req.body?.totp, confirm: req.body?.confirm }, req.admin);
const out = await jobs.scheduleUninstall({ deploymentId: req.params.id, at: req.body?.at, totp: req.body?.totp, confirm: req.body?.confirm, join: typeof req.body?.join === 'boolean' ? req.body.join : undefined, joinJobId: req.body?.joinJobId || undefined }, req.admin);
await audit(req, 'uninstall_scheduled', req.params.id, { at: out.uninstallJob.notBefore });
res.status(201).json(out);
}));
+1 -1
View File
@@ -260,7 +260,7 @@ function statementPdf({ statement: st, customer, settings: s, recipientEmail })
y = party(doc, y, 'Statement for', customer, recipientEmail);
const rows = [
[shortDate(st.from), '', { text: 'Balance brought forward', bold: true }, '', '', { text: money(st.openingCents), bold: true }],
...st.entries.map(e => [shortDate(e.date), e.reference, e.description, e.debitCents ? money(e.debitCents) : '', e.creditCents ? money(e.creditCents) : '', money(e.balanceCents)]),
...st.entries.map(e => [shortDate(e.date), e.reference, e.description, e.debitCents || e.kind === 'invoice' ? money(e.debitCents) : '', e.creditCents ? money(e.creditCents) : '', money(e.balanceCents)]),
];
y = table(doc, y, [
{ label: 'Date', width: 72 },
+32
View File
@@ -0,0 +1,32 @@
/**
* Hub 2.12.0: a customer's email and billing email can each hold several addresses, kept as one
* comma-separated value ("a@church.org, b@church.org"). The mailer sends to all of them, and an
* invoice keeps the list it went to.
*/
const ONE = /^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/;
const MAX_ADDRESSES = 10;
/** The addresses in a stored value (or what was typed: commas, semicolons or spaces between them). */
function emailsOf(value) {
return String(value || '').split(/[\s,;]+/).map(s => s.trim()).filter(Boolean);
}
/**
* Checks a list (an array or a string) and returns it as stored: each address once, in order,
* joined with ", ", or null when empty. Throws an Error with `status: 400` naming the bad address.
*/
function emailList(value) {
const list = Array.isArray(value) ? value.flatMap(emailsOf) : emailsOf(value);
const seen = new Set();
const out = [];
for (const e of list) {
if (e.length > 254 || !ONE.test(e)) throw Object.assign(new Error(`"${e}" doesn't look like an email address.`), { status: 400 });
const key = e.toLowerCase();
if (!seen.has(key)) { seen.add(key); out.push(e); }
}
if (out.length > MAX_ADDRESSES) throw Object.assign(new Error(`At most ${MAX_ADDRESSES} email addresses.`), { status: 400 });
return out.length ? out.join(', ') : null;
}
module.exports = { emailList, emailsOf, MAX_ADDRESSES };
+183 -24
View File
@@ -34,6 +34,8 @@ const SCHEDULE_MIN_HOURS = 4;
const EMERGENCY_MIN_MINUTES = 15;
const AGENT_ONLINE_MS = 2 * MIN;
const EXPORT_DAYS = 30;
// The crosscode script's order (Accounts first: the others sign in through it).
const PRODUCT_ORDER = ['accounts', 'events', 'website', 'app'];
const SHORT_NAME = /^[a-z][a-z0-9-]{1,30}$/;
const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/;
@@ -213,7 +215,7 @@ async function afterJob(job, { exportKey }, now) {
await emailSiteAdmin(deployment, 'Your church\'s data from Cross Code', {
heading: 'Your data is ready to download',
blocks: [
{ p: `Here is all of ${deployment.customer?.name || 'your church'}'s data from ${PRODUCT_NAMES[deployment.product]}: events, people, registrations, payments, check-ins and rosters, with the uploaded files.` },
{ p: `Here is all of ${deployment.customer?.name || 'your church'}'s data from ${(job.args.products || [deployment.product]).map(p => PRODUCT_NAMES[p]).join(' and ')}: events, people, registrations, payments, check-ins and rosters, with the uploaded files.` },
{ button: { label: 'Download your data', url: link } },
{ note: { kind: 'warning', title: 'Keep this email', text: `The link works until ${exp ? sast(exp.expiresAt) : `${EXPORT_DAYS} days from now`}. The file is encrypted, and only this link (the part after #) can open it: we can't read it, and we can't send the link again.` } },
],
@@ -232,21 +234,31 @@ async function afterJob(job, { exportKey }, now) {
case 'uninstall':
if (!deployment) break;
if (ok) {
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'removed', removedAt: now } });
await prisma.port.updateMany({ where: { port: { in: [deployment.webPort, deployment.apiPort] } }, data: { releasedAt: now, deploymentId: deployment.id } });
if (deployment.installId) await prisma.install.update({ where: { id: deployment.installId }, data: { releasedAt: now } });
await makeJob(prisma, { serverId: deployment.serverId, type: 'purge', args: { church: deployment.shortName }, deploymentId: deployment.id, notBefore: new Date(now.getTime() + EXPORT_DAYS * DAY), windowMinutes: 3 * 24 * 60 });
await emailJoshua(`Uninstalled: ${deployment.shortName}`, {
heading: `${deployment.domain} is uninstalled`,
// Hub 2.12.0: with `products` (agent 1.5.0) only those went. Without it the agent removed
// the whole church, so its other products on this server are gone too (before 2.12.0
// they stayed "live" here, and their own uninstall failed later).
// A run can name several products (one joined to another's uninstall). When the script
// reports nothing left of the church (`remaining` empty: the last product went, so the
// church's folder and app user went too), every product of it here is gone.
const whole = !job.args?.products;
const all = [deployment, ...(await churchSiblings(deployment))];
const remaining = job.report?.result?.remaining;
const churchGone = whole || (Array.isArray(remaining) && remaining.length === 0);
const gone = churchGone ? all : all.filter(x => job.args.products.includes(x.product));
for (const g of gone) await markRemoved(g, now, { except: job.id, why: `Not needed: ${g.domain} was uninstalled by ${job.id}.` });
await makeJob(prisma, { serverId: deployment.serverId, type: 'purge', args: { church: deployment.shortName, ...(whole ? {} : { products: job.args.products }) }, deploymentId: deployment.id, notBefore: new Date(now.getTime() + EXPORT_DAYS * DAY), windowMinutes: 3 * 24 * 60 });
await emailJoshua(`Uninstalled: ${deployment.shortName}${whole ? '' : ` (${job.args.products.map(p => PRODUCT_NAMES[p]).join(' and ')})`}`, {
heading: `${gone.map(g => g.domain).join(' and ')} ${gone.length === 1 ? 'is' : 'are'} uninstalled`,
sub: 'One thing left to do by hand.',
blocks: [
{ note: { kind: 'warning', title: 'Remove the FastPanel site', text: `${deployment.domain} (ports ${deployment.webPort} and ${deployment.apiPort}).` } },
...gone.map(g => ({ note: { kind: 'warning', title: 'Remove the FastPanel site', text: `${g.domain} (ports ${g.webPort} and ${g.apiPort}).` } })),
...(churchGone ? [{ p: `Nothing of ${deployment.shortName} is left on ${deployment.server?.name || 'the server'}: its folder and app user were removed too.` }] : []),
{ p: `The final backup is kept on the server for ${EXPORT_DAYS} days, then purged.` },
...jobReportBlocks(job),
],
});
} else {
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: statusBeforeUninstall(deployment) } });
await uninstallNotRun(job, deployment);
await emailJoshua(`Uninstall failed: ${deployment.shortName}`, jobReport(job, `${deployment.domain} wasn't uninstalled`, 'The site is as it was.'));
}
break;
@@ -307,7 +319,7 @@ async function advanceBatch(job, now) {
// An uninstall that won't run (its export failed): the install is still there. Before 2.3.2 it
// stayed "uninstalling" for good.
if (j.deployment && j.type === 'uninstall') {
await prisma.deployment.update({ where: { id: j.deployment.id }, data: { status: statusBeforeUninstall(j.deployment) } });
await uninstallNotRun(j, j.deployment);
}
// Hub 2.5.0: the product after a failed Accounts install never ran: its record fails and its ports are freed.
if (j.deployment && (j.type === 'install' || j.type === 'add-product')) {
@@ -1234,7 +1246,7 @@ async function cancelJob(jobId, admin, now = new Date()) {
});
}
if (job.batchId) await advanceBatch(updated, now);
if (job.type === 'uninstall' && job.deployment) await prisma.deployment.update({ where: { id: job.deployment.id }, data: { status: statusBeforeUninstall(job.deployment) } });
if (job.type === 'uninstall' && job.deployment) await uninstallNotRun(job, job.deployment);
return updated;
}
@@ -1243,6 +1255,19 @@ function statusBeforeUninstall(d) {
return d.liveAt || d.installId ? 'live' : 'waiting_for_proxy';
}
/**
* An uninstall that failed or won't run: every install it named is still on the server (2.12.0:
* a run can name several products, when one was added to another's uninstall).
*/
async function uninstallNotRun(job, deployment) {
const products = job.args?.products;
const all = products ? [deployment, ...(await churchSiblings(deployment))] : [deployment];
for (const t of all) {
if (t.id !== deployment.id && (!products.includes(t.product) || t.status !== 'uninstalling')) continue;
await prisma.deployment.update({ where: { id: t.id }, data: { status: statusBeforeUninstall(t) } });
}
}
/**
* Whether an install never made it onto the server, so its record can simply be removed: its
* install failed (the server already removed what it made) and nothing is planned for it. Also
@@ -1268,36 +1293,170 @@ async function removeFailedInstall(deploymentId) {
return d;
}
const agentAtLeast = (server, version) => compareVersions(server?.agentVersion || '0.0.0', version) >= 0;
/** The church's other products on the same server that are still there (2.12.0). */
function churchSiblings(d) {
return prisma.deployment.findMany({ where: { serverId: d.serverId, shortName: d.shortName, id: { not: d.id }, status: { notIn: ['removed', 'failed'] } }, include: { install: true, server: true, customer: true } });
}
/**
* An install is gone from its server: removed here, its ports freed (after 30 days, as for any
* uninstall), its licence's heartbeats refused, and what was still planned for it cancelled.
*/
async function markRemoved(d, now, { except = null, why = 'Not needed: the install is removed.' } = {}) {
await prisma.deployment.update({ where: { id: d.id }, data: { status: 'removed', removedAt: now } });
await prisma.port.updateMany({ where: { port: { in: [d.webPort, d.apiPort] } }, data: { releasedAt: now, deploymentId: d.id } });
if (d.installId) await prisma.install.update({ where: { id: d.installId }, data: { releasedAt: now } });
const open = await prisma.job.findMany({ where: { deploymentId: d.id, status: { in: ['scheduled', 'queued'] } } });
for (const j of open) {
if (j.id === except) continue;
await prisma.job.update({ where: { id: j.id }, data: { status: 'cancelled', message: why, finishedAt: now } });
if (j.noticeId) await endNotice(j.noticeId, now);
}
}
/**
* The church's uninstalls on this server that haven't run yet (2.12.0), soonest first: when, what
* they remove (`products` null: the whole church), and whether another product can still be added
* to the run (its export hasn't started).
*/
async function pendingUninstalls(d, siblings) {
const list = await prisma.job.findMany({ where: { type: 'uninstall', deploymentId: { in: [d.id, ...siblings.map(s => s.id)] }, status: { in: ['scheduled', 'queued'] } }, orderBy: { notBefore: 'asc' } });
const out = [];
for (const job of list) {
const exportJob = job.batchId ? await prisma.job.findFirst({ where: { batchId: job.batchId, type: 'export' } }) : null;
const products = job.args?.products || null;
const joinable = !!products && job.status === 'scheduled' && (!exportJob || ['scheduled', 'queued'].includes(exportJob.status));
out.push({ job, exportJob, products, joinable });
}
return out;
}
/**
* What an uninstall of this install would remove (for the install's page): only this product, or
* the whole church with an agent before 1.5.0 (then refused while there are others). `pending`:
* the church's uninstalls not run yet, which this one can join. `lastProduct`: every other product
* is being uninstalled, so (at its own, later time) this one takes the whole church with it.
*/
async function uninstallPlan(d) {
const others = await churchSiblings(d);
const pending = await pendingUninstalls(d, others);
return {
onlyThisProduct: agentAtLeast(d.server, agent.PRODUCT_UNINSTALL_MIN_AGENT),
minAgent: agent.PRODUCT_UNINSTALL_MIN_AGENT,
others: others.map(o => ({ id: o.id, product: o.product, domain: o.domain, status: o.status })),
pending: pending.map(p => ({ jobId: p.job.id, notBefore: p.job.notBefore, products: p.products, joinable: p.joinable })),
lastProduct: others.length > 0 && others.every(o => o.status === 'uninstalling'),
};
}
/** Hub 2.12.0: an install's record can be removed by hand once it's sent nothing for this long. */
const STALE_MS = DAY;
/** When the install was last heard from: its last heartbeat, else when it went live or was made. */
function lastHeardAt(d) {
return d.install?.lastHeartbeatAt || d.liveAt || d.createdAt || null;
}
/** Whether an install's record can be removed without an uninstall: no heartbeat for 24 hours. */
function staleness(d, now = new Date()) {
const since = lastHeardAt(d);
const stale = !['removed', 'failed', 'installing'].includes(d.status) && !!since && now - new Date(since) >= STALE_MS;
return { since, stale };
}
/**
* Remove an install from the Hub that's no longer on its server (uninstalled by hand, the server
* rebuilt …): nothing runs on the server. Only after 24 hours without a heartbeat, typing the short
* name; what was planned for it is cancelled.
*/
async function forgetStale(deploymentId, { confirm }, now = new Date()) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to confirm.`);
if (!staleness(d, now).stale) throw fail(409, 'NOT_STALE', 'Only an install that hasn\'t sent a heartbeat for 24 hours can be removed from the Hub; a working one is uninstalled.');
const running = await prisma.job.count({ where: { deploymentId: d.id, status: 'delivered' } });
if (running) throw fail(409, 'BUSY', 'The agent is running a job for it: wait for its report.');
await markRemoved(d, now, { why: 'Not needed: the install was removed from the Hub (no heartbeat for 24 hours).' });
return d;
}
/**
* Uninstall (§9): 2FA, typing the short name, at least 4 hours ahead. A batch of two: the export
* (encrypted, emailed to the site admin), then the uninstall, which only runs if the export worked.
*
* Hub 2.12.0: one product at a time (agent 1.5.0). When another product of the church is already
* planned for uninstall, `join` says what to do: true adds this product to that run (one export
* and one uninstall for both), false gives it its own batch at `at`. Not given: refused with
* CHOOSE, so the page asks. The script removes the whole church (folder, app user) when a run
* names every product it still has, so the last product to go always takes the church with it.
*/
async function scheduleUninstall({ deploymentId, at, totp, confirm }, admin, now = new Date()) {
async function scheduleUninstall({ deploymentId, at, totp, confirm, join, joinJobId }, admin, now = new Date()) {
requireTotp(admin, totp);
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, server: true } });
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, server: true, customer: true } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to confirm.`);
if (['removed', 'uninstalling'].includes(d.status)) throw fail(409, 'ALREADY', `It's already ${d.status}.`);
if (d.status === 'failed') throw fail(409, 'NOT_INSTALLED', 'Its install failed, so nothing of it is on the server: remove the record instead.');
if (d.status === 'installing') throw fail(409, 'BUSY', 'Wait until the install has finished.');
const when = new Date(at || now.getTime() + 7 * DAY);
if (when - now < SCHEDULE_MIN_HOURS * HOUR) throw fail(400, 'TOO_SOON', `An uninstall is planned at least ${SCHEDULE_MIN_HOURS} hours ahead.`);
const exportId = servers.newId('exp');
const batchId = servers.newId('batch');
const noticeId = await addNotice(d, { title: `${PRODUCT_NAMES[d.product]} is closing`, message: `This site closes on ${sast(when)}. Your admin gets a download of all your data by email first.`, endsAt: new Date(when.getTime() + 2 * HOUR), level: 'warning' }, now);
await prisma.export.create({ data: { id: exportId, deploymentId: d.id, expiresAt: new Date(when.getTime() + EXPORT_DAYS * DAY) } });
const exportJob = await makeJob(prisma, { serverId: d.serverId, type: 'export', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 0, notBefore: when, args: { church: d.shortName, exportId } });
const uninstallJob = await makeJob(prisma, { serverId: d.serverId, type: 'uninstall', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 1, status: 'scheduled', notBefore: when, noticeId, args: { church: d.shortName } });
// Only this product goes (agent 1.5.0). An older agent removes the whole church, so it's refused
// while the church has other products on the server.
const siblings = await churchSiblings(d);
const onlyThis = agentAtLeast(d.server, agent.PRODUCT_UNINSTALL_MIN_AGENT);
if (!onlyThis && siblings.length) {
throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}: it would remove all of ${d.shortName} (${[d, ...siblings].map(x => PRODUCT_NAMES[x.product]).join(' and ')}). Update the agent to ${agent.PRODUCT_UNINSTALL_MIN_AGENT} or later to uninstall only ${PRODUCT_NAMES[d.product]}.`);
}
// Another product's uninstall that hasn't run yet: join it, or a time of its own.
const pending = await pendingUninstalls(d, siblings);
const whole = pending.find(p => !p.products);
if (whole) throw fail(409, 'ALREADY', `${PRODUCT_NAMES[d.product]} already goes with the uninstall of all of ${d.shortName} on ${sast(whole.job.notBefore)}.`);
if (pending.length && join === undefined) {
const first = pending[0];
throw Object.assign(fail(409, 'CHOOSE', `${first.products.map(p => PRODUCT_NAMES[p]).join(' and ')} of ${d.shortName} is already being uninstalled on ${sast(first.job.notBefore)}: add ${PRODUCT_NAMES[d.product]} to that, or give it its own time.`), { details: { jobId: first.job.id, notBefore: first.job.notBefore } });
}
const target = join ? pending.find(p => (joinJobId ? p.job.id === joinJobId : true) && p.joinable) : null;
if (join && !target) throw fail(409, 'NOT_JOINABLE', 'That uninstall has already started (its export ran): give this one its own time.');
const when = target ? target.job.notBefore : new Date(at || now.getTime() + 7 * DAY);
// The church gets at least 4 hours' notice, also when this joins a run planned earlier.
if (when - now < SCHEDULE_MIN_HOURS * HOUR) throw fail(400, 'TOO_SOON', target ? `That uninstall is less than ${SCHEDULE_MIN_HOURS} hours away, too soon to tell the church: give this one its own time.` : `An uninstall is planned at least ${SCHEDULE_MIN_HOURS} hours ahead.`);
// The church's other products sign in through Accounts: it goes last (or in the same run).
if (d.product === 'accounts' && siblings.length) {
const staying = siblings.filter(s => s.status !== 'uninstalling');
if (staying.length) throw fail(409, 'ACCOUNTS_IN_USE', `${staying.map(s => PRODUCT_NAMES[s.product]).join(' and ')} of ${d.shortName} sign${staying.length === 1 ? 's' : ''} in through Accounts: uninstall ${staying.length === 1 ? 'it' : 'them'} first, then Accounts.`);
const later = pending.filter(p => p.job.notBefore > when).pop();
if (later) throw fail(400, 'ACCOUNTS_FIRST', `Accounts goes after the church's other products: plan it for ${sast(later.job.notBefore)} or later, or add it to that uninstall.`);
}
let exportJob;
let uninstallJob;
if (target) {
// One run for both: the export and the uninstall name every product, in deploy order.
const products = [...new Set([...target.products, d.product])].sort((a, b) => PRODUCT_ORDER.indexOf(a) - PRODUCT_ORDER.indexOf(b));
uninstallJob = await prisma.job.update({ where: { id: target.job.id }, data: { args: agent.jobArgsSchemas.uninstall.parse({ ...target.job.args, products }) } });
exportJob = target.exportJob ? await prisma.job.update({ where: { id: target.exportJob.id }, data: { args: agent.jobArgsSchemas.export.parse({ ...target.exportJob.args, products }) } }) : null;
await addNotice(d, { title: `${PRODUCT_NAMES[d.product]} is closing`, message: `This site closes on ${sast(when)}. Your admin gets a download of all your data by email first.`, endsAt: new Date(when.getTime() + 2 * HOUR), level: 'warning' }, now);
} else {
const products = onlyThis ? { products: [d.product] } : {};
const exportId = servers.newId('exp');
const batchId = servers.newId('batch');
const noticeId = await addNotice(d, { title: `${PRODUCT_NAMES[d.product]} is closing`, message: `This site closes on ${sast(when)}. Your admin gets a download of all your data by email first.`, endsAt: new Date(when.getTime() + 2 * HOUR), level: 'warning' }, now);
await prisma.export.create({ data: { id: exportId, deploymentId: d.id, expiresAt: new Date(when.getTime() + EXPORT_DAYS * DAY) } });
exportJob = await makeJob(prisma, { serverId: d.serverId, type: 'export', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 0, notBefore: when, args: { church: d.shortName, exportId, ...products } });
uninstallJob = await makeJob(prisma, { serverId: d.serverId, type: 'uninstall', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 1, status: 'scheduled', notBefore: when, noticeId, args: { church: d.shortName, ...products } });
}
await prisma.deployment.update({ where: { id: d.id }, data: { status: 'uninstalling' } });
await emailSiteAdmin(d, `${PRODUCT_NAMES[d.product]} at ${d.domain} closes on ${sast(when)}`, {
heading: `${PRODUCT_NAMES[d.product]} is closing`,
blocks: [
{ p: `As agreed, ${PRODUCT_NAMES[d.product]} at ${d.domain} will be closed.` },
{ rows: [['Site', d.domain], ['Closes on', sast(when)]] },
{ note: { kind: 'info', title: 'Your data', text: `Shortly before, you'll get an email with a link to download all your data (events, people, registrations, payments and files). The link works for ${EXPORT_DAYS} days.` } },
{ note: { kind: 'info', title: 'Your data', text: `Shortly before, ${target ? 'the church\'s site admin gets' : 'you\'ll get'} an email with a link to download all the data (events, people, registrations, payments and files). The link works for ${EXPORT_DAYS} days.` } },
],
});
return { exportJob, uninstallJob };
return { exportJob, uninstallJob, joined: !!target, lastProduct: siblings.every(s => s.status === 'uninstalling') };
}
/** An agent's encrypted export (PUT /api/agent/v1/exports/:id). */
@@ -1468,6 +1627,6 @@ module.exports = {
readEnv, setEnv, envState, readFrp, writeFrp, portsProbed, probeServers, PROBE_SPARE,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
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,
};
+17
View File
@@ -412,3 +412,20 @@ describe('monthly recurring revenue (dashboard)', () => {
expect(monthlyRecurringCents(customer({ billingCycle: 'none' }), [events()], now)).toBe(0);
});
});
describe('2.12.0: R0 invoices on statements, several email addresses', () => {
const { emailList } = require('../src/utils/emails');
test('a sent R0 invoice is on the statement, with its amount (R0.00), and isn\'t owing', () => {
const zero = { number: 'INV-0', status: 'sent', issueDate: day('2026-12-01'), dueDate: day('2026-12-08'), periodStart: day('2026-12-01'), periodEnd: day('2026-12-31'), totalCents: 0, payments: [] };
const st = statement({ invoices: [zero], payments: [], from: '2026-12-01', to: '2026-12-31' });
expect(st.entries).toEqual([expect.objectContaining({ kind: 'invoice', reference: 'INV-0', debitCents: 0, balanceCents: 0 })]);
expect(st.outstanding).toEqual([]);
});
test('email lists: commas, semicolons or a list; each once; a bad one named', () => {
expect(emailList('a@church.org; b@church.org, A@church.org')).toBe('a@church.org, b@church.org');
expect(emailList(['a@church.org', ' ', 'c@church.org'])).toBe('a@church.org, c@church.org');
expect(emailList('')).toBeNull();
expect(() => emailList('a@church.org, not-an-email')).toThrow(/not-an-email/);
});
});
+159
View File
@@ -956,3 +956,162 @@ describe("frp's config from the Hub (2.11.0)", () => {
expect(missing.map(p => p.type)).toEqual(['frp_config_missing']);
});
});
describe('uninstalling one product of a church, and stale installs (2.12.0)', () => {
const at = new Date(NOW.getTime() + 5 * H);
const pollAs = (server, agentVersion, when = at) => jobs.poll(server, { agentApiVersion: 1, agentVersion, mode: 'church', runningJobId: null }, when);
async function church({ agentVersion = '1.5.0' } = {}) {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.server.update({ where: { id: server.id }, data: { agentVersion } });
const evInst = await db.install.create({ data: { id: 'inst-ev', customerId: 'cust-1', product: 'events', name: 'Hope', url: 'https://events.hope.co.za', secret: 'x', lastHeartbeatAt: NOW } });
const accInst = await db.install.create({ data: { id: 'inst-acc', customerId: 'cust-1', product: 'accounts', name: 'Hope', url: 'https://accounts.hope.co.za', secret: 'x', lastHeartbeatAt: NOW } });
const ev = await db.deployment.create({ data: { id: 'dep-ev', serverId: server.id, customerId: 'cust-1', installId: evInst.id, product: 'events', shortName: 'hope', domain: 'events.hope.co.za', webPort: 20000, apiPort: 20001, status: 'live', liveAt: NOW, createdAt: NOW } });
const acc = await db.deployment.create({ data: { id: 'dep-acc', serverId: server.id, customerId: 'cust-1', installId: accInst.id, product: 'accounts', shortName: 'hope', domain: 'accounts.hope.co.za', webPort: 20002, apiPort: 20003, status: 'live', liveAt: NOW, createdAt: NOW } });
for (const port of [20000, 20001, 20002, 20003]) await db.port.create({ data: { port, serverId: server.id, role: port % 2 ? 'api' : 'web' } });
return { server, ev, acc };
}
async function runBatch(server, agentVersion) {
const exp = (await pollAs(server, agentVersion)).jobs[0];
await jobs.receiveReport(server, signedReport(exp, 'succeeded'), at);
const un = (await pollAs(server, agentVersion)).jobs[0];
await jobs.receiveReport(server, signedReport(un, 'succeeded'), at);
return { exp, un };
}
test('agent 1.5.0: only Events goes, Accounts stays live; then Accounts on its own', async () => {
const { server, ev, acc } = await church();
await jobs.scheduleUninstall({ deploymentId: ev.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW);
const { exp, un } = await runBatch(server, '1.5.0');
expect(exp.args.products).toEqual(['events']);
expect(un.args).toEqual({ church: 'hope', products: ['events'] });
expect(await db.deployment.findUnique({ where: { id: ev.id } })).toMatchObject({ status: 'removed' });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'live' });
expect((await db.job.findFirst({ where: { type: 'purge', deploymentId: ev.id } })).args).toEqual({ church: 'hope', products: ['events'] });
await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW);
const second = await runBatch(server, '1.5.0');
expect(second.un.args).toEqual({ church: 'hope', products: ['accounts'] });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
});
test('Accounts goes last: refused while Events stays, and not planned before Events\' uninstall', async () => {
const { ev, acc } = await church();
await expect(jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW)).rejects.toMatchObject({ code: 'ACCOUNTS_IN_USE' });
await jobs.scheduleUninstall({ deploymentId: ev.id, totp: totpNow(), confirm: 'hope', at: new Date(at.getTime() + H) }, admin, NOW);
await expect(jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at, join: false }, admin, NOW)).rejects.toMatchObject({ code: 'ACCOUNTS_FIRST' });
await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at: new Date(at.getTime() + 2 * H), join: false }, admin, NOW);
});
test('an older agent would remove the whole church: refused while it has other products', async () => {
const { ev } = await church({ agentVersion: '1.4.0' });
await expect(jobs.scheduleUninstall({ deploymentId: ev.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD' });
const plan = await jobs.uninstallPlan(await db.deployment.findUnique({ where: { id: ev.id }, include: { server: true } }));
expect(plan).toMatchObject({ onlyThisProduct: false, others: [{ product: 'accounts' }] });
});
test('a whole-church uninstall (no products) removes every product of it here, and cancels what was planned for them', async () => {
const { server, ev, acc } = await church({ agentVersion: '1.4.0' });
// As from Hub 2.11.0: an uninstall without products, and Accounts' own batch planned after it.
const un = await jobs.makeJob(db, { serverId: server.id, type: 'uninstall', deploymentId: ev.id, args: { church: 'hope' }, notBefore: at });
const later = await jobs.makeJob(db, { serverId: server.id, type: 'export', deploymentId: acc.id, status: 'scheduled', args: { church: 'hope', exportId: 'exp_abcdefgh' }, notBefore: new Date(at.getTime() + H) });
const job = (await pollAs(server, '1.4.0')).jobs[0];
expect(job.id).toBe(un.id);
await jobs.receiveReport(server, signedReport(job, 'succeeded'), at);
expect(await db.deployment.findUnique({ where: { id: ev.id } })).toMatchObject({ status: 'removed' });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
expect((await db.install.findUnique({ where: { id: 'inst-acc' } })).releasedAt).toEqual(at);
expect(await db.job.findUnique({ where: { id: later.id } })).toMatchObject({ status: 'cancelled' });
expect((await db.job.findFirst({ where: { type: 'purge', deploymentId: ev.id } })).args).toEqual({ church: 'hope' });
});
test('an install without a heartbeat for 24 hours can be removed from the Hub; a fresh one can\'t', async () => {
const { server, acc } = await church();
const later = new Date(NOW.getTime() + 23 * H);
await expect(jobs.forgetStale(acc.id, { confirm: 'hope' }, later)).rejects.toMatchObject({ code: 'NOT_STALE' });
const dayLater = new Date(NOW.getTime() + 25 * H);
await expect(jobs.forgetStale(acc.id, { confirm: 'nope' }, dayLater)).rejects.toMatchObject({ code: 'CONFIRM' });
const planned = await jobs.makeJob(db, { serverId: server.id, type: 'env-read', deploymentId: acc.id, args: { church: 'hope', product: 'accounts' }, status: 'scheduled', notBefore: dayLater });
await jobs.forgetStale(acc.id, { confirm: 'hope' }, dayLater);
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
expect((await db.install.findUnique({ where: { id: 'inst-acc' } })).releasedAt).toEqual(dayLater);
expect(await db.job.findUnique({ where: { id: planned.id } })).toMatchObject({ status: 'cancelled' });
expect((await db.port.findMany({ where: { port: { in: [20002, 20003] } } })).every(p => p.releasedAt)).toBe(true);
});
});
describe('a second product while another is being uninstalled (2.12.0)', () => {
const at = new Date(NOW.getTime() + 5 * H);
const poll = (server, when = at) => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.5.0', mode: 'church', runningJobId: null }, when);
async function church() {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const ev = await db.deployment.create({ data: { id: 'dep-ev', serverId: server.id, customerId: 'cust-1', product: 'events', shortName: 'hope', domain: 'events.hope.co.za', webPort: 20000, apiPort: 20001, status: 'live', liveAt: NOW, createdAt: NOW } });
const acc = await db.deployment.create({ data: { id: 'dep-acc', serverId: server.id, customerId: 'cust-1', product: 'accounts', shortName: 'hope', domain: 'accounts.hope.co.za', webPort: 20002, apiPort: 20003, status: 'live', liveAt: NOW, createdAt: NOW } });
await db.server.update({ where: { id: server.id }, data: { agentVersion: '1.5.0' } });
await jobs.scheduleUninstall({ deploymentId: ev.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW);
return { server, ev, acc };
}
test('the Hub asks: join that run, or a time of its own', async () => {
const { acc } = await church();
await expect(jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at }, admin, NOW)).rejects.toMatchObject({ code: 'CHOOSE' });
const plan = await jobs.uninstallPlan(await db.deployment.findUnique({ where: { id: acc.id }, include: { server: true } }));
expect(plan).toMatchObject({ lastProduct: true, pending: [{ products: ['events'], joinable: true }] });
});
test('joined: one export and one uninstall for both, which removes the whole church', async () => {
const { server, ev, acc } = await church();
const out = await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', join: true }, admin, NOW);
expect(out.joined).toBe(true);
expect(out.uninstallJob.notBefore).toEqual(at);
expect(await db.job.count({ where: { type: 'uninstall' } })).toBe(1);
const exp = (await poll(server)).jobs[0];
expect(exp.args.products).toEqual(['accounts', 'events']);
await jobs.receiveReport(server, signedReport(exp, 'succeeded'), at);
const un = (await poll(server)).jobs[0];
expect(un.args).toEqual({ church: 'hope', products: ['accounts', 'events'] });
await jobs.receiveReport(server, signedReport(un, 'succeeded', { result: { products: ['accounts', 'events'], remaining: [] } }), at);
expect(await db.deployment.findUnique({ where: { id: ev.id } })).toMatchObject({ status: 'removed' });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
});
test('joined, and the export fails: both are live again', async () => {
const { server, ev, acc } = await church();
await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', join: true }, admin, NOW);
const exp = (await poll(server)).jobs[0];
await jobs.receiveReport(server, signedReport(exp, 'failed'), at);
expect(await db.deployment.findUnique({ where: { id: ev.id } })).toMatchObject({ status: 'live' });
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'live' });
});
test('a run less than 4 hours away can\'t be joined (the church needs notice)', async () => {
const { acc } = await church();
await expect(jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', join: true }, admin, new Date(at.getTime() - 2 * H))).rejects.toMatchObject({ code: 'TOO_SOON' });
});
test('its own, later time: the last product left takes the whole church with it', async () => {
const { server, ev, acc } = await church();
const later = new Date(at.getTime() + H);
await jobs.scheduleUninstall({ deploymentId: acc.id, totp: totpNow(), confirm: 'hope', at: later, join: false }, admin, NOW);
expect(await db.job.count({ where: { type: 'uninstall' } })).toBe(2);
// 10:00: Events only; the church keeps Accounts.
const exp1 = (await poll(server)).jobs[0];
await jobs.receiveReport(server, signedReport(exp1, 'succeeded'), at);
const un1 = (await poll(server)).jobs[0];
expect(un1.args.products).toEqual(['events']);
await jobs.receiveReport(server, signedReport(un1, 'succeeded', { result: { products: ['events'], remaining: ['accounts'] } }), at);
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'uninstalling' });
// 11:00: Accounts, the last one: the script removes the church (remaining is empty).
const exp2 = (await poll(server, later)).jobs[0];
await jobs.receiveReport(server, signedReport(exp2, 'succeeded'), later);
const un2 = (await poll(server, later)).jobs[0];
expect(un2.args.products).toEqual(['accounts']);
await jobs.receiveReport(server, signedReport(un2, 'succeeded', { result: { products: ['accounts'], remaining: [] } }), later);
expect(await db.deployment.findUnique({ where: { id: acc.id } })).toMatchObject({ status: 'removed' });
expect(mockMails.some(m => m.subject.includes('Uninstalled: hope') && m.text.includes('folder and app user'))).toBe(true);
});
});
Binary file not shown.
Binary file not shown.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.11.0",
"version": "2.12.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.11.0",
"version": "2.12.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.11.0",
"version": "2.12.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+18 -3
View File
@@ -3,7 +3,7 @@
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ArrowLeft, Copy, KeyRound } from "lucide-react";
import { Archive, ArchiveRestore, ArrowLeft, Copy, KeyRound } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { PLANS_BY_PRODUCT } from "@/lib/tiers";
@@ -11,6 +11,7 @@ import { KEY_WHERE, PRODUCTS, PRODUCT_NAMES, byProduct, type Product } from "@/l
import type { Customer, Licence, LicenceStatus } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
import { CustomerBilling } from "@/components/billing/CustomerBilling";
import { EmailList } from "@/components/EmailList";
type Msg = { type: "ok" | "err"; text: string } | null;
const dateInput = (d: string | null) => (d ? d.slice(0, 10) : "");
@@ -170,10 +171,24 @@ export default function CustomerPage() {
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
// Hub 2.12.0: archive (left out of the list and pickers) or restore.
const setArchivedState = async (archive: boolean) => {
if (archive && !confirm(`Archive ${c.name}? It's left out of the customer list until you restore it (Customers → Archived). Nothing else changes.`)) return;
try {
await api(`/api/admin/customers/${id}/${archive ? "archive" : "restore"}`, { method: "POST" });
setMsg({ type: "ok", text: archive ? "Archived. Find it under Customers → Archived." : "Restored: it's in the customer list again." });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<Link href="/customers" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Customers</Link>
<PageTitle title={c.name} subtitle={`Customer since ${fmtDate(c.createdAt, false)}`} />
<PageTitle title={c.name}
subtitle={c.archivedAt ? `Archived ${fmtDate(c.archivedAt, false)} · customer since ${fmtDate(c.createdAt, false)}` : `Customer since ${fmtDate(c.createdAt, false)}`}
actions={c.archivedAt
? <button className="btn-secondary" onClick={() => setArchivedState(false)}><ArchiveRestore className="h-4 w-4" /> Restore</button>
: <button className="btn-secondary" onClick={() => setArchivedState(true)}><Archive className="h-4 w-4" /> Archive</button>} />
<div className="mb-4"><Message msg={msg} /></div>
<div className="grid gap-6 lg:grid-cols-[1fr_2fr]">
@@ -181,7 +196,7 @@ export default function CustomerPage() {
<h2 className="font-semibold">Details</h2>
<div><label className="label">Name</label><input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required /></div>
<div><label className="label">Contact person</label><input className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<div><label className="label">Email</label><input type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
<EmailList id="c-email" label="Email" value={form.email} onChange={email => setForm({ ...form, email })} placeholder="office@church.org" />
<div><label className="label">Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div><label className="label">Notes</label><textarea className="input" rows={4} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Plan, billing, anything worth remembering" /></div>
<div className="grid gap-3 sm:grid-cols-2">
+17 -5
View File
@@ -10,6 +10,7 @@ import { matches, usePaged } from "@/lib/paging";
import type { Customer } from "@/lib/types";
import { PRODUCT_NAMES, byProduct } from "@/lib/products";
import { Badge, Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
import { EmailList } from "@/components/EmailList";
export default function CustomersPage() {
const router = useRouter();
@@ -19,10 +20,15 @@ export default function CustomersPage() {
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const [query, setQuery] = useState("");
// Hub 2.12.0: archived customers are only shown here, on their own.
const [archived, setArchived] = useState(false);
const shown = useMemo(() => (list || []).filter(c => matches(query, c.name, c.contactName, c.email, c.phone, ...c.installs.map(i => i.url))), [list, query]);
const paged = usePaged(shown, query);
const paged = usePaged(shown, `${archived}|${query}`);
const load = useCallback(() => api<Customer[]>("/api/admin/customers").then(setList).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
const load = useCallback(() => {
setList(null);
return api<Customer[]>(`/api/admin/customers${archived ? "?archived=1" : ""}`).then(setList).catch(e => setMsg({ type: "err", text: errorText(e) }));
}, [archived]);
useEffect(() => { load(); }, [load]);
const add = async (e: React.FormEvent) => {
@@ -40,15 +46,21 @@ export default function CustomersPage() {
<form onSubmit={add} className="card mb-6 grid gap-3 md:grid-cols-2">
<div className="md:col-span-2"><label className="label" htmlFor="name">Name</label><input id="name" className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required placeholder="Hope Family Church" /></div>
<div><label className="label" htmlFor="contact">Contact person</label><input id="contact" className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<div><label className="label" htmlFor="email">Email</label><input id="email" type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
<EmailList id="email" label="Email" value={form.email} onChange={email => setForm({ ...form, email })} placeholder="office@church.org" />
<div><label className="label" htmlFor="phone">Phone</label><input id="phone" className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div className="flex items-end gap-2"><button className="btn-primary">Save</button><button type="button" className="btn-secondary" onClick={() => setAdding(false)}>Cancel</button></div>
</form>
)}
<Message msg={msg} />
{!list ? <Loading /> : list.length === 0 ? <p className="text-sm text-slate-500">No customers yet.</p> : (
<div className="mb-3 flex flex-wrap items-center gap-3">
<div className="inline-flex rounded-lg border border-slate-200 p-0.5 text-sm" role="group" aria-label="Which customers">
<button type="button" aria-pressed={!archived} className={`rounded-md px-3 py-1 ${!archived ? "bg-indigo-50 font-medium text-indigo-700" : "text-slate-600"}`} onClick={() => setArchived(false)}>Active</button>
<button type="button" aria-pressed={archived} className={`rounded-md px-3 py-1 ${archived ? "bg-indigo-50 font-medium text-indigo-700" : "text-slate-600"}`} onClick={() => setArchived(true)}>Archived</button>
</div>
{!!list?.length && <SearchInput className="w-full sm:w-72" value={query} onChange={setQuery} placeholder="Search name, contact or site" />}
</div>
{!list ? <Loading /> : list.length === 0 ? <p className="text-sm text-slate-500">{archived ? "No archived customers." : "No customers yet."}</p> : (
<>
<SearchInput className="mb-3 w-full sm:w-72" value={query} onChange={setQuery} placeholder="Search name, contact or site" />
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Customer</th><th className="p-3">Licences</th><th className="p-3">Site</th></tr></thead>
@@ -17,8 +17,20 @@ 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;
};
};
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). */
@@ -33,6 +45,9 @@ export default function DeploymentPage() {
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<Release[]>([]);
// Hub 2.6.0: every job of this install, a page at a time (it showed the last 50).
@@ -98,14 +113,33 @@ export default function DeploymentPage() {
} 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) }); }
};
if (!d) return <div><ServersNav active="/servers/installs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const x = d.deployment;
const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H;
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;
return (
<div className="space-y-6">
<div>
<PageTitle title={`${x.customer?.name} (${x.shortName})`} subtitle={<>{x.domain} · on <Link className="text-indigo-700 hover:underline" href={`/servers/${x.serverId}`}>{x.server.name}</Link> · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} <StatusPill status={x.status} /></>} />
<PageTitle title={`${x.customer?.name} (${x.shortName})`} subtitle={<>{x.domain} · on <Link className="text-indigo-700 hover:underline" href={`/servers/${x.serverId}`}>{x.server.name}</Link> · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} <StatusPill status={d.stale.stale ? "stale" : x.status} /></>} />
<ServersNav active="/servers/installs" />
<Message msg={msg} />
{/* Hub 2.6.0: whether the site has registered with the Hub (its banners, licence and heartbeats need it). */}
@@ -228,14 +262,52 @@ export default function DeploymentPage() {
</div>
)}
{/* Hub 2.12.0: gone from its server without the Hub (uninstalled by hand, server rebuilt …). */}
{d.stale.stale && (
<form className="card grid gap-3 border-red-200 md:grid-cols-[1fr_auto] md:items-end" onSubmit={e => { e.preventDefault(); removeFromHub(); }}>
<div className="md:col-span-2">
<h2 className="font-medium text-red-800">Remove from the Hub</h2>
<p className="mt-1 text-sm text-slate-500">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&apos;s heartbeats are refused. If it&apos;s still there, uninstall it instead.</p>
</div>
<div><label className="label" htmlFor="f-c">Type {x.shortName}</label><input id="f-c" className="input" value={forget} onChange={e => setForget(e.target.value)} /></div>
<button className="btn-danger" disabled={forget !== x.shortName || busy}>Remove from the Hub</button>
</form>
)}
{["live", "waiting_for_proxy"].includes(x.status) && (
<form className="card grid gap-3 border-red-200 md:grid-cols-3" onSubmit={e => { e.preventDefault(); if (window.confirm(`Uninstall ${x.shortName} on ${un.at.replace("T", " ")}? The church gets its data first.`)) act(`/api/admin/deployments/${x.id}/uninstall`, { at: fromInput(un.at), totp: un.totp, confirm: un.confirm }, "Uninstall planned: the site admin was emailed and sees a banner. The export runs first."); }}>
<h2 className="font-medium text-red-800 md:col-span-3">Uninstall</h2>
<p className="text-sm text-slate-500 md:col-span-3">At the time: the church&apos;s data is exported (encrypted; the link goes to the site admin), then the site, its tunnels and database are removed. The final backup stays on the server for 30 days.</p>
<div><label className="label" htmlFor="x-at">When</label><input id="x-at" type="datetime-local" className="input" value={un.at} onChange={e => setUn({ ...un, at: e.target.value })} /></div>
<form className="card grid gap-3 border-red-200 md:grid-cols-3" onSubmit={e => {
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.");
}}>
<h2 className="font-medium text-red-800 md:col-span-3">Uninstall {productName(x.product)}</h2>
<p className="text-sm text-slate-500 md:col-span-3">At the time: {productName(x.product)}&apos;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 ")}.</>}</p>
{/* Hub 2.12.0: another product of the church is already planned for uninstall. */}
{plan.onlyThisProduct && pendingRuns.length > 0 && (
<fieldset className="space-y-2 rounded-lg border border-slate-200 p-3 text-sm md:col-span-3">
<legend className="px-1 font-medium">{pendingRuns.map(p => `${p.products!.map(productName).join(" and ")} on ${fmtDate(p.notBefore)}`).join("; ")}: already planned for uninstall</legend>
<label className={`flex items-start gap-2 ${joinable ? "" : "text-slate-400"}`}>
<input type="radio" name="x-join" className="mt-1" checked={joining && !!joinable} disabled={!joinable} onChange={() => setJoining(true)} />
<span>Add {productName(x.product)} to that uninstall{joinable ? ` on ${fmtDate(joinable.notBefore)}` : ""}: one export and one uninstall for both{plan.lastProduct ? ", which removes the whole church" : ""}.{!joinable && " (Not possible: it has already started.)"}{joinable && new Date(joinable.notBefore).getTime() - Date.now() < 4 * H && " (Under 4 hours away: the church wouldn't get notice in time, so the Hub will refuse.)"}</span>
</label>
<label className="flex items-start gap-2">
<input type="radio" name="x-join" className="mt-1" checked={!joining || !joinable} onChange={() => setJoining(false)} />
<span>At its own time (below).{plan.lastProduct && " It's then the church's last product here, so it removes the whole church (its folder and app user) when it runs."}</span>
</label>
</fieldset>
)}
{plan.onlyThisProduct && plan.lastProduct && !pendingRuns.length && <p className="text-sm text-slate-600 md:col-span-3">This is the church&apos;s last product here: the uninstall removes the whole church (its folder and app user).</p>}
{wholeChurch && <p className="text-sm font-medium text-red-800 md:col-span-3">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.</p>}
{accountsInUse && <p className="text-sm font-medium text-amber-800 md:col-span-3">{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).</p>}
{joining && joinable
? <div><span className="label">When</span><p className="mt-2 text-sm">{fmtDate(joinable.notBefore)}, with {joinable.products!.map(productName).join(" and ")}</p></div>
: <div><label className="label" htmlFor="x-at">When</label><input id="x-at" type="datetime-local" className="input" value={un.at} onChange={e => setUn({ ...un, at: e.target.value })} /></div>}
<div><label className="label" htmlFor="x-c">Type {x.shortName}</label><input id="x-c" className="input" required value={un.confirm} onChange={e => setUn({ ...un, confirm: e.target.value })} /></div>
<div><label className="label" htmlFor="x-t">Two-factor code</label><input id="x-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={un.totp} onChange={e => setUn({ ...un, totp: e.target.value })} /></div>
<div className="md:col-span-3"><button className="btn-danger" disabled={un.confirm !== x.shortName || busy}>Plan the uninstall</button></div>
<div className="md:col-span-3"><button className="btn-danger" disabled={un.confirm !== x.shortName || busy || wholeChurch || accountsInUse}>Plan the uninstall</button></div>
</form>
)}
</div>
@@ -9,7 +9,7 @@ import { ago } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import { Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
import { ServersNav, StatusPill, pct, type Deployment, type ServerSummary } from "@/components/servers";
import { ServersNav, StatusPill, pct, shownStatus, type Deployment, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Customer = { id: string; name: string; domain?: string | null };
@@ -162,7 +162,7 @@ export default function InstallsPage() {
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="px-4 py-1">Church</th><th>Product</th><th>Domain</th><th>Server</th><th>Version</th><th>Last heartbeat</th><th>Status</th></tr></thead>
<tbody>{paged.rows.map(d => (
<tr key={d.id} className="border-t"><td className="px-4 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${d.id}`}>{d.customer?.name} ({d.shortName})</Link>{d.isDemo && <span className="ml-1 rounded bg-sky-100 px-1.5 text-xs text-sky-800">demo</span>}</td><td>{PRODUCT_NAMES[d.product as keyof typeof PRODUCT_NAMES] || d.product}</td><td>{d.domain}</td><td>{d.server?.name}</td><td>{d.install?.version || d.version || "–"}</td><td>{d.installId ? ago(d.install?.lastHeartbeatAt) : <span className="text-amber-800">not registered</span>}</td><td><StatusPill status={d.status} /></td></tr>
<tr key={d.id} className="border-t"><td className="px-4 py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${d.id}`}>{d.customer?.name} ({d.shortName})</Link>{d.isDemo && <span className="ml-1 rounded bg-sky-100 px-1.5 text-xs text-sky-800">demo</span>}</td><td>{PRODUCT_NAMES[d.product as keyof typeof PRODUCT_NAMES] || d.product}</td><td>{d.domain}</td><td>{d.server?.name}</td><td>{d.install?.version || d.version || "–"}</td><td>{d.installId ? ago(d.install?.lastHeartbeatAt) : <span className="text-amber-800">not registered</span>}</td><td><StatusPill status={shownStatus(d)} /></td></tr>
))}</tbody>
</table>
{!list.length ? <p className="px-4 py-3 text-sm text-slate-500">No installs on servers yet.</p> : !shown.length && <p className="px-4 py-3 text-sm text-slate-500">No installs match.</p>}
+41
View File
@@ -0,0 +1,41 @@
"use client";
import React from "react";
import { Plus, X } from "lucide-react";
/** The addresses in a stored value ("a@x.org, b@x.org"). */
export const emailsOf = (value: string | null | undefined) => String(value || "").split(/[\s,;]+/).map(s => s.trim()).filter(Boolean);
/**
* Hub 2.12.0: one or more email addresses, one per row, with + to add another. The value is the
* comma-separated list the API stores ("a@x.org, b@x.org"); empty rows are dropped when saved.
*/
export function EmailList({ id, label, value, onChange, placeholder, max = 10 }: {
id: string; label: string; value: string; onChange: (v: string) => void; placeholder?: string; max?: number;
}) {
// Keep an empty row while typing: split on commas only, so a half-typed address stays put.
const rows = value === "" ? [""] : value.split(",").map(s => s.trim());
const set = (next: string[]) => onChange(next.join(", "));
return (
<div>
<label className="label" htmlFor={`${id}-0`}>{label}</label>
<div className="space-y-2">
{rows.map((r, i) => (
<div key={i} className="flex gap-2">
<input id={`${id}-${i}`} type="email" className="input" value={r} placeholder={i === 0 ? placeholder : "another@church.org"}
aria-label={i === 0 ? undefined : `${label} ${i + 1}`}
onChange={e => set(rows.map((x, j) => (j === i ? e.target.value.replace(/[,;\s]/g, "") : x)))} />
{rows.length > 1 && (
<button type="button" className="btn-secondary px-2" aria-label={`Remove ${r || "this address"}`} onClick={() => set(rows.filter((_, j) => j !== i))}><X className="h-4 w-4" /></button>
)}
</div>
))}
</div>
{rows.length < max && (
<button type="button" className="mt-2 inline-flex items-center gap-1 text-sm text-indigo-600 hover:underline" onClick={() => set([...rows, ""])}>
<Plus className="h-4 w-4" /> Add another address
</button>
)}
</div>
);
}
@@ -8,6 +8,7 @@ import { fmtDate } from "@/lib/format";
import { CYCLE, EMAIL_KIND, METHOD, StateBadge, centsFrom, day, money, randInput, todayYmd, type BillingCycle, type BillingEmail, type Invoice, type LicenceChange, type Line, type Payment, type PlanChange } from "@/lib/billing";
import { PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
import { RecordPayment } from "./RecordPayment";
import { EmailList } from "@/components/EmailList";
type Msg = { type: "ok" | "err"; text: string } | null;
/** A plan of a product: the Events tiers have an income ceiling (upTo), the App tiers a member band. */
@@ -303,7 +304,10 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
<div><label className="label" htmlFor="f-note">Note</label><input id="f-note" className="input" value={form.foundingNote} onChange={e => setForm({ ...form, foundingNote: e.target.value })} placeholder="e.g. Founding church 3 of 10" /></div>
</div>
)}
<div><label className="label" htmlFor="b-email">Billing email</label><input id="b-email" type="email" className="input" value={form.billingEmail} onChange={e => setForm({ ...form, billingEmail: e.target.value })} placeholder={c.sendsTo || ""} /><p className="mt-1 text-xs text-slate-500">Blank: the site&apos;s admin contact, then the customer&apos;s email. Now going to {c.sendsTo || "nobody (add one)"}.</p></div>
<div>
<EmailList id="b-email" label="Billing email" value={form.billingEmail} onChange={billingEmail => setForm({ ...form, billingEmail })} placeholder={c.sendsTo || "accounts@church.org"} />
<p className="mt-1 text-xs text-slate-500">Invoices, statements and receipts go to every address here. Blank: the site&apos;s admin contact, then the customer&apos;s email. Now going to {c.sendsTo || "nobody (add one)"}.</p>
</div>
<div><label className="label" htmlFor="b-addr">Postal address (on invoices)</label><textarea id="b-addr" className="input" rows={2} value={form.billingAddress} onChange={e => setForm({ ...form, billingAddress: e.target.value })} /></div>
<button className="btn-secondary">Save billing details</button>
</form>
+15
View File
@@ -49,6 +49,8 @@ const STATUS: Record<string, [string, string]> = {
// deployments
installing: ["Installing", "blue"], waiting_for_proxy: ["Waiting for proxy", "amber"], live: ["Live", "green"], failed: ["Failed", "red"],
uninstalling: ["Uninstalling", "amber"], removed: ["Removed", "grey"],
// 2.12.0: on the Hub as live, but no heartbeat for 24 hours
stale: ["No heartbeat", "red"],
// servers: busy = running a job the Hub handed it (agents before 1.1.1 go quiet then)
busy: ["Running a job", "blue"],
// jobs
@@ -64,6 +66,19 @@ export function StatusPill({ status }: { status: string }) {
return <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset ${TONE[tone]}`}>{label}</span>;
}
/** Hub 2.12.0: an install can be removed from the Hub after this long without a heartbeat. */
export const STALE_MS = 24 * 60 * 60 * 1000;
/** When an install was last heard from: its last heartbeat, else when it went live or was made (as the Hub counts it). */
export const lastHeardAt = (d: Deployment) => d.install?.lastHeartbeatAt || d.liveAt || d.createdAt || null;
/** The status to show: "stale" for an install still on the Hub that's sent nothing for 24 hours. */
export function shownStatus(d: Deployment, now = Date.now()) {
if (["removed", "failed", "installing"].includes(d.status)) return d.status;
const at = lastHeardAt(d);
return at && now - new Date(at).getTime() >= STALE_MS ? "stale" : d.status;
}
export const pct = (n: number | null | undefined) => (n == null ? "–" : `${Math.round(n)}%`);
// <input type="datetime-local"> works in the browser's time; the API takes ISO.
+2
View File
@@ -40,6 +40,8 @@ export type Customer = {
phone: string | null;
notes: string | null;
createdAt: string;
/** Hub 2.12.0: archived (left out of the customer list until restored). */
archivedAt?: string | null;
/** Hub 2.0: the church's AI allowance, shared by all its installs. */
aiMonthlyCapCents: number;
aiMarkupPercent: number | null;