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:
Generated
+6
-6
@@ -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"
|
||||
|
||||
@@ -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);
|
||||
@@ -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[]
|
||||
|
||||
@@ -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 } = {}) {
|
||||
|
||||
@@ -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}.` });
|
||||
}));
|
||||
|
||||
@@ -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);
|
||||
}));
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
Reference in New Issue
Block a user