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:
@@ -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'));
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -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.
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user