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
+54 -1
View File
@@ -5,7 +5,60 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.25.1] - 2026-11-27
## [2.26.0] - 2026-11-30
The Church App (crosscode-platform docs/APP-1.0-PLAN.md §6, §12). One migration
(`20261130120000_app_scenarios_devotionals`: `Customer.demoScenario`, `demoScenarioAt`,
`demoScenarioJobId`, `Deployment.demoScenario`, and the `Devotional` table). No API is removed.
Contracts 1.23.0 (vendored).
### Added
- **The Church App from New install**, on `app.<church's address>` (app.hope.co.za →
accounts.hope.co.za). It always signs in through the church's Accounts and takes its email and
WhatsApp from it, so a church without Accounts gets Accounts installed first (as for the Website
and Cross Events 3), and one whose Accounts is older than 1.9.0 is asked to update it, even when
the App's release notes don't say "requires". A `CCP-` licence on the Mustard Seed tier.
- **Load a demo scenario** on a demo client (customer → "Load a demo scenario"): one of the eight
demo churches (contracts `DEMO_SCENARIOS`) on every product the client has, in one
`seed-scenario` job (agent 1.7.0+): Accounts first (the church profile, logo and people), then
Cross Events, the Website and the App, skipping what isn't installed. The popup shows each
install it replaces, in order, and what stops it: not a demo client, an agent before 1.7.0, an
install on a release older than the scenario needs (Accounts 1.9.0, Events 3.8.0, Website 1.8.0,
App 1.0.0), installs under more than one short name, or a scenario already loading. Typing the
short name confirms it. The report's `loaded` / `skipped` go in the email; a failure says which
products are out of step. The customer shows the scenario last loaded and when; an install
shows "Scenario: …" or "Out of step with the scenario" (one product's demo loaded on its own).
`GET /api/admin/demo-scenarios`, `GET|POST /api/admin/customers/:id/scenario`, audited as
`demo_scenario_queued`.
- **Devotionals** (new page): Cross Code's devotionals for every App set to "From Cross Code".
Write and schedule them up to 3 months ahead in the free translations only (KJV, BSB; others
need their publisher's written permission), on a calendar of the days filled and empty, with a
warning for a passage over 25 verses. **Import CSV** checks every row first (contracts
`checkDevotionalCsv`: dates, required fields, a passage YouVersion can open, the translation,
days already filled, too far ahead) and imports the valid rows, skipping or replacing days
already filled; the template CSV downloads from the page. Admin API under
`/api/admin/devotionals`; audited as `devotional_created` / `_updated` / `_deleted` and
`devotionals_imported`.
- **`GET /api/v2/devotionals?from=YYYY-MM-DD`** for App installs (contracts
`hub.DEVOTIONALS_PATH`, `devotionalsReplySchema`): the next 3 months, with the install's licence
token as `Authorization: Bearer`. App licences only (`403 NOT_AN_APP`), active or in their grace
days (`403 LICENCE_INACTIVE`); a missing or forged token is `401 BAD_LICENCE`.
- **The App's tier**: an App whose active-member band (heartbeat `activeMembers90d`) is above its
licence's tier gets an alert (`tier_above`, info) saying which tier the annual review moves it to.
### Changed
- **Demo data for every product.** The App and Accounts can have a scenario church's demo loaded
on their own (agent 1.7.0+, App 1.0.0 / Accounts 1.9.0), and Cross Events has the eight scenario
churches next to its four profiles (Events 3.8.0+; `RELEASE_TOO_OLD` on an older one). One
product's demo on its own marks that install out of step with its customer's scenario.
- **An install's .env from the Hub for the Website and the App too** (the Website's on agent
1.6.0+, the App's on 1.7.0+), not only Cross Events and Accounts.
- **The App everywhere a product is listed**: New install, the installs list's product filter
(now from the products list), and the Updates tabs (the App's tab showed only once it had an
install).
No migration; no API is removed. Frontend only.
+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.
+18
View File
@@ -259,6 +259,24 @@ X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3)
- Rate-limited to 60 a minute per IP (against runaway loops; money is limited by the cap).
- A Hub older than 1.6.0 answers `404 NOT_FOUND`: the install treats that as "AI off".
## 3c. Devotionals (Church App, Hub 2.26.0)
`GET /api/v2/devotionals?from=YYYY-MM-DD` (contracts `hub.DEVOTIONALS_PATH`), with
`Authorization: Bearer <the install's licence token>` (§4); no signature. An App set to "From
Cross Code" calls it once a night (and on "Sync now") and keeps what it gets, so a Hub outage
changes nothing.
- `from` defaults to today (South Africa); the answer covers `from` to 3 months on, one
devotional per day at most, oldest first (`devotionalsReplySchema`, `crosscode.devotional/1`,
each with `source: "crosscode"`). The App replaces its copy of that range: a day missing from
the list was removed in the Hub.
- Only the free translations are ever in it (KJV, BSB: contracts `FREE_BIBLE_TRANSLATION_IDS`);
the App shows each passage's `copyright` line under it.
- `401 BAD_LICENCE`: no token, a forged one, or an unknown licence. `403 NOT_AN_APP`: another
product's licence. `403 LICENCE_INACTIVE`: suspended, revoked, or past its grace days.
`400 INVALID_REQUEST`: `from` isn't a date. Rate-limited to 20 a minute per IP.
- A Hub older than 2.26.0 answers `404 NOT_FOUND`: the App keeps what it has.
## 4. Licence token
`hel1.<payload>.<signature>` — `payload` is base64url JSON, `signature` is the base64url
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.25.1",
"version": "2.26.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.25.1",
"version": "2.26.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.25.1",
"version": "2.26.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
@@ -18,6 +18,7 @@ import { AiCard, AiModal } from "@/components/customer/AiCard";
import { SitesCard } from "@/components/customer/SitesCard";
import { ChurchUpdateModal } from "@/components/customer/ChurchUpdateModal";
import { DemoClientModal } from "@/components/customer/DemoClientModal";
import { ScenarioModal } from "@/components/customer/ScenarioModal";
import { ProductCard } from "@/components/customer/ProductCard";
import { AddProductModal } from "@/components/customer/AddProductModal";
import { NextInvoiceModal } from "@/components/customer/NextInvoice";
@@ -147,6 +148,7 @@ export default function CustomerPage() {
{popup === "address" && b && <AddressModal b={b} onClose={close} onDone={done} />}
{popup === "ai" && <AiModal c={c} onClose={close} onDone={done} />}
{popup === "demo" && <DemoClientModal c={c} onClose={close} onDone={done} />}
{popup === "scenario" && c.isDemo && <ScenarioModal c={c} onClose={close} onDone={done} />}
{popup === "update" && <ChurchUpdateModal customerId={id} name={c.name} onClose={close} onDone={done} />}
</>
);
+264
View File
@@ -0,0 +1,264 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Download, Plus, Upload } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Stat, useSubmit } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
type Translation = { id: string; name: string; language: string; copyright: string; acknowledgement: string };
type Passage = { reference: string; translation: string; text: string; location: unknown };
type Devotional = { id: string; date: string; title: string; passage: Passage; body: string; prayer: string | null; author: string | null; updatedAt: string };
type Overview = {
today: string; latest: string; aheadMonths: number; devotionals: Devotional[]; empty: string[];
translations: Translation[]; csv: { columns: string[]; template: string };
};
type CsvIssue = { column: string | null; message: string };
type CsvRow = { line: number; devotional: { date: string; title: string; passage: Passage } | null; errors: CsvIssue[]; warnings: CsvIssue[]; taken: boolean };
type CsvResult = { fileError: string | null; rows: CsvRow[] };
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const longDate = (d: string) => new Date(`${d}T12:00:00Z`).toLocaleDateString("en-ZA", { weekday: "short", day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });
/** The months from today's to the last day's, each as its days (null before the 1st, Monday first). */
function months(from: string, to: string) {
const out: { label: string; days: (string | null)[] }[] = [];
let [y, m] = from.split("-").map(Number);
const [ty, tm] = to.split("-").map(Number);
while (y < ty || (y === ty && m <= tm)) {
const first = new Date(Date.UTC(y, m - 1, 1));
const count = new Date(Date.UTC(y, m, 0)).getUTCDate();
const pad = (first.getUTCDay() + 6) % 7;
const days: (string | null)[] = Array(pad).fill(null);
for (let d = 1; d <= count; d++) days.push(`${y}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`);
out.push({ label: `${MONTHS[m - 1]} ${y}`, days });
m++;
if (m > 12) { m = 1; y++; }
}
return out;
}
/** The days from today to 3 months ahead: filled ones open their devotional, empty ones a new one. */
function Calendar({ o, onOpen }: { o: Overview; onOpen: (date: string, d: Devotional | null) => void }) {
const byDate = useMemo(() => new Map(o.devotionals.map(d => [d.date, d])), [o]);
return (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
{months(o.today, o.latest).map(month => (
<div key={month.label} className="card p-3">
<p className="mb-2 text-sm font-medium">{month.label}</p>
<div className="grid grid-cols-7 gap-1 text-center text-xs">
{DAYS.map(d => <span key={d} className="text-slate-400">{d}</span>)}
{month.days.map((day, i) => {
if (!day) return <span key={`pad-${i}`} />;
const inRange = day >= o.today && day <= o.latest;
const d = byDate.get(day) || null;
const label = `${longDate(day)}: ${d ? d.title : inRange ? "no devotional yet" : "outside the 3 months"}`;
return (
<button key={day} type="button" disabled={!inRange} title={label} aria-label={label} onClick={() => onOpen(day, d)}
className={`rounded py-1 ${!inRange ? "text-slate-300" : d ? "bg-emerald-100 font-medium text-emerald-900 hover:bg-emerald-200" : "bg-amber-50 text-amber-900 ring-1 ring-inset ring-amber-200 hover:bg-amber-100"} ${day === o.today ? "outline outline-2 outline-indigo-500" : ""}`}>
{Number(day.slice(8))}
</button>
);
})}
</div>
</div>
))}
</div>
);
}
type Form = { date: string; title: string; reference: string; translation: string; passageText: string; body: string; prayer: string; author: string };
/** Write or edit one devotional. The passage is quoted as written, never by AI (BIBLE-PERMISSIONS.md). */
function DevotionalModal({ o, date, existing, onClose, onDone }: { o: Overview; date: string; existing: Devotional | null; onClose: () => void; onDone: (m: Msg) => void }) {
const first: Form = existing
? { date: existing.date, title: existing.title, reference: existing.passage.reference, translation: existing.passage.translation, passageText: existing.passage.text, body: existing.body, prayer: existing.prayer || "", author: existing.author || "" }
: { date, title: "", reference: "", translation: o.translations[0]?.id || "BSB", passageText: "", body: "", prayer: "", author: "Cross Code" };
const [form, setForm] = useState<Form>(first);
const { busy, error, run } = useSubmit();
const f = (k: keyof Form) => ({ value: form[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => setForm({ ...form, [k]: e.target.value }) });
const translation = o.translations.find(t => t.id === form.translation);
const dirty = (Object.keys(first) as (keyof Form)[]).some(k => form[k] !== first[k]);
const save = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await api<{ devotional: Devotional; warnings: string[] }>(existing ? `/api/admin/devotionals/${existing.id}` : "/api/admin/devotionals", { method: existing ? "PUT" : "POST", body: form });
onDone({ type: "ok", text: `${existing ? "Saved" : "Added"}: ${r.devotional.title} on ${longDate(r.devotional.date)}.${r.warnings.length ? ` ${r.warnings.join(" ")}` : ""}` });
});
};
const remove = () => {
if (!existing || !window.confirm(`Delete "${existing.title}" (${longDate(existing.date)})? Apps drop it at their next nightly fetch.`)) return;
run(async () => {
await api(`/api/admin/devotionals/${existing.id}`, { method: "DELETE" });
onDone({ type: "ok", text: `Deleted: ${existing.title}.` });
});
};
return (
<Modal title={existing ? "Edit devotional" : "Write a devotional"} onClose={onClose} dirty={dirty} wide>
<form onSubmit={save} className="grid gap-3 md:grid-cols-2">
<div><label className="label" htmlFor="dv-date">Date</label><input id="dv-date" type="date" className="input" required min={existing ? undefined : o.today} max={o.latest} {...f("date")} /></div>
<div><label className="label" htmlFor="dv-title">Title</label><input id="dv-title" className="input" required maxLength={200} {...f("title")} /></div>
<div><label className="label" htmlFor="dv-ref">Passage</label><input id="dv-ref" className="input" required placeholder="1 Corinthians 13:4-7" maxLength={100} {...f("reference")} /><p className="mt-1 text-xs text-slate-500">The passage it&apos;s about, not whole chapters: more than 25 verses gets a warning.</p></div>
<div>
<label className="label" htmlFor="dv-tr">Translation</label>
<select id="dv-tr" className="input" {...f("translation")}>
{o.translations.map(t => <option key={t.id} value={t.id}>{t.name} ({t.id})</option>)}
</select>
<p className="mt-1 text-xs text-slate-500">Only the free translations until a publisher gives written permission.</p>
</div>
<div className="md:col-span-2">
<label className="label" htmlFor="dv-text">The passage&apos;s text</label>
<textarea id="dv-text" className="input min-h-24" required maxLength={10000} {...f("passageText")} />
{translation && <p className="mt-1 text-xs text-slate-500">Shown under it in the App, email and WhatsApp: {translation.copyright}</p>}
</div>
<div className="md:col-span-2"><label className="label" htmlFor="dv-body">Devotional</label><textarea id="dv-body" className="input min-h-40" required maxLength={20000} {...f("body")} /><p className="mt-1 text-xs text-slate-500">Markdown: a blank line between paragraphs, **bold**, *italic*.</p></div>
<div className="md:col-span-2"><label className="label" htmlFor="dv-prayer">Prayer (optional)</label><textarea id="dv-prayer" className="input min-h-16" maxLength={5000} {...f("prayer")} /></div>
<div><label className="label" htmlFor="dv-author">Author (optional)</label><input id="dv-author" className="input" maxLength={200} {...f("author")} /></div>
<div className="md:col-span-2"><FormError error={error} /></div>
<div className="flex flex-wrap items-center justify-between gap-2 md:col-span-2">
{existing ? <button type="button" className="btn-secondary text-red-700" disabled={busy} onClick={remove}>Delete</button> : <span />}
<ModalButtons busy={busy} onCancel={onClose} label={existing ? "Save" : "Add"} />
</div>
</form>
</Modal>
);
}
/** Import CSV: choose a file, see every row checked, then import the valid ones. */
function ImportModal({ o, onClose, onDone }: { o: Overview; onClose: () => void; onDone: (m: Msg) => void }) {
const [csv, setCsv] = useState<string | null>(null);
const [fileName, setFileName] = useState("");
const [result, setResult] = useState<CsvResult | null>(null);
const [replace, setReplace] = useState(false);
const { busy, error, run } = useSubmit();
const choose = async (file: File | undefined) => {
setResult(null);
if (!file) return;
const text = await file.text();
setCsv(text);
setFileName(file.name);
run(async () => setResult(await api<CsvResult>("/api/admin/devotionals/import/preview", { method: "POST", body: { csv: text } })));
};
const valid = result?.rows.filter(r => r.devotional) || [];
const taken = valid.filter(r => r.taken).length;
const importing = replace ? valid.length : valid.length - taken;
const submit = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await api<{ created: number; replaced: number; skipped: number; invalid: number }>("/api/admin/devotionals/import", { method: "POST", body: { csv, replace } });
onDone({ type: "ok", text: `Imported ${r.created} new${r.replaced ? `, replaced ${r.replaced}` : ""}${r.skipped ? `, skipped ${r.skipped} day${r.skipped === 1 ? "" : "s"} already filled` : ""}${r.invalid ? `; ${r.invalid} row${r.invalid === 1 ? "" : "s"} with errors left out` : ""}.` });
});
};
return (
<Modal title="Import devotionals from CSV" onClose={onClose} dirty={!!csv} wide>
<form onSubmit={submit} className="space-y-4">
<p className="text-sm text-slate-500">
Columns: {o.csv.columns.join(", ")} (prayer and author may be empty). Dates as YYYY-MM-DD, up to {longDate(o.latest)}; translations {o.translations.map(t => t.id).join(" or ")}. Nothing is saved until you import.
</p>
<div>
<label className="label" htmlFor="im-file">CSV file</label>
<input id="im-file" type="file" accept=".csv,text/csv" className="block text-sm" onChange={e => choose(e.target.files?.[0])} />
</div>
{busy && !result && <Loading />}
{result?.fileError && <FormError error={`${fileName}: ${result.fileError}`} />}
{result && !result.fileError && (
<>
<p className="text-sm">{valid.length} of {result.rows.length} rows can be imported{taken ? `; ${taken} are for days that already have one` : ""}.</p>
<div className="max-h-80 overflow-y-auto rounded-lg border border-slate-200">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-white"><tr className="text-left text-xs text-slate-500"><th className="px-2 py-1">Line</th><th>Date</th><th>Title</th><th>Check</th></tr></thead>
<tbody>{result.rows.map(r => (
<tr key={r.line} className="border-t align-top">
<td className="px-2 py-1">{r.line}</td>
<td className="whitespace-nowrap pr-2">{r.devotional?.date || ""}</td>
<td className="pr-2">{r.devotional ? `${r.devotional.title} · ${r.devotional.passage.reference} (${r.devotional.passage.translation})` : ""}</td>
<td className="py-1 pr-2">
{r.errors.map((x, i) => <p key={`e${i}`} className="text-red-700">{x.message}</p>)}
{r.warnings.map((x, i) => <p key={`w${i}`} className="text-amber-800">{x.message}</p>)}
{r.devotional && r.taken && <p className="text-amber-800">That day already has one</p>}
{r.devotional && !r.taken && !r.warnings.length && <p className="text-emerald-700">OK</p>}
</td>
</tr>
))}</tbody>
</table>
</div>
{taken > 0 && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={replace} onChange={e => setReplace(e.target.checked)} /> Replace the {taken} day{taken === 1 ? "" : "s"} already filled (otherwise they&apos;re skipped)</label>}
</>
)}
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label={`Import ${importing} devotional${importing === 1 ? "" : "s"}`} disabled={!result || !!result.fileError || importing === 0} />
</form>
</Modal>
);
}
/**
* Hub 2.26.0 (APP-1.0-PLAN §6): Cross Code's devotionals, for every Church App set to "From Cross
* Code". Written or imported up to 3 months ahead, in the free translations (KJV, BSB). Apps fetch
* the next 3 months once a night, so a change here reaches them by the next morning.
*/
export default function DevotionalsPage() {
const [o, setO] = useState<Overview | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [popup, setPopup] = useState<{ kind: "edit"; date: string; d: Devotional | null } | { kind: "import" } | null>(null);
const load = useCallback(() => api<Overview>("/api/admin/devotionals").then(setO).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
useEffect(() => { load(); }, [load]);
const done = (m: Msg) => { setPopup(null); setMsg(m); load(); };
const downloadTemplate = () => {
if (!o) return;
const url = URL.createObjectURL(new Blob([o.csv.template], { type: "text/csv;charset=utf-8" }));
const a = Object.assign(document.createElement("a"), { href: url, download: "cross-code-devotionals-template.csv" });
a.click();
URL.revokeObjectURL(url);
};
const total = o ? o.devotionals.length + o.empty.length : 0;
return (
<div>
<PageTitle title="Devotionals" subtitle="Cross Code's devotionals for every Church App set to “From Cross Code”: up to 3 months ahead, in the King James Version or the Berean Standard Bible. Apps fetch them every night."
actions={o && (
<div className="flex flex-wrap gap-2">
<button type="button" className="btn-secondary" onClick={downloadTemplate}><Download className="h-4 w-4" /> Template</button>
<button type="button" className="btn-secondary" onClick={() => setPopup({ kind: "import" })}><Upload className="h-4 w-4" /> Import CSV</button>
<button type="button" className="btn-primary" onClick={() => setPopup({ kind: "edit", date: o.empty[0] || o.today, d: null })}><Plus className="h-4 w-4" /> Write a devotional</button>
</div>
)} />
<PageMessage msg={msg} onClose={() => setMsg(null)} />
{!o ? (msg ? null : <Loading />) : (
<div className="space-y-6">
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
<Stat label="Filled" value={`${o.devotionals.length} of ${total} days`} tone={o.empty.length ? "amber" : undefined} />
<Stat label="Next empty day" small value={o.empty[0] ? longDate(o.empty[0]) : "None"} onClick={o.empty[0] ? () => setPopup({ kind: "edit", date: o.empty[0], d: null }) : undefined} />
<Stat label="Filled until" small value={(() => { const gap = o.empty[0]; const until = o.devotionals.filter(d => !gap || d.date < gap).at(-1); return until ? longDate(until.date) : "Not today yet"; })()} />
<Stat label="Up to" small value={longDate(o.latest)} sub={`${o.aheadMonths} months ahead`} />
</div>
<Calendar o={o} onOpen={(date, d) => setPopup({ kind: "edit", date, d })} />
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="px-4 py-2">Date</th><th>Title</th><th>Passage</th><th>Author</th></tr></thead>
<tbody>{o.devotionals.map(d => (
<tr key={d.id} className="border-t">
<td className="whitespace-nowrap px-4 py-1.5">{longDate(d.date)}</td>
<td><button type="button" className="text-left text-indigo-700 hover:underline" onClick={() => setPopup({ kind: "edit", date: d.date, d })}>{d.title}</button></td>
<td className="whitespace-nowrap pr-2">{d.passage.reference} ({d.passage.translation})</td>
<td className="pr-4">{d.author || ""}</td>
</tr>
))}</tbody>
</table>
{!o.devotionals.length && <p className="px-4 py-3 text-sm text-slate-500">None yet. Write one, or import a CSV (download the template to start).</p>}
</div>
</div>
)}
{o && popup?.kind === "edit" && <DevotionalModal o={o} date={popup.date} existing={popup.d} onClose={() => setPopup(null)} onDone={done} />}
{o && popup?.kind === "import" && <ImportModal o={o} onClose={() => setPopup(null)} onDone={done} />}
</div>
);
}
+3 -1
View File
@@ -3,7 +3,7 @@
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone, Receipt, Server } from "lucide-react";
import { LayoutDashboard, Building2, BellRing, BookOpen, Settings, LogOut, Rocket, Megaphone, Receipt, Server } from "lucide-react";
import { api, getToken, setToken } from "@/lib/api";
import { Logo } from "@/components/ui";
@@ -17,6 +17,8 @@ const NAV = [
{ href: "/alerts", label: "Alerts", icon: BellRing },
{ href: "/releases", label: "Releases", icon: Rocket },
{ href: "/notices", label: "Notices", icon: Megaphone },
// 2.26.0: Cross Code's devotionals for the Church App.
{ href: "/devotionals", label: "Devotionals", icon: BookOpen },
{ href: "/settings", label: "Settings", icon: Settings },
];
@@ -75,7 +75,8 @@ export default function DeploymentPage() {
if (!d) return <div><ServersNav active="/servers/installs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const x = d.deployment;
const plan = uninstallPlan(d);
const hasEnv = ["events", "accounts"].includes(x.product) && running(x);
// 2.26.0: every product's .env (the Website's from agent 1.6.0, the App's from 1.7.0).
const hasEnv = ["events", "accounts", "website", "app"].includes(x.product) && running(x);
const tabs: { key: Tab; label: string }[] = [
{ key: "jobs", label: "Jobs" },
...(hasEnv ? [{ key: "settings" as const, label: "Settings (.env)" }] : []),
@@ -7,7 +7,7 @@ import { Link2, Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import { PRODUCT_NAMES } from "@/lib/products";
import { PRODUCTS, PRODUCT_NAMES } from "@/lib/products";
import type { Release } from "@/lib/types";
import { ReleaseSelect } from "@/components/ReleaseSelect";
import { FormError, Loading, Modal, ModalButtons, PageMessage, PageTitle, Pager, SearchInput, useSubmit } from "@/components/ui";
@@ -17,7 +17,7 @@ type Msg = { type: "ok" | "err"; text: string } | null;
type Customer = { id: string; name: string; domain?: string | null };
type InstallRow = { id: string; name: string; url: string; customer: { id: string; name: string } | null; version: string | null };
/** The Accounts domain the Hub makes when none is given (backend accountsDomainFor). */
/** The Accounts domain the Hub makes when none is given (backend accountsDomainFor): app.hope.co.za → accounts.hope.co.za. */
function accountsPlaceholder(product: string, domain: string) {
if (!domain) return "accounts.hope.co.za";
return product === "website" ? `accounts.${domain.replace(/^www\./, "")}` : domain.replace(/^[^.]+./, "accounts.");
@@ -43,11 +43,11 @@ function NewInstallModal({ servers, onClose }: { servers: ServerSummary[]; onClo
e.preventDefault();
run(async () => {
const r = await api<{ deployment: Deployment; warnings: string[]; checkingPorts?: boolean; alsoInstalling?: { product: string; domain: string; version: string } }>("/api/admin/deployments", { method: "POST", body: { ...form, version: form.version || undefined, accountsDomain: form.accountsDomain || undefined } });
// Hub 2.5.0: Cross Events 3.x for a church without Accounts installs Accounts first.
// Hub 2.5.0: Cross Events 3.x (2.21.0 the Website, 2.26.0 the App) for a church without Accounts installs Accounts first.
const notes = [
// Hub 2.11.0: the ports are checked on the central server and this one first.
...(r.checkingPorts ? ["The ports are being checked on the central server and this server first; the install starts on ports free on both (about a minute)."] : []),
...(r.alsoInstalling ? [`Accounts ${r.alsoInstalling.version} is installed first at ${r.alsoInstalling.domain}; Cross Events follows when it has finished.`] : []),
...(r.alsoInstalling ? [`Accounts ${r.alsoInstalling.version} is installed first at ${r.alsoInstalling.domain}; ${PRODUCT_NAMES[form.product as keyof typeof PRODUCT_NAMES] || "the product"} follows when it has finished.`] : []),
...r.warnings,
];
router.push(`/servers/installs/${r.deployment.id}${notes.length ? `?warn=${encodeURIComponent(notes.join(" "))}` : ""}`);
@@ -64,20 +64,23 @@ function NewInstallModal({ servers, onClose }: { servers: ServerSummary[]; onClo
<option value="events">Cross Events</option>
<option value="accounts">Accounts (the church&apos;s sign-in)</option>
<option value="website">Church Website</option>
<option value="app">Church App</option>
</select>
<p className="mt-1 text-xs text-slate-500">
{form.product === "accounts"
? "Install Accounts before the Website, the App or Cross Events 3.0. Use the church's short name to add it next to its Events on the same server."
: form.product === "website"
? "On the church's own address: www.hope.co.za (its bare domain is sent to www.), or a Cross Code address like hope.crosscode.co.za. A church that already has a product here keeps its short name."
: "A church that already has a product here keeps its short name: the new one is added next to it on the same server."}
: form.product === "app"
? "On app. in front of the church's address: app.hope.co.za, or app.hope.crosscode.co.za. It needs the church's Accounts 1.9.0 or later; a church that already has a product here keeps its short name."
: "A church that already has a product here keeps its short name: the new one is added next to it on the same server."}
</p>
</div>
<div><label className="label" htmlFor="n-cust">Customer</label><select id="n-cust" className="input" required {...f("customerId")}><option value="">Choose…</option>{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select></div>
<div><label className="label" htmlFor="n-short">Short name</label><input id="n-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...f("shortName")} /><p className="mt-1 text-xs text-slate-500">Folders, database and tunnels: a-z, 0-9 and -.</p></div>
<div><label className="label" htmlFor="n-domain">Domain</label><input id="n-domain" className="input" required placeholder={form.product === "accounts" ? "accounts.hope.co.za" : form.product === "website" ? "www.hope.co.za" : "events.hope.co.za"} {...f("domain")} /></div>
{(form.product === "events" || form.product === "website") && (
<div><label className="label" htmlFor="n-acc">Accounts domain</label><input id="n-acc" className="input" placeholder={accountsPlaceholder(form.product, form.domain)} {...f("accountsDomain")} /><p className="mt-1 text-xs text-slate-500">{form.product === "website" ? "The Website" : "Cross Events 3"} signs in through the church&apos;s Accounts: a church without it gets it installed first, here.</p></div>
<div><label className="label" htmlFor="n-domain">Domain</label><input id="n-domain" className="input" required placeholder={form.product === "accounts" ? "accounts.hope.co.za" : form.product === "website" ? "www.hope.co.za" : form.product === "app" ? "app.hope.co.za" : "events.hope.co.za"} {...f("domain")} /></div>
{form.product !== "accounts" && (
<div><label className="label" htmlFor="n-acc">Accounts domain</label><input id="n-acc" className="input" placeholder={accountsPlaceholder(form.product, form.domain)} {...f("accountsDomain")} /><p className="mt-1 text-xs text-slate-500">{form.product === "website" ? "The Website" : form.product === "app" ? "The App" : "Cross Events 3"} signs in through the church&apos;s Accounts: a church without it gets it installed first, here.</p></div>
)}
<div><label className="label" htmlFor="n-tz">Time zone</label><input id="n-tz" className="input" placeholder="Africa/Johannesburg" {...f("timezone")} /></div>
<div><label className="label" htmlFor="n-an">Site admin name</label><input id="n-an" className="input" {...f("adminName")} /></div>
@@ -184,9 +187,7 @@ export default function InstallsPage() {
<div className="flex flex-wrap gap-2 p-4">
<select className="input w-48" aria-label="Product" value={product} onChange={e => setProduct(e.target.value)}>
<option value="">Every product</option>
<option value="events">{PRODUCT_NAMES.events}</option>
<option value="accounts">{PRODUCT_NAMES.accounts}</option>
<option value="website">{PRODUCT_NAMES.website}</option>
{PRODUCTS.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
</select>
<SearchInput className="w-full sm:w-72" value={query} onChange={setQuery} placeholder="Search a church, domain or server" />
</div>
@@ -95,7 +95,7 @@ export default function UpdatesPage() {
{!all ? <Loading /> : (
<form className="card space-y-4" onSubmit={submit}>
<Tabs tabs={UPDATABLE.filter(p => p !== "app" || (all || []).some(d => d.product === p)).map(p => ({ key: p, label: `${PRODUCT_NAMES[p]} (${(all || []).filter(d => d.product === p).length})` }))} active={product} onChange={pick} />
<Tabs tabs={UPDATABLE.map(p => ({ key: p, label: `${PRODUCT_NAMES[p]} (${(all || []).filter(d => d.product === p).length})` }))} active={product} onChange={pick} />
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="text-slate-500">Select:</span>
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.map(d => d.id))}>All live {name} ({deployments.length})</button>
@@ -2,16 +2,17 @@
import React from "react";
import Link from "next/link";
import { ArrowLeft, FilePlus, KeyRound, Plus, Star } from "lucide-react";
import { ArrowLeft, FilePlus, KeyRound, Plus, Sparkles, Star } from "lucide-react";
import { day, money } from "@/lib/billing";
import { fmtDate } from "@/lib/format";
import { PRODUCT_NAMES, byProduct } from "@/lib/products";
import { scenarioName } from "@/lib/scenarios";
import type { Customer } from "@/lib/types";
import { Menu, Stat } from "@/components/ui";
import { ADDRESS_OPTIONS, type CustomerBillingData, type Preview } from "./shared";
/** What the header's tiles open, and its buttons. */
export type HeaderAction = "payment" | "oneoff" | "add" | "preview" | "address" | "ai" | "history" | "demo";
export type HeaderAction = "payment" | "oneoff" | "add" | "preview" | "address" | "ai" | "history" | "demo" | "scenario";
/**
* Hub 2.14.0: always at the top of the customer page: who the church is, what it has, what it
@@ -40,11 +41,16 @@ export function CustomerHeader({ c, b, preview, canAdd, onAction, onArchive }: {
{c.isDemo && <span title="Every install is a demo site, and it isn't billed" className="rounded-full bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700 ring-1 ring-inset ring-indigo-200">Demo client</span>}
{c.archivedAt && <span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600 ring-1 ring-inset ring-slate-200">Archived {fmtDate(c.archivedAt, false)}</span>}
</h1>
<p className="mt-1 text-sm text-slate-500">Customer since {fmtDate(c.createdAt, false)}</p>
<p className="mt-1 text-sm text-slate-500">
Customer since {fmtDate(c.createdAt, false)}
{/* 2.26.0: the demo scenario last loaded on its installs. */}
{c.isDemo && (c.demoScenarioJobId ? " · A demo scenario is loading" : c.demoScenario ? ` · Demo scenario: ${scenarioName(c.demoScenario)}${c.demoScenarioAt ? `, loaded ${fmtDate(c.demoScenarioAt)}` : ""}` : "")}
</p>
</div>
<div className="flex flex-wrap gap-2">
<button type="button" className="btn-primary" onClick={() => onAction("payment")}><Plus className="h-4 w-4" /> Record payment</button>
{!c.isDemo && <button type="button" className="btn-secondary" onClick={() => onAction("oneoff")}><FilePlus className="h-4 w-4" /> One-off invoice</button>}
{c.isDemo && <button type="button" className="btn-secondary" onClick={() => onAction("scenario")}><Sparkles className="h-4 w-4" /> Load a demo scenario</button>}
{canAdd && <button type="button" className="btn-secondary" onClick={() => onAction("add")}><KeyRound className="h-4 w-4" /> Add product</button>}
<Menu label="More actions for this customer" items={[
c.isDemo ? { label: "Not a demo client any more…", onClick: () => onAction("demo") } : { label: "Make it a demo client…", onClick: () => onAction("demo") },
@@ -39,7 +39,7 @@ export function DemoClientModal({ c, onClose, onDone }: { c: Customer; onClose:
<Modal title="Make it a demo client" onClose={onClose} dirty={!!confirmName}>
<form onSubmit={submit} className="space-y-4">
<ul className="list-disc space-y-1 pl-5 text-sm text-slate-500">
<li>Every install of {c.name} becomes a demo site, Accounts included, and so does any it gets later. Demo data can then be loaded on its Events and Website.</li>
<li>Every install of {c.name} becomes a demo site, Accounts included, and so does any it gets later. Demo data can then be loaded on each of them, or a whole demo scenario on all of them at once.</li>
<li>It isn&apos;t billed: billing is set to &quot;not invoiced&quot;, and no invoice of it is drafted or sent.</li>
<li>Only for churches used for showing Cross Code, never a real customer.</li>
</ul>
@@ -0,0 +1,106 @@
"use client";
import React, { useEffect, useState } from "react";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { PRODUCT_NAMES, type Product } from "@/lib/products";
import { scenarioName } from "@/lib/scenarios";
import type { Customer } from "@/lib/types";
import { FormError, Loading, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { post } from "@/components/install/shared";
import type { Done } from "./shared";
type Scenario = { key: string; church: string; label: string; description: string; campuses: number; language: "en" | "af"; appActiveMembers: string };
type PlanInstall = { id: string; product: Product; domain: string; version: string | null; minVersion: string | null; tooOld: boolean; covered: boolean; profile: string | null; demoScenario: string | null; outOfStep: boolean };
export type ScenarioPlan = {
customer: { demoScenario: string | null; demoScenarioAt: string | null; demoScenarioJobId: string | null };
scenario: Scenario | null; shortName: string | null; server: { name: string; agentVersion: string | null } | null;
installs: PlanInstall[]; notCovered: Product[]; problems: string[];
};
/**
* Hub 2.26.0 (APP-1.0-PLAN §12): load a demo scenario on a demo client. Pick one of the eight
* churches, see which installs it replaces (Accounts first) and anything that stops it, type the
* short name once. One seed-scenario job: the server loads every product the church has there.
*/
export function ScenarioModal({ c, onClose, onDone }: { c: Customer; onClose: () => void; onDone: Done }) {
const [scenarios, setScenarios] = useState<Scenario[] | null>(null);
const [key, setKey] = useState(c.demoScenario || "");
const [plan, setPlan] = useState<ScenarioPlan | null>(null);
const [planError, setPlanError] = useState<string | null>(null);
const [confirmName, setConfirmName] = useState("");
const { busy, error, run } = useSubmit();
useEffect(() => {
api<Scenario[]>("/api/admin/demo-scenarios").then(list => { setScenarios(list); setKey(k => k || list[0]?.key || ""); }).catch(e => setPlanError(errorText(e)));
}, []);
useEffect(() => {
if (!key) return;
setPlan(null);
api<ScenarioPlan>(`/api/admin/customers/${c.id}/scenario?scenario=${encodeURIComponent(key)}`).then(p => { setPlan(p); setPlanError(null); }).catch(e => setPlanError(errorText(e)));
}, [c.id, key]);
const submit = (e: React.FormEvent) => {
e.preventDefault();
if (!plan?.scenario) return;
if (!window.confirm(`Replace the demo data of every install of ${plan.shortName} with ${plan.scenario.church}? Each product takes a backup first.`)) return;
run(async () => {
await post(`/api/admin/customers/${c.id}/scenario`, { scenario: key, confirm: confirmName });
onDone({ type: "ok", text: `Queued: the agent loads ${plan.scenario!.church} on its next poll, Accounts first (see Jobs). You get an email when it's done.` });
});
};
const chosen = scenarios?.find(s => s.key === key);
const blocked = !plan || plan.problems.length > 0;
return (
<Modal title="Load a demo scenario" onClose={onClose} dirty={!!confirmName} wide>
{!scenarios ? (planError ? <FormError error={planError} /> : <Loading />) : (
<form onSubmit={submit} className="space-y-4">
<p className="text-sm text-slate-500">
Every product {c.name} has gets the same demo church: Accounts&apos; church profile (name, logo, colours, details) and people, then Cross Events, the Website and the App around them. Demo logins use the password Demo@1234.
</p>
<div>
<label className="label" htmlFor="sc-k">Scenario</label>
<select id="sc-k" className="input" value={key} onChange={e => setKey(e.target.value)}>
{scenarios.map(s => <option key={s.key} value={s.key}>{s.label}</option>)}
</select>
{chosen && <p className="mt-1 text-xs text-slate-500">{chosen.description} {chosen.campuses > 1 ? `${chosen.campuses} campuses. ` : ""}{chosen.language === "af" ? "Mostly Afrikaans. " : ""}App active members {chosen.appActiveMembers}.</p>}
</div>
{planError && <FormError error={planError} />}
{!plan && !planError && <Loading />}
{plan && (
<>
<div>
<p className="label">It replaces, in this order{plan.server ? ` (on ${plan.server.name})` : ""}</p>
<ol className="list-decimal space-y-1 pl-5 text-sm">
{plan.installs.map(i => (
<li key={i.id}>
<span className="font-medium">{PRODUCT_NAMES[i.product]}</span> · {i.domain} · {i.version || "version unknown"}
{i.tooOld && <span className="ml-1 text-red-700">needs {i.minVersion} or later</span>}
{!i.covered && <span className="ml-1 text-amber-800">not in this scenario</span>}
{i.outOfStep && <span className="ml-1 text-amber-800">out of step now</span>}
</li>
))}
</ol>
{plan.installs.length < 4 && <p className="mt-1 text-xs text-slate-500">Products it doesn&apos;t have are skipped.</p>}
</div>
{plan.customer.demoScenario && <p className="text-xs text-slate-500">Last loaded: {scenarioName(plan.customer.demoScenario)}{plan.customer.demoScenarioAt ? `, ${fmtDate(plan.customer.demoScenarioAt)}` : ""}.</p>}
{plan.problems.length > 0 && (
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
<p className="font-medium">It can&apos;t be loaded yet:</p>
<ul className="mt-1 list-disc space-y-0.5 pl-5">{plan.problems.map(p => <li key={p}>{p}</li>)}</ul>
</div>
)}
{!blocked && plan.shortName && (
<div><label className="label" htmlFor="sc-c">Type {plan.shortName}</label><input id="sc-c" className="input" autoComplete="off" value={confirmName} onChange={e => setConfirmName(e.target.value)} /></div>
)}
</>
)}
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Load the scenario" danger disabled={blocked || confirmName !== plan?.shortName} />
</form>
)}
</Modal>
);
}
+24 -5
View File
@@ -2,16 +2,27 @@
import React, { useState } from "react";
import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { DEMO_SCENARIOS, DEMO_SCENARIO_MIN_VERSIONS } from "@/lib/scenarios";
import { post, withWarnings, type Done, type Install } from "./shared";
/** Each product's demo data sets (contracts `DEMO_PROFILES` and, 2.25.0, `WEBSITE_DEMO_PROFILES`). */
/** 2.26.0: a scenario's church, as one product's demo (Events 3.8.0, the App and Accounts). */
const scenarioProfiles = (product: "events" | "app" | "accounts") =>
DEMO_SCENARIOS.map(s => ({ key: s.key, label: `${s.church}: ${s.kind}${product === "events" ? " (Events 3.8.0+)" : ""}` }));
/**
* Each product's demo data sets (contracts `EVENTS_DEMO_PROFILES`, `WEBSITE_DEMO_PROFILES`, and,
* 2.26.0, `APP_DEMO_PROFILES` and `ACCOUNTS_DEMO_PROFILES`: one per scenario church).
*/
const PROFILES: Record<string, { key: string; label: string }[]> = {
events: [
{ key: "small", label: "Small church: the essentials" },
{ key: "events", label: "Events and conferences" },
{ key: "ministry", label: "Weekly ministry: courses, kids, volunteers" },
{ key: "multicampus", label: "Three campuses" },
...scenarioProfiles("events"),
],
app: scenarioProfiles("app"),
accounts: scenarioProfiles("accounts"),
website: [
{ key: "heritage-parish", label: "Heritage: a parish church with a long history" },
{ key: "heritage-city", label: "Heritage: a city-centre church (other layouts)" },
@@ -24,13 +35,14 @@ const PROFILES: Record<string, { key: string; label: string }[]> = {
],
};
/** Whether a product has demo data to load (Accounts and the App are only tagged). */
/** Whether a product has demo data to load (2.26.0: every product). */
export const hasDemoData = (product: string) => product in PROFILES;
/**
* An install used for showing Cross Code: mark it as a demo site, or (once it is one) replace its
* data with a demo set. Unmarking is a menu item on the page. 2.25.0: the Website's eight demo
* churches; Accounts and the App can be marked (a tag) but have no demo data.
* churches. 2.26.0: the App's and Accounts' (a scenario's church on its own; the customer page loads
* a whole scenario on every product at once).
*/
export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => void; onDone: Done }) {
const profiles = PROFILES[x.product] || [];
@@ -49,7 +61,9 @@ export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => v
};
const seed = (e: React.FormEvent) => {
e.preventDefault();
const what = website ? "content (pages, ministries, messages, events, pictures)" : "data";
const what = website ? "content (pages, ministries, messages, events, pictures)"
: x.product === "app" ? "content (prayer wall, campaigns, devotionals, announcements, events)"
: x.product === "accounts" ? "church profile and demo people" : "data";
if (!window.confirm(`Replace ALL of ${x.shortName}'s ${what} with the "${profile}" demo? A backup is taken first.`)) return;
run(async () => {
const r = await post(`/api/admin/deployments/${x.id}/seed-demo`, { profile, confirm: confirmName });
@@ -83,8 +97,13 @@ export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => v
<p className="text-sm text-slate-500">
{website
? "Replaces the site's content with a demo church on its template, and publishes it. The church's profile (name, logo, colours, service times, contact), the site settings, the site icon and the admins stay, and the demo's text uses the church's name. Needs agent 1.6.0 and Website 1.3.0."
: <>Replaces everything (events, people, payments) with a demo set, keeping the site settings and {x.adminEmail || "the site's first admin"}. Demo logins use the password Demo@1234.</>}
: x.product === "app"
? `Replaces the App's content (prayer wall, campaign, testimonies, devotionals, announcements, events) with the church's, around its demo people. Admins and settings stay. Needs agent 1.7.0 and App ${DEMO_SCENARIO_MIN_VERSIONS.app}.`
: x.product === "accounts"
? `Replaces the church profile (name, logo, icon, colours, details) with the demo church's and its demo people (password Demo@1234); real people and admins stay. Every linked product shows the new profile. Needs agent 1.7.0 and Accounts ${DEMO_SCENARIO_MIN_VERSIONS.accounts}.`
: <>Replaces everything (events, people, payments) with a demo set, keeping the site settings and {x.adminEmail || "the site's first admin"}. Demo logins use the password Demo@1234. The named churches need Events {DEMO_SCENARIO_MIN_VERSIONS.events}.</>}
</p>
{x.customer?.isDemo && <p className="rounded-lg border border-sky-200 bg-sky-50 p-3 text-sm text-sky-900">One product on its own is out of step with the others. To load the same church on all of them, use <strong>Load a demo scenario</strong> on the customer.</p>}
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="d-p">Demo</label>
@@ -7,6 +7,7 @@ import { ArrowLeft, RefreshCw } from "lucide-react";
import { ago } from "@/lib/format";
import { Menu, Stat } from "@/components/ui";
import { StatusPill } from "@/components/servers";
import { scenarioName } from "@/lib/scenarios";
import { productName, running, type Detail } from "./shared";
import { hasDemoData } from "./DemoModal";
@@ -33,6 +34,10 @@ export function InstallHeader({ d, onAction }: { d: Detail; onAction: (a: Instal
<span className="break-words">{x.customer?.name} ({x.shortName})</span>
<StatusPill status={d.stale.stale ? "stale" : x.status} />
{x.isDemo && <span className="rounded-full bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700 ring-1 ring-inset ring-indigo-200">Demo site</span>}
{/* 2.26.0: whether its demo data is its customer's scenario, or one product's demo loaded on its own. */}
{x.isDemo && x.customer?.demoScenario && (x.demoScenario === x.customer.demoScenario
? <span title={scenarioName(x.customer.demoScenario)} className="rounded-full bg-sky-50 px-2 py-0.5 text-xs font-medium text-sky-800 ring-1 ring-inset ring-sky-200">Scenario: {scenarioName(x.customer.demoScenario).split(" (")[0]}</span>
: <span title="Its demo data isn't the scenario its customer last loaded. Load the scenario again from the customer." className="rounded-full bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-800 ring-1 ring-inset ring-amber-200">Out of step with the scenario</span>)}
</h1>
<p className="mt-1 text-sm text-slate-500">
{productName(x.product)} · {x.customer ? <Link className="text-indigo-700 hover:underline" href={`/customers/${x.customerId}`}>customer</Link> : "customer"}
@@ -42,7 +47,7 @@ export function InstallHeader({ d, onAction }: { d: Detail; onAction: (a: Instal
{live && <button type="button" className="btn-primary" onClick={() => onAction("update")}><RefreshCw className="h-4 w-4" /> Schedule update</button>}
<Menu label="More actions for this install" items={[
live && x.install?.version?.startsWith("2.1.") && { label: "Move onto the monorepo…", onClick: () => onAction("adopt") },
// 2.25.0: any product can be a demo site; Events and the Website have demo data.
// 2.25.0: any product can be a demo site; 2.26.0: every product has demo data.
running(x) && !x.isDemo && { label: "Mark as a demo site…", onClick: () => onAction("demo") },
running(x) && x.isDemo && hasDemoData(x.product) && { label: "Load demo data…", onClick: () => onAction("demo") },
running(x) && x.isDemo && !x.customer?.isDemo && { label: "It isn't a demo site any more", onClick: () => onAction("undemo") },
+3 -1
View File
@@ -27,8 +27,10 @@ export type ServerSummary = {
export type Deployment = {
id: string; serverId: string; customerId: string; installId: string | null; product: string; shortName: string; domain: string;
webPort: number; apiPort: number; status: string; version: string | null; adminName: string | null; adminEmail: string | null; isDemo?: boolean;
/** 2.26.0: the demo scenario its data is from (null after one product's demo on its own). */
demoScenario?: string | null;
liveAt: string | null; createdAt: string;
server?: { id: string; name: string }; customer?: { id: string; name: string; isDemo?: boolean };
server?: { id: string; name: string }; customer?: { id: string; name: string; isDemo?: boolean; demoScenario?: string | null };
install?: { id: string; version: string | null; lastHeartbeatAt: string | null; url: string } | null;
};
+27
View File
@@ -0,0 +1,27 @@
// The demo scenarios (Hub 2.26.0, contracts agent.DEMO_SCENARIOS; APP-1.0-PLAN §12): eight preset
// churches, one per Website demo profile. The same keys as the backend's list
// (GET /api/admin/demo-scenarios has the descriptions); every church in them is fictional.
import type { Product } from "./products";
export const DEMO_SCENARIOS = [
{ key: "heritage-parish", church: "St Columba's", kind: "Heritage: a parish church" },
{ key: "heritage-city", church: "Grace Cathedral", kind: "Heritage: a city-centre church" },
{ key: "bold-youth", church: "Ignite Church", kind: "Bold: young and music-led" },
{ key: "bold-plant", church: "Harbour City", kind: "Bold: a new church plant" },
{ key: "community-family", church: "Acacia Hill", kind: "Community: a family church" },
{ key: "community-town", church: "Karoo Gemeenskapskerk", kind: "Community: a country-town church" },
{ key: "clean-modern", church: "Northpoint", kind: "Clean: a contemporary church" },
{ key: "clean-campus", church: "Riverside", kind: "Clean: three campuses near the university" },
] as const;
export type DemoScenarioKey = (typeof DEMO_SCENARIOS)[number]["key"];
/** The first release of each product that loads a scenario (contracts DEMO_SCENARIO_MIN_VERSIONS). */
export const DEMO_SCENARIO_MIN_VERSIONS: Record<Product, string> = { accounts: "1.9.0", events: "3.8.0", website: "1.8.0", app: "1.0.0" };
/** "Acacia Hill (Community: a family church)", or the key for one the Hub doesn't know. */
export const scenarioName = (key: string | null | undefined) => {
const s = DEMO_SCENARIOS.find(x => x.key === key);
return s ? `${s.church} (${s.kind})` : key || "";
};
+4
View File
@@ -47,6 +47,10 @@ export type Customer = {
/** Hub 2.25.0: a demo client: all its installs are demo sites, and it isn't billed. */
isDemo?: boolean;
demoSince?: string | null;
/** Hub 2.26.0: the demo scenario last loaded on its installs, when, and the job loading one now. */
demoScenario?: string | null;
demoScenarioAt?: string | null;
demoScenarioJobId?: string | null;
/** Hub 2.0: the church's AI allowance, shared by all its installs. */
aiMonthlyCapCents: number;
aiMarkupPercent: number | null;