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
+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([]);
});
});