Hub 2.26.0: the Church App, demo scenarios and devotionals

The App installs from New install on app.<address>, with Accounts 1.9.0
first, and is in every product list and filter (installs, Updates).
Every product has demo data; a demo client loads a whole demo scenario
in one seed-scenario job (agent 1.7.0), and installs show whether they
are out of step with it. The Website's and App's .env from the Hub.

Devotionals: written or imported from CSV up to 3 months ahead in the
free translations (KJV, BSB), and GET /api/v2/devotionals for App
licences. An alert when an App's active-member band is above its tier.

Contracts 1.23.0 vendored. Migration 20261130120000_app_scenarios_devotionals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 22:24:28 +02:00
co-authored by Claude Opus 5.5
parent 9b551bf9ed
commit 16f69afa6f
34 changed files with 1395 additions and 62 deletions
+6 -6
View File
@@ -1,16 +1,16 @@
{
"name": "events-hub-backend",
"version": "2.25.1",
"version": "2.26.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.25.1",
"version": "2.26.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.19.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.23.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.19.0",
"resolved": "file:vendor/crosscode-contracts-1.19.0.tgz",
"integrity": "sha512-s6gXVYT6FmoABS0ozcLVhavC/AeD7cGBngvDVl1WkZb0NB8qRYaK42JR/HD5IM79x4WOZcsfUXZGeuDbYUULrA==",
"version": "1.23.0",
"resolved": "file:vendor/crosscode-contracts-1.23.0.tgz",
"integrity": "sha512-2P86mOLRiPsfSFBxBdx65cATKqsUpZ/dcOWC6qIGJjLNq0h4RH1+nz3yYkbfMjl6HjdkBE6qc491cc5tLKIFZQ==",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.25.1",
"version": "2.26.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.19.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.23.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -0,0 +1,22 @@
-- Hub 2.26.0: demo scenarios (APP-1.0-PLAN §12) and Cross Code's devotionals (§6).
ALTER TABLE "Customer" ADD COLUMN "demoScenario" TEXT;
ALTER TABLE "Customer" ADD COLUMN "demoScenarioAt" TIMESTAMP(3);
ALTER TABLE "Customer" ADD COLUMN "demoScenarioJobId" TEXT;
ALTER TABLE "Deployment" ADD COLUMN "demoScenario" TEXT;
CREATE TABLE "Devotional" (
"id" TEXT NOT NULL,
"date" TEXT NOT NULL,
"title" TEXT NOT NULL,
"passage" JSONB NOT NULL,
"body" TEXT NOT NULL,
"prayer" TEXT,
"author" TEXT,
"createdById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Devotional_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "Devotional_date_key" ON "Devotional"("date");
+26
View File
@@ -74,6 +74,11 @@ model Customer {
// installs can have demo data loaded.
isDemo Boolean @default(false)
demoSince DateTime?
// Hub 2.26.0 (APP-1.0-PLAN §12): the demo scenario last loaded on its installs (contracts
// agent.DEMO_SCENARIOS), when, and the seed-scenario job loading one now.
demoScenario String?
demoScenarioAt DateTime?
demoScenarioJobId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
@@ -606,6 +611,9 @@ model Deployment {
adminEmail String?
// A demo site (2.4.0): only these can have their data replaced with demo data (seed-demo jobs).
isDemo Boolean @default(false)
// Hub 2.26.0: the demo scenario its data is from. A scenario load sets it; loading this product's
// demo on its own clears it, so it shows as out of step with its customer's demoScenario.
demoScenario String?
status DeploymentStatus @default(installing)
// The release it runs (from reports and heartbeats).
version String?
@@ -701,3 +709,21 @@ model Export {
deletedAt DateTime?
createdAt DateTime @default(now())
}
// Hub 2.26.0 (APP-1.0-PLAN §6, contracts crosscode.devotional/1): Cross Code's devotionals, one per
// day, written here up to 3 months ahead and fetched by Apps set to "From Cross Code"
// (GET /api/v2/devotionals). Only the free translations (FREE_BIBLE_TRANSLATION_IDS).
model Devotional {
id String @id @default(uuid())
// The day it's for, YYYY-MM-DD (shown from midnight in each church's timezone).
date String @unique
title String
// { reference, location, translation, text } (contracts devotionalPassageSchema)
passage Json
body String
prayer String?
author String?
createdById String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
+5
View File
@@ -8,6 +8,10 @@ app.disable('x-powered-by');
// Installs call the Hub server-to-server; only the dashboard needs CORS.
app.use(cors({ origin: (process.env.FRONTEND_URL || 'http://localhost:3200').replace(/\/$/, '') }));
// 2.26.0: a devotionals CSV is up to 2 MB (contracts DEVOTIONAL_CSV_MAX_BYTES), sent as JSON text.
// Parsed here first; the parser below skips a body already read.
app.use('/api/admin/devotionals/import', express.json({ limit: '4mb' }));
// Keep the exact bytes: heartbeat signatures are over the raw body. 300 KB fits the largest AI
// request the Hub accepts (utils/ai.js MAX_INPUT_TOKENS).
app.use(express.json({ limit: '1mb', verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } }));
@@ -18,6 +22,7 @@ app.use('/api/exports', require('./routes/exports'));
app.use('/api', require('./routes/installApi'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/admin/billing', require('./routes/billing'));
app.use('/api/admin/devotionals', require('./routes/devotionals'));
app.use('/api/admin', require('./routes/servers'));
app.use('/api/admin', require('./routes/admin'));
+66
View File
@@ -0,0 +1,66 @@
/**
* Cross Code's devotionals (Hub 2.26.0, APP-1.0-PLAN §6): write and schedule them up to 3 months
* ahead, the calendar, Import CSV with its preview, and the template. Admin login required.
*/
const express = require('express');
const { DEVOTIONAL_CSV_TEMPLATE } = require('@crosscode/contracts');
const { protect } = require('../middleware/auth');
const { audit } = require('../utils/audit');
const devotionals = require('../utils/devotionals');
const router = express.Router();
router.use(protect);
const wrap = fn => (req, res) => fn(req, res).catch(e => {
const status = e.status || 500;
if (status >= 500) console.error('[devotionals]', e);
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message, ...(e.code && e.status ? { code: e.code } : {}) });
});
const dateParam = v => (v && devotionals.DATE.test(String(v)) ? String(v) : undefined);
router.get('/', wrap(async (req, res) => {
if (req.query.from || req.query.to) return res.json(await devotionals.list({ from: dateParam(req.query.from), to: dateParam(req.query.to) }));
res.json(await devotionals.overview());
}));
router.get('/template.csv', (req, res) => {
res.set('Content-Type', 'text/csv; charset=utf-8');
res.set('Content-Disposition', 'attachment; filename="cross-code-devotionals-template.csv"');
res.send(DEVOTIONAL_CSV_TEMPLATE);
});
// A CSV comes as text in JSON ({ csv }), up to 2 MB (app.js parses these two with a larger limit).
router.post('/import/preview', wrap(async (req, res) => {
res.json(await devotionals.previewCsv(req.body?.csv));
}));
router.post('/import', wrap(async (req, res) => {
const out = await devotionals.importCsv(req.body?.csv, { replace: req.body?.replace === true }, req.admin);
await audit(req, 'devotionals_imported', null, out);
res.json(out);
}));
router.get('/:id', wrap(async (req, res) => {
res.json(await devotionals.get(req.params.id));
}));
router.post('/', wrap(async (req, res) => {
const out = await devotionals.create(req.body, req.admin);
await audit(req, 'devotional_created', out.devotional.id, { date: out.devotional.date, title: out.devotional.title });
res.status(201).json(out);
}));
router.put('/:id', wrap(async (req, res) => {
const out = await devotionals.update(req.params.id, req.body);
await audit(req, 'devotional_updated', out.devotional.id, { date: out.devotional.date, title: out.devotional.title });
res.json(out);
}));
router.delete('/:id', wrap(async (req, res) => {
const gone = await devotionals.remove(req.params.id);
await audit(req, 'devotional_deleted', gone.id, { date: gone.date, title: gone.title });
res.json({ ok: true });
}));
module.exports = router;
+31
View File
@@ -20,6 +20,7 @@ const { requestMessage, requestedVersionOf, isOutdated } = require('../utils/upd
const { sendMail } = require('../utils/mail');
const { render } = require('../utils/emailLayout');
const storage = require('../utils/storage');
const devotionals = require('../utils/devotionals');
/** An update-request email to Joshua (2.10.0: laid out as the Hub's other emails). */
const updateRequestEmail = ({ heading, note, rows, link }) => render({
@@ -41,6 +42,8 @@ const HEARTBEAT_MINUTES = 15;
const registerLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts.', code: 'RATE_LIMITED' } });
const heartbeatLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } });
const updateRequestLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } });
// 2.26.0: Apps fetch devotionals once a night (and on "Sync now").
const devotionalsLimiter = rateLimit({ windowMs: 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } });
// AI is limited by money (the cap); this only stops a runaway loop.
const aiLimiter = rateLimit({ windowMs: 60 * 1000, max: 60, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many AI requests — wait a minute.', code: 'RATE_LIMITED' } });
@@ -403,6 +406,34 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req,
}
});
// ─── Cross Code's devotionals (Hub 2.26.0, contracts hub.DEVOTIONALS_PATH) ─────
/**
* GET /api/v2/devotionals?from=YYYY-MM-DD: the next 3 months of Cross Code's devotionals for an App
* set to "From Cross Code" (once a night, and on "Sync now"). `Authorization: Bearer <licence
* token>`: App licences only, active or in their grace days.
*/
router.get('/v2/devotionals', devotionalsLimiter, async (req, res) => {
try {
const token = String(req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim();
let payload = null;
try { payload = token ? licenceToken.verify(token) : null; } catch { payload = null; }
if (!payload?.licenceId) return fail(res, 401, 'BAD_LICENCE', 'Send the install\'s licence token as Authorization: Bearer <token>.');
if (payload.product !== 'app') return fail(res, 403, 'NOT_AN_APP', 'Cross Code\'s devotionals are for the Church App.');
const licence = await prisma.licence.findUnique({ where: { id: payload.licenceId } });
if (!licence || licence.product !== 'app') return fail(res, 401, 'BAD_LICENCE', 'That licence isn\'t known to the Hub.');
const now = new Date();
const lapsed = licence.expiresAt && now.getTime() >= new Date(licence.expiresAt).getTime() + (licence.graceDays || 0) * 86400000;
if (licence.status !== 'active' || lapsed) return fail(res, 403, 'LICENCE_INACTIVE', 'This App\'s licence isn\'t active.');
const from = req.query.from === undefined ? null : String(req.query.from);
if (from !== null && !devotionals.DATE.test(from)) return fail(res, 400, 'INVALID_REQUEST', 'from is a date: YYYY-MM-DD.');
res.json(await devotionals.reply(from, now));
} catch (e) {
console.error('[devotionals]', e);
fail(res, 500, 'SERVER_ERROR', 'The Hub could not fetch the devotionals.');
}
});
// ─── AI (Cross Events 2.0, §3b) ───────────────────────────────────────────────
// What the install's AI buttons should do: hidden, working, or disabled until the allowance renews.
+16 -1
View File
@@ -216,7 +216,7 @@ 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, isDemo: true } }, install: true, jobs: { orderBy: { createdAt: 'desc' }, take: 50 }, exports: { select: { id: true, bytes: true, expiresAt: true, downloadedAt: true, deletedAt: true, createdAt: true } } } });
const d = await prisma.deployment.findUnique({ where: { id: req.params.id }, include: { server: true, customer: { select: { id: true, name: true, isDemo: true, demoScenario: 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), stale: jobs.staleness(d), uninstall: await jobs.uninstallPlan(d) });
}));
@@ -263,6 +263,21 @@ router.post('/customers/:id/demo', wrap(async (req, res) => {
res.json({ isDemo: customer.isDemo, sites, warnings });
}));
// Demo scenarios (2.26.0): the list, what one would replace on a demo client, and loading it.
router.get('/demo-scenarios', wrap(async (req, res) => {
res.json(agent.DEMO_SCENARIOS.map(s => ({ key: s.key, church: s.church, label: s.label, description: s.description, campuses: s.campuses, language: s.language, appActiveMembers: s.appActiveMembers, profiles: s.profiles })));
}));
router.get('/customers/:id/scenario', wrap(async (req, res) => {
res.json(await jobs.scenarioPlan(req.params.id, req.query.scenario ? String(req.query.scenario) : null));
}));
router.post('/customers/:id/scenario', wrap(async (req, res) => {
const { job, plan } = await jobs.loadScenario(req.params.id, { scenario: req.body?.scenario, confirm: req.body?.confirm }, req.admin);
await audit(req, 'demo_scenario_queued', req.params.id, { job: job.id, scenario: job.args.scenario, church: job.args.church, products: plan.installs.map(i => i.product) });
res.status(201).json({ job });
}));
// An install's .env (2.8.0): the last read (secrets only as set or not), read it again, change values.
router.get('/deployments/:id/env', wrap(async (req, res) => {
res.json(await jobs.envState(req.params.id));
+17
View File
@@ -78,9 +78,26 @@ function problems(install, settings, now = new Date()) {
out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${latest}` });
}
if (lastSeen) out.push(...signInProblems(install, now));
const tier = appTierProblem(install);
if (tier) out.push(tier);
return out;
}
/**
* Hub 2.26.0 (APP-1.0-PLAN §12, ROADMAP §10): a Church App whose active-member band (heartbeat
* `activeMembers90d`) is above its licence's tier. Nothing changes until the annual review, which
* moves it; this says so in advance. A custom-priced or unknown plan isn't flagged.
*/
function appTierProblem(install) {
if (install.product !== 'app' || !install.licence?.plan) return null;
const { APP_TIERS } = require('./billing/tiers');
const band = install.stats?.activeMembers90d || null;
const at = APP_TIERS.findIndex(t => t.band === band);
const on = APP_TIERS.findIndex(t => t.name.toLowerCase() === String(install.licence.plan).toLowerCase());
if (at < 0 || on < 0 || at <= on) return null;
return { type: 'tier_above', level: 'info', message: `${band} active members (90 days) is above its ${APP_TIERS[on].name} tier; the annual review moves it to ${APP_TIERS[at].name}.` };
}
/**
* Hub 2.9.0: whether people can sign in (contracts 1.13.0). `install.church` (filled in by
* runAlerts): { accountsInstallIds, hasEvents } for the install's customer.
+206
View File
@@ -0,0 +1,206 @@
/**
* Cross Code's devotionals (Hub 2.26.0, crosscode-platform docs/APP-1.0-PLAN.md §6, decisions 1, 5
* and 14; contracts crosscode.devotional/1). Written here, or imported from CSV, up to 3 months
* ahead, one per day, in the free translations only (KJV and BSB). An App set to "From Cross Code"
* fetches the next 3 months once a night (`GET /api/v2/devotionals`) and keeps its copy.
*
* No AI touches a devotional's passage (Crossway and Biblica forbid it), and nothing here sends
* one: the Apps show and send them.
*/
const {
BIBLE_TRANSLATIONS, FREE_BIBLE_TRANSLATION_IDS, DEVOTIONAL_CSV_TEMPLATE, DEVOTIONAL_CSV_COLUMNS, CROSSCODE_DEVOTIONALS_AHEAD_MONTHS, DEVOTIONAL_SCHEMA, PASSAGE_WARN_VERSES,
checkDevotionalCsv, devotionalContentSchema, devotionalsReplySchema, parseBibleReference, formatBibleReference, passageVerseCount,
youVersionUrl, bibleTranslation,
} = require('@crosscode/contracts');
const prisma = require('../config/db');
const fail = (status, code, message) => Object.assign(new Error(message), { status, code });
const DATE = /^\d{4}-\d{2}-\d{2}$/;
/** Today in South Africa (the Hub's day), as YYYY-MM-DD. */
function today(now = new Date()) {
return new Intl.DateTimeFormat('en-CA', { timeZone: 'Africa/Johannesburg', year: 'numeric', month: '2-digit', day: '2-digit' }).format(now);
}
/** A YYYY-MM-DD date `months` later (the 31st becomes the month's last day). */
function addMonths(date, months) {
const [y, m, d] = date.split('-').map(Number);
const last = new Date(Date.UTC(y, m - 1 + months + 1, 0)).getUTCDate();
return new Date(Date.UTC(y, m - 1 + months, Math.min(d, last))).toISOString().slice(0, 10);
}
/** The last day a devotional can be scheduled for: 3 months from today. */
const latestDate = (now = new Date()) => addMonths(today(now), CROSSCODE_DEVOTIONALS_AHEAD_MONTHS);
/** The translations the Hub offers (the free ones), for the form. */
function translations() {
return BIBLE_TRANSLATIONS.filter(t => FREE_BIBLE_TRANSLATION_IDS.includes(t.id))
.map(t => ({ id: t.id, name: t.name, language: t.language, copyright: t.copyright, acknowledgement: t.acknowledgement }));
}
/** A row as crosscode.devotional/1 content (and the id, for the Hub's own pages). */
function shape(row) {
return {
id: row.id, date: row.date, title: row.title, passage: row.passage, body: row.body, prayer: row.prayer ?? null, author: row.author ?? null,
updatedAt: row.updatedAt instanceof Date ? row.updatedAt.toISOString() : row.updatedAt,
};
}
/**
* The form's fields as devotional content: the passage parsed and written out in the
* translation's language, the free translations only, the date within 3 months.
* Returns { devotional, warnings }.
*/
function contentFrom(input, now = new Date()) {
const b = input || {};
const date = String(b.date || '').trim();
if (!DATE.test(date)) throw fail(400, 'BAD_REQUEST', 'Give the date as YYYY-MM-DD.');
const latest = latestDate(now);
if (date > latest) throw fail(400, 'TOO_FAR_AHEAD', `Devotionals are scheduled up to ${CROSSCODE_DEVOTIONALS_AHEAD_MONTHS} months ahead (the last day is ${latest}).`);
const translation = String(b.translation || '').trim().toUpperCase();
if (!FREE_BIBLE_TRANSLATION_IDS.includes(translation)) {
const t = BIBLE_TRANSLATIONS.find(x => x.id === translation);
throw fail(400, 'TRANSLATION_NOT_FREE', t
? `${t.id} needs ${t.publisher || 'its publisher'}'s written permission; use ${FREE_BIBLE_TRANSLATION_IDS.join(' or ')}.`
: `Choose ${FREE_BIBLE_TRANSLATION_IDS.join(' or ')}.`);
}
const parsed = parseBibleReference(String(b.reference || '').trim());
if (!parsed.ok) throw fail(400, 'BAD_REFERENCE', parsed.error);
const content = {
date,
title: String(b.title || '').trim(),
passage: {
reference: formatBibleReference(parsed.passage, bibleTranslation(translation).language),
location: parsed.passage, translation, text: String(b.passageText || '').trim(),
},
body: String(b.body || '').trim(),
prayer: String(b.prayer || '').trim() || null,
author: String(b.author || '').trim() || null,
};
const check = devotionalContentSchema.safeParse(content);
if (!check.success) {
const issue = check.error.issues[0];
const field = { title: 'The title', body: 'The devotional', prayer: 'The prayer', author: 'The author', passage: 'The passage' }[issue.path[0]] || 'A field';
throw fail(400, 'BAD_REQUEST', `${issue.path[0] === 'passage' && issue.path[1] === 'text' ? 'The passage\'s text' : field}: ${issue.message}.`);
}
const warnings = [];
const verses = passageVerseCount(parsed.passage);
if (verses !== null && verses > PASSAGE_WARN_VERSES) warnings.push(`${verses} verses: quote the passage it's about, not whole chapters.`);
return { devotional: check.data, warnings };
}
/** The devotionals from `from` to `to` (inclusive), oldest first. */
async function list({ from, to } = {}) {
const where = {};
if (from || to) where.date = { ...(from ? { gte: from } : {}), ...(to ? { lte: to } : {}) };
const rows = await prisma.devotional.findMany({ where, orderBy: { date: 'asc' } });
return rows.map(shape);
}
/**
* The Devotionals page's overview: today, the last day allowed, and which days from today to then
* have one (the calendar), with the days still empty.
*/
async function overview(now = new Date()) {
const from = today(now);
const to = latestDate(now);
const rows = await list({ from, to });
const filled = new Set(rows.map(r => r.date));
const empty = [];
for (let d = from; d <= to; d = addDays(d, 1)) if (!filled.has(d)) empty.push(d);
return { today: from, latest: to, aheadMonths: CROSSCODE_DEVOTIONALS_AHEAD_MONTHS, devotionals: rows, empty, translations: translations(),
csv: { columns: DEVOTIONAL_CSV_COLUMNS, template: DEVOTIONAL_CSV_TEMPLATE } };
}
function addDays(date, n) {
const d = new Date(`${date}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() + n);
return d.toISOString().slice(0, 10);
}
async function get(id) {
const row = await prisma.devotional.findUnique({ where: { id } });
if (!row) throw fail(404, 'NOT_FOUND', 'Devotional not found.');
return shape(row);
}
async function create(input, admin, now = new Date()) {
const { devotional, warnings } = contentFrom(input, now);
const taken = await prisma.devotional.findUnique({ where: { date: devotional.date } });
if (taken) throw fail(409, 'DATE_TAKEN', `${devotional.date} already has a devotional ("${taken.title}"). Edit that one instead.`);
const row = await prisma.devotional.create({ data: { ...devotional, createdById: admin?.id || null } });
return { devotional: shape(row), warnings };
}
async function update(id, input, now = new Date()) {
const existing = await prisma.devotional.findUnique({ where: { id } });
if (!existing) throw fail(404, 'NOT_FOUND', 'Devotional not found.');
// An old one keeps its date even when that's now in the past; a new date must be within 3 months.
const { devotional, warnings } = contentFrom(input, now);
if (devotional.date !== existing.date) {
const taken = await prisma.devotional.findUnique({ where: { date: devotional.date } });
if (taken) throw fail(409, 'DATE_TAKEN', `${devotional.date} already has a devotional ("${taken.title}").`);
}
const row = await prisma.devotional.update({ where: { id }, data: devotional });
return { devotional: shape(row), warnings };
}
async function remove(id) {
const existing = await prisma.devotional.findUnique({ where: { id } });
if (!existing) throw fail(404, 'NOT_FOUND', 'Devotional not found.');
await prisma.devotional.delete({ where: { id } });
return shape(existing);
}
/** Import CSV, step 1: every row checked (contracts checkDevotionalCsv), nothing saved. */
async function previewCsv(text, now = new Date()) {
const taken = (await prisma.devotional.findMany({})).map(r => r.date);
return checkDevotionalCsv(String(text || ''), { taken, latestDate: latestDate(now), translations: FREE_BIBLE_TRANSLATION_IDS });
}
/**
* Import CSV, step 2: the valid rows saved. Days already filled are replaced or skipped
* (`replace`); rows with errors are never imported.
*/
async function importCsv(text, { replace = false } = {}, admin, now = new Date()) {
const result = await previewCsv(text, now);
if (result.fileError) throw fail(400, 'BAD_CSV', result.fileError);
let created = 0;
let replaced = 0;
let skipped = 0;
const invalid = result.rows.filter(r => !r.devotional).length;
for (const r of result.rows) {
if (!r.devotional) continue;
const existing = await prisma.devotional.findUnique({ where: { date: r.devotional.date } });
if (existing && !replace) { skipped++; continue; }
if (existing) {
await prisma.devotional.update({ where: { id: existing.id }, data: r.devotional });
replaced++;
} else {
await prisma.devotional.create({ data: { ...r.devotional, createdById: admin?.id || null } });
created++;
}
}
return { created, replaced, skipped, invalid };
}
/**
* `GET /api/v2/devotionals?from=YYYY-MM-DD` (contracts hub.DEVOTIONALS_PATH): the devotionals
* from `from` (today by default) to 3 months on, for an App install.
*/
async function reply(from, now = new Date()) {
const start = from || today(now);
const to = addMonths(start, CROSSCODE_DEVOTIONALS_AHEAD_MONTHS);
const rows = (await list({ from: start, to })).slice(0, 100);
return devotionalsReplySchema.parse({
schema: DEVOTIONAL_SCHEMA, from: start, to,
devotionals: rows.map(r => ({ schema: DEVOTIONAL_SCHEMA, source: 'crosscode', ...r })),
generatedAt: now.toISOString(),
});
}
/** The YouVersion link for a devotional's passage (the page's "Read in YouVersion"). */
const youVersionLink = d => youVersionUrl(d.passage.location, d.passage.translation);
module.exports = { today, addMonths, latestDate, translations, contentFrom, list, overview, get, create, update, remove, previewCsv, importCsv, reply, youVersionLink, DATE };
+163 -15
View File
@@ -37,6 +37,8 @@ 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'];
// 2.26.0: the first Accounts the Church App works with (messaging.get, the WhatsApp opt-out).
const APP_MIN_ACCOUNTS = '1.9.0';
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,}$/;
@@ -203,8 +205,13 @@ async function afterJob(job, { exportKey }, now) {
jobReport(job, `${job.type === 'adopt' ? 'Adopt' : 'Update'} of ${deployment.domain} ${ok ? 'done' : job.status.replace('_', ' ')}`, target ? `To ${target}.` : undefined));
break;
}
case 'seed-scenario':
await afterScenario(job, deployment, now);
break;
case 'seed-demo':
if (!deployment) break;
// 2.26.0: one product's demo on its own leaves it out of step with the client's scenario.
if (ok) await prisma.deployment.update({ where: { id: deployment.id }, data: { demoScenario: job.args.scenario || null } });
await emailJoshua(`Demo data ${ok ? `(${job.args.profile}) loaded` : job.status.replace('_', ' ')}: ${deployment.shortName}`,
jobReport(job, ok ? `Demo data loaded on ${deployment.domain}` : `Demo data on ${deployment.domain}: ${job.status.replace('_', ' ')}`, `Profile: ${job.args.profile}.`));
break;
@@ -645,9 +652,10 @@ async function preflight(server, product, version, now) {
/**
* Products the Hub can install so far (Accounts from Hub 2.3.0, docs/ACCOUNTS-1.0-PLAN.md §9; the
* Church Website from 2.21.0, WEBSITE-1.0-PLAN §11).
* Church Website from 2.21.0, WEBSITE-1.0-PLAN §11; the Church App from 2.26.0, APP-1.0-PLAN §12,
* on app.<church's address> with Accounts installed first).
*/
const INSTALLABLE = new Set(['events', 'accounts', 'website']);
const INSTALLABLE = new Set(['events', 'accounts', 'website', 'app']);
/**
* New install (§7): licence, ports, the install job. A church already on that server (the same
@@ -938,7 +946,10 @@ function accountsDomainFor(domain, product = 'events') {
*/
async function requiredFirst({ release, product, siblings, input, domain, server, now }) {
if (product === 'accounts') return null;
const need = (Array.isArray(release.requires) ? release.requires : []).find(q => q && q.product === 'accounts');
// 2.26.0: the App always signs in through Accounts and takes its email and WhatsApp from it
// (messaging.get, Accounts 1.9.0), even if a release's notes don't say so.
const need = (Array.isArray(release.requires) ? release.requires : []).find(q => q && q.product === 'accounts')
|| (product === 'app' ? { product: 'accounts', version: APP_MIN_ACCOUNTS } : null);
if (!need) return null;
const have = siblings.find(s => s.product === 'accounts');
if (have) {
@@ -1689,12 +1700,32 @@ async function setDemo(deploymentId, { isDemo, confirm }) {
return prisma.deployment.update({ where: { id: d.id }, data: { isDemo: !!isDemo } });
}
/** The products with demo data, their profiles (from the contracts) and the agent each needs. */
/**
* The products with demo data, their profiles (from the contracts) and the agent each needs.
* 2.26.0 (contracts 1.23.0): Events' profiles include one per scenario church (Events 3.8.0+), and
* the App and Accounts have demo data too (a scenario's profile, agent 1.7.0+).
*/
const DEMO_DATA = {
events: { profiles: agent.DEMO_PROFILES, minAgent: agent.SEED_DEMO_MIN_AGENT },
events: { profiles: agent.EVENTS_DEMO_PROFILES, minAgent: agent.SEED_DEMO_MIN_AGENT },
website: { profiles: agent.WEBSITE_DEMO_PROFILES, minAgent: agent.SEED_WEBSITE_DEMO_MIN_AGENT },
app: { profiles: agent.APP_DEMO_PROFILES, minAgent: agent.SEED_APP_DEMO_MIN_AGENT },
accounts: { profiles: agent.ACCOUNTS_DEMO_PROFILES, minAgent: agent.SEED_SCENARIO_MIN_AGENT },
};
/**
* The release a profile needs (2.26.0): a scenario church's profile in Events needs Events 3.8.0,
* and the App's and Accounts' demos came with App 1.0.0 and Accounts 1.9.0. The Website's
* profiles are as old as the Website.
*/
function demoMinVersion(product, profile) {
if (product === 'website') return null;
if (product === 'events' && !agent.DEMO_SCENARIO_KEYS.includes(profile)) return null;
return agent.DEMO_SCENARIO_MIN_VERSIONS[product] || null;
}
/** The release an install runs: its heartbeat's, else the Hub's record. */
const runningVersion = d => d.install?.version || d.version || null;
/**
* Replace a demo site's data with a demo set (`crosscode demo`, a backup is taken first). Only for
* installs marked as demo sites, typing the short name, on an agent that knows the job (1.2.0+;
@@ -1702,28 +1733,141 @@ const DEMO_DATA = {
* church's profile and the site settings.
*/
async function seedDemo({ deploymentId, profile, confirm }, admin, now = new Date()) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { server: true } });
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { server: true, install: true } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (!d.isDemo) throw fail(409, 'NOT_DEMO', `${d.shortName} isn't marked as a demo site.`);
const data = DEMO_DATA[d.product];
if (!data) throw fail(400, 'NO_DEMO_DATA', `${PRODUCT_NAMES[d.product] || d.product} has no demo data (only Cross Events and the Church Website).`);
if (!data) throw fail(400, 'NO_DEMO_DATA', `${PRODUCT_NAMES[d.product] || d.product} has no demo data.`);
if (!['live', 'waiting_for_proxy'].includes(d.status)) throw fail(409, 'NOT_LIVE', `It's ${d.status.replace(/_/g, ' ')}; demo data goes on an installed site.`);
if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to replace its data.`);
if (!data.profiles.includes(profile)) throw fail(400, 'BAD_REQUEST', `Choose one of: ${data.profiles.join(', ')}.`);
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.');
if (compareVersions(d.server.agentVersion || '0.0.0', data.minAgent) < 0) {
throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; ${d.product === 'website' ? 'the Website\'s ' : ''}demo data needs ${data.minAgent} or later (update the agent first).`);
throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; ${d.product === 'events' ? '' : `${PRODUCT_NAMES[d.product]}'s `}demo data needs ${data.minAgent} or later (update the agent first).`);
}
const minVersion = demoMinVersion(d.product, profile);
const version = runningVersion(d);
if (minVersion && compareVersions(version || '0.0.0', minVersion) < 0) {
throw fail(409, 'RELEASE_TOO_OLD', `${PRODUCT_NAMES[d.product]} is ${version || 'an unknown version'} here; the ${profile} demo needs ${minVersion} or later (update it first).`);
}
const running = await prisma.job.findFirst({ where: { serverId: d.serverId, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } });
if (!agentOnline(d.server, now, running)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${d.server.name} isn't online.`);
// Events' jobs keep their old form (no product), so they mean the same to any agent.
if (d.product === 'website') {
return makeJob(prisma, { serverId: d.serverId, type: 'seed-demo', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, args: { church: d.shortName, product: 'website', profile } });
if (d.product !== 'events') {
return makeJob(prisma, { serverId: d.serverId, type: 'seed-demo', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, args: { church: d.shortName, product: d.product, profile } });
}
const adminEmail = d.adminEmail && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.adminEmail) ? d.adminEmail.toLowerCase() : undefined;
return makeJob(prisma, { serverId: d.serverId, type: 'seed-demo', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, args: { church: d.shortName, profile, ...(adminEmail ? { adminEmail } : {}) } });
}
// ─── Demo scenarios (2.26.0, contracts 1.23.0, agent 1.7.0; APP-1.0-PLAN §12) ──
/** A scenario from the contracts, or a 400. */
function scenarioFor(key) {
const s = agent.DEMO_SCENARIOS.find(x => x.key === key);
if (!s) throw fail(400, 'BAD_REQUEST', `Choose one of: ${agent.DEMO_SCENARIOS.map(x => x.key).join(', ')}.`);
return s;
}
/**
* What loading a scenario on a demo client would do: its church (one short name on one server),
* each install it replaces, in the order they're loaded, and why it can't be loaded now, if it
* can't (`problems`). Products the scenario has no profile for are listed in `notCovered`.
*/
async function scenarioPlan(customerId, key, now = new Date()) {
const scenario = key ? scenarioFor(key) : null;
const c = await prisma.customer.findUnique({ where: { id: customerId } });
if (!c) throw fail(404, 'NOT_FOUND', 'Customer not found.');
const all = await prisma.deployment.findMany({ where: { customerId: c.id, status: { notIn: ['removed', 'failed'] } }, include: { server: true, install: true } });
all.sort((a, b) => PRODUCT_ORDER.indexOf(a.product) - PRODUCT_ORDER.indexOf(b.product));
const problems = [];
if (!c.isDemo) problems.push(`${c.name} isn't a demo client (make it one first).`);
if (!all.length) problems.push(`${c.name} has no installs on a server.`);
const churches = [...new Set(all.map(d => `${d.shortName}@${d.serverId}`))];
if (churches.length > 1) problems.push(`${c.name}'s installs are under more than one short name or server (${[...new Set(all.map(d => d.shortName))].join(', ')}); a scenario loads one church.`);
const server = all[0]?.server || null;
if (server) {
if (server.removedAt) problems.push('That server was removed.');
else if (compareVersions(server.agentVersion || '0.0.0', agent.SEED_SCENARIO_JOB_MIN_AGENT) < 0) {
problems.push(`The agent on ${server.name} is ${server.agentVersion || 'an unknown version'}; a demo scenario needs ${agent.SEED_SCENARIO_JOB_MIN_AGENT} or later (update the agent first).`);
} else {
const running = await prisma.job.findFirst({ where: { serverId: server.id, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } });
if (!agentOnline(server, now, running)) problems.push(`The agent on ${server.name} isn't online.`);
}
}
if (c.demoScenarioJobId) {
const job = await prisma.job.findUnique({ where: { id: c.demoScenarioJobId } });
if (job && !DONE.includes(job.status)) problems.push('A demo scenario is already loading: wait for its report.');
}
const installs = all.map(d => {
const min = agent.DEMO_SCENARIO_MIN_VERSIONS[d.product] || null;
const version = runningVersion(d);
const tooOld = !!min && compareVersions(version || '0.0.0', min) < 0;
const covered = !!scenario && !!scenario.profiles[d.product];
if (!d.isDemo) problems.push(`${d.domain} isn't a demo site.`);
if (!['live', 'waiting_for_proxy'].includes(d.status)) problems.push(`${d.domain} is ${d.status.replace(/_/g, ' ')}; wait until it's installed.`);
if (tooOld) problems.push(`${PRODUCT_NAMES[d.product]} is ${version || 'an unknown version'} on ${d.domain}; a demo scenario needs ${min} or later (update it first).`);
return {
id: d.id, product: d.product, domain: d.domain, version, minVersion: min, tooOld, covered,
profile: covered ? scenario.profiles[d.product] : null,
demoScenario: d.demoScenario || null,
outOfStep: !!c.demoScenario && d.demoScenario !== c.demoScenario,
};
});
return {
customer: { id: c.id, name: c.name, isDemo: c.isDemo, demoScenario: c.demoScenario || null, demoScenarioAt: c.demoScenarioAt || null, demoScenarioJobId: c.demoScenarioJobId || null },
scenario, shortName: all[0]?.shortName || null, server: server ? { id: server.id, name: server.name, agentVersion: server.agentVersion || null } : null,
installs, notCovered: installs.filter(i => !i.covered && scenario).map(i => i.product), problems: [...new Set(problems)],
};
}
/**
* Load a demo scenario on a demo client (typing its short name): one seed-scenario job; the
* server loads every product the church has there, Accounts first, and skips the rest.
*/
async function loadScenario(customerId, { scenario: key, confirm }, admin, now = new Date()) {
const plan = await scenarioPlan(customerId, key, now);
if (plan.problems.length) throw fail(409, 'CANT_LOAD_SCENARIO', plan.problems.join(' '));
if ((confirm || '').trim() !== plan.shortName) throw fail(400, 'CONFIRM', `Type ${plan.shortName} to replace its demo data.`);
const events = (await prisma.deployment.findMany({ where: { customerId, product: 'events', status: { notIn: ['removed', 'failed'] } } }))[0];
const adminEmail = events?.adminEmail && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(events.adminEmail) ? events.adminEmail.toLowerCase() : undefined;
const job = await makeJob(prisma, {
serverId: plan.server.id, type: 'seed-scenario', deploymentId: plan.installs[0].id, createdById: admin?.id || null, notBefore: now,
args: { church: plan.shortName, scenario: plan.scenario.key, ...(adminEmail ? { adminEmail } : {}) },
});
await prisma.customer.update({ where: { id: customerId }, data: { demoScenarioJobId: job.id } });
return { job, plan };
}
/** "accounts events" → ['accounts', 'events'] (a seed-scenario report's `loaded` / `skipped`). */
const productList = v => (Array.isArray(v) ? v : String(v || '').split(/[\s,]+/)).filter(p => PRODUCT_ORDER.includes(p));
/** After a seed-scenario job: which installs now hold the scenario, the customer's record, an email. */
async function afterScenario(job, deployment, now) {
const ok = job.status === 'succeeded';
const loaded = productList(job.report?.result?.loaded);
const skipped = productList(job.report?.result?.skipped);
const sites = await prisma.deployment.findMany({ where: { serverId: job.serverId, shortName: job.args.church, status: { notIn: ['removed', 'failed'] } } });
for (const d of sites) {
if (loaded.includes(d.product)) await prisma.deployment.update({ where: { id: d.id }, data: { demoScenario: job.args.scenario } });
// A product it stopped at, or never reached, may hold part of a load: out of step.
else if (!ok && !skipped.includes(d.product)) await prisma.deployment.update({ where: { id: d.id }, data: { demoScenario: null } });
}
const customerId = deployment?.customerId || sites[0]?.customerId;
if (customerId) {
await prisma.customer.update({
where: { id: customerId },
data: { demoScenarioJobId: null, ...(ok || loaded.length ? { demoScenario: job.args.scenario, demoScenarioAt: now } : {}) },
});
}
const s = agent.DEMO_SCENARIOS.find(x => x.key === job.args.scenario);
const names = list => list.map(p => PRODUCT_NAMES[p]).join(', ') || 'none';
const behind = sites.map(d => d.product).filter(p => !loaded.includes(p) && !skipped.includes(p));
await emailJoshua(`Demo scenario ${ok ? 'loaded' : job.status.replace('_', ' ')}: ${job.args.church}`,
jobReport(job, ok ? `${s?.church || job.args.scenario} loaded on ${job.args.church}` : `Demo scenario on ${job.args.church}: ${job.status.replace('_', ' ')}`,
`Scenario: ${s?.label || job.args.scenario}. Loaded: ${names(loaded)}.${skipped.length ? ` Not installed, so skipped: ${names(skipped)}.` : ''}${!ok && behind.length ? ` Out of step: ${names(behind)}; load the scenario again once it's fixed.` : ''}`));
}
/**
* Hub 2.25.0: make a customer a demo client (typing its name), or an ordinary one again. A demo
* client's installs are all demo sites, Accounts included (and any it gets later), and it isn't
@@ -1741,7 +1885,7 @@ async function setCustomerDemo(customerId, { isDemo, confirm }, now = new Date()
where: { id: c.id },
data: isDemo
? { isDemo: true, demoSince: c.isDemo ? c.demoSince : now, billingCycle: 'none', nextInvoiceDate: null }
: { isDemo: false, demoSince: null },
: { isDemo: false, demoSince: null, demoScenario: null, demoScenarioAt: null },
}),
prisma.deployment.updateMany({ where: { customerId: c.id, removedAt: null }, data: { isDemo: !!isDemo } }),
]);
@@ -1751,7 +1895,10 @@ async function setCustomerDemo(customerId, { isDemo, confirm }, now = new Date()
// ─── An install's .env (2.8.0, contracts 1.12.0, agent 1.3.0) ─────────────────
const ENV_PRODUCTS = ['events', 'accounts'];
// 2.26.0: every product. `crosscode env` reads any product's template, but the script only knows
// the Website from agent 1.6.0 and the App from 1.7.0.
const ENV_PRODUCTS = ['events', 'accounts', 'website', 'app'];
const ENV_MIN_AGENT = { website: agent.SEED_WEBSITE_DEMO_MIN_AGENT, app: agent.SEED_APP_DEMO_MIN_AGENT };
const ENV_OPEN = ['queued', 'delivered'];
/** The install, checked for reading or changing its .env: installed, a product the script knows, an agent that can. */
@@ -1761,8 +1908,9 @@ async function envDeployment(deploymentId, now) {
if (!ENV_PRODUCTS.includes(d.product)) throw fail(400, 'NOT_SUPPORTED', `${PRODUCT_NAMES[d.product] || d.product} installs don't have .env settings here yet.`);
if (!['live', 'waiting_for_proxy'].includes(d.status)) throw fail(409, 'NOT_LIVE', `It's ${d.status.replace(/_/g, ' ')}; .env settings are for an installed site.`);
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.');
if (compareVersions(d.server.agentVersion || '0.0.0', agent.ENV_JOBS_MIN_AGENT) < 0) {
throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; .env settings need ${agent.ENV_JOBS_MIN_AGENT} or later (update the agent first).`);
const minAgent = ENV_MIN_AGENT[d.product] || agent.ENV_JOBS_MIN_AGENT;
if (compareVersions(d.server.agentVersion || '0.0.0', minAgent) < 0) {
throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; ${d.product === 'website' || d.product === 'app' ? `${PRODUCT_NAMES[d.product]}'s ` : ''}.env settings need ${minAgent} or later (update the agent first).`);
}
const running = await prisma.job.findFirst({ where: { serverId: d.serverId, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } });
if (!agentOnline(d.server, now, running)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${d.server.name} isn't online.`);
@@ -1814,7 +1962,7 @@ async function setEnv(deploymentId, { file, set, unset, restart }, admin, now =
module.exports = {
readEnv, setEnv, envState, readFrp, writeFrp, listFrpcTunnels, portsProbed, probeServers, PROBE_SPARE,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, setCustomerDemo, customerIsDemo, churchUpdatePlan, scheduleChurchUpdate,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, setCustomerDemo, customerIsDemo, scenarioPlan, loadScenario, churchUpdatePlan, scheduleChurchUpdate,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, staleness, forgetStale, uninstallPlan, STALE_MS, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
fastPanelText, fastPanelSteps, notesBlocks, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
+151
View File
@@ -0,0 +1,151 @@
// Hub 2.26.0 (crosscode-platform docs/APP-1.0-PLAN.md §6): Cross Code's devotionals. Written up to 3
// months ahead in the free translations only, imported from CSV with a preview, and fetched by App
// installs (GET /api/v2/devotionals with the licence token; App licences only). Also the App's
// tier alert (its active-member band above its tier).
const crypto = require('crypto');
jest.mock('../src/config/db', () => require('./fakeDb').createFakeDb());
jest.mock('express-rate-limit', () => () => (req, res, next) => next());
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123';
const hubKey = crypto.generateKeyPairSync('ed25519');
process.env.HUB_SIGNING_KEY = hubKey.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
const express = require('express');
const { DEVOTIONAL_CSV_TEMPLATE, devotionalCsv, devotionalsReplySchema } = require('@crosscode/contracts');
const db = require('../src/config/db');
const devotionals = require('../src/utils/devotionals');
const licenceToken = require('../src/utils/licenceToken');
const { problems } = require('../src/utils/alerts');
// 10:00 in South Africa on 30 November 2026.
const NOW = new Date('2026-11-30T08:00:00.000Z');
const admin = { id: 'admin-1' };
const form = (over = {}) => ({
date: '2026-12-05', title: 'Love that never gives up', reference: '1 Cor 13:4-7', translation: 'BSB',
passageText: 'Love is patient, love is kind.', body: 'Paul wrote these words…', prayer: 'Lord, teach me to love.', author: 'Cross Code', ...over,
});
beforeEach(() => { for (const k of Object.keys(db.tables)) db.tables[k].length = 0; });
describe('writing devotionals', () => {
test('a devotional: the passage written out, in a free translation, within 3 months', async () => {
const { devotional, warnings } = await devotionals.create(form(), admin, NOW);
expect(devotional).toMatchObject({ date: '2026-12-05', passage: { reference: '1 Corinthians 13:4–7', translation: 'BSB', text: 'Love is patient, love is kind.' }, prayer: 'Lord, teach me to love.' });
expect(warnings).toEqual([]);
await expect(devotionals.create(form({ title: 'Another' }), admin, NOW)).rejects.toMatchObject({ code: 'DATE_TAKEN' });
});
test('refused: a translation that needs permission, more than 3 months ahead, a reference that can\'t be read, an empty field', async () => {
expect(devotionals.latestDate(NOW)).toBe('2027-02-28');
await expect(devotionals.create(form({ translation: 'NIV' }), admin, NOW)).rejects.toMatchObject({ code: 'TRANSLATION_NOT_FREE', message: expect.stringContaining('KJV or BSB') });
await expect(devotionals.create(form({ date: '2027-03-01' }), admin, NOW)).rejects.toMatchObject({ code: 'TOO_FAR_AHEAD', message: expect.stringContaining('2027-02-28') });
await expect(devotionals.create(form({ reference: 'Hezekiah 1:1' }), admin, NOW)).rejects.toMatchObject({ code: 'BAD_REFERENCE' });
await expect(devotionals.create(form({ body: ' ' }), admin, NOW)).rejects.toMatchObject({ status: 400, message: expect.stringContaining('The devotional') });
expect(await db.devotional.findMany({})).toEqual([]);
});
test('a long passage is saved, with a warning', async () => {
const { warnings } = await devotionals.create(form({ reference: 'Psalm 119:1-40', translation: 'KJV' }), admin, NOW);
expect(warnings).toEqual([expect.stringContaining('40 verses')]);
});
test('editing, moving to a free day, deleting; the overview lists the empty days', async () => {
const { devotional } = await devotionals.create(form(), admin, NOW);
await devotionals.create(form({ date: '2026-12-06' }), admin, NOW);
await expect(devotionals.update(devotional.id, form({ date: '2026-12-06' }), NOW)).rejects.toMatchObject({ code: 'DATE_TAKEN' });
expect((await devotionals.update(devotional.id, form({ date: '2026-12-07', title: 'Moved' }), NOW)).devotional).toMatchObject({ date: '2026-12-07', title: 'Moved' });
const o = await devotionals.overview(NOW);
expect(o).toMatchObject({ today: '2026-11-30', latest: '2027-02-28', aheadMonths: 3 });
expect(o.devotionals.map(d => d.date)).toEqual(['2026-12-06', '2026-12-07']);
expect(o.empty).toContain('2026-12-05');
expect(o.empty).not.toContain('2026-12-06');
expect(o.translations.map(t => t.id)).toEqual(['KJV', 'BSB']);
expect(o.csv.template).toBe(DEVOTIONAL_CSV_TEMPLATE);
await devotionals.remove(devotional.id);
expect((await devotionals.list()).map(d => d.date)).toEqual(['2026-12-06']);
});
});
describe('Import CSV', () => {
const row = (over = {}) => ({ date: '2026-12-10', title: 'A title', passage: 'John 3:16', translation: 'KJV', passage_text: 'For God so loved the world…', body: 'Body', prayer: '', author: '', ...over });
test('the preview checks every row: a translation needing permission, too far ahead, a day taken', async () => {
await devotionals.create(form({ date: '2026-12-11' }), admin, NOW);
const csv = devotionalCsv([row(), row({ date: '2026-12-11' }), row({ date: '2026-12-12', translation: 'ESV' }), row({ date: '2027-06-01' })]);
const preview = await devotionals.previewCsv(csv, NOW);
expect(preview.fileError).toBeNull();
expect(preview.rows.map(r => [!!r.devotional, r.taken])).toEqual([[true, false], [true, true], [false, false], [false, false]]);
expect(preview.rows[2].errors[0].message).toContain('Crossway');
expect(preview.rows[3].errors[0].message).toContain('3 months');
});
test('importing saves the valid rows; days already filled are skipped or replaced', async () => {
await devotionals.create(form({ date: '2026-12-11', title: 'Old' }), admin, NOW);
const csv = devotionalCsv([row(), row({ date: '2026-12-11', title: 'New' }), row({ date: '2026-12-12', translation: 'NLT' })]);
expect(await devotionals.importCsv(csv, { replace: false }, admin, NOW)).toEqual({ created: 1, replaced: 0, skipped: 1, invalid: 1 });
expect((await db.devotional.findUnique({ where: { date: '2026-12-11' } })).title).toBe('Old');
expect(await devotionals.importCsv(csv, { replace: true }, admin, NOW)).toEqual({ created: 0, replaced: 2, skipped: 0, invalid: 1 });
expect((await db.devotional.findUnique({ where: { date: '2026-12-11' } })).title).toBe('New');
await expect(devotionals.importCsv('nothing,here\n', {}, admin, NOW)).rejects.toMatchObject({ code: 'BAD_CSV' });
});
});
describe('GET /api/v2/devotionals', () => {
let server;
let base;
beforeAll(async () => {
const app = express();
app.use(express.json());
app.use('/api', require('../src/routes/installApi'));
await new Promise(resolve => { server = app.listen(0, '127.0.0.1', resolve); });
base = `http://127.0.0.1:${server.address().port}/api`;
});
afterAll(() => new Promise(resolve => server.close(resolve)));
async function licence(product = 'app', data = {}) {
const l = await db.licence.create({ data: { id: crypto.randomUUID(), customerId: 'cust-1', product, key: `KEY-${product}`, status: 'active', plan: 'Mustard Seed', graceDays: 14, expiresAt: null, ...data } });
return licenceToken.sign(licenceToken.buildPayload(l, { id: 'inst-1' }, 'Hope'));
}
const get = (token, query = '') => fetch(`${base}/v2/devotionals${query}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
test("an App's licence token gets the next 3 months from `from`, as crosscode.devotional/1", async () => {
const today = devotionals.today();
const later = devotionals.addMonths(today, 1);
await db.devotional.create({ data: { id: crypto.randomUUID(), date: later, title: 'Later', passage: { reference: 'John 3:16', location: { book: 'JHN', chapter: 3, verse: 16, endChapter: 3, endVerse: 16 }, translation: 'KJV', text: 'For God so loved the world' }, body: 'Body', prayer: null, author: null, updatedAt: new Date() } });
await db.devotional.create({ data: { id: crypto.randomUUID(), date: '2020-01-01', title: 'Old', passage: { reference: 'John 3:16', location: { book: 'JHN', chapter: 3, verse: 16, endChapter: 3, endVerse: 16 }, translation: 'KJV', text: 'x' }, body: 'Body', prayer: null, author: null, updatedAt: new Date() } });
const res = await get(await licence());
expect(res.status).toBe(200);
const body = await res.json();
expect(devotionalsReplySchema.safeParse(body).success).toBe(true);
expect(body).toMatchObject({ from: today, to: devotionals.addMonths(today, 3) });
expect(body.devotionals.map(d => [d.date, d.source])).toEqual([[later, 'crosscode']]);
});
test('refused: no token or a forged one, another product, an inactive licence, a bad date', async () => {
expect((await get(null)).status).toBe(401);
expect(await (await get('hel1.forged.token')).json()).toMatchObject({ code: 'BAD_LICENCE' });
const events = await get(await licence('events'));
expect([events.status, (await events.json()).code]).toEqual([403, 'NOT_AN_APP']);
const lapsed = await get(await licence('app', { expiresAt: new Date('2026-01-01'), graceDays: 14 }));
expect([lapsed.status, (await lapsed.json()).code]).toEqual([403, 'LICENCE_INACTIVE']);
for (const k of Object.keys(db.tables)) db.tables[k].length = 0;
const suspended = await get(await licence('app', { status: 'suspended' }));
expect((await suspended.json()).code).toBe('LICENCE_INACTIVE');
for (const k of Object.keys(db.tables)) db.tables[k].length = 0;
expect((await get(await licence(), '?from=tomorrow')).status).toBe(400);
});
});
describe("the App's tier (2.26.0)", () => {
const app = (plan, band) => ({ product: 'app', registeredAt: NOW, lastHeartbeatAt: NOW, licence: { status: 'active', plan, expiresAt: null }, stats: { activeMembers90d: band } });
test('an active-member band above its tier is flagged for the annual review; at or below it, or no band, nothing', () => {
const above = problems(app('Mustard Seed', '301–750'), {}, NOW).find(p => p.type === 'tier_above');
expect(above).toMatchObject({ level: 'info', message: expect.stringContaining('moves it to Congregation') });
expect(problems(app('Congregation', '301–750'), {}, NOW).find(p => p.type === 'tier_above')).toBeUndefined();
expect(problems(app('Gathering', '101–300'), {}, NOW).find(p => p.type === 'tier_above')).toBeUndefined();
expect(problems(app('Mustard Seed', null), {}, NOW).find(p => p.type === 'tier_above')).toBeUndefined();
expect(problems({ ...app('Mustard Seed', '301–750'), product: 'events' }, {}, NOW).find(p => p.type === 'tier_above')).toBeUndefined();
});
});
+2 -1
View File
@@ -19,7 +19,8 @@ const RELATIONS = {
};
const KEYS = { port: 'port', setting: 'key' };
const cmp = (a, b) => (a instanceof Date ? a.getTime() : a) - (b instanceof Date ? b.getTime() : b);
// Strings (YYYY-MM-DD dates, 2.26.0) compare as text, as in PostgreSQL.
const cmp = (a, b) => (typeof a === 'string' && typeof b === 'string' ? (a < b ? -1 : a > b ? 1 : 0) : (a instanceof Date ? a.getTime() : a) - (b instanceof Date ? b.getTime() : b));
function matches(row, where = {}) {
for (const [k, cond] of Object.entries(where || {})) {
+143 -8
View File
@@ -465,7 +465,7 @@ describe('Accounts from the Hub (2.3.0)', () => {
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toMatchObject({ status: 'waiting_for_proxy', version: '1.0.0' });
});
test("refused: another server, a product the Hub can't install yet, or while the first is installing", async () => {
test("refused: another server, a product with no release yet, or while the first is installing", async () => {
const { server } = await joinServer();
const other = (await joinServer('church', 'church-2')).server;
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
@@ -473,7 +473,8 @@ describe('Accounts from the Hub (2.3.0)', () => {
await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
await expect(jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'accounts.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'BUSY' });
await expect(jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: other.id, shortName: 'hope', domain: 'accounts.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'OTHER_SERVER' });
await expect(jobs.newInstall({ product: 'app', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'app.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
// 2.26.0: the App can be installed, once it has a release.
await expect(jobs.newInstall({ product: 'app', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'app.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'NO_RELEASE' });
});
});
@@ -720,11 +721,29 @@ describe('demo sites (2.4.0)', () => {
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'bold-plant', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.6.0') });
});
test('2.25.0: any product can be a demo site, but only Events and the Website have demo data', async () => {
const { d } = await liveDemo({ agentVersion: '1.6.0', isDemo: false });
await db.deployment.update({ where: { id: d.id }, data: { product: 'accounts' } });
test('2.26.0: Accounts and the App have demo data too: a scenario profile, agent 1.7.0, Accounts 1.9.0 / App 1.0.0', async () => {
const { server, d } = await liveDemo({ agentVersion: '1.6.0', isDemo: false });
await db.deployment.update({ where: { id: d.id }, data: { product: 'accounts', version: '1.8.0' } });
expect(await jobs.setDemo(d.id, { isDemo: true, confirm: 'demo2' })).toMatchObject({ isDemo: true });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'NO_DEMO_DATA' });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'community-family', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.7.0') });
await db.server.update({ where: { id: server.id }, data: { agentVersion: '1.7.0' } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'community-family', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'RELEASE_TOO_OLD', message: expect.stringContaining('1.9.0') });
await db.deployment.update({ where: { id: d.id }, data: { version: '1.9.0' } });
expect((await jobs.seedDemo({ deploymentId: d.id, profile: 'community-family', confirm: 'demo2' }, admin, NOW)).args).toEqual({ church: 'demo2', product: 'accounts', profile: 'community-family' });
await db.job.deleteMany({});
await db.deployment.update({ where: { id: d.id }, data: { product: 'app', version: '1.0.0' } });
const job = await jobs.seedDemo({ deploymentId: d.id, profile: 'bold-youth', confirm: 'demo2' }, admin, NOW);
expect(job.args).toEqual({ church: 'demo2', product: 'app', profile: 'bold-youth' });
expect(agent.jobArgsSchemas['seed-demo'].safeParse(job.args).success).toBe(true);
});
test("2.26.0: Events' scenario churches need Events 3.8.0; its first four profiles don't", async () => {
const { d } = await liveDemo();
await db.deployment.update({ where: { id: d.id }, data: { version: '3.7.2' } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'clean-campus', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'RELEASE_TOO_OLD', message: expect.stringContaining('3.8.0') });
expect((await jobs.seedDemo({ deploymentId: d.id, profile: 'multicampus', confirm: 'demo2' }, admin, NOW)).args.profile).toBe('multicampus');
});
test('2.25.0: a demo client: all its installs demo sites (Accounts too), billing off, new installs demo too', async () => {
@@ -932,7 +951,7 @@ describe("an install's .env from the Hub (2.8.0)", () => {
expect((await jobs.envState(d.id)).lastSet).toMatchObject({ status: 'succeeded' });
});
test("refused: secrets, values the app can't start with, nothing to change, an old agent, a product without .env support", async () => {
test("refused: secrets, values the app can't start with, nothing to change, an old agent", async () => {
let { d } = await live();
await expect(jobs.setEnv(d.id, { set: { JWT_SECRET: 'x' } }, admin, NOW)).rejects.toMatchObject({ status: 400, message: expect.stringContaining('secret') });
await expect(jobs.setEnv(d.id, { set: { TRUST_PROXY: 'TRUE' } }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_VALUE' });
@@ -942,10 +961,23 @@ describe("an install's .env from the Hub (2.8.0)", () => {
({ d } = await live({ agentVersion: '1.2.0' }));
await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.3.0') });
await seed();
// 2.26.0: the Website's and App's .env too, on an agent whose script knows them.
({ d } = await live({ product: 'website' }));
await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'NOT_SUPPORTED' });
await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.6.0') });
await seed();
({ d } = await live({ product: 'app', agentVersion: '1.6.0' }));
await expect(jobs.readEnv(d.id, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.7.0') });
expect(await db.job.findMany({})).toEqual([]);
});
test('2.26.0: the Website and the App have .env settings too', async () => {
for (const [product, agentVersion] of [['website', '1.6.0'], ['app', '1.7.0']]) {
await seed();
const { d } = await live({ product, agentVersion });
expect(await jobs.readEnv(d.id, admin, NOW)).toMatchObject({ type: 'env-read', args: { church: 'hope', product } });
expect((await jobs.envState(d.id)).supported).toBe(true);
}
});
});
describe('ports checked on both servers before an install (2.11.0)', () => {
@@ -1358,3 +1390,106 @@ describe('a whole church to latest in one go (2.24.0)', () => {
expect(out.jobs[0].notBefore).toEqual(NOW);
});
});
describe('the Church App from the Hub (2.26.0)', () => {
const poll = (server) => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.7.0', mode: 'church', runningJobId: null }, NOW);
beforeEach(async () => {
await db.release.create({ data: { id: 'rp1', product: 'app', version: '1.0.0', notes: '- First release', releasedAt: NOW } });
await db.release.create({ data: { id: 'ra9', product: 'accounts', version: '1.9.0', notes: '- messaging.get', releasedAt: NOW } });
});
test('a new church: Accounts 1.9.0 first (even with no "requires" in its notes), then the App, with a CCP- licence on Mustard Seed', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const out = await jobs.newInstall({ product: 'app', customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'app.grace.co.za' }, admin, NOW);
expect(out.alsoInstalling).toEqual({ product: 'accounts', domain: 'accounts.grace.co.za', version: '1.9.0' });
const [first] = (await poll(server)).jobs;
expect(first).toMatchObject({ type: 'install', args: { products: ['accounts'] } });
await jobs.receiveReport(server, signedReport(first, 'succeeded', { result: { versions: { accounts: 'accounts@1.9.0' } } }), NOW);
const [second] = (await poll(server)).jobs;
expect(second).toMatchObject({ type: 'add-product', args: { church: 'grace', product: 'app', version: 'app@1.0.0', domain: 'app.grace.co.za' } });
expect(agent.agentJobSchema.safeParse(second).success).toBe(true);
const key = signing.openConfig(second.config, keys.x.privateKeyPem).install.app.HUB_LICENCE_KEY;
expect(key).toMatch(/^CCP-/);
expect(await db.licence.findFirst({ where: { key } })).toMatchObject({ product: 'app', plan: 'Mustard Seed' });
});
test('a church whose Accounts is older than 1.9.0 is asked to update it first', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
await db.deployment.create({ data: { id: 'acc-old', serverId: server.id, customerId: 'cust-1', product: 'accounts', shortName: 'hope', domain: 'accounts.hope.co.za', webPort: 20000, apiPort: 20001, status: 'live', version: '1.8.0' } });
await expect(jobs.newInstall({ product: 'app', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'app.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'REQUIREMENT_NOT_MET', message: expect.stringContaining('1.9.0') });
});
test('the FastPanel steps for app.<address>', async () => {
const text = await jobs.fastPanelText({ id: 'd1', product: 'app', shortName: 'grace', domain: 'app.grace.co.za', webPort: 20010, apiPort: 20011, customer: { name: 'Grace' } });
expect(text).toContain('Grace, Church App');
expect(text).toContain('location ^~ /api/ {');
expect(text).not.toContain('301');
});
});
describe('demo scenarios (2.26.0)', () => {
const VERSIONS = { accounts: '1.9.0', events: '3.8.0', website: '1.8.0', app: '1.0.0' };
async function demoClient({ products = ['accounts', 'events', 'website', 'app'], agentVersion = '1.7.0', versions = {} } = {}) {
const { server } = await joinServer();
await db.server.update({ where: { id: server.id }, data: { agentVersion, lastSeenAt: NOW } });
await db.customer.update({ where: { id: 'cust-1' }, data: { isDemo: true } });
let port = 20000;
for (const product of products) {
await db.deployment.create({ data: { id: `dep-${product}`, serverId: server.id, customerId: 'cust-1', product, shortName: 'demo2', domain: `${product}.demo2.test`, webPort: port++, apiPort: port++, status: 'live', isDemo: true, version: versions[product] || VERSIONS[product], adminEmail: product === 'events' ? 'Jane@Hope.test' : null } });
}
return { server };
}
test('the plan lists what it replaces, Accounts first; loading it is one seed-scenario job the agent can verify', async () => {
const { server } = await demoClient({ products: ['website', 'accounts', 'events'] });
const plan = await jobs.scenarioPlan('cust-1', 'bold-youth', NOW);
expect(plan).toMatchObject({ shortName: 'demo2', problems: [], notCovered: [] });
expect(plan.installs.map(i => [i.product, i.profile])).toEqual([['accounts', 'bold-youth'], ['events', 'bold-youth'], ['website', 'bold-youth']]);
await expect(jobs.loadScenario('cust-1', { scenario: 'bold-youth', confirm: 'nope' }, admin, NOW)).rejects.toMatchObject({ code: 'CONFIRM' });
const { job } = await jobs.loadScenario('cust-1', { scenario: 'bold-youth', confirm: 'demo2' }, admin, NOW);
expect(job).toMatchObject({ type: 'seed-scenario', deploymentId: 'dep-accounts', args: { church: 'demo2', scenario: 'bold-youth', adminEmail: 'jane@hope.test' } });
const polled = await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.7.0', mode: 'church', runningJobId: null }, NOW);
expect(agent.agentJobSchema.safeParse(polled.jobs[0]).success).toBe(true);
// A second one waits for the first.
expect((await jobs.scenarioPlan('cust-1', 'bold-youth', NOW)).problems).toEqual([expect.stringContaining('already loading')]);
await jobs.receiveReport(server, signedReport(polled.jobs[0], 'succeeded', { result: { loaded: 'accounts events website', skipped: 'app' } }), NOW);
expect(await db.customer.findUnique({ where: { id: 'cust-1' } })).toMatchObject({ demoScenario: 'bold-youth', demoScenarioAt: NOW, demoScenarioJobId: null });
expect((await db.deployment.findMany({})).map(d => d.demoScenario)).toEqual(['bold-youth', 'bold-youth', 'bold-youth']);
expect(mockMails.at(-1).subject).toBe('Cross Code Hub: Demo scenario loaded: demo2');
expect((await jobs.scenarioPlan('cust-1', null, NOW)).installs.every(i => !i.outOfStep)).toBe(true);
});
test("a failure stops the rest: the products it didn't load are out of step", async () => {
const { server } = await demoClient();
const { job } = await jobs.loadScenario('cust-1', { scenario: 'clean-campus', confirm: 'demo2' }, admin, NOW);
await jobs.receiveReport(server, signedReport(job, 'failed', { result: { loaded: 'accounts', skipped: '' } }), NOW);
expect(await db.customer.findUnique({ where: { id: 'cust-1' } })).toMatchObject({ demoScenario: 'clean-campus', demoScenarioJobId: null });
const plan = await jobs.scenarioPlan('cust-1', null, NOW);
expect(plan.installs.map(i => [i.product, i.outOfStep])).toEqual([['accounts', false], ['events', true], ['website', true], ['app', true]]);
expect(mockMails.at(-1).subject).toBe('Cross Code Hub: Demo scenario failed: demo2');
});
test('one product loaded on its own is out of step with the scenario', async () => {
const { server } = await demoClient({ products: ['accounts', 'events'] });
const { job } = await jobs.loadScenario('cust-1', { scenario: 'heritage-city', confirm: 'demo2' }, admin, NOW);
await jobs.receiveReport(server, signedReport(job, 'succeeded', { result: { loaded: 'accounts events', skipped: 'website app' } }), NOW);
const single = await jobs.seedDemo({ deploymentId: 'dep-events', profile: 'small', confirm: 'demo2' }, admin, NOW);
await jobs.receiveReport(server, signedReport(single, 'succeeded'), NOW);
expect((await jobs.scenarioPlan('cust-1', null, NOW)).installs.find(i => i.product === 'events')).toMatchObject({ outOfStep: true, demoScenario: null });
});
test('refused: not a demo client, an old agent, an install on too old a release, unknown scenario', async () => {
await demoClient({ agentVersion: '1.6.0', versions: { events: '3.7.2' } });
const plan = await jobs.scenarioPlan('cust-1', 'heritage-parish', NOW);
expect(plan.problems).toEqual(expect.arrayContaining([expect.stringContaining('1.7.0'), expect.stringContaining('Cross Events is 3.7.2')]));
expect(plan.installs.find(i => i.product === 'events')).toMatchObject({ tooOld: true, minVersion: '3.8.0' });
await expect(jobs.loadScenario('cust-1', { scenario: 'heritage-parish', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'CANT_LOAD_SCENARIO' });
await expect(jobs.scenarioPlan('cust-1', 'everything', NOW)).rejects.toMatchObject({ status: 400 });
await db.customer.update({ where: { id: 'cust-1' }, data: { isDemo: false } });
expect((await jobs.scenarioPlan('cust-1', 'heritage-parish', NOW)).problems).toEqual(expect.arrayContaining([expect.stringContaining("isn't a demo client")]));
expect(await db.job.findMany({})).toEqual([]);
});
});
Binary file not shown.
Binary file not shown.