Compare commits

..
Author SHA1 Message Date
joshua 2a4cf7acab Merge branch 'feat/website-backups' 2026-11-27 09:50:35 +02:00
joshuaandClaude Opus 5.5 a3ac3da5a5 Website 1.4.0: nightly database backups and background jobs
As Accounts and Cross Events: a gzipped pg_dump every night (02:20) into
backend/backups/, the same website-*.sql.gz files crosscode makes before
updates, with Admin -> Backups (back up now, download, how many to keep).
The heartbeat, event feed and YouTube move from plain timers onto pg-boss
with the backup, and Admin -> Background jobs switches each on or off,
changes its schedule or runs it now. The heartbeat now reports the newest
backup (before: always none, so the Hub warned) and the real job state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:47:30 +02:00
joshua 8e52bd2d33 Merge branch 'docs/released-hub-2.25.0-website-1.3.0' 2026-11-27 09:31:08 +02:00
joshuaandClaude Opus 5.5 7b49ec2b70 docs: Hub 2.25.0, Website 1.3.0, agent 1.6.0, contracts 1.19.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:31:07 +02:00
joshua d3e04127f3 Merge branch 'feat/website-demo-seeds' 2026-11-27 09:30:15 +02:00
joshuaandClaude Opus 5.5 2fb7ac57da Website 1.3.0, agent 1.6.0, contracts 1.19.0: demo data for the Church Website
Eight demo churches, two per template (the second on the template's other
recommended variants and header), loaded from the Hub on demo sites with
`crosscode demo <church> website --profile <p>`. A profile replaces the
content only: the church's profile from Accounts, the site settings, the
site icon and the admins stay, and the copy names the church.

- contracts: WEBSITE_DEMO_PROFILES, DEMO_PRODUCTS, SEED_WEBSITE_DEMO_MIN_AGENT;
  seed-demo takes an optional product (events by default)
- agent: a Website seed-demo job runs `crosscode demo <church> website`
- crosscode script: backup, demo as the site's user, reload, health check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:20:09 +02:00
joshua 81c01d8a9f Merge branch 'docs/deployed-hub-2.24.1-website-1.2.0' 2026-11-27 08:44:56 +02:00
joshuaandClaude Opus 5.5 2335fd46e4 docs: Hub 2.24.1 deployed, Website 1.2.0 on cross-demo2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:44:55 +02:00
joshua f58711603a Merge branch 'docs/hub-2.24.1' 2026-11-27 08:36:19 +02:00
joshuaandClaude Opus 5.5 d1354a6a17 docs: Hub 2.24.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:36:18 +02:00
joshua 175a6b41eb Merge branch 'docs/hub-2.24.0' 2026-11-27 08:30:15 +02:00
joshuaandClaude Opus 5.5 80d8e903dd docs: Hub 2.24.0 deployed (Website 1.2.0 not on cross-demo2 yet)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:30:15 +02:00
joshua 35501deb0d Merge branch 'fix/website-starter-pages' 2026-11-27 08:18:53 +02:00
joshuaandClaude Opus 5.5 79e1450df6 Website 1.2.0: starter pages on a new install, and a site icon
A new install had no pages, so the home page and its live preview showed
only the header and footer (found on cross-demo2). The backend now adds the
fixed pages with starter text at startup. Settings -> Site icon sets the
favicon, with a default from the church's colour and initial. The Latest
message's Card layout has its name; the media picker's placeholder has
enough contrast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:18:47 +02:00
48 changed files with 2161 additions and 187 deletions
+33
View File
@@ -2,6 +2,39 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## website@1.4.0 - 2026-11-27
Database backups and background jobs for the Church Website, as Accounts and Cross Events have.
Details in `apps/website/CHANGELOG.md`. No migration (pg-boss makes its own `pgboss_website`
schema on first start).
- **Backups:** a gzipped `pg_dump` every night at 02:20 into `backend/backups/`, the same
`website-*.sql.gz` files the crosscode script makes before updates; Admin → Backups.
- **Background jobs** on pg-boss: the backup, the Hub heartbeat, the event feed and YouTube (before:
plain timers); Admin → Background jobs switches each on or off, changes its schedule, runs one now.
- **The heartbeat tells the Hub the truth:** the newest backup (before: always none, so the Hub
warned "No backup reported") and the real job mode and failures.
## contracts@1.19.0 + agent@1.6.0 + website@1.3.0 + crosscode script - 2026-11-27
Demo data for the Church Website, from the Hub (Hub 2.25.0). Additive: an Events `seed-demo` job
means what it did. Details in each app's CHANGELOG.md. No migrations.
- **contracts 1.19.0:** `agent.WEBSITE_DEMO_PROFILES` (eight, two per template:
`heritage-parish`, `heritage-city`, `bold-youth`, `bold-plant`, `community-family`,
`community-town`, `clean-modern`, `clean-campus`), `DEMO_PRODUCTS`, `DEMO_PROFILES_BY_PRODUCT`,
`SEED_WEBSITE_DEMO_MIN_AGENT` (1.6.0). `seed-demo` args take an optional `product` (`events`,
the default, or `website`); the profile must be one of that product's, and a Website demo takes
no `adminEmail`.
- **agent 1.6.0:** a Website `seed-demo` job runs `crosscode demo <church> website --profile <p>`.
- **website 1.3.0:** the eight demo churches (`backend/src/demo/seeds.ts`,
`npm run demo -- --profile <p>`, `--list`). They replace the content only: the church's profile
from Accounts, the site settings, the site icon and the admins stay, and the copy names the
church. `--template` alone is still the Acacia Hill development church.
- **crosscode script:** `crosscode demo <church> website --profile <p>`: backup, the demo as the
site's user (`--force`), reload, wait for `/api/health`. Refused on a Website release without
the profiles (before 1.3.0).
## accounts@1.8.0 + website@1.1.0 - 2026-11-26
The admins of both, redesigned as Cross Events' admin dashboard and settings. Details in each app's
+6
View File
@@ -13,6 +13,12 @@ Write for the person updating servers: what the agent can now do from the Hub, a
contracts version needs it. The developer log is the commit history of apps/agent.
-->
## 1.6.0
- **Demo data for the Church Website.** The Hub (2.25.0 and later) can load one of the Website's
eight demo churches on a demo site, as it already could for Cross Events. Needs Website 1.3.0 on
the site. Cross Events' demo data works as before.
## 1.5.0
- **One product of a church at a time.** Uninstall, export and purge jobs can name products: only
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.5.0",
"version": "1.6.0",
"private": true,
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
"license": "UNLICENSED",
+3 -1
View File
@@ -59,7 +59,9 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
return out;
}
case "seed-demo":
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
// 1.6.0: the Website's demo names the product; Events' (no product) keeps its old form.
return ["demo", job.args.church, ...(job.args.product === "website" ? ["website"] : []), "--profile", job.args.profile,
...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
case "export":
if (!opts.exportFile) throw new Error("export needs a file to write");
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
+1 -1
View File
@@ -12,7 +12,7 @@ import { paths } from "./paths";
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.5.0";
export const AGENT_VERSION = "1.6.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+3
View File
@@ -47,6 +47,9 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "ministry" } }))).toEqual(["demo", "hope", "--profile", "ministry"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "events", adminEmail: "jane@hope.test" } })))
.toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]);
// 1.6.0: the Website's demo.
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant" } }))).toEqual(["demo", "hope", "website", "--profile", "bold-plant"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "small" } }))).toEqual(["demo", "hope", "--profile", "small"]);
});
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
+86
View File
@@ -1,5 +1,91 @@
# Changelog — Church Website
## [1.4.0] — 2026-11-27
No migration: pg-boss makes its own schema (`pgboss_website`) on first start, as in Accounts. New
dependencies `pg-boss` and `cron-parser`. Needs `pg_dump` on the server (it's there: the
crosscode script uses it for the backups before updates).
### Added
- **Database backups** (`src/backups/backups.ts`, as Accounts 1.3.0): a gzipped `pg_dump` into
`backend/backups/` every night at 02:20 (after Accounts' at 02:00 on the same server) and when an
admin asks; the newest 14 kept (`backup_retain_count`), nightly on by default
(`backup_nightly`), the last failure in `backup_last_error`. Same names as the crosscode
script's backups before updates (`website-YYYYMMDD-HHMMSS.sql.gz`), so the list shows both. A
dump that fails part-way leaves no file. The database only: the uploads aren't in it (as Events).
- **Admin → Backups** (Owners and Admins): back up now, download one (audited, never cached), turn
nightly backups off, how many to keep. `GET /api/v1/admin/backups`, `POST …/backups/run`,
`PUT …/backups/settings`, `GET …/backups/:file/download`.
- **Background jobs on pg-boss** (`src/jobs.ts`, as Accounts 1.4.0): `backup`, `hub-heartbeat`
(every 15 minutes), `event-feed` (every 15 minutes) and `youtube` (hourly). One run per
schedule however many processes run; timers in the process if the queue can't start;
`JOBS_ENABLED=false` turns them all off. Per job: its .env flag (`BACKUP_ENABLED`,
`HUB_HEARTBEAT_ENABLED`, `FEED_JOB_ENABLED`, `YOUTUBE_JOB_ENABLED`) and `JOB_SCHEDULE_<NAME>`.
- **Admin → Background jobs** (Owners and Admins): each job's schedule, next run and last runs;
switch it on or off, change its schedule (kept in `job_overrides`, winning over the .env, live
at once), or run it now. Audited (`job_settings_changed`, `job_run`).
### Changed
- **The heartbeat reports the newest backup** (`lastBackupAt`; before always null, so the Hub
showed "No backup reported" on every Website) **and the real job mode and failed runs in the
last 24 hours** (before always "queue" and 0).
- The heartbeat, the event feed and YouTube were plain timers (`startHeartbeats`,
`startFeedSync`, `startYoutubeSync`, removed); they're jobs now. The first event-feed and
YouTube runs are on their schedule rather than 20 and 30 seconds after a start.
## [1.3.0] — 2026-11-27
No migration, no new environment settings. Needs contracts 1.19.0 (in this checkout).
### Added
- **Eight demo churches**, two per template, for the Hub's demo sites (Hub 2.25.0, agent 1.6.0,
`crosscode demo <church> website --profile <p>`): `heritage-parish`, `heritage-city`,
`bold-youth`, `bold-plant`, `community-family`, `community-town`, `clean-modern`,
`clean-campus` (`src/demo/seeds.ts`, ids from contracts `agent.WEBSITE_DEMO_PROFILES`). Each is
its own kind of church: home page, Plan your visit, About, Give, four ministries, four leaders, a
message series with three messages, and three upcoming events. The second of each template starts
on the template's second recommended variant of every homepage section and its second header, so
the eight show every recommended look.
- **They keep the organisation settings:** a profile replaces the content only. The church's
profile (from Accounts, else `church_profile_local`) stays, the copy names the church
(`{name}`, `{short}`, `{city}`) and the illustrations use its colours. The site settings, the
site icon (`favicon_media_id` and its picture) and the admins stay. Acacia Hill's profile is
saved only on a site with no profile at all, so it still has a name. Slug history and preview
links go with the old content.
- `npm run demo -- --profile <p> [--force]` and `--list`. `--template <t>` alone still loads the
Acacia Hill development church exactly as before (its profile too), so the e2e suite and its
screenshots are unchanged.
## [1.2.0] — 2026-11-27
No migration, no new environment settings. Its first start on an existing site adds the missing
fixed pages (below).
### Fixed
- **A new install had no pages**, so its home page (and the live preview of it) showed only the
header and footer whatever was chosen under Template and style, and Plan your visit, About, Give,
Contact and the rest didn't exist. Only `npm run demo` made pages. Now the backend adds the fixed
pages at startup (`src/site/starter.ts`) with starter text: Home with every homepage section,
Plan your visit, About us, Ministries, Leadership, Events, Messages, Give, Contact, and Terms and
Safeguarding (footer links, not in the menu; WEBSITE-1.0-PLAN §2). All of them while a site has
none of them (pages it made itself move after them; an address already taken is skipped), else
only a missing home page. A removed page isn't brought back. They're drafts, published with the
site; the audit log says "Added the starter pages". Found on cross-demo2.
- **Template and style → Home page layout:** the Latest message's Card layout had no name.
- **Media picker:** the "No image" placeholder had too little contrast (WCAG AA).
### Added
- **Site icon** (Settings): a picture from the media library as the favicon, live at once
(setting `favicon_media_id`; `favicon` in the site content). Without one the site uses the
church's icon from its profile, else a default: the church's initial on its brand colour (a cross
before the church is known). Every page links `/site-icon?v=…`, which redirects to the icon or
serves the default SVG; the version changes with the icon.
## [1.1.0] — 2026-11-26
No migration, no new settings, no backend changes. The admin redesigned as Cross Events' admin
+22
View File
@@ -3,6 +3,28 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged).
## 1.4.0
- **Your website is backed up every night.** A copy of your site's content is kept on the server
every night, and before every update. Owners and Admins find them under **Backups**: make one
now, download one, or choose how many to keep. Your photos and files aren't in them.
- **Background jobs:** under **Background jobs**, see what your site does on a schedule (backups,
your events from Cross Events, new videos from YouTube), and switch each one on or off.
## 1.3.0
- Nothing changes on your site. Behind the scenes, Cross Code can now load demo content on the
websites it uses for demonstrations.
## 1.2.0
- **Your home page and the other pages are there from the start:** a new website now comes with
its home page, Plan your visit, About us, Give, Contact and the rest, with some starter text to
change. Before, a new website had no pages, so the home page and its preview were empty apart
from the header and footer.
- **Your own site icon:** under **Settings → Site icon**, choose the little picture that shows in
the browser tab and bookmarks. Until you do, your site shows your church's initial in its colour.
## 1.1.0
- **An easier admin.** A menu with icons down the side, and a dashboard with a tile for every part
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-backend",
"version": "1.1.0",
"version": "1.4.0",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true,
"type": "module",
@@ -22,8 +22,10 @@
"@crosscode/contracts": "*",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"cron-parser": "^5.10.2",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"pg-boss": "^11.1.2",
"sharp": "^0.35.5",
"zod": "^4.6.7"
},
+21 -9
View File
@@ -1,25 +1,37 @@
/**
* Loads the demo church (src/demo/demoChurch.ts) into a template and publishes it.
* Loads a demo into the site and publishes it.
*
* npm run demo -- --template heritage|bold|community|clean [--force]
* npm run demo -- --template heritage|bold|community|clean [--force] the Acacia Hill church (development)
* npm run demo -- --profile <profile> [--force] one of the eight demo churches (1.3.0),
* keeping the church's profile and settings
* npm run demo -- --list the profiles
*
* It replaces the site's content, so a site that has been published needs --force.
* It replaces the site's content, so a site that has been published needs --force. On a server,
* `crosscode demo <church> website --profile …` runs it (backup first), for the Hub's demo sites.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { websiteTemplateSchema } from '@crosscode/contracts';
import { agent, websiteTemplateSchema } from '@crosscode/contracts';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { createCtx } from '../src/context.js';
import { loadDemo } from '../src/demo/demoChurch.js';
import { demoSeeds } from '../src/demo/seeds.js';
import { loadConfig } from '../src/lib/config.js';
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
return i > 0 ? process.argv[i + 1] : undefined;
};
const template = websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
if (!template.success) {
console.error('Usage: npm run demo -- --template heritage|bold|community|clean [--force]');
const usage = 'Usage: npm run demo -- --template heritage|bold|community|clean | --profile <profile> [--force] | --list';
if (process.argv.includes('--list')) {
for (const s of demoSeeds()) console.log(`${s.id.padEnd(18)} ${s.label}`);
process.exit(0);
}
const profileArg = arg('profile');
const what = profileArg !== undefined ? agent.websiteDemoProfileSchema.safeParse(profileArg) : websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
if (!what.success) {
console.error(profileArg !== undefined ? `Unknown profile "${profileArg}" (npm run demo -- --list).` : usage);
process.exit(2);
}
@@ -31,6 +43,6 @@ if (published && !process.argv.includes('--force')) {
await db.$disconnect();
process.exit(1);
}
const version = await loadDemo(ctx, template.data);
console.log(`Demo church loaded on ${template.data} and published (version ${version.number}).`);
const version = await loadDemo(ctx, what.data);
console.log(`Demo ${what.data} loaded and published (version ${version.number}).`);
await db.$disconnect();
@@ -0,0 +1,93 @@
/**
* Settings → Backups and Settings → Background jobs (1.4.0, as Accounts and Cross Events). Admins
* only: a backup holds the whole site, and a job switched off stops the heartbeat or the backups.
*/
import fs from 'node:fs';
import express from 'express';
import type { Ctx } from '../context.js';
import { requireRole } from '../auth/sessions.js';
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
import { ApiError, handle, sendError } from '../http.js';
import { audit } from '../lib/audit.js';
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
type Who = { id: string; role: string };
export function maintenanceRouter(ctx: Ctx, who: (req: express.Request) => Who) {
const r = express.Router();
const json = express.json({ limit: '16kb' });
// On each route, not r.use: this router is mounted on the admin API's root.
const admin = requireRole(ctx, 'admin');
const jobError = (e: unknown) => {
if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message);
throw e;
};
// ─── Backups ───
r.get('/backups', admin, handle(async () => ({
items: (await listBackups(ctx)).map((b) => ({ filename: b.filename, size: b.size, createdAt: b.createdAt })),
nightly: await ctx.settings.bool('backup_nightly', true),
retain: await retainCount(ctx),
lastError: await ctx.settings.get('backup_last_error'),
})));
r.post('/backups/run', admin, handle(async (req) => {
let b;
try {
b = await runBackup(ctx);
} catch (e) {
throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(e as Error).message}`);
}
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_made', targetType: 'backup', targetId: b.filename });
return { filename: b.filename, size: b.size, createdAt: b.createdAt };
}));
r.put('/backups/settings', admin, json, handle(async (req) => {
const retain = Number(req.body?.retain);
if (!Number.isInteger(retain) || retain < 1 || retain > 365) throw new ApiError(400, 'VALIDATION', 'Keep between 1 and 365 backups.', { retain: 'Between 1 and 365' });
const nightly = req.body?.nightly !== false;
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: nightly ? 'true' : 'false' });
const deleted = await rotate(ctx);
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly, deleted } });
return { retain, nightly, deleted };
}));
// A download holds the whole site's content and its editors: audited, never cached.
r.get('/backups/:file/download', admin, async (req, res) => {
try {
const file = backupPath(ctx, String(req.params.file));
if (!file) throw new ApiError(404, 'NOT_FOUND', 'That backup isn\'t there any more.');
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_downloaded', targetType: 'backup', targetId: String(req.params.file) });
res.setHeader('Content-Type', 'application/gzip');
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Content-Disposition', `attachment; filename="${String(req.params.file)}"`);
fs.createReadStream(file).pipe(res);
} catch (e) {
sendError(res, e);
}
});
// ─── Background jobs ───
r.get('/jobs', admin, handle(() => jobStatus(ctx)));
r.put('/jobs/:name', admin, json, handle(async (req) => {
const name = String(req.params.name);
const out = await setOverride(ctx, name, { enabled: req.body?.enabled, cron: req.body?.cron }).catch(jobError);
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: out });
return { name, override: out };
}));
r.post('/jobs/:name/run', admin, handle(async (req) => {
const name = String(req.params.name);
const out = await runNow(ctx, name).catch(jobError);
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'job_run', targetType: 'job', targetId: name, metadata: { queued: out.queued } });
return out;
}));
return r;
}
+4
View File
@@ -24,6 +24,7 @@ import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js';
import { MAX_UPLOAD_BYTES, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
import { maintenanceRouter } from './maintenance.js';
const who = (req: Request) => ({ id: req.signed!.user.id, role: req.signed!.user.role });
const param = (req: Request, name: string) => String(req.params[name] ?? '');
@@ -213,5 +214,8 @@ export function adminRouter(ctx: Ctx) {
r.post('/preview-links', editor, handle((req) => createPreviewLink(ctx, who(req))));
r.delete('/preview-links/:id', editor, handle(async (req) => { await revokePreviewLink(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── Backups and background jobs (1.4.0, admins only) ───
r.use(maintenanceRouter(ctx, who));
return r;
}
+12 -5
View File
@@ -1,7 +1,9 @@
/**
* The site's own settings (WEBSITE-1.0-PLAN §10, "Settings"), live at once (they aren't the site's
* design): the Coming soon line (§5), and the search engines' verification codes (ROADMAP-v3 §11:
* Google Search Console and Bing Webmaster Tools), shown as `<meta>` tags on the home page. Also the
* Google Search Console and Bing Webmaster Tools), shown as `<meta>` tags on the home page, and the
* site's icon (1.2.0: the favicon, a picture from the media library; without one the site uses the
* church's icon from its profile, else one made from its colour and initial). Also the
* menu's order, and the audit log.
*/
import { z } from 'zod';
@@ -18,13 +20,14 @@ const schema = z.object({
comingSoonText: z.string().trim().max(300).optional(),
googleVerification: code.optional(),
bingVerification: code.optional(),
faviconId: z.string().uuid().nullable().optional(),
});
export type SiteSettings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
export type SiteSettings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null; faviconId: string | null };
export async function getSettings(ctx: Ctx): Promise<SiteSettings> {
const [coming, google, bing] = await Promise.all([ctx.settings.get('coming_soon_text'), ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]);
return { comingSoonText: coming || 'Our new website is on its way.', googleVerification: google || null, bingVerification: bing || null };
const [coming, google, bing, favicon] = await Promise.all([ctx.settings.get('coming_soon_text'), ctx.settings.get('google_verification'), ctx.settings.get('bing_verification'), ctx.settings.get('favicon_media_id')]);
return { comingSoonText: coming || 'Our new website is on its way.', googleVerification: google || null, bingVerification: bing || null, faviconId: favicon || null };
}
export async function saveSettings(ctx: Ctx, body: unknown, by: { id: string; role: string }) {
@@ -35,10 +38,14 @@ export async function saveSettings(ctx: Ctx, body: unknown, by: { id: string; ro
throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', fields);
}
const s = r.data;
if (s.faviconId && !(await ctx.db.mediaAsset.findUnique({ where: { id: s.faviconId } }))) {
throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', { faviconId: 'That picture isn\'t in the media library' });
}
await ctx.settings.setMany({
...(s.comingSoonText !== undefined ? { coming_soon_text: s.comingSoonText || null } : {}),
...(s.googleVerification !== undefined ? { google_verification: s.googleVerification || null } : {}),
...(s.bingVerification !== undefined ? { bing_verification: s.bingVerification || null } : {}),
...(s.faviconId !== undefined ? { favicon_media_id: s.faviconId || null } : {}),
});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'settings_changed', targetType: 'settings', targetId: null, metadata: { fields: Object.keys(s) } });
return getSettings(ctx);
@@ -59,7 +66,7 @@ export async function orderPages(ctx: Ctx, body: unknown, by: { id: string }) {
}
const ACTIONS: Record<string, string> = {
site_published: 'Published the site', change_discarded: 'Discarded a change', version_restored: 'Restored a version',
site_published: 'Published the site', change_discarded: 'Discarded a change', version_restored: 'Restored a version', starter_pages_added: 'Added the starter pages',
preview_link_created: 'Made a preview link', preview_link_revoked: 'Stopped a preview link',
first_owner_signed_in: 'Signed in as the first Owner', admin_signed_in: 'Signed in', admin_signed_out: 'Signed out',
admin_sign_in_refused: 'Was refused sign-in (no role here)', website_user_added: 'Gave someone access',
+130
View File
@@ -0,0 +1,130 @@
/**
* Database backups (1.4.0, as Accounts' and Cross Events' Settings → Backups): a gzipped
* `pg_dump` into backend/backups/ every night (02:20, after Accounts' at 02:00) and whenever an
* admin asks, kept on this server only. The `crosscode` script makes the same files before every
* deploy and uninstall (scripts/products/website.sh), so the admin's list shows both, newest first.
* The database only: the uploads (backend/uploads) aren't in it, as in Events.
*
* Settings: `backup_nightly` (default on), `backup_retain_count` (default 14), and what the last
* run did (`backup_last_error`). Needs the `pg_dump` program on the server (Postgres client).
*/
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import type { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { fileURLToPath } from 'node:url';
import zlib from 'node:zlib';
import type { Ctx } from '../context.js';
/** backend/backups, from src/ and dist/ alike (never relative to where the process started). */
export const DEFAULT_BACKUP_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'backups');
/** The names this module and the crosscode script give a backup: website-YYYYMMDD-HHMMSS.sql.gz. */
export const BACKUP_FILE = /^website-\d{8}-\d{6}\.sql\.gz$/;
export const DEFAULT_RETAIN = 14;
const MAX_RETAIN = 365;
export type Backup = { filename: string; size: number; createdAt: Date };
/** Something that writes a plain-SQL dump of the database to a stream (tests pass their own). */
export type Dumper = (databaseUrl: string) => { stdout: Readable; done: Promise<void> };
const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR;
/** `pg_dump`, plain SQL, without owners or privileges (restores into any database user). */
export const pgDump: Dumper = (databaseUrl) => {
const child = spawn('pg_dump', ['--no-owner', '--no-privileges', databaseUrl], { stdio: ['ignore', 'pipe', 'pipe'] });
let stderr = '';
child.stderr.on('data', (d) => { stderr += String(d); });
const done = new Promise<void>((resolve, reject) => {
child.on('error', (e) => reject(new Error(`pg_dump couldn't start (${e.message}). Install the PostgreSQL client on this server.`)));
child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`pg_dump stopped (exit ${code}): ${stderr.trim().slice(0, 400)}`))));
});
return { stdout: child.stdout, done };
};
const pad = (n: number) => String(n).padStart(2, '0');
/** website-20261120-020000.sql.gz in the server's local time, as the crosscode script names them. */
export function backupName(at: Date): string {
return `website-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}.sql.gz`;
}
export async function retainCount(ctx: Ctx): Promise<number> {
const n = Number(await ctx.settings.get('backup_retain_count'));
return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_RETAIN) : DEFAULT_RETAIN;
}
/** Every backup in the folder, newest first. */
export async function listBackups(ctx: Ctx): Promise<Backup[]> {
let names: string[];
try {
names = await fs.promises.readdir(dir(ctx));
} catch {
return [];
}
const items = await Promise.all(names.filter((n) => BACKUP_FILE.test(n)).map(async (filename) => {
const st = await fs.promises.stat(path.join(dir(ctx), filename));
return { filename, size: st.size, createdAt: st.mtime };
}));
return items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.filename.localeCompare(a.filename));
}
/** The newest backup's time, for the Hub heartbeat. */
export async function lastBackupAt(ctx: Ctx): Promise<Date | null> {
return (await listBackups(ctx))[0]?.createdAt ?? null;
}
/** The full path of a backup to download, or null if there's no such backup (or a bad name). */
export function backupPath(ctx: Ctx, filename: string): string | null {
if (!BACKUP_FILE.test(filename)) return null;
const p = path.join(dir(ctx), filename);
return fs.existsSync(p) ? p : null;
}
/** Deletes the oldest backups beyond the number kept. */
export async function rotate(ctx: Ctx): Promise<number> {
const old = (await listBackups(ctx)).slice(await retainCount(ctx));
await Promise.all(old.map((b) => fs.promises.unlink(path.join(dir(ctx), b.filename)).catch(() => {})));
return old.length;
}
/**
* Makes a backup now. A dump that fails part-way leaves no file behind (a truncated one would
* look like a real backup). Records the outcome for the admin page.
*/
export async function runBackup(ctx: Ctx, dumper: Dumper = pgDump): Promise<Backup> {
const url = ctx.config.databaseUrl;
try {
if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.');
await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 });
// Two in the same second (the button pressed twice): the next free second's name.
const at = ctx.now().getTime();
let filename = backupName(new Date(at));
for (let s = 1; fs.existsSync(path.join(dir(ctx), filename)); s++) filename = backupName(new Date(at + s * 1000));
const file = path.join(dir(ctx), filename);
const { stdout, done } = dumper(url);
// Both must finish: pg_dump exiting cleanly, and the file written. Wait for both either way,
// so a failed one's file is deleted after the last write, not before it.
const [dumped, written] = await Promise.allSettled([done, pipeline(stdout, zlib.createGzip(), fs.createWriteStream(file, { mode: 0o600 }))]);
const failed = [dumped, written].find((r): r is PromiseRejectedResult => r.status === 'rejected');
if (failed) {
await fs.promises.unlink(file).catch(() => {});
throw failed.reason;
}
await rotate(ctx);
await ctx.settings.set('backup_last_error', null);
const st = await fs.promises.stat(file);
return { filename, size: st.size, createdAt: st.mtime };
} catch (e) {
await ctx.settings.set('backup_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600));
throw e;
}
}
/** The nightly `backup` job: skipped when an admin has turned nightly backups off. */
export async function runBackupJob(ctx: Ctx) {
if (!(await ctx.settings.bool('backup_nightly', true))) return { skipped: true };
const b = await runBackup(ctx);
return { filename: b.filename, size: b.size };
}
+160 -76
View File
@@ -3,17 +3,24 @@
* illustrated images (no photos of anyone), loaded into a template for development, the Hub's demo
* sites and the crosscode-site screenshots. `npm run demo -- --template bold`.
*
* 1.3.0: also the eight demo profiles (seeds.ts, `npm run demo -- --profile bold-plant`), which
* keep the church's own profile (Accounts' organisation settings), the site settings, the site
* icon and the admins, and name the church in the copy. A template alone (development, e2e) is
* still Acacia Hill, profile and all, exactly as before.
*
* It replaces the Website's content (never the admins), so the script refuses on a site that has
* been published unless told otherwise.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { CHURCH_SCHEMA, type Church, type WebsiteTemplate } from '@crosscode/contracts';
import { CHURCH_SCHEMA, WEBSITE_TEMPLATES, type agent, type Church, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import type { SectionData } from '../site/sections.js';
import { publish } from '../site/snapshot.js';
import { defaultDesign } from '../site/variants.js';
import { TEMPLATE_HEADERS, TEMPLATE_VARIANTS, SECTION_TYPES, defaultDesign, type SiteDesign } from '../site/variants.js';
import { DEMO_SEEDS, type DemoSeed } from './seeds.js';
export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' };
@@ -48,8 +55,8 @@ export function demoProfile(publicUrl: string): Church {
}
/** An illustrated "photo": hills, a sun and a path in the church's colours (SVG, no people). */
export function illustration(seed: number, w = 1600, h = 1000): string {
const hues = [DEMO_COLOURS.primary, DEMO_COLOURS.accent, '#7fb7be', '#f3e3c3', '#284b52'];
export function illustration(seed: number, w = 1600, h = 1000, colours: { primary: string; accent: string } = DEMO_COLOURS): string {
const hues = [colours.primary, colours.accent, '#7fb7be', '#f3e3c3', '#284b52'];
const c = (i: number) => hues[(seed + i) % hues.length];
const y = (f: number) => Math.round(h * f);
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">
@@ -64,26 +71,17 @@ export function illustration(seed: number, w = 1600, h = 1000): string {
type Ids = Record<string, string>;
async function demoMedia(ctx: Ctx, uploadDir: string): Promise<Ids> {
const items: [string, string, number][] = [
['hero', 'The hills behind Acacia Hill at sunrise (illustration)', 0],
['collage2', 'A path through the veld (illustration)', 1],
['collage3', 'Evening over the valley (illustration)', 2],
['welcome', 'The church garden (illustration)', 3],
['pastor', 'Illustration standing in for the pastor\'s photo', 4],
['invite', 'A sunny Sunday morning (illustration)', 5],
['kids', 'Illustration for Kids church', 6],
['youth', 'Illustration for Youth', 7],
['care', 'Illustration for Care and prayer', 8],
['music', 'Illustration for Worship', 9],
];
const HEX = /^#[0-9a-f]{6}$/i;
async function demoMedia(ctx: Ctx, uploadDir: string, alts: Record<string, string>, colours: { primary: string; accent: string }): Promise<Ids> {
const items: [string, number][] = [['hero', 0], ['collage2', 1], ['collage3', 2], ['welcome', 3], ['pastor', 4], ['invite', 5], ['kids', 6], ['youth', 7], ['care', 8], ['music', 9]];
const ids: Ids = {};
fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true });
for (const [key, alt, seed] of items) {
for (const [key, seed] of items) {
const filename = `demo/${key}.svg`;
const svg = illustration(seed);
const svg = illustration(seed, 1600, 1000, colours);
fs.writeFileSync(path.join(uploadDir, filename), svg);
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt } });
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt: alts[key]! } });
ids[key] = row.id;
}
return ids;
@@ -91,57 +89,160 @@ async function demoMedia(ctx: Ctx, uploadDir: string): Promise<Ids> {
export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads');
/** Replaces the content with the demo church's on `template`, then publishes it. */
export async function loadDemo(ctx: Ctx, template: WebsiteTemplate, opts: { uploadDir?: string; publishedBy?: string } = {}) {
/** The development demo church (Acacia Hill), on any template: what a template alone loads. */
const CLASSIC: Omit<DemoSeed, 'template'> & { pastorName: string; ctaText: string; descriptions: Record<string, string>; alts: Record<string, string> } = {
id: 'classic', label: 'Acacia Hill (development)', alternate: false,
hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', button: { label: 'Plan your visit', href: '/visit' } },
serviceNote: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.',
welcome: {
heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.',
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.',
quote: 'We would love to meet you. Come and say hello at the welcome table.',
},
ministriesIntro: 'There is something for every age and stage.',
teamIntro: null,
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' } },
visit: {
expect: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.',
kids: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.',
cta: 'Questions before you come?',
},
ctaText: 'Send us a WhatsApp and we will get back to you.',
about: { story: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.', quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' },
give: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.'],
['youth', 'Youth', 'High schoolers, Friday nights at 18:30.'],
['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.'],
['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.'],
],
leaders: [['Thandi Mokoena', 'Lead pastor'], ['Pieter van Wyk', 'Associate pastor'], ['Lerato Dlamini', 'Kids and families'], ['Johan Botha', 'Worship']],
pastorName: 'Pastor Thandi Mokoena',
series: ['hope-for-today', 'Hope for today'],
messages: [['hope-that-holds', 'A hope that holds', 3, 'Psalm 23'], ['bread-for-the-road', 'Bread for the road', 10, 'Psalm 23'], ['the-good-shepherd', 'The good shepherd', 17, 'Psalm 23']],
events: [
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'],
['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'],
['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'],
],
venue: 'Acacia Hill Church',
descriptions: {
home: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.',
visit: 'What to expect on your first Sunday at Acacia Hill Church.',
about: 'Our story, what we believe and what we value.',
ministries: 'Kids, youth, worship, care and prayer at Acacia Hill.',
leadership: 'The team who lead Acacia Hill Church.',
events: 'What is coming up at Acacia Hill Church.',
messages: 'Sunday messages from Acacia Hill Church.',
give: 'How to give to Acacia Hill Church.',
contact: 'Find Acacia Hill Church in Westridge, Pretoria.',
},
alts: {
hero: 'The hills behind Acacia Hill at sunrise (illustration)', collage2: 'A path through the veld (illustration)', collage3: 'Evening over the valley (illustration)',
welcome: 'The church garden (illustration)', pastor: 'Illustration standing in for the pastor\'s photo', invite: 'A sunny Sunday morning (illustration)',
kids: 'Illustration for Kids church', youth: 'Illustration for Youth', care: 'Illustration for Care and prayer', music: 'Illustration for Worship',
},
};
/** A demo profile's design: the template's defaults, or (alternate) its second recommendations and header. */
export function seedDesign(template: WebsiteTemplate, alternate: boolean): SiteDesign {
const design = defaultDesign(template);
if (!alternate) return design;
const variants = Object.fromEntries(SECTION_TYPES.map((s) => {
const options = TEMPLATE_VARIANTS[template][s] as readonly string[];
return [s, options[1] ?? options[0]!];
})) as SiteDesign['variants'];
const headers = TEMPLATE_HEADERS[template] as readonly string[];
return { ...design, variants, style: { ...design.style, header: headers[1] ?? headers[0]! } };
}
export const isDemoTemplate = (v: string): v is WebsiteTemplate => (WEBSITE_TEMPLATES as readonly string[]).includes(v);
/**
* Replaces the content with a demo, then publishes it. `what`: a template (the Acacia Hill church,
* its profile saved too) or a demo profile (keeps the church's profile; Acacia Hill's is saved
* only on a site that has none at all, so the site still has a name).
*/
export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDemoProfile, opts: { uploadDir?: string; publishedBy?: string } = {}) {
const db = ctx.db;
const uploadDir = opts.uploadDir ?? ctx.config.uploadDir ?? defaultUploadDir();
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'mediaAsset', 'siteVersion', 'siteDesign'] as const) {
const classic = isDemoTemplate(what);
const seed: DemoSeed = classic ? { ...CLASSIC, template: what } : DEMO_SEEDS[what];
const extra = classic ? CLASSIC : null;
// The church: Acacia Hill for a template; else whoever the site belongs to.
let church = classic ? null : await churchProfile(ctx);
if (!church) {
church = demoProfile(ctx.config.publicUrl);
await ctx.settings.set('church_profile_local', JSON.stringify(church));
}
const name = church.name;
const short = church.shortName || church.name;
const city = church.contact?.address?.city || church.contact?.address?.suburb || 'town';
const t = (s: string) => s.replaceAll('{name}', name).replaceAll('{short}', short).replaceAll('{city}', city);
const brand = church.branding?.colours;
const colours = classic || !brand?.primary || !HEX.test(brand.primary)
? DEMO_COLOURS
: { primary: brand.primary, accent: brand.accent && HEX.test(brand.accent) ? brand.accent : DEMO_COLOURS.accent };
// The site icon is a setting, so its picture stays; every other picture goes with the content.
const faviconId = classic ? null : await ctx.settings.get('favicon_media_id');
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'siteVersion', 'siteDesign', 'slugHistory', 'previewLink'] as const) {
await (db[m] as unknown as { deleteMany: (a?: object) => Promise<unknown> }).deleteMany({});
}
const img = await demoMedia(ctx, uploadDir);
const design = defaultDesign(template);
await db.siteDesign.create({ data: { id: 1, template, variants: design.variants as never, home: design.home as never, style: design.style as never } });
await ctx.settings.set('church_profile_local', JSON.stringify(demoProfile(ctx.config.publicUrl)));
await db.mediaAsset.deleteMany(faviconId ? { where: { NOT: { id: faviconId } } } : undefined);
const [pastorName] = seed.leaders[0]!;
const ministryNames = seed.ministries.map(([, n]) => t(n));
const alts = extra?.alts ?? {
hero: `${t(seed.hero.headline)} (illustration)`, collage2: 'A path through the veld (illustration)', collage3: 'Evening over the valley (illustration)',
welcome: `${short} (illustration)`, pastor: `Illustration standing in for ${pastorName}'s photo`, invite: 'A sunny Sunday morning (illustration)',
kids: `Illustration for ${ministryNames[0]}`, youth: `Illustration for ${ministryNames[1]}`, music: `Illustration for ${ministryNames[2]}`, care: `Illustration for ${ministryNames[3]}`,
};
const img = await demoMedia(ctx, uploadDir, alts, colours);
const design = classic ? defaultDesign(seed.template) : seedDesign(seed.template, seed.alternate);
await db.siteDesign.create({ data: { id: 1, template: seed.template, variants: design.variants as never, home: design.home as never, style: design.style as never } });
const speaker = extra?.pastorName ?? pastorName;
const home: SectionData = {
hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: { label: 'Plan your visit', href: '/visit' } },
serviceTimes: { heading: 'Join us this Sunday', note: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.' },
hero: { headline: t(seed.hero.headline), subline: t(seed.hero.subline), images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: seed.hero.button },
serviceTimes: { heading: 'Join us this Sunday', note: t(seed.serviceNote) },
welcome: {
heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.',
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.',
imageId: img.welcome!, pastor: { name: 'Pastor Thandi Mokoena', role: 'Lead pastor', quote: 'We would love to meet you. Come and say hello at the welcome table.', photoId: img.pastor! },
heading: t(seed.welcome.heading), mission: t(seed.welcome.mission), body: t(seed.welcome.body),
imageId: img.welcome!, pastor: { name: speaker, role: seed.leaders[0]![1], quote: t(seed.welcome.quote), photoId: img.pastor! },
},
ministries: { heading: 'Find your place', intro: 'There is something for every age and stage.' },
team: { heading: 'Our team', intro: null },
ministries: { heading: 'Find your place', intro: t(seed.ministriesIntro) },
team: { heading: 'Our team', intro: seed.teamIntro ? t(seed.teamIntro) : null },
events: { heading: 'Coming up', count: 3 },
latestMessage: { heading: 'Latest message' },
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' }, imageId: img.invite! },
invitation: { heading: t(seed.invitation.heading), text: t(seed.invitation.text), button: seed.invitation.button, imageId: img.invite! },
};
const d = (kind: string, fallback: string) => extra?.descriptions[kind] ?? t(fallback);
const pages: { kind: string; slug: string; title: string; position: number; description: string; sections: { type: string; variant?: string; data: unknown }[] }[] = [
{ kind: 'home', slug: 'home', title: 'Home', position: 0, description: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.', sections: Object.entries(home).map(([type, data]) => ({ type, data })) },
{ kind: 'home', slug: 'home', title: 'Home', position: 0, description: d('home', `${seed.hero.subline}`), sections: Object.entries(home).map(([type, data]) => ({ type, data })) },
{
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: 'What to expect on your first Sunday at Acacia Hill Church.', sections: [
{ type: 'text', data: { heading: 'What to expect', body: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.' } },
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.', imageId: img.kids, button: null } },
{ type: 'cta', data: { heading: 'Questions before you come?', text: 'Send us a WhatsApp and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [
{ type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } },
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.kids, button: null } },
{ type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
],
},
{
kind: 'about', slug: 'about', title: 'About us', position: 2, description: 'Our story, what we believe and what we value.', sections: [
{ type: 'text', data: { heading: 'Our story', body: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.' } },
{ type: 'quote', data: { quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' } },
kind: 'about', slug: 'about', title: 'About us', position: 2, description: d('about', 'Our story, what we believe and what we value.'), sections: [
{ type: 'text', data: { heading: 'Our story', body: t(seed.about.story) } },
{ type: 'quote', data: { quote: seed.about.quote, by: seed.about.by } },
],
},
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: 'Kids, youth, worship, care and prayer at Acacia Hill.', sections: [] },
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: 'The team who lead Acacia Hill Church.', sections: [] },
{ kind: 'events', slug: 'events', title: 'Events', position: 5, description: 'What is coming up at Acacia Hill Church.', sections: [] },
{ kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: 'Sunday messages from Acacia Hill Church.', sections: [] },
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: d('ministries', `${ministryNames.join(', ')} at {short}.`), sections: [] },
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: d('leadership', 'The team who lead {name}.'), sections: [] },
{ kind: 'events', slug: 'events', title: 'Events', position: 5, description: d('events', 'What is coming up at {name}.'), sections: [] },
{ kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: d('messages', 'Sunday messages from {name}.'), sections: [] },
{
kind: 'give', slug: 'give', title: 'Give', position: 7, description: 'How to give to Acacia Hill Church.', sections: [
{ type: 'text', data: { heading: 'Giving', body: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).' } },
kind: 'give', slug: 'give', title: 'Give', position: 7, description: d('give', 'How to give to {name}.'), sections: [
{ type: 'text', data: { heading: 'Giving', body: t(seed.give) } },
],
},
{ kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: 'Find Acacia Hill Church in Westridge, Pretoria.', sections: [] },
{ kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: d('contact', 'Find {name} in {city}.'), sections: [] },
];
for (const p of pages) {
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: p.position, description: p.description } });
@@ -149,38 +250,21 @@ export async function loadDemo(ctx: Ctx, template: WebsiteTemplate, opts: { uplo
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, variant: s.variant ?? null, position: i++, data: s.data as never } });
}
const ministries: [string, string, string, string][] = [
['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.', img.kids!],
['youth', 'Youth', 'High schoolers, Friday nights at 18:30.', img.youth!],
['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.', img.music!],
['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.', img.care!],
];
const pictures = [img.kids!, img.youth!, img.music!, img.care!];
let n = 0;
for (const [slug, name, summary, imageId] of ministries) await db.ministry.create({ data: { slug, name, summary, imageId, position: n++ } });
const leaders: [string, string, string | null][] = [
['Thandi Mokoena', 'Lead pastor', img.pastor!],
['Pieter van Wyk', 'Associate pastor', null],
['Lerato Dlamini', 'Kids and families', null],
['Johan Botha', 'Worship', null],
];
for (const [slug, , summary] of seed.ministries) await db.ministry.create({ data: { slug, name: ministryNames[n]!, summary: t(summary), imageId: pictures[n]!, position: n++ } });
n = 0;
for (const [name, role, photoId] of leaders) await db.leader.create({ data: { name, role, photoId, position: n++ } });
for (const [leader, role] of seed.leaders) await db.leader.create({ data: { name: leader, role, photoId: n === 0 ? img.pastor! : null, position: n++ } });
const now = ctx.now();
const day = 864e5;
const series = await db.messageSeries.create({ data: { slug: 'hope-for-today', title: 'Hope for today' } });
const messages: [string, string, number][] = [['hope-that-holds', 'A hope that holds', 3], ['bread-for-the-road', 'Bread for the road', 10], ['the-good-shepherd', 'The good shepherd', 17]];
for (const [slug, title, ago] of messages) {
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', speaker: 'Pastor Thandi Mokoena', passage: 'Psalm 23', seriesId: series.id, publishedAt: now } });
const series = await db.messageSeries.create({ data: { slug: seed.series[0], title: seed.series[1] } });
for (const [slug, title, ago, passage] of seed.messages) {
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', speaker, passage, seriesId: series.id, publishedAt: now } });
}
const events: [string, string, number, string][] = [
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'],
['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'],
['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'],
];
for (const [slug, title, inDays, description] of events) {
for (const [slug, title, inDays, description] of seed.events) {
const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3);
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: 'Acacia Hill Church', description, publishedAt: now } });
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: t(seed.venue), description: t(description), publishedAt: now } });
}
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, `Demo church on ${template}`);
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, classic ? `Demo church on ${seed.template}` : `Demo: ${seed.label}`);
}
+334
View File
@@ -0,0 +1,334 @@
/**
* The Website's demo profiles (1.3.0, contracts `WEBSITE_DEMO_PROFILES`): eight fictional churches,
* two per template, for the Hub's demo sites (`crosscode demo <church> website --profile …`).
*
* A demo replaces the content only. The church's profile (name, logo, colours, service times,
* contact: Accounts' organisation settings) stays, so the copy names the church with placeholders:
* `{name}` (Hope Family Church), `{short}` (Hope Family) and `{city}` (Pretoria). The second
* profile of each template starts on the template's other recommended variants and header, so the
* eight show every recommended look.
*
* Every person and place in here is made up. A profile id never changes once released.
*/
import { agent, type WebsiteTemplate } from '@crosscode/contracts';
type WebsiteDemoProfile = agent.WebsiteDemoProfile;
type Button = { label: string; href: string };
export type DemoSeed = {
id: WebsiteDemoProfile | 'classic';
template: WebsiteTemplate;
/** What the Hub shows: "Heritage: a parish church". */
label: string;
/** Start on the template's second recommended variant of every section, and its second header. */
alternate: boolean;
hero: { headline: string; subline: string; button: Button };
serviceNote: string;
welcome: { heading: string; mission: string; body: string; quote: string };
ministriesIntro: string;
teamIntro: string | null;
invitation: { heading: string; text: string; button: Button };
visit: { expect: string; kids: string; cta: string };
about: { story: string; quote: string; by: string };
give: string;
/** Four: [slug, name, summary]. Their pictures are the kids, youth, music and care illustrations, in order. */
ministries: [string, string, string][];
/** Four: [name, role]. The first is the pastor on the home page and the speaker of the messages. */
leaders: [string, string][];
series: [string, string];
/** Three: [slug, title, days ago, passage]. */
messages: [string, string, number, string][];
/** Three: [slug, title, in days, description]. */
events: [string, string, number, string][];
/** Where the events are. */
venue: string;
};
const visitButton: Button = { label: 'Plan your visit', href: '/visit' };
export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
'heritage-parish': {
id: 'heritage-parish', template: 'heritage', label: 'Heritage: a parish church with a long history', alternate: false,
hero: { headline: 'Worshipping together since 1896', subline: 'An old church with a warm welcome in the heart of {city}. Traditional services, every generation together.', button: visitButton },
serviceNote: 'Holy Communion on the first Sunday of the month. Tea in the parish hall after every service.',
welcome: {
heading: 'Welcome to {name}', mission: 'Rooted in prayer, open to all, serving {city}.',
body: 'For more than a century people have gathered here to pray, to sing the old hymns and to hear God\'s word. Our services follow the prayer book, our choir sings most Sundays, and our doors are open to anyone who wants to come in out of the noise.',
quote: 'Whether this is your first time in a church or your thousandth, you are welcome here.',
},
ministriesIntro: 'Ways to belong, from the choir stalls to the Sunday school.',
teamIntro: 'The clergy and lay ministers who care for the parish.',
invitation: { heading: 'There is always a place in the pews', text: 'Join us this Sunday. Someone at the door will show you the way.', button: visitButton },
visit: {
expect: 'Our services follow a set order with readings, prayers and hymns. The words are printed in the service sheet, so you can follow along. A service lasts about an hour.',
kids: 'Sunday school meets in the hall during the sermon, and the children come back in for the blessing.',
cta: 'Would you like to talk to the rector before you come?',
},
about: { story: '{name} was founded by a handful of families in 1896, and the stone church was finished in 1912. The stained glass, the organ and the bell are all gifts from the parish over the years.', quote: 'Be still, and know that I am God.', by: 'Psalm 46:10' },
give: 'Thank you for supporting the life of the parish and the upkeep of the church building. You can give by EFT or in the plate on Sundays (demo details only: this is not a real account).',
ministries: [
['sunday-school', 'Sunday school', 'Bible stories, songs and crafts for ages 4 to 11 during the sermon.'],
['servers', 'Altar servers', 'Teenagers who help lead worship on Sunday mornings.'],
['choir', 'The parish choir', 'Choral evensong once a month and anthems every Sunday. New voices welcome.'],
['pastoral-care', 'Pastoral visiting', 'Home communion and visits for those who can\'t come to church.'],
],
leaders: [['The Revd Margaret Pillay', 'Rector'], ['The Revd Sipho Ndlovu', 'Assistant priest'], ['Anne Fourie', 'Director of music'], ['David Smith', 'Churchwarden']],
series: ['the-lords-prayer', 'The Lord\'s Prayer'],
messages: [['your-kingdom-come', 'Your kingdom come', 3, 'Matthew 6:10'], ['our-daily-bread', 'Our daily bread', 10, 'Matthew 6:11'], ['forgive-us', 'Forgive us as we forgive', 17, 'Matthew 6:12']],
events: [
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share on the rectory lawn. Games for the children.'],
['advent-carols', 'Advent carol service', 13, 'Readings and carols by candlelight, sung by the parish choir.'],
['christmas-eve', 'Christmas Eve midnight mass', 27, 'The first Communion of Christmas, with carols from 23:15.'],
],
venue: '{name}',
},
'heritage-city': {
id: 'heritage-city', template: 'heritage', label: 'Heritage: a city-centre church with weekday services', alternate: true,
hero: { headline: 'A quiet place in a busy city', subline: 'In the middle of {city}, open every weekday for prayer, lunchtime services and a cup of tea.', button: { label: 'Come in this week', href: '/visit' } },
serviceNote: 'Lunchtime service on weekdays at 13:05, twenty-five minutes, back at your desk in time.',
welcome: {
heading: 'Right in the heart of {city}', mission: 'A church for the city: for workers, students, visitors and neighbours.',
body: 'Thousands of people walk past our doors every day. Some come in to sit in the quiet, some to light a candle, some for the lunchtime service. On Sundays we worship as a congregation drawn from all over {city}.',
quote: 'The city needs places that are quiet and kind. We try to be one.',
},
ministriesIntro: 'Serving the city through the week.',
teamIntro: null,
invitation: { heading: 'The doors are open', text: 'Monday to Friday from 08:00 to 16:00. Come in for a moment, or for the service.', button: { label: 'When we are open', href: '/visit' } },
visit: {
expect: 'The weekday service is short and simple: a reading, a short talk and prayers. On Sundays the service is longer, with the choir and Communion.',
kids: 'Children are welcome at every service. There are activity bags at the back of the church.',
cta: 'Want to know more about the city ministries?',
},
about: { story: '{name} has stood on this corner since the city was young. Today our congregation is students, office workers, families and people who sleep on the streets nearby, all at the same tables.', quote: 'Seek the welfare of the city, and pray to the Lord on its behalf.', by: 'Jeremiah 29:7' },
give: 'Your gifts keep the doors open on weekdays and fund the soup kitchen (demo details only: this is not a real account).',
ministries: [
['students', 'Students', 'Supper and a Bible study for students on Tuesday evenings.'],
['young-workers', 'Young professionals', 'Breakfast before work on Thursdays at 07:00.'],
['lunchtime-music', 'Lunchtime concerts', 'Free organ and chamber music on Wednesdays.'],
['soup-kitchen', 'The soup kitchen', 'Soup and bread for anyone who needs it, every weekday at noon.'],
],
leaders: [['Canon Peter Mahlangu', 'Vicar'], ['The Revd Claire Jacobs', 'City chaplain'], ['Tom Venter', 'Organist'], ['Nomsa Khumalo', 'Soup kitchen coordinator']],
series: ['songs-of-ascent', 'Songs of Ascent'],
messages: [['unless-the-lord-builds', 'Unless the Lord builds the house', 4, 'Psalm 127'], ['i-lift-up-my-eyes', 'I lift up my eyes', 11, 'Psalm 121'], ['how-good-and-pleasant', 'How good and pleasant', 18, 'Psalm 133']],
events: [
['organ-recital', 'Lunchtime organ recital', 2, 'Bach and Buxtehude, 13:05 to 13:40. Free, with a retiring collection.'],
['blue-christmas', 'Blue Christmas', 16, 'A quiet service for anyone who finds Christmas hard.'],
['city-carols', 'Carols for the city', 23, 'Readings and carols for everyone who works in {city}.'],
],
venue: '{name}',
},
'bold-youth': {
id: 'bold-youth', template: 'bold', label: 'Bold: a young, music-led church', alternate: false,
hero: { headline: 'Loud worship. Real people. Good news.', subline: '{short} is a church for {city}: come for the music, stay for the family.', button: { label: 'Visit this Sunday', href: '/visit' } },
serviceNote: 'Doors open half an hour before. Coffee bar in the foyer, kids church at the morning service.',
welcome: {
heading: 'This is {short}', mission: 'Helping people find and follow Jesus, together.',
body: 'We are a young church with a big heart for {city}. Sundays are full of energy: a live band, a message you can use on Monday, and people who will remember your name. Wherever you are coming from, you belong here.',
quote: 'We are not a perfect church. We are a family learning to follow Jesus together.',
},
ministriesIntro: 'Get connected. There is a place for you.',
teamIntro: null,
invitation: { heading: 'Your seat is waiting', text: 'Tell us you are coming and we will have a coffee ready for you.', button: { label: 'I am coming', href: '/visit' } },
visit: {
expect: 'Expect about 30 minutes of live worship and a 30-minute message. Come as you are: jeans are fine.',
kids: 'Kids church is high energy, safe and fun. Check your kids in at the kids desk when you arrive.',
cta: 'Got questions? Our team will get back to you.',
},
about: { story: '{short} started in a living room with twelve students and a guitar. Today we are a church of every age, but we have never lost the joy of that first night.', quote: 'I have come that they may have life, and have it to the full.', by: 'John 10:10' },
give: 'Generosity is part of who we are. Give online, by EFT or at the giving station (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids', 'Ages 2 to 12, every Sunday morning.'],
['youth', 'Youth', 'Grades 8 to 12, Friday nights. Games, worship, real talk.'],
['creative', 'Worship and creative', 'Band, sound, lights and media. Auditions every term.'],
['groups', 'Connect groups', 'Meet in a home during the week and do life together.'],
],
leaders: [['Jason and Lindi Naidoo', 'Lead pastors'], ['Kagiso Molefe', 'Youth pastor'], ['Megan Steyn', 'Worship pastor'], ['Ruan Pretorius', 'Connect groups']],
series: ['unstoppable', 'Unstoppable'],
messages: [['fearless', 'Fearless', 3, 'Joshua 1:9'], ['all-in', 'All in', 10, 'Romans 12:1-2'], ['no-turning-back', 'No turning back', 17, 'Luke 9:62']],
events: [
['worship-night', 'Worship night', 5, 'Two hours of worship and prayer. Bring your friends.'],
['youth-camp', 'Summer youth camp', 19, 'Three days at the river for grades 8 to 12. Registration is open.'],
['christmas-experience', 'The Christmas experience', 26, 'Music, lights and the Christmas story for the whole family.'],
],
venue: 'The {short} auditorium',
},
'bold-plant': {
id: 'bold-plant', template: 'bold', label: 'Bold: a new church plant meeting in a school', alternate: true,
hero: { headline: 'A new church for {city}', subline: 'We are launching soon. Meet us on Sundays in the school hall and be part of something new.', button: { label: 'Find out more', href: '/about' } },
serviceNote: 'We meet in the school hall. Look for the flags at the gate; parking is on the field.',
welcome: {
heading: 'Something new is starting', mission: 'A church for people who don\'t go to church.',
body: '{short} is a brand-new church. We are a small team who moved to {city} to start a church for our neighbours. Every week we set up chairs in a school hall, and every week new people walk in. There is room for you on the team.',
quote: 'Every great church was once a few people setting out chairs.',
},
ministriesIntro: 'Small team, big vision. Find where you fit.',
teamIntro: 'The launch team.',
invitation: { heading: 'Join the launch team', text: 'Help us set up, welcome, play or pray. Every hand matters right now.', button: { label: 'Get involved', href: '/contact' } },
visit: {
expect: 'Our services are relaxed and short: songs, a talk and time to talk over coffee afterwards. Nobody will put you on the spot.',
kids: 'Kids are part of the service for the songs, then go to their own room in the classroom next door.',
cta: 'Want to meet the team first?',
},
about: { story: '{short} was planted last year by a team of eight with the support of churches across the country. We have met in lounges, a coffee shop and now the school hall.', quote: 'See, I am doing a new thing! Now it springs up; do you not perceive it?', by: 'Isaiah 43:19' },
give: 'Every gift helps us reach a new neighbourhood with the good news (demo details only: this is not a real account).',
ministries: [
['kids-room', 'Kids room', 'A safe, fun room for children during the service.'],
['set-up', 'Set-up team', 'Chairs, sound and signs from 07:30. Breakfast is on us.'],
['band', 'Band', 'Guitar, keys, drums or voice. We need you.'],
['dinner-church', 'Dinner church', 'Supper and a conversation about Jesus on Wednesdays.'],
],
leaders: [['Ben and Zanele Moore', 'Church planters'], ['Ayesha Patel', 'Kids'], ['Chris Hendricks', 'Music'], ['Grace Okafor', 'Community']],
series: ['new-beginnings', 'New beginnings'],
messages: [['why-church', 'Why church?', 4, 'Acts 2:42-47'], ['the-first-step', 'The first step', 11, 'Mark 1:16-20'], ['a-seat-at-the-table', 'A seat at the table', 18, 'Luke 14:15-24']],
events: [
['launch-sunday', 'Launch Sunday', 7, 'Our first public service. Bring everyone you know.'],
['street-braai', 'Street braai', 14, 'Food and games for the neighbourhood in the school grounds.'],
['christmas-in-the-hall', 'Christmas in the hall', 24, 'A family carol service with mince pies.'],
],
venue: 'The school hall',
},
'community-family': {
id: 'community-family', template: 'community', label: 'Community: a family church with small groups', alternate: false,
hero: { headline: 'Come as you are, bring the family', subline: 'A friendly church in {city} where kids are noisy, coffee is hot and everyone knows your name.', button: visitButton },
serviceNote: 'Kids church for every age during the service. Coffee and juice afterwards on the lawn.',
welcome: {
heading: 'Hello, we are {short}', mission: 'Families following Jesus together, every day of the week.',
body: 'We are mums, dads, grandparents, singles, teenagers and toddlers. On Sundays we worship together, and during the week we meet in homes across {city} to eat, pray and look after each other.',
quote: 'Church is not a building we go to. It is a family we belong to.',
},
ministriesIntro: 'Something for every member of the family.',
teamIntro: 'The people who look after our church family.',
invitation: { heading: 'Pop in this Sunday', text: 'Let us know you are coming and we will save you a spot (and a muffin).', button: visitButton },
visit: {
expect: 'Our services are friendly and informal and last about an hour and a quarter. You don\'t need to know the songs or the Bible to feel at home.',
kids: 'Babies to grade 7 have their own groups with trained, screened leaders. There is a parents\' room with the service on a screen.',
cta: 'Questions about the kids? Ask us anything.',
},
about: { story: '{short} began when three families started meeting for a Bible study and the kids outnumbered the grown-ups. We still think that is a good sign.', quote: 'As for me and my household, we will serve the Lord.', by: 'Joshua 24:15' },
give: 'Thank you for helping us care for families in {city} (demo details only: this is not a real account).',
ministries: [
['little-ones', 'Little ones', 'Babies and toddlers, with a play area and story time.'],
['teens', 'Teens', 'Grades 6 to 12 on Friday evenings: games, food and faith.'],
['worship-team', 'Worship team', 'Singers and musicians of all ages lead us on Sundays.'],
['home-groups', 'Home groups', 'Twelve groups across {city}, every Tuesday or Wednesday.'],
],
leaders: [['Pastor Andile Zulu', 'Senior pastor'], ['Michelle de Beer', 'Children\'s pastor'], ['Kevin and Tracy Reddy', 'Home groups'], ['Lwazi Mthembu', 'Youth']],
series: ['family-matters', 'Family matters'],
messages: [['love-at-home', 'Love at home', 3, '1 Corinthians 13'], ['raising-faith', 'Raising faith', 10, 'Deuteronomy 6:4-9'], ['better-together', 'Better together', 17, 'Ecclesiastes 4:9-12']],
events: [
['fun-day', 'Family fun day', 6, 'Jumping castles, a cake sale and a soccer match for dads.'],
['holiday-club', 'Holiday club', 15, 'Four mornings of games, crafts and stories for ages 4 to 12.'],
['christmas-family-service', 'Christmas family service', 25, 'Our nativity, sung by the kids, followed by tea.'],
],
venue: '{name}',
},
'community-town': {
id: 'community-town', template: 'community', label: 'Community: a country-town church serving its district', alternate: true,
hero: { headline: 'Neighbours, friends, family', subline: 'The church in {city} that has been part of farm and town life for generations.', button: { label: 'Meet us on Sunday', href: '/visit' } },
serviceNote: 'Combined service on the last Sunday of the month, with a bring-and-share lunch.',
welcome: {
heading: 'Welcome to {name}', mission: 'Loving God and serving our district, farm and town alike.',
body: 'In a small town everyone knows everyone, and the church is where we meet in good times and hard ones. We pray for the rain, we help with the harvest festival, and when someone is in need we turn up with a casserole.',
quote: 'A small church can have a big heart. Come and see.',
},
ministriesIntro: 'Serving town and farm through the week.',
teamIntro: null,
invitation: { heading: 'You are always welcome here', text: 'Visiting the district? Join us on Sunday morning and stay for tea.', button: { label: 'Find us', href: '/contact' } },
visit: {
expect: 'A friendly, simple service with hymns and newer songs, a Bible message and prayers for the district. About an hour.',
kids: 'Children start in the service and go to Sunday school after the first songs.',
cta: 'Need a lift to church? Let us know.',
},
about: { story: 'The first service in {city} was held under a tree in the square. The church was built by local farmers and townspeople, stone by stone, and it is still the heart of the town.', quote: 'While the earth remains, seedtime and harvest shall not cease.', by: 'Genesis 8:22' },
give: 'Your gifts help us support families in the district through hard seasons (demo details only: this is not a real account).',
ministries: [
['sunday-school', 'Sunday school', 'Every Sunday for children of the town and the farms.'],
['youth', 'Youth', 'Friday evenings for high schoolers from the district.'],
['music', 'Choir and band', 'Old hymns and new songs, rehearsing on Thursdays.'],
['outreach', 'Farm outreach', 'Visits, food parcels and prayer for farmworker families.'],
],
leaders: [['Ds. Willem Coetzee', 'Minister'], ['Elsie Maritz', 'Sunday school'], ['Bongani Sithole', 'Farm outreach'], ['Marie Louw', 'Music']],
series: ['seasons', 'Seasons'],
messages: [['a-time-to-plant', 'A time to plant', 4, 'Ecclesiastes 3:1-8'], ['waiting-for-rain', 'Waiting for rain', 11, 'James 5:7-8'], ['the-harvest-is-plentiful', 'The harvest is plentiful', 18, 'Matthew 9:35-38']],
events: [
['harvest-festival', 'Harvest festival', 8, 'Produce, baking and crafts in the church hall, for the district\'s food bank.'],
['farm-carols', 'Carols on the farm', 20, 'An evening carol service at the Botha family\'s farm. Bring a chair.'],
['new-year-prayer', 'New Year prayer breakfast', 36, 'Pray for the year ahead over breakfast in the hall.'],
],
venue: '{name}',
},
'clean-modern': {
id: 'clean-modern', template: 'clean', label: 'Clean: a contemporary church, simply put', alternate: false,
hero: { headline: 'Faith for real life', subline: 'Sundays in {city}. Honest conversations, good coffee, and Jesus at the centre.', button: visitButton },
serviceNote: 'One service, about an hour. Kids programme included.',
welcome: {
heading: 'A church without the fuss', mission: 'Clear about Jesus. Open to questions.',
body: 'We keep things simple so the important things stand out. Our Sundays are thoughtful and relaxed, and our groups are a good place to ask the questions you have been carrying around.',
quote: 'Bring your questions. We are not afraid of them.',
},
ministriesIntro: 'A few things, done well.',
teamIntro: null,
invitation: { heading: 'See you on Sunday', text: 'No pressure, no spotlight. Just come.', button: visitButton },
visit: {
expect: 'A few songs, a talk that takes the Bible and your life seriously, and time to chat afterwards.',
kids: 'Kids have their own programme during the service, in age groups up to grade 7.',
cta: 'Prefer to message first?',
},
about: { story: '{short} began in 2015 with a simple idea: a church where it is normal to doubt, to ask and to grow. We are still that church.', quote: 'Come to me, all you who are weary and burdened, and I will give you rest.', by: 'Matthew 11:28' },
give: 'Giving is simple: by EFT or with a card at the welcome desk (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids', 'Age groups up to grade 7, every Sunday.'],
['students', 'Students', 'University and college students, Sunday evenings.'],
['music', 'Music', 'A small band leading simple, honest worship.'],
['alpha', 'Alpha', 'Ten weeks, a meal and a conversation about life and faith.'],
],
leaders: [['Daniel Joubert', 'Pastor'], ['Refilwe Mokoena', 'Kids'], ['Sam Abrahams', 'Music'], ['Nadia Govender', 'Alpha']],
series: ['questions', 'Questions'],
messages: [['why-suffering', 'Why is there suffering?', 3, 'Romans 8:18-28'], ['can-i-trust-the-bible', 'Can I trust the Bible?', 10, '2 Timothy 3:14-17'], ['who-is-jesus', 'Who is Jesus?', 17, 'Mark 8:27-30']],
events: [
['alpha-starts', 'Alpha starts', 9, 'Ten Thursday evenings with dinner. Ask anything.'],
['carols-and-coffee', 'Carols and coffee', 18, 'A short carol service and a coffee cart.'],
['christmas-day', 'Christmas Day', 28, 'One family service at 09:00, about 45 minutes.'],
],
venue: '{name}',
},
'clean-campus': {
id: 'clean-campus', template: 'clean', label: 'Clean: a church near the university', alternate: true,
hero: { headline: 'Students, staff and neighbours', subline: 'A church across the road from campus in {city}. Sunday evenings, with supper.', button: { label: 'First time?', href: '/visit' } },
serviceNote: 'Evening service with free supper afterwards during term.',
welcome: {
heading: 'Welcome to {short}', mission: 'Thinking hard, loving well, following Jesus.',
body: 'Most of us are students or work at the university, and plenty of us live in the streets around it. We meet on Sunday evenings, eat together, and spend the week in small groups across campus.',
quote: 'University is where you ask the big questions. Church is a good place to ask them out loud.',
},
ministriesIntro: 'Find your people.',
teamIntro: 'The staff team.',
invitation: { heading: 'Supper is on us', text: 'Every Sunday in term, after the evening service.', button: { label: 'Come for supper', href: '/visit' } },
visit: {
expect: 'The evening service has songs, a Bible talk and prayer, and ends with supper in the hall. It lasts about an hour before the food.',
kids: 'Staff and neighbours with children: there is a morning family service on the first Sunday of the month.',
cta: 'New to the city? We would love to help you settle in.',
},
about: { story: '{short} started as a student Bible study in a residence common room. It grew into a church for the whole campus community and the neighbourhood around it.', quote: 'Love the Lord your God with all your heart and with all your soul and with all your mind.', by: 'Matthew 22:37' },
give: 'If you are a student, please don\'t worry about giving. If you can, your gifts fund supper every Sunday (demo details only: this is not a real account).',
ministries: [
['families', 'Families', 'A monthly family service for staff and neighbours with children.'],
['res-groups', 'Residence groups', 'Bible studies in every residence, weeknights.'],
['music', 'Music', 'Student musicians lead the evening service.'],
['international', 'International students', 'A welcome, a meal and help settling in.'],
],
leaders: [['Dr Ian Mabaso', 'Pastor'], ['Lisa Roberts', 'Student worker'], ['Thabo Nkosi', 'Music'], ['Priya Singh', 'International students']],
series: ['big-questions', 'Big questions'],
messages: [['what-is-truth', 'What is truth?', 4, 'John 18:37-38'], ['does-god-care', 'Does God care?', 11, 'Psalm 139'], ['what-makes-a-good-life', 'What makes a good life?', 18, 'Micah 6:8']],
events: [
['exam-prayer', 'Exam prayer and pizza', 3, 'A break from studying: prayer, pizza and encouragement.'],
['end-of-term-dinner', 'End of term dinner', 12, 'A three-course dinner to celebrate the end of term.'],
['carols-on-campus', 'Carols on campus', 19, 'Carols on the library lawn for students who are still here.'],
],
venue: '{name}',
},
};
/** The profiles in the contracts' order (what the Hub offers). */
export const demoSeeds = (): DemoSeed[] => agent.WEBSITE_DEMO_PROFILES.map((id: WebsiteDemoProfile) => DEMO_SEEDS[id]);
-10
View File
@@ -161,13 +161,3 @@ export async function syncAll(ctx: Ctx) {
return { links: links.length, failed };
}
/** Every 15 minutes (ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback"). */
export function startFeedSync(ctx: Ctx): () => void {
if (!ctx.config.jobsEnabled) return () => {};
const run = () => syncAll(ctx).catch((e) => console.warn('[feed]', (e as Error).message));
const first = setTimeout(run, 20_000);
const timer = setInterval(run, 15 * 60 * 1000);
first.unref?.();
timer.unref?.();
return () => { clearTimeout(first); clearInterval(timer); };
}
+6 -12
View File
@@ -15,6 +15,8 @@ import { connectAccountsIfListed } from '../links/connect.js';
import { keyPair, saveLinkedProducts } from '../links/store.js';
import { hubPublicKey, verifyToken } from './licence.js';
import { storage } from '../admin/media.js';
import { lastBackupAt } from '../backups/backups.js';
import { jobsHealth } from '../jobs.js';
export const PROTOCOL_VERSION = 2;
const TIMEOUT_MS = 15000;
@@ -62,8 +64,10 @@ export async function health(ctx: Ctx) {
return {
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
db: await dbUp(ctx),
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
lastBackupAt: null,
// 1.4.0: the real job mode and failures, and the newest backup (before: always null, so the
// Hub warned "No backup reported").
jobs: await jobsHealth(ctx),
lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null,
disk: null,
errorsLast24h: null,
pendingMigrations: 0,
@@ -190,16 +194,6 @@ export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000
return { connected: false, reason: 'unreachable' };
}
/** Heartbeats every 15 minutes until stopped (pg-boss comes with the Website's other jobs). */
export function startHeartbeats(ctx: Ctx): () => void {
if (!ctx.config.jobsEnabled) return () => {};
const timer = setInterval(() => {
heartbeat(ctx).catch((e) => console.warn('[hub] Heartbeat failed:', (e as Error).message));
}, 15 * 60 * 1000);
timer.unref?.();
return () => clearInterval(timer);
}
/**
* "Get more storage" (WEBSITE-1.0-PLAN §10, decision 12; contracts 1.18.0): asks the Hub for more
* 5 GB steps. The Hub emails Cross Code; the new limit arrives with a later heartbeat answer.
+13 -12
View File
@@ -1,18 +1,18 @@
/**
* Starts the Church Website's backend: database, HTTP server, and (on a Hub install) registering
* with the Hub from HUB_LICENCE_KEY, then heartbeats, which also link the site to the church's
* Accounts once the Hub lists it, and the hourly YouTube feed (§7). The other jobs (storage emails,
* the event feed) come with their features (docs/WEBSITE-1.0-PLAN.md §1).
* with the Hub from HUB_LICENCE_KEY, then the background jobs (src/jobs.ts, 1.4.0): heartbeats,
* which also link the site to the church's Accounts once the Hub lists it, the event feed, the
* hourly YouTube feed (§7) and the nightly database backup.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from './generated/prisma/client.js';
import { createApp } from './app.js';
import { createCtx } from './context.js';
import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js';
import { connectFromEnv, heartbeat } from './hub/client.js';
import { startJobs } from './jobs.js';
import { loadConfig } from './lib/config.js';
import { startYoutubeSync } from './site/youtube.js';
import { startFeedSync } from './feed/feed.js';
import { ensureStarterPages } from './site/starter.js';
async function main() {
const config = loadConfig();
@@ -20,20 +20,21 @@ async function main() {
if (!url) throw new Error('DATABASE_URL isn\'t set.');
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
const ctx = createCtx(config, db);
// A new install's fixed pages (home, Plan your visit, …), before anything is served.
await ensureStarterPages(ctx)
.then((kinds) => { if (kinds.length) console.log(`[website] Added the starter pages: ${kinds.join(', ')}.`); })
.catch((e) => console.error('[website] Couldn\'t add the starter pages:', (e as Error).message));
const app = createApp(ctx);
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
const stopHeartbeats = startHeartbeats(ctx);
const stopYoutube = startYoutubeSync(ctx);
const stopFeed = startFeedSync(ctx);
// 1.4.0: the heartbeat, the event feed, YouTube and the nightly backup, on pg-boss.
const stopJobs = await startJobs(ctx, url);
connectFromEnv(ctx).then((r) => {
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
}).catch(() => {});
const stop = async () => {
stopHeartbeats();
stopYoutube();
stopFeed();
await stopJobs();
server.close();
await db.$disconnect();
process.exit(0);
+306
View File
@@ -0,0 +1,306 @@
/**
* Background jobs on pg-boss (1.4.0, as Accounts and Cross Events): one run per schedule however
* many processes run, and timers in this process if the queue can't start. JOBS_ENABLED=false
* turns them all off. Before 1.4.0 the heartbeat, the event feed and YouTube were plain timers.
*
* Admin → Background jobs shows each job's schedule and last runs, runs one now, and switches one
* on or off or changes its schedule. That choice is kept in the database (`job_overrides`), wins
* over the .env (a job's own flag, e.g. BACKUP_ENABLED=false, and JOB_SCHEDULE_<NAME>) and takes
* effect straight away (in other processes within 30 seconds).
*/
import { CronExpressionParser } from 'cron-parser';
import PgBoss from 'pg-boss';
import type { Ctx } from './context.js';
import { runBackupJob } from './backups/backups.js';
import { syncAll } from './feed/feed.js';
import { heartbeat } from './hub/client.js';
import { syncYoutube } from './site/youtube.js';
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
export const JOBS: Job[] = [
// A database backup every night (Settings → Backups), after Accounts' at 02:00 on the same server.
{ name: 'backup', label: 'Database backup', cron: '20 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
// ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback".
{ name: 'event-feed', label: 'Events from the church\'s other sites (Cross Events)', cron: '*/15 * * * *', env: 'FEED_JOB_ENABLED', run: (ctx) => syncAll(ctx) },
{ name: 'youtube', label: 'Messages: new videos from the church\'s YouTube channel', cron: '7 * * * *', env: 'YOUTUBE_JOB_ENABLED', run: (ctx) => syncYoutube(ctx) },
];
const SCHEMA = 'pgboss_website';
const OVERRIDES_KEY = 'job_overrides';
const OVERRIDES_TTL_MS = 30_000;
export type Override = { enabled?: boolean; cron?: string };
type Run = { state: string; createdOn?: Date | null; startedOn: Date | null; completedOn: Date | null; output: unknown };
/** The running queue or timers, the admin's choices (cached), and a short history for timer mode. */
type State = {
mode: 'queue' | 'timers' | 'off';
boss: PgBoss | null;
timers: Map<string, NodeJS.Timeout>;
history: Map<string, Run[]>;
overrides: Record<string, Override>;
overridesAt: number;
env: NodeJS.ProcessEnv;
};
const state: State = { mode: 'off', boss: null, timers: new Map(), history: new Map(), overrides: {}, overridesAt: 0, env: process.env };
/** Tests: a different environment for the env flags and schedules. */
export function useEnvForTest(env: NodeJS.ProcessEnv): void {
state.env = env;
}
const flag = (name: string | null) => {
if (!name) return true;
const v = state.env[name];
return v === undefined || v === '' ? true : String(v).toLowerCase() !== 'false';
};
export function isCron(cron: unknown, tz = 'Africa/Johannesburg'): cron is string {
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
try {
CronExpressionParser.parse(cron, { tz });
return true;
} catch {
return false;
}
}
export async function loadOverrides(ctx: Ctx, force = false): Promise<Record<string, Override>> {
if (!force && state.overridesAt && Date.now() - state.overridesAt < OVERRIDES_TTL_MS) return state.overrides;
try {
// Straight from the table: Settings caches for 30 s too, and a save must show at once here.
const row = await ctx.db.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
const parsed = row?.value ? JSON.parse(row.value) : {};
state.overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
state.overridesAt = Date.now();
} catch (e) {
if (force) console.warn('[jobs] Could not read the job overrides:', (e as Error).message);
}
return state.overrides;
}
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
export const envEnabled = (job: Job) => flag(job.env);
/** JOBS_ENABLED=false turns all off; then the admin's choice; then the job's env flag. */
export function isEnabled(ctx: Ctx, job: Job): boolean {
if (!ctx.config.jobsEnabled) return false;
const o = state.overrides[job.name];
if (o && typeof o.enabled === 'boolean') return o.enabled;
return envEnabled(job);
}
/** The .env's schedule (JOB_SCHEDULE_<NAME>, checked) or the job's own. */
export function envCronFor(ctx: Ctx, job: Job): string {
const v = state.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
if (v && isCron(v, ctx.config.timezone)) return v;
if (v) console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${v}"`);
return job.cron;
}
export function cronFor(ctx: Ctx, job: Job): string {
const o = state.overrides[job.name];
if (o && isCron(o.cron, ctx.config.timezone)) return o.cron;
return envCronFor(ctx, job);
}
export const nextRun = (cron: string, tz: string, from = new Date()) => CronExpressionParser.parse(cron, { tz, currentDate: from }).next().toDate();
function remember(name: string, run: Run) {
state.history.set(name, [run, ...(state.history.get(name) ?? [])].slice(0, 10));
}
async function runJob(ctx: Ctx, job: Job) {
return (await job.run(ctx)) ?? null;
}
function startTimer(ctx: Ctx, job: Job) {
const tz = ctx.config.timezone;
const scheduleNext = () => {
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
const delay = Math.max(1000, nextRun(cronFor(ctx, job), tz).getTime() - Date.now());
state.timers.set(job.name, setTimeout(async () => {
await loadOverrides(ctx);
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(ctx, job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: (e as Error).message };
console.warn(`[jobs] ${job.name}:`, (e as Error).message);
} finally {
entry.completedOn = new Date();
remember(job.name, entry);
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
}
async function applyJob(ctx: Ctx, job: Job) {
if (state.mode === 'queue' && state.boss) {
if (isEnabled(ctx, job)) await state.boss.schedule(job.name, cronFor(ctx, job), undefined, { tz: ctx.config.timezone });
else await state.boss.unschedule(job.name).catch(() => {});
} else if (state.mode === 'timers') {
clearTimeout(state.timers.get(job.name));
state.timers.delete(job.name);
startTimer(ctx, job);
}
}
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
if (!ctx.config.jobsEnabled) {
state.mode = 'off';
return async () => {};
}
await loadOverrides(ctx, true);
const tz = ctx.config.timezone;
try {
const boss = new PgBoss({ connectionString, schema: SCHEMA, application_name: 'crosscode-website-jobs' });
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
await boss.start();
state.boss = boss;
state.mode = 'queue';
for (const job of JOBS) {
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
// Every job has a worker (an admin can switch one on later); only those on are scheduled.
await boss.work(job.name, async (batch) => {
await loadOverrides(ctx);
const manual = (Array.isArray(batch) ? batch : [batch]).some((j) => (j as { data?: { manual?: boolean } })?.data?.manual);
if (!manual && !isEnabled(ctx, job)) return { skipped: 'switched off' };
return runJob(ctx, job);
});
if (isEnabled(ctx, job)) await boss.schedule(job.name, cronFor(ctx, job), undefined, { tz });
else await boss.unschedule(job.name).catch(() => {});
}
const off = JOBS.filter((j) => !isEnabled(ctx, j)).map((j) => j.name);
console.log(`[jobs] Job queue started: ${JOBS.filter((j) => isEnabled(ctx, j)).map((j) => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`);
return async () => { await boss.stop({ graceful: true }); state.boss = null; state.mode = 'off'; };
} catch (e) {
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
state.boss = null;
state.mode = 'timers';
for (const job of JOBS) startTimer(ctx, job);
return async () => { state.timers.forEach(clearTimeout); state.timers.clear(); state.mode = 'off'; };
}
}
export class JobError extends Error {
constructor(public status: number, message: string) { super(message); }
}
/**
* Saves an admin's choice for one job and applies it. `enabled` / `cron`: a value wins over the
* .env, null goes back to it, undefined leaves it.
*/
export async function setOverride(ctx: Ctx, name: string, change: { enabled?: unknown; cron?: unknown }): Promise<{ enabled: boolean | null; cron: string | null }> {
const job = JOBS.find((j) => j.name === name);
if (!job) throw new JobError(404, 'There\'s no such job.');
const { enabled, cron } = change;
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw new JobError(400, '"enabled" must be true, false or null.');
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim(), ctx.config.timezone))) {
throw new JobError(400, 'That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
}
const all = { ...(await loadOverrides(ctx, true)) };
const entry: Override = { ...(all[name] ?? {}) };
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled as boolean; }
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = (cron as string).trim(); }
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
const value = JSON.stringify(all);
await ctx.db.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
ctx.settings.forget();
state.overrides = all;
state.overridesAt = Date.now();
await applyJob(ctx, job);
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
}
/** Runs a job now: queued in queue mode (it runs even when switched off), here otherwise. */
export async function runNow(ctx: Ctx, name: string): Promise<{ queued: boolean; output?: unknown }> {
const job = JOBS.find((j) => j.name === name);
if (!job) throw new JobError(404, 'There\'s no such job.');
if (state.mode === 'queue' && state.boss) {
await state.boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
return { queued: true };
}
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(ctx, job);
entry.state = 'completed';
return { queued: false, output: entry.output };
} catch (e) {
entry.state = 'failed';
entry.output = { message: (e as Error).message };
throw new JobError(502, `The job failed: ${(e as Error).message}`);
} finally {
entry.completedOn = new Date();
remember(job.name, entry);
}
}
/** Each job with its switch, schedule, what the .env says, the admin's choice, and its last runs. */
export async function jobStatus(ctx: Ctx) {
await loadOverrides(ctx, true);
const tz = ctx.config.timezone;
const recent = new Map<string, Run[]>();
if (state.mode === 'queue') {
try {
// As in Cross Events: timestamptz as plain UTC, so Prisma's pg adapter doesn't drop the offset.
const rows = await ctx.db.$queryRawUnsafe<(Run & { name: string })[]>(`
SELECT name, state, created_on AT TIME ZONE 'UTC' AS "createdOn", started_on AT TIME ZONE 'UTC' AS "startedOn",
completed_on AT TIME ZONE 'UTC' AS "completedOn", output
FROM (
SELECT name, state::text, created_on, started_on, completed_on, output,
row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn
FROM ${SCHEMA}.job WHERE name = ANY($1::text[])
) ranked WHERE rn <= 10 ORDER BY "createdOn" DESC`, JOBS.map((j) => j.name));
for (const r of rows) recent.set(r.name, [...(recent.get(r.name) ?? []), r]);
} catch (e) {
console.warn('[jobs] Could not read the run history:', (e as Error).message);
}
} else {
for (const [name, list] of state.history) recent.set(name, list);
}
return {
mode: state.mode,
timezone: tz,
jobsEnabledEnv: ctx.config.jobsEnabled,
jobs: JOBS.map((job) => {
const cron = cronFor(ctx, job);
const enabled = isEnabled(ctx, job);
const o = state.overrides[job.name] ?? {};
return {
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
envEnabled: envEnabled(job), envCron: envCronFor(ctx, job), defaultCron: job.cron,
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron, tz) ? o.cron : null },
nextRun: enabled && state.mode !== 'off' ? nextRun(cron, tz) : null,
recent: recent.get(job.name) ?? [],
};
}),
};
}
/** What the Hub's heartbeat reports (hub.healthSchema `jobs`): the real mode and failed runs in 24 hours. */
export async function jobsHealth(ctx: Ctx): Promise<{ mode: 'queue' | 'timers' | 'off'; failedLast24h: number }> {
const since = ctx.now().getTime() - 24 * 3600e3;
if (state.mode === 'queue') {
try {
const rows = await ctx.db.$queryRawUnsafe<{ n: number | bigint }[]>(
`SELECT count(*)::int AS n FROM ${SCHEMA}.job WHERE state = 'failed' AND name = ANY($1::text[]) AND completed_on > now() - interval '24 hours'`,
JOBS.map((j) => j.name),
);
return { mode: 'queue', failedLast24h: Number(rows[0]?.n ?? 0) };
} catch {
return { mode: 'queue', failedLast24h: 0 };
}
}
let failed = 0;
for (const runs of state.history.values()) failed += runs.filter((r) => r.state === 'failed' && (r.completedOn?.getTime() ?? 0) > since).length;
return { mode: state.mode, failedLast24h: failed };
}
+6
View File
@@ -27,6 +27,10 @@ export type Config = {
allowPrivateLinks: boolean;
/** How long an admin stays signed in (days). */
sessionDays: number;
/** 1.4.0: for the backups' pg_dump (DATABASE_URL, as Prisma uses). */
databaseUrl: string | null;
/** 1.4.0: where backups go; default backend/backups (tests use their own folder). */
backupDir: string | null;
};
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
@@ -62,5 +66,7 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
uploadDir: env.UPLOAD_DIR?.trim() || null,
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
sessionDays: Math.min(90, Math.max(1, Number(env.SESSION_DAYS) || 14)),
databaseUrl: env.DATABASE_URL?.trim() || null,
backupDir: null,
};
}
+8 -4
View File
@@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import { buildPalette, type Palette } from './palette.js';
import { buildSnapshot, imageOf, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { buildSnapshot, imageOf, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
export type SiteEvent = {
@@ -50,6 +50,8 @@ type Common = {
style: { fontPairing: string; corners: string };
/** Search engines' verification codes, for the home page's meta tags (§11). */
verification: { google: string | null; bing: string | null };
/** 1.2.0: the site's own icon (Settings), else null: the church's icon, else one made for it. */
favicon: string | null;
};
export type SiteContent =
@@ -158,13 +160,15 @@ export async function previewContent(ctx: Ctx, opts: { asTemplate?: WebsiteTempl
}
async function contentFrom(ctx: Ctx, church: Church | null, published: { number: number; publishedAt: Date; snapshot: Snapshot } | null): Promise<SiteContent> {
const [google, bing] = await Promise.all([ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]);
const [google, bing, faviconId] = await Promise.all([ctx.settings.get('google_verification'), ctx.settings.get('bing_verification'), ctx.settings.get('favicon_media_id')]);
const verification = { google: google || null, bing: bing || null };
const icon = faviconId ? await ctx.db.mediaAsset.findUnique({ where: { id: faviconId } }) : null;
const favicon = icon ? mediaUrl(icon.filename) : null;
if (!published) {
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
return {
mode: 'coming-soon', template, church, ...brandFor(church, template), verification,
mode: 'coming-soon', template, church, ...brandFor(church, template), verification, favicon,
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
};
}
@@ -175,5 +179,5 @@ async function contentFrom(ctx: Ctx, church: Church | null, published: { number:
return [p.path, headerIsTransparent(template, snapshot.design.style.header, hero)];
}));
const [messages, events] = await Promise.all([liveMessages(ctx), liveEvents(ctx)]);
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), verification, messages, events };
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), verification, favicon, messages, events };
}
+88
View File
@@ -0,0 +1,88 @@
/**
* The fixed pages (WEBSITE-1.0-PLAN §6) with starter text, for a site that has no pages yet: a new
* install. Without them the home page had no sections (the site and its preview showed only the
* header and footer) and the other pages didn't exist. Terms and Safeguarding come from starter
* text too (§2), linked from the footer rather than the menu.
*
* Checked at startup (ensureStarterPages): a site with none of the fixed pages gets them all, one
* without a home page gets that. A page a church removed (archived) isn't brought back, except home,
* which can't be removed. Nothing is published: the pages are drafts like any other change. The text names no church, since a new install isn't
* always linked to its church profile yet; every section and block can be edited.
*/
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import type { SectionData } from './sections.js';
type Block = { type: string; data: Record<string, unknown> };
type StarterPage = { kind: string; slug: string; title: string; inNav?: boolean; description: string; sections: Block[] };
const VISIT = { label: 'Plan your visit', href: '/visit' };
export const STARTER_HOME: SectionData = {
hero: { headline: 'You are welcome here', subline: 'Join us this Sunday. Come as you are.', images: [], videoId: null, button: VISIT },
serviceTimes: { heading: 'Join us this Sunday', note: null },
welcome: {
heading: 'Welcome', mission: null, imageId: null, pastor: null,
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here.',
},
ministries: { heading: 'Find your place', intro: 'There is something for every age and stage.' },
team: { heading: 'Our team', intro: null },
events: { heading: 'Coming up', count: 3 },
latestMessage: { heading: 'Latest message' },
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: VISIT, imageId: null },
};
const text = (heading: string | null, body: string): Block => ({ type: 'text', data: { heading, body } });
export const STARTER_PAGES: StarterPage[] = [
{ kind: 'home', slug: 'home', title: 'Home', description: 'Join us this Sunday. Come as you are.', sections: Object.entries(STARTER_HOME).map(([type, data]) => ({ type, data })) },
{
kind: 'visit', slug: 'visit', title: 'Plan your visit', description: 'What to expect on your first Sunday with us.', sections: [
text('What to expect', 'We sing together, pray, and hear a message from the Bible. Dress is casual, and there is coffee after the service.'),
{ type: 'cta', data: { heading: 'Questions before you come?', text: 'Get in touch and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
],
},
{ kind: 'about', slug: 'about', title: 'About us', description: 'Our story, what we believe and what we value.', sections: [text('Our story', 'Tell your church\'s story here: how it started, what you believe and what you value.')] },
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', description: 'Find your place in our church family.', sections: [] },
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', description: 'The team who lead our church.', sections: [] },
{ kind: 'events', slug: 'events', title: 'Events', description: 'What is coming up at our church.', sections: [] },
{ kind: 'messages', slug: 'messages', title: 'Messages', description: 'Sunday messages from our church.', sections: [] },
{ kind: 'give', slug: 'give', title: 'Give', description: 'How to give to our church.', sections: [text('Giving', 'Thank you for giving. Add how to give here: your bank details, or links to SnapScan, Zapper or PayFast.')] },
{ kind: 'contact', slug: 'contact', title: 'Contact', description: 'How to find us and get in touch.', sections: [] },
{
kind: 'terms', slug: 'terms', title: 'Terms of use', inNav: false, description: 'The terms for using this website.', sections: [
text(null, 'This website is run by our church to share who we are, what we do and when we meet. You may use it for your own, personal purposes.\n\nWe do our best to keep it accurate and up to date, but things change: please check service times and events with us if you are unsure.\n\nLinks to other websites are for your convenience; we are not responsible for what they say.\n\nHow we handle personal information is in our privacy notice, linked at the bottom of every page.'),
],
},
{
kind: 'safeguarding', slug: 'safeguarding', title: 'Safeguarding', inNav: false, description: 'How we keep children and vulnerable adults safe.', sections: [
text(null, 'We are committed to the safety of every child and vulnerable adult in our care. Everyone who serves with children or vulnerable adults is screened and trained, and we follow a written safeguarding policy.\n\nIf you are worried about someone\'s safety, or about how anyone at our church has behaved, please speak to a member of our leadership team. If someone is in immediate danger, contact the police.'),
],
},
];
/**
* Adds the fixed pages a site is missing: all of them while it has none of them (only pages it made
* itself, or nothing at all), else just the home page if that's missing. A page whose address
* another page already has is left out. Custom pages move after them. Returns the kinds added.
*/
export async function ensureStarterPages(ctx: Ctx): Promise<string[]> {
const db = ctx.db;
const existing = await db.page.findMany({ select: { id: true, kind: true, slug: true, position: true, archivedAt: true } });
const fixed = existing.filter((p) => p.kind !== 'custom');
const wanted = fixed.length === 0 ? STARTER_PAGES : fixed.some((p) => p.kind === 'home' && !p.archivedAt) ? [] : STARTER_PAGES.filter((p) => p.kind === 'home');
const slugs = new Set(existing.map((p) => p.slug));
const adding = wanted.filter((p) => !slugs.has(p.slug));
if (!adding.length) return [];
// The site's own pages keep their order, after the fixed ones.
for (const p of existing.filter((x) => x.kind === 'custom')) await db.page.update({ where: { id: p.id }, data: { position: p.position + adding.length } });
let position = 0;
for (const p of adding) {
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: position++, description: p.description, inNav: p.inNav ?? true } });
let i = 0;
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, position: i++, data: s.data as never } });
}
const kinds = adding.map((p) => p.kind);
await audit(ctx, { actorId: null, actorRole: 'system', action: 'starter_pages_added', targetType: 'page', metadata: { kinds } });
return kinds;
}
-10
View File
@@ -99,13 +99,3 @@ export async function syncYoutube(ctx: Ctx, fetcher: Fetcher = (u) => fetch(u, {
return { added };
}
/** Every hour while the site runs (pg-boss comes with the other jobs). */
export function startYoutubeSync(ctx: Ctx): () => void {
if (!ctx.config.jobsEnabled) return () => {};
const run = () => syncYoutube(ctx).catch((e) => console.warn('[youtube]', (e as Error).message));
const first = setTimeout(run, 30_000);
const timer = setInterval(run, 60 * 60 * 1000);
first.unref?.();
timer.unref?.();
return () => { clearTimeout(first); clearInterval(timer); };
}
@@ -0,0 +1,175 @@
// 1.4.0: database backups (Settings → Backups) and the background jobs (Settings → Background
// jobs), as Accounts and Cross Events; the heartbeat reports both to the Hub.
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Readable } from 'node:stream';
import zlib from 'node:zlib';
import request from 'supertest';
import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, type Dumper } from '../src/backups/backups.js';
import { health } from '../src/hub/client.js';
import { JOBS, cronFor, isEnabled, jobsHealth, runNow, useEnvForTest } from '../src/jobs.js';
import { hashToken } from '../src/lib/crypto.js';
import { harness, SITE } from './support/harness.js';
type Role = 'owner' | 'admin' | 'editor';
const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() });
const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) });
after(() => useEnvForTest(process.env));
async function site() {
const h = await harness({ linked: false });
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-backups-'));
h.ctx.config.backupDir = dir;
h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/website_test';
const as = async (role: Role) => {
const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor'].indexOf(role) + 1}`;
await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role } });
await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const cookie = `ccw_session=token-${role}`;
return {
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie),
put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
};
};
return { ...h, dir, as };
}
describe('backups (1.4.0)', () => {
it('a backup is the gzipped dump, named as the crosscode script names them', async () => {
const h = await site();
const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Page" ();\n'));
assert.match(b.filename, BACKUP_FILE);
assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(h.dir, b.filename))).toString(), 'CREATE TABLE "Page" ();\n');
assert.equal(backupName(new Date(2026, 10, 27, 2, 20, 5)), 'website-20261127-022005.sql.gz');
const again = await runBackup(h.ctx, dumpOf('-- again\n'));
assert.notEqual(again.filename, b.filename, 'a second one in the same second gets its own name');
});
it('a dump that fails part-way leaves no file, and says why', async () => {
const h = await site();
await assert.rejects(runBackup(h.ctx, failing), /connection refused/);
assert.equal((await listBackups(h.ctx)).length, 0);
assert.match(String(await h.ctx.settings.get('backup_last_error')), /connection refused/);
await runBackup(h.ctx, dumpOf('-- fine\n'));
assert.equal(await h.ctx.settings.get('backup_last_error'), null);
});
it('only the newest are kept; a download only by a backup\'s own name', async () => {
const h = await site();
await h.ctx.settings.set('backup_retain_count', '2');
for (const n of [1, 2, 3]) await runBackup(h.ctx, dumpOf(`-- ${n}\n`));
const left = await listBackups(h.ctx);
assert.equal(left.length, 2);
assert.ok(backupPath(h.ctx, left[0]!.filename));
assert.equal(backupPath(h.ctx, '../.env'), null);
assert.equal(backupPath(h.ctx, 'accounts-20200101-000000.sql.gz'), null);
});
it('the nightly backup is skipped while it\'s turned off', async () => {
const h = await site();
await h.ctx.settings.set('backup_nightly', 'false');
assert.deepEqual(await runBackupJob(h.ctx), { skipped: true });
});
it('admins see, change and download them; editors can\'t', async () => {
const h = await site();
await runBackup(h.ctx, dumpOf('-- a backup\n'));
const editor = await h.as('editor');
assert.equal((await editor.get('/backups')).status, 403);
assert.equal((await editor.post('/backups/run')).status, 403);
assert.equal((await editor.get('/pages')).status, 200, 'the admin-only routes don\'t stop the others');
const admin = await h.as('admin');
const list = await admin.get('/backups');
assert.equal(list.status, 200, JSON.stringify(list.body));
assert.equal(list.body.nightly, true);
assert.equal(list.body.retain, 14);
const file = await admin.get(`/backups/${list.body.items[0].filename}/download`).buffer(true).parse((res, cb) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => cb(null, Buffer.concat(chunks)));
});
assert.equal(file.status, 200);
assert.equal(file.headers['cache-control'], 'no-store');
assert.equal(zlib.gunzipSync(file.body as Buffer).toString(), '-- a backup\n');
assert.equal((await admin.get('/backups/nope.sql.gz/download')).status, 404);
assert.equal(await h.db.auditLog.count({ where: { action: 'backup_downloaded' } }), 1);
assert.equal((await admin.put('/backups/settings', { retain: 0, nightly: true })).status, 400);
const saved = await admin.put('/backups/settings', { retain: 30, nightly: false });
assert.deepEqual(saved.body, { retain: 30, nightly: false, deleted: 0 });
assert.equal(await h.ctx.settings.bool('backup_nightly', true), false);
});
it('the heartbeat reports the newest backup and the real job mode (before: null, so the Hub warned)', async () => {
const h = await site();
assert.equal((await health(h.ctx)).lastBackupAt, null);
await runBackup(h.ctx, dumpOf('-- x\n'));
const report = await health(h.ctx);
assert.ok(report.lastBackupAt && Date.parse(report.lastBackupAt) > Date.now() - 60e3);
assert.deepEqual(report.jobs, await jobsHealth(h.ctx));
assert.equal(report.jobs.mode, 'off', 'no job system started in the tests');
});
});
describe('background jobs (1.4.0)', () => {
const backup = JOBS.find((j) => j.name === 'backup')!;
it('the heartbeat, the event feed, YouTube and the backup are jobs', () => {
assert.deepEqual(JOBS.map((j) => j.name).sort(), ['backup', 'event-feed', 'hub-heartbeat', 'youtube']);
});
it('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => {
const h = await site();
useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' });
h.ctx.config.jobsEnabled = true; // nothing is started here either way
const admin = await h.as('admin');
type Row = { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } };
let job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, false);
assert.equal(job.cron, '30 1 * * *');
assert.deepEqual(job.override, { enabled: null, cron: null });
const on = await admin.put('/jobs/backup', { enabled: true, cron: '0 3 * * *' });
assert.equal(on.status, 200, JSON.stringify(on.body));
assert.deepEqual(on.body.override, { enabled: true, cron: '0 3 * * *' });
assert.equal(isEnabled(h.ctx, backup), true);
assert.equal(cronFor(h.ctx, backup), '0 3 * * *');
job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, true);
assert.equal(job.envEnabled, false);
const back = await admin.put('/jobs/backup', { enabled: null, cron: null });
assert.deepEqual(back.body.override, { enabled: null, cron: null });
assert.equal(isEnabled(h.ctx, backup), false);
assert.equal(await h.db.auditLog.count({ where: { action: 'job_settings_changed' } }), 2);
useEnvForTest(process.env);
});
it('a bad schedule, a bad switch and an unknown job are refused; editors can\'t change jobs', async () => {
const h = await site();
const admin = await h.as('admin');
assert.equal((await admin.put('/jobs/backup', { cron: 'every night' })).status, 400);
assert.equal((await admin.put('/jobs/backup', { enabled: 'yes' })).status, 400);
assert.equal((await admin.put('/jobs/nope', { enabled: true })).status, 404);
const editor = await h.as('editor');
assert.equal((await editor.get('/jobs')).status, 403);
assert.equal((await editor.put('/jobs/backup', { enabled: false })).status, 403);
});
it('running one now runs it here (no queue in the tests) and remembers the run', async () => {
const h = await site();
h.ctx.config.databaseUrl = null;
await assert.rejects(runNow(h.ctx, 'backup'), /DATABASE_URL/);
const admin = await h.as('admin');
const ran = await admin.post('/jobs/youtube/run');
assert.equal(ran.status, 200, JSON.stringify(ran.body));
assert.deepEqual(ran.body, { queued: false, output: { added: 0, skipped: 'no source' } });
});
});
@@ -55,6 +55,18 @@ describe('settings, the menu and the audit log', () => {
assert.equal((await go('put', '/settings', { googleVerification: '<script>' })).status, 400);
});
it('sets the site icon from the media library, live at once, and takes it off again', async () => {
const { go, ctx, db } = await site();
assert.equal((await siteContent(ctx)).favicon, null, 'none: the site uses its default');
const m = await db.mediaAsset.create({ data: { filename: 'icon.png', mime: 'image/png', bytes: 100, width: 512, height: 512 } });
assert.equal((await go('put', '/settings', { faviconId: '00000000-0000-4000-8000-0000000000ff' })).body.error.fields.faviconId, 'That picture isn\'t in the media library');
const r = await go('put', '/settings', { faviconId: m.id });
assert.equal(r.body.faviconId, m.id);
assert.equal((await siteContent(ctx)).favicon, '/api/uploads/icon.png');
assert.equal((await go('put', '/settings', { faviconId: null })).body.faviconId, null);
assert.equal((await siteContent(ctx)).favicon, null);
});
it('orders the menu, and the audit log says who did what', async () => {
const { go, db } = await site();
const a = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', position: 1 } });
+64 -2
View File
@@ -4,8 +4,9 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
import { loadDemo } from '../src/demo/demoChurch.js';
import { WEBSITE_TEMPLATES, agent } from '@crosscode/contracts';
import { demoProfile, loadDemo, seedDesign } from '../src/demo/demoChurch.js';
import { DEMO_SEEDS, demoSeeds } from '../src/demo/seeds.js';
import { siteContent, spotifyEmbed, youtubeId } from '../src/site/content.js';
import { buildPalette, contrast, hexToRgb } from '../src/site/palette.js';
import { parseSectionData } from '../src/site/sections.js';
@@ -122,6 +123,67 @@ describe('the public site\'s content', () => {
});
}
for (const profile of agent.WEBSITE_DEMO_PROFILES) {
it(`1.3.0: loads the ${profile} demo, keeping the church's own profile and naming it`, async () => {
const h = await harness({ linked: false });
const dir = tmp();
const own = { ...demoProfile('http://x.test'), name: 'Grace Point Church', shortName: 'Grace Point', branding: { ...demoProfile('').branding, colours: { primary: '#8a1538', accent: '#f2c14e' } } };
await h.ctx.settings.set('church_profile_local', JSON.stringify(own));
await loadDemo(h.ctx, profile, { uploadDir: dir });
const c = await siteContent(h.ctx);
assert.equal(c.mode, 'published');
if (c.mode !== 'published') return;
const seed = DEMO_SEEDS[profile];
assert.equal(c.snapshot.design.template, seed.template);
assert.equal(c.church?.name, 'Grace Point Church', 'the organisation settings stay');
assert.equal(c.snapshot.pages.length, 9);
assert.equal(c.snapshot.ministries.length, 4);
assert.equal(c.messages.length, 3);
assert.equal(c.events.length, 3);
const all = JSON.stringify(c.snapshot);
assert.doesNotMatch(all, /\{(name|short|city)\}/, 'every placeholder is filled in');
assert.doesNotMatch(all, /Acacia/, 'nothing of the development church');
assert.equal(c.snapshot.design.variants.hero, seedDesign(seed.template, seed.alternate).variants.hero);
assert.match(fs.readFileSync(path.join(dir, 'demo', 'hero.svg'), 'utf8'), /#8a1538/, 'pictures in the church\'s colours');
});
}
it('1.3.0: the two profiles of a template differ, the second on its other recommended variants and header', () => {
for (const template of WEBSITE_TEMPLATES) {
const [a, b] = demoSeeds().filter((s) => s.template === template);
assert.ok(a && b && !a.alternate && b.alternate, template);
const alt = seedDesign(template, true);
assert.notDeepEqual(alt.variants, seedDesign(template, false).variants);
assert.notEqual(alt.style.header, seedDesign(template, false).style.header);
assert.notEqual(a.hero.headline, b.hero.headline);
}
});
it('1.3.0: a profile keeps the site icon and the settings, and clears the old content, slugs and preview links', async () => {
const h = await harness({ linked: false });
const dir = tmp();
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const icon = (await h.db.mediaAsset.create({ data: { filename: 'icon.png', mime: 'image/png', bytes: 10, width: 64, height: 64, alt: 'Icon' } })) as { id: string };
await h.ctx.settings.set('favicon_media_id', icon.id);
await h.ctx.settings.set('coming_soon_text', 'Soon!');
await h.db.slugHistory.create({ data: { slug: 'old-about', pageId: 'gone' } });
await loadDemo(h.ctx, 'community-town', { uploadDir: dir });
assert.ok(await h.db.mediaAsset.findUnique({ where: { id: icon.id } }), 'the site icon stays');
assert.equal(await h.ctx.settings.get('favicon_media_id'), icon.id);
assert.equal(await h.ctx.settings.get('coming_soon_text'), 'Soon!');
assert.equal(await h.db.mediaAsset.count(), 11, 'the ten pictures and the icon');
assert.equal(await h.db.slugHistory.count(), 0);
assert.equal((await siteContent(h.ctx)).church?.name, 'Acacia Hill Church', 'the profile saved by the first demo stays');
});
it('1.3.0: a profile on a site with no church profile at all saves the demo one, so the site has a name', async () => {
const h = await harness({ linked: false });
await loadDemo(h.ctx, 'clean-campus', { uploadDir: tmp() });
const c = await siteContent(h.ctx);
assert.equal(c.church?.name, 'Acacia Hill Church');
assert.ok(c.mode === 'published' && JSON.stringify(c.snapshot).includes('Welcome to Acacia Hill'));
});
it('serves the uploads, never a folder or outside it, and the content over HTTP', async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
@@ -0,0 +1,42 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { previewContent } from '../src/site/content.js';
import { ensureStarterPages, STARTER_PAGES } from '../src/site/starter.js';
import { harness } from './support/harness.js';
describe('a new install\'s starter pages', () => {
it('adds the fixed pages to a site with none, and the preview shows every homepage section', async () => {
const { ctx, db } = await harness({ linked: false });
assert.deepEqual(await ensureStarterPages(ctx), STARTER_PAGES.map((p) => p.kind));
const c = await previewContent(ctx);
assert.equal(c.mode, 'published');
if (c.mode !== 'published') return;
const home = c.snapshot.pages.find((p) => p.kind === 'home')!;
assert.deepEqual(home.sections.map((s) => s.type).sort(), ['events', 'hero', 'invitation', 'latestMessage', 'ministries', 'serviceTimes', 'team', 'welcome']);
// Every starter block fits its schema (a broken one would be left out of the site).
for (const p of STARTER_PAGES) assert.equal(c.snapshot.pages.find((x) => x.kind === p.kind)!.sections.length, p.sections.length, p.kind);
// Terms and Safeguarding are footer links, not menu items.
assert.equal(c.snapshot.pages.filter((p) => p.inNav).some((p) => p.kind === 'terms' || p.kind === 'safeguarding'), false);
// Only once.
assert.deepEqual(await ensureStarterPages(ctx), []);
assert.equal(await db.page.count(), STARTER_PAGES.length);
});
it('keeps the church\'s own pages, after the fixed ones, and skips an address they already use', async () => {
const { ctx, db } = await harness({ linked: false });
await db.page.create({ data: { kind: 'custom', slug: 'test', title: 'Test', position: 1 } });
await db.page.create({ data: { kind: 'custom', slug: 'give', title: 'Giving', position: 2 } });
const kinds = await ensureStarterPages(ctx);
assert.ok(kinds.includes('home') && !kinds.includes('give'));
const pages = await db.page.findMany({ orderBy: { position: 'asc' } });
assert.equal(pages[0]!.kind, 'home');
assert.deepEqual(pages.slice(-2).map((p) => p.slug), ['test', 'give']);
});
it('adds only a missing home page to a site that has its other fixed pages', async () => {
const { ctx, db } = await harness({ linked: false });
await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', archivedAt: new Date() } });
assert.deepEqual(await ensureStarterPages(ctx), ['home']);
assert.deepEqual(await ensureStarterPages(ctx), []);
});
});
+2 -2
View File
@@ -169,10 +169,10 @@ test("an event added and published shows on the site at once (its own Publish)",
});
test("the admin's screens are accessible", async ({ page, context }) => {
// Thirteen screens, each checked by axe.
// Fifteen screens, each checked by axe (1.4.0: Backups and Background jobs).
test.setTimeout(240_000);
await signIn(context, "owner");
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/messages", "/admin/events", "/admin/linked", "/admin/media", "/admin/publish", "/admin/settings", "/admin/people", "/admin/audit"]) {
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/messages", "/admin/events", "/admin/linked", "/admin/media", "/admin/publish", "/admin/settings", "/admin/people", "/admin/audit", "/admin/backups", "/admin/jobs"]) {
await page.goto(path);
await expect(page.getByRole("heading", { level: 1 })).toBeVisible();
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-frontend",
"version": "1.1.0",
"version": "1.4.0",
"private": true,
"description": "Church Website: the church's public site in its template, and the admin",
"scripts": {
+1 -1
View File
@@ -59,7 +59,7 @@ export function ImagePicker({ value, onChange, label }: { value: string | null;
<span className="block text-sm font-medium text-gray-800">{label}</span>
<div className="mt-1 flex items-center gap-3">
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-400">No image</span>}
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No image</span>}
</div>
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
{value && <Btn kind="link" onClick={() => onChange(null)}>Remove</Btn>}
+10 -2
View File
@@ -1,7 +1,7 @@
/** The admin's sections, in groups (the sidebar) with a line each (the dashboard's tiles). */
import {
Building2, CalendarDays, FileText, HandHeart, Image as ImageIcon, LayoutDashboard, Link2, Mic, Palette, ScrollText,
Send, Settings, UserCog, Users, type LucideIcon,
Building2, CalendarDays, DatabaseBackup, FileText, HandHeart, Image as ImageIcon, LayoutDashboard, Link2, Mic, Palette, ScrollText,
Send, Settings, Timer, UserCog, Users, type LucideIcon,
} from "lucide-react";
export type NavItem = { href: string; label: string; description: string; icon: LucideIcon; managers?: boolean };
@@ -41,6 +41,14 @@ export const NAV_GROUPS: { title: string | null; items: NavItem[] }[] = [
{ href: "/admin/audit", label: "Audit log", description: "Who changed what, and when", icon: ScrollText, managers: true },
],
},
{
// 1.4.0, as Accounts and Cross Events.
title: "Looking after it",
items: [
{ href: "/admin/backups", label: "Backups", description: "Copies of your site's database: back up now, download, how many to keep", icon: DatabaseBackup, managers: true },
{ href: "/admin/jobs", label: "Background jobs", description: "What runs on a schedule, and when: switch each on or off", icon: Timer, managers: true },
],
},
];
export const NAV: NavItem[] = NAV_GROUPS.flatMap((g) => g.items);
@@ -0,0 +1,87 @@
"use client";
/**
* Settings → Backups (1.4.0, as Accounts and Cross Events): the database backups on this server,
* every night and before every update. Back up now, download one, how many to keep. Owners and
* Admins only.
*/
import { useState } from "react";
import { DatabaseBackup, Download } from "lucide-react";
import { api } from "@/admin/api";
import { Btn, Field, Loading, Notice, Panel, Title, inputClass, useAction, useAdmin, when } from "@/admin/ui";
type BackupList = { items: { filename: string; size: number; createdAt: string }[]; nightly: boolean; retain: number; lastError: string | null };
const size = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`);
export default function Backups() {
const list = useAdmin<BackupList>("/backups");
const now = useAction();
const save = useAction();
const [nightly, setNightly] = useState<boolean | null>(null);
const [retain, setRetain] = useState<string | null>(null);
if (!list.data) return <Loading error={list.error} />;
const d = list.data;
const nightlyOn = nightly ?? d.nightly;
const keep = retain ?? String(d.retain);
return (
<>
<Title icon={DatabaseBackup} sub="Copies of your website's database, kept on this server only and never sent anywhere.">Backups</Title>
<div className="space-y-6">
<Panel title="Database backups" sub="Every night at 02:20, and before every update of your website. Your photos and files (the media library) aren't in them.">
{d.lastError && <div className="mb-4"><Notice tone="warning">The last backup didn&apos;t work: {d.lastError}</Notice></div>}
{now.message && <div className="mb-4"><Notice tone={now.message.tone}>{now.message.text}</Notice></div>}
<Btn kind="primary" busy={now.busy} onClick={async () => {
const b = await now.run(() => api<{ filename: string }>("/backups/run", { method: "POST" }));
if (b) now.setMessage({ tone: "success", text: `Backup made: ${b.filename}` });
list.reload();
}}>Back up now</Btn>
<form className="mt-6 space-y-4 border-t border-gray-200 pt-4" onSubmit={async (e) => {
e.preventDefault();
const r = await save.run(() => api<{ deleted: number }>("/backups/settings", { method: "PUT", body: { retain: Number(keep), nightly: nightlyOn } }));
if (r) save.setMessage({ tone: "success", text: r.deleted ? `Saved. ${r.deleted} older backup${r.deleted === 1 ? " was" : "s were"} deleted.` : "Saved." });
setNightly(null);
setRetain(null);
list.reload();
}}>
<label className="flex items-start gap-3">
<input type="checkbox" className="mt-1 h-4 w-4 rounded border-gray-300" checked={nightlyOn} onChange={(e) => setNightly(e.target.checked)} />
<span><span className="block text-sm font-medium text-gray-800">Back up every night</span><span className="block text-xs text-gray-500">Backups before each update are made either way.</span></span>
</label>
<div className="max-w-xs">
<Field label="Keep the newest" hint="Older backups are deleted (1 to 365)." error={save.fields.retain}>
<input type="number" min={1} max={365} className={inputClass} value={keep} onChange={(e) => setRetain(e.target.value)} />
</Field>
</div>
{save.message && <Notice tone={save.message.tone}>{save.message.text}</Notice>}
<Btn type="submit" busy={save.busy}>Save</Btn>
</form>
</Panel>
<Panel title="Backups on this server" sub="A backup holds your whole site and the names and email addresses of its editors: keep a downloaded copy somewhere safe, and delete it when you're done.">
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="text-gray-600"><tr><th className="py-2 pr-4 font-medium">Made</th><th className="py-2 pr-4 font-medium">Size</th><th className="py-2 font-medium"><span className="sr-only">Download</span></th></tr></thead>
<tbody className="divide-y divide-gray-200">
{d.items.map((b) => (
<tr key={b.filename}>
<td className="whitespace-nowrap py-2 pr-4">{when(b.createdAt)}</td>
<td className="py-2 pr-4 text-gray-600">{size(b.size)}</td>
<td className="py-2 text-right">
<a href={`/api/v1/admin/backups/${encodeURIComponent(b.filename)}/download`} download className="inline-flex items-center gap-1.5 text-brand-text underline-offset-4 hover:underline">
<Download className="h-3.5 w-3.5" aria-hidden /> Download<span className="sr-only"> the backup made {when(b.createdAt)}</span>
</a>
</td>
</tr>
))}
{!d.items.length && <tr><td colSpan={3} className="py-3 text-gray-600">No backups yet.</td></tr>}
</tbody>
</table>
</div>
</Panel>
</div>
</>
);
}
@@ -0,0 +1,159 @@
"use client";
/**
* Settings → Background jobs (1.4.0, as Accounts and Cross Events): what the server does on a
* schedule. Switch a job on or off, change when it runs (that choice wins over the server's .env
* and applies straight away), run one now, and see its last runs. Owners and Admins only.
*/
import { useState } from "react";
import { RefreshCw, Timer } from "lucide-react";
import { api } from "@/admin/api";
import { Btn, Loading, Notice, Panel, Title, cx, inputClass, useAction, useAdmin, when } from "@/admin/ui";
type JobRun = { state: string; createdOn?: string | null; startedOn: string | null; completedOn: string | null; output: unknown };
type JobInfo = {
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
envEnabled: boolean; envCron: string; defaultCron: string; override: { enabled: boolean | null; cron: string | null };
};
type JobList = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
const RUN_STATE: Record<string, string> = {
completed: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-800", active: "bg-blue-50 text-blue-800",
created: "bg-gray-100 text-gray-700", retry: "bg-amber-50 text-amber-900", cancelled: "bg-gray-100 text-gray-700",
};
const SCHEDULES = [
{ label: "Every 5 minutes", cron: "*/5 * * * *" }, { label: "Every 15 minutes", cron: "*/15 * * * *" },
{ label: "Every hour", cron: "0 * * * *" }, { label: "Daily at 02:20", cron: "20 2 * * *" }, { label: "Daily at 07:00", cron: "0 7 * * *" },
];
function describeCron(cron: string): string {
if (cron === "* * * * *") return "Every minute";
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
if (m) return `Every ${m[1]} minutes`;
const h = /^(\d+) \* \* \* \*$/.exec(cron);
if (h) return `Every hour at :${h[1]!.padStart(2, "0")}`;
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
if (d) return `Daily at ${d[2]!.padStart(2, "0")}:${d[1]!.padStart(2, "0")}`;
return cron;
}
function runText(r: JobRun): string {
if (r.output === null || r.output === undefined) return "";
if (r.state === "failed" && typeof r.output === "object" && r.output && "message" in r.output) return String((r.output as { message: unknown }).message);
try { return JSON.stringify(r.output); } catch { return ""; }
}
/** An on/off switch (role="switch", so screen readers hear on and off). */
function Toggle({ on, label, disabled, onChange }: { on: boolean; label: string; disabled?: boolean; onChange: (on: boolean) => void }) {
return (
<button type="button" role="switch" aria-checked={on} aria-label={label} disabled={disabled} onClick={() => onChange(!on)}
className={cx("relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50", on ? "bg-brand" : "bg-gray-400")}>
<span className={cx("inline-block h-5 w-5 rounded-full bg-white shadow transition-transform", on ? "translate-x-5" : "translate-x-0.5")} />
</button>
);
}
export default function Jobs() {
const list = useAdmin<JobList>("/jobs");
const act = useAction();
const [busy, setBusy] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
if (!list.data) return <Loading error={list.error} />;
const d = list.data;
const off = d.mode === "off";
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
setBusy(job.name);
const r = await act.run(() => api(`/jobs/${encodeURIComponent(job.name)}`, { method: "PUT", body: change }), done);
setBusy(null);
if (r) setEditing(null);
list.reload();
};
const runNow = async (job: JobInfo) => {
setBusy(job.name);
const r = await act.run(() => api<{ queued: boolean }>(`/jobs/${encodeURIComponent(job.name)}/run`, { method: "POST" }));
setBusy(null);
if (r) act.setMessage({ tone: "success", text: r.queued ? `"${job.label}" queued: it starts within a few seconds.` : `"${job.label}" ran.` });
setTimeout(() => list.reload(), r?.queued ? 4000 : 0);
};
return (
<>
<Title icon={Timer} sub="What the server does on a schedule. Your choice here wins over the server's settings and applies straight away."
actions={<Btn onClick={() => list.reload()}><RefreshCw className="h-4 w-4" aria-hidden /> Refresh</Btn>}>Background jobs</Title>
<Panel sub={`Times are ${d.timezone}. Each job runs once per schedule, however many server processes there are.`}>
<div className="space-y-3">
{off && <Notice tone="warning">All background jobs are switched off in the server&apos;s settings (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.</Notice>}
{d.mode === "timers" && <Notice tone="warning">The job queue couldn&apos;t start, so jobs run on simple timers in this process (history only since the last restart).</Notice>}
{act.message && <Notice tone={act.message.tone}>{act.message.text}</Notice>}
</div>
<ul className="mt-3 divide-y divide-gray-200 rounded-lg border border-gray-200">
{d.jobs.map((job) => {
const last = job.recent[0];
const mine = busy === job.name;
const isEditing = editing?.name === job.name;
return (
<li key={job.name} className="p-3">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<Toggle on={job.enabled} disabled={mine || off} label={`${job.label}: ${job.enabled ? "on" : "off"}`}
onChange={(on) => void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} />
<div className="mr-auto min-w-0">
<div className={cx("text-sm font-medium", job.enabled ? "text-gray-900" : "text-gray-600")}>{job.label}</div>
<div className="text-xs text-gray-600">
{job.enabled ? `${describeCron(job.cron)}${job.nextRun ? ` · next ${when(job.nextRun)}` : ""}` : "Off"}
{job.override.enabled !== null
? <> · {job.enabled ? "switched on" : "switched off"} here · <button type="button" disabled={mine} className="underline hover:text-gray-900" onClick={() => void save(job, { enabled: null }, `"${job.label}" follows the server's settings again.`)}>use the server&apos;s setting ({job.envEnabled ? "on" : "off"})</button></>
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the server's settings)` : ""}
</div>
</div>
{last && (
<button type="button" onClick={() => setOpen(open === job.name ? null : job.name)} aria-expanded={open === job.name}
className={cx("rounded px-2 py-0.5 text-xs", RUN_STATE[last.state] ?? "bg-gray-100 text-gray-700")}>
Last run: {last.state}{last.completedOn ? `, ${when(last.completedOn)}` : ""}
</button>
)}
<Btn disabled={mine} onClick={() => setEditing(isEditing ? null : { name: job.name, cron: job.cron })}>Schedule</Btn>
<Btn disabled={mine || off} busy={mine} onClick={() => void runNow(job)}>Run now</Btn>
</div>
{isEditing && (
<form className="mt-3 flex flex-wrap items-end gap-2 rounded-lg bg-gray-50 p-3" onSubmit={(e) => { e.preventDefault(); void save(job, { cron: editing.cron }, `"${job.label}": ${describeCron(editing.cron)}.`); }}>
<label className="block">
<span className="block text-xs font-medium text-gray-700">When it runs</span>
<select className={cx(inputClass, "mt-1 w-48")} value={SCHEDULES.some((s) => s.cron === editing.cron) ? editing.cron : ""} onChange={(e) => e.target.value && setEditing({ name: job.name, cron: e.target.value })}>
<option value="">Custom</option>
{SCHEDULES.map((s) => <option key={s.cron} value={s.cron}>{s.label}</option>)}
</select>
</label>
<label className="block">
<span className="block text-xs font-medium text-gray-700">Cron (minute hour day month weekday)</span>
<input className={cx(inputClass, "mt-1 w-48 font-mono")} value={editing.cron} onChange={(e) => setEditing({ name: job.name, cron: e.target.value })} />
</label>
<Btn type="submit" kind="primary" busy={mine}>Save</Btn>
{job.override.cron !== null && <Btn kind="link" disabled={mine} onClick={() => void save(job, { cron: null }, `"${job.label}" is back on ${describeCron(job.envCron)}.`)}>Back to {describeCron(job.envCron)}</Btn>}
</form>
)}
{open === job.name && (
<table className="mt-3 w-full text-left text-xs">
<thead className="text-gray-600"><tr><th className="py-1 pr-3 font-medium">Started</th><th className="py-1 pr-3 font-medium">Result</th><th className="py-1 font-medium">Details</th></tr></thead>
<tbody className="divide-y divide-gray-100">
{job.recent.map((r, i) => (
<tr key={i}>
<td className="whitespace-nowrap py-1 pr-3">{when(r.startedOn ?? r.createdOn ?? null)}</td>
<td className="py-1 pr-3"><span className={cx("rounded px-1.5 py-0.5", RUN_STATE[r.state] ?? "bg-gray-100 text-gray-700")}>{r.state}</span></td>
<td className="break-all py-1 font-mono text-gray-700">{runText(r)}</td>
</tr>
))}
</tbody>
</table>
)}
</li>
);
})}
</ul>
</Panel>
</>
);
}
@@ -8,9 +8,10 @@ import Link from "next/link";
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
import { Hourglass, ListOrdered, Search, Settings } from "lucide-react";
import { AppWindow, Hourglass, ListOrdered, Search, Settings } from "lucide-react";
import { ImagePicker } from "@/admin/media";
type Settings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
type Settings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null; faviconId: string | null };
type PageRow = { id: string; kind: string; title: string; inNav: boolean };
export default function SettingsPage() {
@@ -42,6 +43,18 @@ export default function SettingsPage() {
</div>
<p className="mt-3 text-sm text-gray-600">A Google Business Profile helps people find your church on Google Maps: set one up at business.google.com with the same address as your church details.</p>
</Panel>
<Panel icon={AppWindow} title="Site icon">
<p className="mb-3 text-sm text-gray-600">The little picture in the browser tab and bookmarks. Choose a square picture (512 × 512 pixels is best; a PNG can have a see-through background). Without one, your site uses your church&apos;s icon, or your church&apos;s initial on its colour. This goes live straight away.</p>
<div className="flex flex-wrap items-end gap-6">
<ImagePicker label="Icon" value={s.faviconId} onChange={(faviconId) => setForm({ ...form, faviconId })} />
{/* What the site shows now (the default when none is chosen). */}
<div className="text-sm text-gray-600">
<span className="block font-medium text-gray-800">In use now</span>
<img src={`/site-icon?saved=${encodeURIComponent(settings.data.faviconId ?? "none")}`} alt="" width={32} height={32} className="mt-1 h-8 w-8 rounded" />
</div>
</div>
{fields.faviconId && <p className="mt-2 text-sm text-red-700">{fields.faviconId}</p>}
</Panel>
<Panel icon={Hourglass} title="Coming soon">
<Field label="The line under “Coming soon”" hint="Shown until you first publish your site." error={fields.comingSoonText}>
<input className={inputClass} value={s.comingSoonText} maxLength={300} onChange={(e) => setForm({ ...form, comingSoonText: e.target.value })} />
@@ -26,7 +26,7 @@ const SECTIONS: Record<string, string> = { hero: "Top of the page", serviceTimes
const VARIANT_NAMES: Record<string, string> = {
photo: "Photo", video: "Video", collage: "Collage", split: "Split", text: "Text only", panel: "Panel", strip: "Inline strip", map: "With map",
"image-text": "Image and text", pastor: "With pastor", cards: "Cards", list: "List", bands: "Alternating bands", faces: "Faces", featured: "Featured",
calendar: "Calendar strip", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
calendar: "Calendar strip", card: "Card", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
};
const ALL_VARIANTS: Record<string, string[]> = {
hero: ["photo", "video", "collage", "split", "text"], serviceTimes: ["panel", "strip", "map"], welcome: ["text", "image-text", "pastor"], ministries: ["cards", "list", "bands"],
+10 -1
View File
@@ -6,12 +6,21 @@ import { brandAttributes } from "@crosscode/ui";
import { loadContent } from "@/site/load";
import { PreviewBar } from "@/site/PreviewBar";
/** A short, stable version for the icon's address. */
const iconVersion = (s: string) => {
let h = 0;
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
return (h >>> 0).toString(36);
};
export async function generateMetadata(): Promise<Metadata> {
const c = await loadContent();
const name = c.church?.name ?? "Church Website";
return {
title: { default: name, template: `%s · ${name}` },
icons: c.church?.branding.iconUrl ? { icon: c.church.branding.iconUrl } : undefined,
// 1.2.0: always an icon (app/site-icon): the site's own, the church's, or a default. The
// version changes with it, so browsers don't keep showing an old one.
icons: { icon: `/site-icon?v=${iconVersion(c.favicon ?? c.church?.branding.iconUrl ?? `${c.palette.brand}|${c.church?.shortName ?? c.church?.name ?? ""}`)}` },
// A preview is never indexed (§4).
...(c.mode === "published" && c.preview ? { robots: { index: false, follow: false } } : {}),
};
@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import { loadContent } from "@/site/load";
import { localRedirect } from "@/lib/localRedirect";
/**
* 1.2.0: the site's icon (favicon). The one chosen under Settings, else the church's icon from its
* profile, else a default made for the church: its initial on its brand colour (a cross when the
* church isn't known yet). The layout links here with a version, so a new icon shows at once.
*/
export async function GET() {
const c = await loadContent();
if (c.favicon) return localRedirect(c.favicon);
const shared = c.church?.branding.iconUrl;
if (shared && /^https:\/\//.test(shared)) return new NextResponse(null, { status: 303, headers: { Location: shared } });
return new NextResponse(defaultIcon(c.palette.brand, c.palette.onBrand, c.church?.shortName || c.church?.name || null), {
headers: { "Content-Type": "image/svg+xml", "Cache-Control": "public, max-age=300" },
});
}
const rgb = (v: string, otherwise: string) => (/^\d{1,3} \d{1,3} \d{1,3}$/.test(v) ? `rgb(${v.replace(/ /g, ",")})` : otherwise);
function defaultIcon(brand: string, onBrand: string, name: string | null): string {
const bg = rgb(brand, "rgb(31,78,121)");
const fg = rgb(onBrand, "#fff");
const initial = name?.trim().match(/\p{L}|\p{N}/u)?.[0]?.toUpperCase();
const mark = initial
? `<text x="32" y="44" text-anchor="middle" font-family="Georgia, 'Times New Roman', serif" font-size="38" font-weight="700" fill="${fg}">${initial.replace(/[<>&"']/g, "")}</text>`
: `<path d="M28 12h8v12h12v8H36v20h-8V32H16v-8h12z" fill="${fg}"/>`;
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="${bg}"/>${mark}</svg>`;
}
+5 -1
View File
@@ -72,7 +72,11 @@ export type SiteMessage = {
thumbnail: string | null;
};
type Common = { church: Church | null; palette: Palette; style: { fontPairing: string; corners: string }; verification?: { google: string | null; bing: string | null } };
type Common = {
church: Church | null; palette: Palette; style: { fontPairing: string; corners: string }; verification?: { google: string | null; bing: string | null };
/** 1.2.0: the site's own icon (Settings); absent from a backend before 1.2.0. */
favicon?: string | null;
};
export type ComingSoon = Common & { mode: "coming-soon"; template: Template; comingSoonText: string };
+37 -9
View File
@@ -1,6 +1,6 @@
# Versions — the latest release of everything
Last updated: 2026-11-26. Taken from the git tags, which is what a release is here (branch → merge →
Last updated: 2026-11-27. Taken from the git tags, which is what a release is here (branch → merge →
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
@@ -11,13 +11,13 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.1** | `events@3.7.1` | 2026-11-26 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.1.0** | `website@1.1.0` | 2026-11-26 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.3.0** | `website@1.3.0` | 2026-11-27 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 2026-11-26 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.5.0** | `agent@1.5.0` | 2026-11-23 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.18.0** | `contracts@1.18.0` | 2026-11-25 |
| Cross Code Hub | `events-hub` | **2.23.1** | `v2.23.1` | 2026-11-26 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.6.0** | `agent@1.6.0` | 2026-11-27 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.19.0** | `contracts@1.19.0` | 2026-11-27 |
| Cross Code Hub | `events-hub` | **2.25.0** | `v2.25.0` | 2026-11-27 |
| crosscode.co.za | `crosscode-site` | **1.7.0** | `v1.7.0` | 2026-11-26 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-23 (last change: uninstall, export and purge one product of a church) |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-27 (last change: `crosscode demo <church> website`) |
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
on each run, so merging to `main` and pushing releases it. Its changes are listed in
@@ -30,7 +30,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
| Website | `apps/website` | 1.1.0 (1.0.0–1.1.0 released 2026-11-26; installed for the demo church cross-demo2 (1.0.1) only, Hope Family Church next) |
| Website | `apps/website` | 1.3.0 (1.0.0–1.1.0 released 2026-11-26, 1.2.0 and 1.3.0 on 2026-11-27; installed for the demo church cross-demo2 (1.2.0) only, Hope Family Church next) |
| App | `apps/app` | 0.0.0 (not started, phase 6) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't
@@ -38,6 +38,34 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Hub 2.25.0 + Church Website 1.3.0 + agent 1.6.0 + contracts 1.19.0 + crosscode script
(2026-11-27):** demo clients and demo data for the Website. Hub: a customer can be a demo client:
every install a demo site (Accounts included, and any it gets later) and never billed (billing
off and locked, no invoice drafted, sent or made by hand). Any install can be marked as a demo
site; Events and the Website have demo data. One migration (`Customer.isDemo`, `demoSince`).
Website: eight demo churches, two per template, that replace the content only (the church's
profile from Accounts, the site settings, the site icon and the admins stay). Agent and script:
`crosscode demo <church> website --profile <p>`. No migrations outside the Hub. Checked:
contracts (271), agent (58), the Website's backend tests (115) and build, the script's bats
tests (107), the Hub's backend tests (283), frontend typecheck and lint. **Not deployed yet**:
the Hub needs `prisma migrate deploy`; demo sites need agent 1.6.0 and Website 1.3.0.
- **Hub 2.24.1 (2026-11-27):** Servers → Updates offers every product. Its tabs were a fixed list of
Cross Events and Accounts from before the Church Website, so Website installs couldn't be updated
in a batch there; now Events, Accounts, the Church Website, and the App once it has an install.
Frontend only, plus one error message. No migration. Checked: the backend tests (279), frontend
typecheck and lint. **Deployed 2026-11-27.**
- **Church Website 1.2.0 + Hub 2.24.0 (2026-11-27):** Website: a new install had no pages, so the
home page and its live preview showed only the header and footer (found on cross-demo2); the
backend now adds the fixed pages with starter text at startup (all of them to a site with none,
else a missing home page; never one a church removed), Terms and Safeguarding included. Settings →
Site icon (a favicon from the media library; else the church's icon, else its initial on its
colour). The Latest message's Card layout got its name. No migration. Hub: "Update everything to
latest" on a customer's Sites card plans every product that's behind in one batch (Accounts
first, one at a time, stopping at the first failure), scheduled or as an emergency, planned whole
or not at all; later products keep Accounts at the batch's new version. No migration. Checked:
the Website's backend tests (104), the admin e2e (11, with axe), typechecks and lint; the Hub's
backend tests (279), frontend typecheck and lint. **Hub 2.24.0 deployed 2026-11-27; Website
1.2.0 on cross-demo2 the same day** (its health check says 1.2.0, `/site-icon` serves the default).
- **Accounts 1.8.0 + Church Website 1.1.0 (2026-11-26):** both admins redesigned as Cross Events' admin
dashboard and settings. Accounts: `/admin` is an overview, People moved to `/admin/people`, a
grouped sidebar showing the part you're in. Website: an icon sidebar, a dashboard, steps to the
@@ -289,10 +317,10 @@ you deploy one.
| What | Running | Since | Notes |
|------|---------|-------|-------|
| Hub | 2.23.1 | 2026-11-26 | A church's Accounts version comes from its heartbeat in New install, and heartbeats keep the install record's version current. Before it, 2.23.0 (2026-11-26): release requirements carry forward (`requires accounts …` written once in WHATS-NEW.md) |
| Hub | 2.24.1 | 2026-11-27 | Servers → Updates offers every product (the Church Website too). Before it, 2.24.0 (2026-11-27): "Update everything to latest" on a customer's Sites card: every product that's behind, in one batch (Accounts first); before that, 2.23.1 (2026-11-26): a church's Accounts version comes from its heartbeat in New install, and heartbeats keep the install record's version current; 2.23.0 (2026-11-26): release requirements carry forward (`requires accounts …` written once in WHATS-NEW.md) |
| Agent on church-server1 | 1.5.0 | 2026-11-23 | Uninstalls one product of a church at a time |
| Agent on the central server | 1.5.0 | 2026-11-23 | Reads and changes frps's config from the Hub (no longer read-only; decision 35 superseded) |
| Cross Events (churches) | 3.6.1 | 2026-11-20 | Every install adopted onto the monorepo and signing in through Accounts |
| Accounts (churches) | 1.6.0 | 2026-11-20 | |
| cross-demo2 (demo church) | Accounts 1.7.1, Cross Events 3.7.1, Church Website 1.0.2 | 2026-11-26 | The first Church Website install (`demo2.crosscode.co.za`, added next to the church's Accounts) |
| cross-demo2 (demo church) | Accounts 1.7.1, Cross Events 3.7.1, Church Website 1.2.0 | 2026-11-27 | The first Church Website install (`demo2.crosscode.co.za`, added next to the church's Accounts) |
| crosscode.co.za | 1.6.1 | 2026-11-23 | Clearer web address choices on the Cross Events page |
+6 -4
View File
@@ -114,7 +114,7 @@
},
"apps/agent": {
"name": "@crosscode/agent",
"version": "1.5.0",
"version": "1.6.0",
"license": "UNLICENSED",
"dependencies": {
"@crosscode/contracts": "*",
@@ -360,15 +360,17 @@
},
"apps/website/backend": {
"name": "@crosscode/website-backend",
"version": "1.1.0",
"version": "1.4.0",
"hasInstallScript": true,
"dependencies": {
"@crosscode/auth-client": "*",
"@crosscode/contracts": "*",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"cron-parser": "^5.10.2",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"pg-boss": "^11.1.2",
"sharp": "^0.35.5",
"zod": "^4.6.7"
},
@@ -387,7 +389,7 @@
},
"apps/website/frontend": {
"name": "@crosscode/website-frontend",
"version": "1.1.0",
"version": "1.4.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
@@ -23183,7 +23185,7 @@
},
"packages/contracts": {
"name": "@crosscode/contracts",
"version": "1.18.0",
"version": "1.19.0",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/contracts",
"version": "1.18.0",
"version": "1.19.0",
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
"license": "UNLICENSED",
"type": "commonjs",
+28 -4
View File
@@ -819,13 +819,37 @@
"type": "string",
"pattern": "^[a-z][a-z0-9-]{1,30}$"
},
"profile": {
"product": {
"type": "string",
"enum": [
"small",
"events",
"ministry",
"multicampus"
"website"
]
},
"profile": {
"anyOf": [
{
"type": "string",
"enum": [
"small",
"events",
"ministry",
"multicampus"
]
},
{
"type": "string",
"enum": [
"heritage-parish",
"heritage-city",
"bold-youth",
"bold-plant",
"community-family",
"community-town",
"clean-modern",
"clean-campus"
]
}
]
},
"adminEmail": {
+39 -4
View File
@@ -59,9 +59,33 @@ export const DEMO_PROFILES = ["small", "events", "ministry", "multicampus"] as c
export const demoProfileSchema = z.enum(DEMO_PROFILES);
export type DemoProfile = z.infer<typeof demoProfileSchema>;
/**
* The Church Website's demo data sets (1.19.0, `apps/website/backend/src/demo/seeds.ts`): two per
* template, each its own kind of church, the second on the template's other recommended variants.
*/
export const WEBSITE_DEMO_PROFILES = [
"heritage-parish", "heritage-city",
"bold-youth", "bold-plant",
"community-family", "community-town",
"clean-modern", "clean-campus",
] as const;
export const websiteDemoProfileSchema = z.enum(WEBSITE_DEMO_PROFILES);
export type WebsiteDemoProfile = z.infer<typeof websiteDemoProfileSchema>;
/** The products with demo data (`seed-demo` jobs). */
export const DEMO_PRODUCTS = ["events", "website"] as const;
export const demoProductSchema = z.enum(DEMO_PRODUCTS);
export type DemoProduct = z.infer<typeof demoProductSchema>;
/** Each demo product's profiles. */
export const DEMO_PROFILES_BY_PRODUCT: Record<DemoProduct, readonly string[]> = { events: DEMO_PROFILES, website: WEBSITE_DEMO_PROFILES };
/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */
export const SEED_DEMO_MIN_AGENT = "1.2.0";
/** The first agent that runs `seed-demo` jobs for the Website (`product: "website"`; an older one refuses the unknown key). */
export const SEED_WEBSITE_DEMO_MIN_AGENT = "1.6.0";
/** The first agent that runs `env-read` and `env-set` jobs (an older one refuses the unknown types). */
export const ENV_JOBS_MIN_AGENT = "1.3.0";
@@ -135,11 +159,22 @@ export const jobArgsSchemas = {
/** `crosscode restart <church> [product] --json` (PM2 reload) */
restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }),
/**
* `crosscode demo <church> --profile <profile> [--admin-email <email>] --json`: replaces Cross
* Events' data with a demo set (a backup is taken first). The Hub only makes it for installs
* marked as demo sites. `adminEmail`: the account kept (default: the release's own choice).
* `crosscode demo <church> [website] --profile <profile> [--admin-email <email>] --json`: replaces
* Cross Events' data (or, 1.19.0 with `product: "website"`, the Website's content) with a demo
* set (a backup is taken first). The Hub only makes it for installs marked as demo sites.
* `adminEmail` (Events only): the account kept (default: the release's own choice). No `product`
* is Events, so older Hubs' jobs mean what they did.
*/
"seed-demo": z.strictObject({ church: shortNameSchema, profile: demoProfileSchema, adminEmail: z.email().max(254).optional() }),
"seed-demo": z.strictObject({
church: shortNameSchema,
product: demoProductSchema.optional(),
profile: z.union([demoProfileSchema, websiteDemoProfileSchema]),
adminEmail: z.email().max(254).optional(),
}).superRefine((a, ctx) => {
const product = a.product ?? "events";
if (!DEMO_PROFILES_BY_PRODUCT[product].includes(a.profile)) ctx.addIssue({ code: "custom", path: ["profile"], message: `${a.profile} isn't a ${product} demo` });
if (product === "website" && a.adminEmail) ctx.addIssue({ code: "custom", path: ["adminEmail"], message: "the Website's demo keeps every admin" });
}),
/**
* `crosscode env <church> <product> --json`: the product's .env values, secrets hidden (only
* whether they're set). The report's `result` is an {@link envReadResultSchema}.
+9
View File
@@ -165,6 +165,15 @@ describe("seed-demo jobs", () => {
expect(agent.JOB_TYPES).toContain("seed-demo");
expect(agent.CENTRAL_JOB_TYPES).not.toContain("seed-demo");
});
it("1.19.0: a Website demo names the product and takes only a Website profile", () => {
expect(args({ church: "hope", product: "website", profile: "bold-plant" })).toBe(true);
expect(args({ church: "hope", product: "events", profile: "small" })).toBe(true);
expect(args({ church: "hope", product: "website", profile: "small" })).toBe(false);
expect(args({ church: "hope", profile: "bold-plant" })).toBe(false);
expect(args({ church: "hope", product: "website", profile: "clean-campus", adminEmail: "jane@hope.test" })).toBe(false);
expect(args({ church: "hope", product: "accounts", profile: "small" })).toBe(false);
expect(agent.WEBSITE_DEMO_PROFILES).toHaveLength(8);
});
});
describe("env-read and env-set jobs (1.12.0)", () => {
+1 -1
View File
@@ -96,7 +96,7 @@ crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" r
crosscode adopt <church> --events-dir <old folder> move an existing Cross Events install here
crosscode adopt <church> --undo go back to the old folder (within 14 days)
crosscode restart <church> [events] reload the PM2 processes
crosscode demo <church> --profile <profile> replace Events' data with a demo set
crosscode demo <church> [website] --profile <p> replace Events' (or the Website's) data with a demo
crosscode env <church> <product> [--set NAME=value] show or change a product's .env values
crosscode export <church> [product …] --out <zip> the church's data and uploads
crosscode uninstall <church> [product …] --confirm <church>
+46 -1
View File
@@ -10,6 +10,12 @@ crosscode demo <church> --profile <profile> [--admin-email <email>]
replace Cross Events' data with a demo set
(small, events, ministry, multicampus); a backup
is taken first, one admin account is kept
crosscode demo <church> website --profile <profile>
replace the Website's content with a demo church
(heritage-parish, heritage-city, bold-youth,
bold-plant, community-family, community-town,
clean-modern, clean-campus); a backup is taken
first; the church's profile, settings and admins stay
crosscode env <church> <product> the product's .env values (secrets hidden)
crosscode env <church> <product> [--file backend/.env] --set NAME=value … [--unset NAME …] [--restart]
change values (a copy is kept; never secrets or
@@ -83,22 +89,32 @@ cmd_restart() {
}
DEMO_PROFILES="small events ministry multicampus"
# The Website's (contracts WEBSITE_DEMO_PROFILES): two per template.
WEBSITE_DEMO_PROFILES="heritage-parish heritage-city bold-youth bold-plant community-family community-town clean-modern clean-campus"
# Replaces Events' data with a demo set (apps/events/backend/scripts/set-demo.js), as the site's
# user (its .env is readable only by that user). The Hub sends it only for installs marked as demo
# sites. Afterwards Events is reloaded: the demo switches campuses on or off.
# `crosscode demo <church> website --profile <p>`: the Website's content instead (cmd_demo_website).
cmd_demo() {
local church="" profile="" email="" dir user app
local church="" product="events" profile="" email="" dir user app
while [ $# -gt 0 ]; do
case "$1" in
--profile) [ $# -ge 2 ] || die "--profile needs a value."; profile="$2"; shift 2 ;;
--admin-email) [ $# -ge 2 ] || die "--admin-email needs a value."; email="$2"; shift 2 ;;
-h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help demo)." ;;
events|website) [ -n "$church" ] || die "Name the church first (crosscode demo hope website …)."; product="$1"; shift ;;
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
esac
done
[ -n "$church" ] || die "Name the church."
if [ "$product" = website ]; then
[[ " $WEBSITE_DEMO_PROFILES " == *" $profile "* ]] || die "--profile: one of $WEBSITE_DEMO_PROFILES."
[ -z "$email" ] || die "--admin-email: the Website's demo keeps every admin."
cmd_demo_website "$church" "$profile"
return
fi
[[ " $DEMO_PROFILES " == *" $profile "* ]] || die "--profile: one of $DEMO_PROFILES."
[ -z "$email" ] || [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || die "--admin-email: not an email address."
require_root
@@ -128,6 +144,35 @@ cmd_demo() {
die "Events didn't answer after the reload (sudo -u $user pm2 logs)."
}
# The Website's demo (Website 1.3.0+, backend/src/demo/seeds.ts): its content replaced with one of
# the eight demo churches, keeping the church's profile, the site settings and the admins. Backup
# first; then reloaded, so nothing cached from before is shown.
cmd_demo_website() {
local church="$1" profile="$2" dir user app
require_root
load_church "$church"
church_has_product website || die "$church has no Church Website."
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/website.sh"
dir="$(pvar website DIR)"
user="$(pvar website USER)"
app="$(website_app "$dir")"
[ -f "$app/backend/src/demo/seeds.ts" ] || die "This release of the Website ($(checkout_ref "$dir" website)) has no demo profiles (1.3.0 or later has)."
step "Website: backup first"
website_backup "$dir" "$user" || die "The backup failed, so the demo wasn't loaded."
step "Website: demo ($profile)"
run_as "$user" "$app/backend" npm run --silent demo -- --profile "$profile" --force ||
die "The demo wasn't loaded (see above). If it got as far as changing anything, the backup from just now has the content from before."
step "Website: reloading PM2"
website_reload "$dir" "$user"
step "Website: waiting for it to answer"
wait_for_version "$(website_health_url)" "$(website_expected_version "$dir")" 60 ||
die "The Website didn't answer after the reload (sudo -u $user pm2 logs)."
}
# crosscode env <church> <product>: the product's .env values, secrets hidden (the Hub's env-read).
# With --set / --unset (the Hub's env-set): changes one file (--file, default backend/.env), keeping
# a copy first; when the frontend's file changed, the frontend is rebuilt (Next.js builds its values
+41 -8
View File
@@ -17,6 +17,15 @@ setup() {
export CROSSCODE_HOME="$TMP/home"
mkdir -p "$CROSSCODE_HOME/products" "$TMP/sites/hope/events/apps/events/backend/scripts"
touch "$TMP/sites/hope/events/apps/events/backend/scripts/set-demo.js"
mkdir -p "$TMP/sites/hope/website/apps/website/backend/src/demo"
touch "$TMP/sites/hope/website/apps/website/backend/src/demo/seeds.ts"
cat > "$CROSSCODE_HOME/products/website.sh" <<EOF2
website_app() { printf '%s/apps/website' "\$1"; }
website_backup() { echo "backup \$2" >> "$CALLS"; [ -z "\${FAIL_BACKUP:-}" ]; }
website_reload() { echo "reload \$2" >> "$CALLS"; }
website_health_url() { echo http://127.0.0.1:5300/api/health; }
website_expected_version() { echo 1.3.0; }
EOF2
cat > "$CROSSCODE_HOME/products/events.sh" <<EOF
events_app() { printf '%s/apps/events' "\$1"; }
events_backup() { echo "backup \$2" >> "$CALLS"; [ -z "\${FAIL_BACKUP:-}" ]; }
@@ -26,9 +35,9 @@ events_expected_version() { echo 2.4.1; }
EOF
require_root() { :; }
load_church() { [ "$1" = hope ] || die "There's no church $1 here."; }
church_has_product() { [ "$1" = events ]; }
pvar() { case "$2" in DIR) echo "$TMP/sites/hope/events" ;; USER) echo cc-hope ;; esac; }
checkout_ref() { echo events@2.4.1; }
church_has_product() { [ "$1" = events ] || [ "$1" = website ]; }
pvar() { case "$2" in DIR) echo "$TMP/sites/hope/$1" ;; USER) echo "cc-hope-$1" ;; esac; }
checkout_ref() { echo "$2@1.0.0"; }
wait_for_version() { echo "wait $2" >> "$CALLS"; }
run_as() { local user="$1" dir="$2"; shift 2; echo "run $user ${dir#"$TMP"/} $*" >> "$CALLS"; [ -z "${FAIL_SEED:-}" ]; }
}
@@ -49,23 +58,23 @@ EOF
@test "backup, then the demo as the site's user (no prompt), then a reload" {
run cmd_demo hope --profile ministry
[ "$status" -eq 0 ]
[ "$(cat "$CALLS")" = "backup cc-hope
run cc-hope sites/hope/events/apps/events/backend env node scripts/set-demo.js --profile=ministry --yes
reload cc-hope
[ "$(cat "$CALLS")" = "backup cc-hope-events
run cc-hope-events sites/hope/events/apps/events/backend env node scripts/set-demo.js --profile=ministry --yes
reload cc-hope-events
wait 2.4.1" ]
}
@test "the admin to keep goes in DEMO_ADMIN_EMAIL (older releases only read that)" {
run cmd_demo hope --profile small --admin-email jane@hope.test
[ "$status" -eq 0 ]
grep -qx 'run cc-hope sites/hope/events/apps/events/backend env DEMO_ADMIN_EMAIL=jane@hope.test node scripts/set-demo.js --profile=small --yes' "$CALLS"
grep -qx 'run cc-hope-events sites/hope/events/apps/events/backend env DEMO_ADMIN_EMAIL=jane@hope.test node scripts/set-demo.js --profile=small --yes' "$CALLS"
}
@test "a failed backup stops it before the data is touched" {
FAIL_BACKUP=1 run cmd_demo hope --profile small
[ "$status" -eq 1 ]
[[ "$output" == *"The backup failed"* ]]
[ "$(cat "$CALLS")" = "backup cc-hope" ]
[ "$(cat "$CALLS")" = "backup cc-hope-events" ]
}
@test "a failed demo isn't followed by a reload" {
@@ -81,3 +90,27 @@ wait 2.4.1" ]
[[ "$output" == *"has no demo data"* ]]
[ ! -s "$CALLS" ]
}
@test "website: backup, then the demo profile as the site's user, then a reload" {
run cmd_demo hope website --profile bold-plant
[ "$status" -eq 0 ]
[ "$(cat "$CALLS")" = "backup cc-hope-website
run cc-hope-website sites/hope/website/apps/website/backend npm run --silent demo -- --profile bold-plant --force
reload cc-hope-website
wait 1.3.0" ]
}
@test "website: only its own profiles, no admin email, and only a release that has them" {
run cmd_demo hope website --profile small
[ "$status" -eq 1 ]
[[ "$output" == *"heritage-parish"* ]]
run cmd_demo hope website --profile clean-campus --admin-email jane@hope.test
[ "$status" -eq 1 ]
run cmd_demo hope --profile clean-campus
[ "$status" -eq 1 ]
rm "$TMP/sites/hope/website/apps/website/backend/src/demo/seeds.ts"
run cmd_demo hope website --profile clean-campus
[ "$status" -eq 1 ]
[[ "$output" == *"no demo profiles"* ]]
[ ! -s "$CALLS" ]
}