Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5e3a6bb6c | ||
|
|
2e8e4c04ca | ||
|
|
7391f97cfa | ||
|
|
c8e270dbf1 | ||
|
|
b2a163bb39 | ||
|
|
2eef8d1da3 | ||
|
|
dfd7278f7b | ||
|
|
aacfd228a6 | ||
|
|
e32d9ecb09 | ||
|
|
49153e6f07 | ||
|
|
5b9dc559b6 | ||
|
|
ad488c3280 |
@@ -2,6 +2,85 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## agent@1.7.0 + contracts@1.23.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in the server agent (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
|
||||
|
||||
- **Contracts 1.23.0:** the `seed-scenario` job (`church`, `scenario`, optional `adminEmail`; 45
|
||||
minutes): a whole demo scenario in one job, on whatever the church has installed.
|
||||
`SEED_SCENARIO_JOB_MIN_AGENT` (1.7.0). Additive.
|
||||
- **Agent 1.7.0:** `seed-scenario` → `crosscode demo <church> --scenario <s>`; `seed-demo` for `accounts` and `app` (`crosscode demo <church> <product> …`),
|
||||
and `scenario` passed on as `--scenario` for every product (contracts `SEED_SCENARIO_MIN_AGENT`,
|
||||
`SEED_APP_DEMO_MIN_AGENT`). Events' jobs keep their old form (no product).
|
||||
- **crosscode script:** `crosscode demo <church> --scenario <s>` (no product, no profile) loads the
|
||||
scenario on every product the church has here, in deploy order, skipping the others; checks
|
||||
every installed release against the scenario minimums first; each product takes its own
|
||||
backup; the first failure stops the rest and names what's out of step (`loaded`, `skipped` in
|
||||
the report). Events' demo is now `cmd_demo_events`. `crosscode demo <church> app …` says the
|
||||
App's demo comes with App 1.0.0, instead of misreading `app` as a second church.
|
||||
|
||||
## website@1.8.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in the Church Website (docs/APP-1.0-PLAN.md §12, "Demo scenarios"). No
|
||||
migration. Details in `apps/website/CHANGELOG.md`.
|
||||
|
||||
- **Website 1.8.0:** `npm run demo -- --profile <p> --scenario <p>` loads a profile as part of its
|
||||
demo scenario: the leaders are the scenario's people (`@crosscode/demo`), the pastor the home
|
||||
page's and the messages' speaker; with a linked Cross Events, Events' events show through the
|
||||
feed (Show events from, fetched at once) instead of the profile's own.
|
||||
- **crosscode script:** `crosscode demo <church> website … --scenario <p>` passes it on and refuses a
|
||||
Website before 1.8.0; the Website installs and builds `packages/demo`.
|
||||
|
||||
## contracts@1.22.0 - 2026-11-30
|
||||
|
||||
Bible translations for the Church App's devotionals (docs/BIBLE-PERMISSIONS.md, APP-1.0-PLAN.md §6
|
||||
and decision 14). Additive except for the notice texts and one translation's name; no id changes,
|
||||
nothing has shown them yet.
|
||||
|
||||
- **Only free translations in 1.0:** each translation has a `licence` ("public-domain" or
|
||||
"permission"); `FREE_BIBLE_TRANSLATION_IDS` (KJV, BSB) is what the Hub and the App offer, and
|
||||
`checkDevotionalCsv(text, { translations })` refuses any other, naming the publisher to ask.
|
||||
- **The Berean Standard Bible (`BSB`)**, public domain since 2023, YouVersion 3034. The CSV template
|
||||
and the devotionals sample now quote the BSB and the KJV.
|
||||
- **Notices corrected** to each publisher's current wording: NLT (Tyndale House Ministries), ESV
|
||||
(ESV Text Edition: 2025, the Creative Commons and translation clauses), AFR53 and AFR83 (the
|
||||
Bible Society's digital short form). The NIV and NKJV notices were already right.
|
||||
- **`AFR83` is named "Afrikaans 1983/1992-vertaling"**, as the Bible Society names it.
|
||||
- **New per translation:** `acknowledgement` (the full notice, for the App's Acknowledgements
|
||||
page), `disclaimer` (the Bible Society's, required with its translations next to content it
|
||||
hasn't approved; null for the others), `publisher` and `permissionsUrl` (null for the KJV).
|
||||
- **`FREE_QUOTE_VERSES`** (500) and **`quotedVerses(passages)`**: verses quoted per translation,
|
||||
so the Hub and the App can warn before the free allowance runs out. `devotionalDisclaimer`.
|
||||
|
||||
## events@3.8.0 + @crosscode/demo 1.1.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in Cross Events (docs/APP-1.0-PLAN.md §8 and §12). One migration.
|
||||
Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
- **Events 3.8.0:** STOP stops all WhatsApp (not only news), checked before every message, kept by
|
||||
number and per account (`whatsapp_opted_out` from Accounts), passed on to Accounts
|
||||
(`whatsapp.optout`); START turns it back on without Accounts. The eight demo scenarios
|
||||
(`set-demo.js --profile=<scenario>`), built around the scenario's own people and campuses.
|
||||
- **`@crosscode/demo` 1.1.0:** each person's `gender` (for Events' gendered events and cabins).
|
||||
- **crosscode script:** Events takes the scenarios as demo profiles; Events installs and builds
|
||||
`packages/demo`.
|
||||
|
||||
## accounts@1.9.0 + @crosscode/demo 1.0.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in Accounts (docs/APP-1.0-PLAN.md §8 and §12). One migration. Details
|
||||
in `apps/accounts/CHANGELOG.md`.
|
||||
|
||||
- **Accounts 1.9.0:** `messaging.get` and the `messaging.changed` hint (the App sends with the
|
||||
church's one set of email and WhatsApp settings); the WhatsApp opt-out for every product
|
||||
(`whatsapp.optout`, its own WAWP webhook for a church without Events, `whatsapp_opted_out` in
|
||||
`user.updated`, "Turn WhatsApp back on" on the account page); a demo scenario's church profile,
|
||||
logo, icon and people (`npm run demo -- --profile <scenario> --force`).
|
||||
- **`@crosscode/demo` 1.0.0** (new, `packages/demo`, not tagged): the eight scenarios' churches,
|
||||
people (same `sub` in every product) and SVG logos, for every product's demo loader.
|
||||
- **crosscode script:** `crosscode demo <church> accounts --profile <scenario>` (backup, load,
|
||||
reload); `--scenario <s>` on every demo (the profile must be the scenario's); Accounts installs
|
||||
and builds `packages/demo`.
|
||||
|
||||
## contracts@1.21.0 - 2026-11-30
|
||||
|
||||
Demo scenarios (docs/APP-1.0-PLAN.md §12, "Demo scenarios"): one choice on a demo client in the
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
# Cross Code platform
|
||||
|
||||
The monorepo for the Cross Code products that come after Cross Events, and the formats they share.
|
||||
The plan for every product is in [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) (decided 2026-11-03); where
|
||||
things stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md).
|
||||
The monorepo for every Cross Code product except the Hub, and the formats they share. The plan for
|
||||
every product is in [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) (decided 2026-11-03); where things
|
||||
stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md), and the latest release of everything in
|
||||
[`docs/VERSIONS.md`](./docs/VERSIONS.md).
|
||||
|
||||
| Folder | What | Status |
|
||||
|--------|------|--------|
|
||||
| `packages/contracts` | `@crosscode/contracts`: the shared JSON formats (zod schemas, JSON Schema, TypeScript types, sample payloads) used by every product, including Cross Events and the Hub | Phase 0, in progress |
|
||||
| `packages/ui` | `@crosscode/ui`: shared UI for the Website, App and Accounts | Placeholder, filled in during the Website phase |
|
||||
| `apps/accounts` | Accounts: the per-church sign-in (OpenID Connect) | Placeholder (phase 3) |
|
||||
| `apps/website` | Church Website | Placeholder (phase 5) |
|
||||
| `apps/app` | Church App (PWA) | Placeholder (phase 6) |
|
||||
| `apps/events` | Cross Events (moved in from `joshua/hope-events` in 2.2.0) | Released and in use |
|
||||
| `apps/accounts` | Accounts: the per-church sign-in (OpenID Connect), the church profile | Released and in use |
|
||||
| `apps/website` | Church Website | Released and in use (phase 5) |
|
||||
| `apps/app` | Church App (PWA, House of Prayer) | Placeholder, being built (phase 6, [`docs/APP-1.0-PLAN.md`](./docs/APP-1.0-PLAN.md)) |
|
||||
| `apps/agent` | The server agent: runs the Hub's signed jobs through the `crosscode` script | Released and in use |
|
||||
| `packages/contracts` | `@crosscode/contracts`: the shared JSON formats (zod schemas, JSON Schema, TypeScript types, sample payloads) used by every product, including the Hub | Released and in use |
|
||||
| `packages/auth-client` | `@crosscode/auth-client`: how a product signs in through Accounts | In use |
|
||||
| `packages/seo` | `@crosscode/seo`: JSON-LD and meta for every public site | In use |
|
||||
| `packages/ui` | `@crosscode/ui`: fonts, brand style, `ChurchFooter` | In use |
|
||||
| `packages/demo` | `@crosscode/demo`: the demo scenarios' churches, people and logos | In use (Accounts, Events) |
|
||||
| `scripts/` | The `crosscode` script: install, deploy, demo, env, export, uninstall on the servers | In use (`main` is the release) |
|
||||
|
||||
Cross Events (`joshua/hope-events`) moves in as `apps/events` in Events 2.2.0
|
||||
([`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md)). Cross Code Hub (`joshua/events-hub`) stays in
|
||||
its own repo and gets `@crosscode/contracts` as a packed release committed there (decision 22).
|
||||
Cross Code Hub (`joshua/events-hub`) stays in its own repo and gets `@crosscode/contracts` as a
|
||||
packed release committed there (decision 22).
|
||||
|
||||
## Docs
|
||||
|
||||
@@ -22,8 +28,11 @@ its own repo and gets `@crosscode/contracts` as a packed release committed there
|
||||
|------|------|
|
||||
| [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) | The plan: products, contracts, Accounts, sync, Hub, servers, build order, pricing, decisions |
|
||||
| [`docs/HANDOVER.md`](./docs/HANDOVER.md) | Where each phase stands and what's next |
|
||||
| [`docs/VERSIONS.md`](./docs/VERSIONS.md) | The latest release of everything, and what's deployed where |
|
||||
| [`docs/hub-protocol.md`](./docs/hub-protocol.md) | Install ↔ Hub protocol, versions 1 and 2 (a copy lives in `events-hub`) |
|
||||
| [`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md) | Phase 1b: Cross Events into the monorepo, the `crosscode` script |
|
||||
| `docs/*-PLAN.md` | Each phase's plan and decisions (Events 2.2, 2.4, 3.0; Accounts 1.0; Agent 1.0; Website 1.0; App 1.0) |
|
||||
| [`docs/ROLLOUT-1.0.md`](./docs/ROLLOUT-1.0.md) | The rollout checklist |
|
||||
| [`docs/BIBLE-PERMISSIONS.md`](./docs/BIBLE-PERMISSIONS.md) | The Bible publishers' terms for the Church App's devotionals, the permission requests and their status |
|
||||
|
||||
## Rules (ROADMAP-v3 §1)
|
||||
|
||||
|
||||
@@ -1,5 +1,57 @@
|
||||
# Changelog — Accounts
|
||||
|
||||
## [1.9.0] - 2026-11-30
|
||||
|
||||
Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the
|
||||
`crosscode` script on `main` builds it). **One migration** (`20261130000000_accounts_1_9`): two
|
||||
columns on `Account`, one on `ProductLink`, a `WhatsAppOptOut` table. No new .env variables. Part of
|
||||
Church App 1.0.0 (docs/APP-1.0-PLAN.md §8 and §12).
|
||||
|
||||
### Added
|
||||
|
||||
- **`messaging.get`** (contracts 1.20.0): a linked product gets the church's email (SMTP) and
|
||||
WhatsApp (WAWP) settings, the password and token sealed with the link's secret, and is
|
||||
remembered (`ProductLink.messagingWantedAt`). The reply is never kept in `ProductRequest`.
|
||||
- **`messaging.changed`**: when an admin changes the email or WhatsApp settings here, or a product
|
||||
saves them (`messaging.set`), each product that asked is sent the hint at
|
||||
`/api/accounts/v1/messaging-changed` (a `Delivery`, retried as the other calls), except the one
|
||||
that made the change.
|
||||
- **The WhatsApp opt-out for every product** (APP-1.0-PLAN decision 11):
|
||||
- `whatsapp.optout` from a product that received a STOP: the number is kept (`WhatsAppOptOut`),
|
||||
every account with it is opted out (`Account.whatsappOptedOut`), its news on WhatsApp turned
|
||||
off (a consent change, `whatsapp_stop`), and `user.updated` goes to every product with
|
||||
`whatsapp_opted_out: true`. A number without an account is kept too: an account that gets it
|
||||
later (sign-up, the account page, `people.ensure`, `people.update`, an import) starts opted out.
|
||||
- **Accounts' own WAWP webhook**, `POST /api/v2/webhooks/whatsapp?secret=…`, for a church without
|
||||
Cross Events: a STOP (English or Afrikaans: STOP, STOPP, UNSUBSCRIBE, OPT OUT, UITTEKEN) opts
|
||||
the number out and answers once with how to undo it. Admin → Email and WhatsApp → **WhatsApp
|
||||
replies (STOP)** shows the address to give WAWP and when it last called (or that Cross Events
|
||||
takes the replies).
|
||||
- Accounts sends an opted-out person no WhatsApp: sign-in codes go by email, setting WhatsApp up
|
||||
as the two-step method is refused, sign-in notices skip it.
|
||||
- **Turn WhatsApp back on** on the account page (Privacy), `POST /api/v2/me/whatsapp-on`: the
|
||||
number's STOP is forgotten and the products are told. News on WhatsApp stays off until ticked.
|
||||
- "Download my data" shows whether WhatsApp is off and since when.
|
||||
- **Demo scenarios** (contracts 1.21.0, APP-1.0-PLAN §12), for demo sites only:
|
||||
- `npm run demo -- --profile <scenario> --force` (`--list` for the eight), run by
|
||||
`crosscode demo <church> accounts --profile <scenario>` after a backup. The church profile
|
||||
becomes the scenario's church (name, short name, locale, colours, font pairing, corners,
|
||||
campuses, service times, contact, social links), and `church.changed` goes to the products.
|
||||
- Its **logo and icon**, drawn for the demo (`@crosscode/demo`), at
|
||||
`/api/demo-assets/<scenario>/logo.svg` and `icon.svg`.
|
||||
- Its **people** (54 to about 2 450, enough for the scenario's App band), at example.com with the
|
||||
password `Demo@1234`, each with the same account id on every load and in every product
|
||||
(`demoId`). Demo people from another scenario are anonymised; real people (any other address)
|
||||
and Accounts admins are never touched; loading a scenario again brings its people back with
|
||||
their ids.
|
||||
|
||||
### Checked on PostgreSQL 18
|
||||
|
||||
All three migrations on an empty database (the result matches the schema exactly); scenario loads
|
||||
(Acacia Hill 0.8 s, Riverside's 2 457 people 3.4 s, switching back 14.7 s), the people's ids kept,
|
||||
a real person untouched; the STOP opt-out, a known number on a new account, turning it back on;
|
||||
`messaging.changed` queued; `npm run demo` with and without `--force`.
|
||||
|
||||
## [1.8.0] - 2026-11-26
|
||||
|
||||
No migrations, no new settings, no backend changes. The admin redesigned as Cross Events' admin
|
||||
|
||||
@@ -16,6 +16,10 @@ sign-in settings, linked products and the church profile here.
|
||||
- Roles stay in each product: Accounts only knows who someone is (plan §2, "Roles stay in each
|
||||
product").
|
||||
- Products sign in with `@crosscode/auth-client` (packages/auth-client).
|
||||
- 1.9.0: the church's one set of email and WhatsApp settings for the App (`messaging.get`,
|
||||
`messaging.changed`); the WhatsApp opt-out for every product (`src/accounts/whatsapp.ts`, its own
|
||||
WAWP webhook in `src/links/whatsappWebhook.ts`); demo scenarios (`npm run demo -- --profile
|
||||
<scenario> --force`, `src/demo/scenario.ts`, with `@crosscode/demo`; demo sites only).
|
||||
|
||||
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `ACCOUNTS_URL=http://localhost:3200`,
|
||||
`LINKS_ALLOW_PRIVATE=true`), `npx prisma migrate deploy`, then `npm run dev` in both folders (the
|
||||
|
||||
@@ -3,6 +3,17 @@
|
||||
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.9.0
|
||||
|
||||
- **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no
|
||||
WhatsApp from any of your church's sites any more, reminders and sign-in codes included (codes
|
||||
come by email instead). They can turn WhatsApp back on from their account page. Without Cross
|
||||
Events, Admin → Email and WhatsApp shows the address to give WAWP, so the replies reach Accounts.
|
||||
- Getting ready for the **Church App**: it will send with the email and WhatsApp settings you
|
||||
already have, without asking for its own, and pick up any change you make here.
|
||||
- **Demo churches** for Cross Code's demo sites: a church's name, logo, colours, service times and
|
||||
people for each of eight demo scenarios. Never used on a real church's sign-in.
|
||||
|
||||
## 1.8.0
|
||||
|
||||
- **An easier admin.** Admin opens on an overview: how many people have an account, anything that
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -14,10 +14,12 @@
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"prisma:status": "prisma migrate status"
|
||||
"prisma:status": "prisma migrate status",
|
||||
"demo": "tsx scripts/demo.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the WhatsApp opt-out for every product, and the
|
||||
-- products that asked for the church's email and WhatsApp settings (messaging.get).
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Account" ADD COLUMN "whatsappOptedOut" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "whatsappOptedOutAt" TIMESTAMP(3);
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "ProductLink" ADD COLUMN "messagingWantedAt" TIMESTAMP(3);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "WhatsAppOptOut" (
|
||||
"phone" TEXT NOT NULL,
|
||||
"keyword" TEXT NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"receivedAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "WhatsAppOptOut_pkey" PRIMARY KEY ("phone")
|
||||
);
|
||||
@@ -58,6 +58,10 @@ model Account {
|
||||
// 1.1.0: moved in from a product with 2FA but without recovery codes (Events keys its codes with
|
||||
// its own secret, so they can't move): new ones are shown after the next sign-in's second step.
|
||||
recoveryCodesNeeded Boolean @default(false)
|
||||
// 1.9.0: replied STOP to the church's WhatsApp number (APP-1.0-PLAN §8): no product sends them
|
||||
// WhatsApp until they turn it back on here. Sent to products as `whatsapp_opted_out`.
|
||||
whatsappOptedOut Boolean @default(false)
|
||||
whatsappOptedOutAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -201,20 +205,23 @@ model AppSetting {
|
||||
// A linked product (Connect, crosscode.link/1). Each is also an OIDC client (§4): client_id is
|
||||
// installId, the client secret is derived from `secret`, the addresses are fixed paths on `url`.
|
||||
model ProductLink {
|
||||
installId String @id
|
||||
product String // events | website | app
|
||||
url String
|
||||
publicKey String
|
||||
secret String // encrypted
|
||||
connectedAt DateTime
|
||||
connectedById String?
|
||||
installId String @id
|
||||
product String // events | website | app
|
||||
url String
|
||||
publicKey String
|
||||
secret String // encrypted
|
||||
connectedAt DateTime
|
||||
connectedById String?
|
||||
// 1.1.0: a move of this product's users into Accounts is under way (import.begin … finish).
|
||||
importStartedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deliveries Delivery[]
|
||||
people ProductPerson[]
|
||||
requests ProductRequest[]
|
||||
importStartedAt DateTime?
|
||||
// 1.9.0: asked for the church's email and WhatsApp settings (messaging.get), so it's sent
|
||||
// messaging.changed when they change.
|
||||
messagingWantedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deliveries Delivery[]
|
||||
people ProductPerson[]
|
||||
requests ProductRequest[]
|
||||
}
|
||||
|
||||
// 1.1.0: the people a linked product knows (imported by it, added by it, or signed in through it).
|
||||
@@ -244,6 +251,16 @@ model ProductRequest {
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
// 1.9.0: numbers that replied STOP (APP-1.0-PLAN §8), kept with or without an account, so an
|
||||
// account that gets the number later starts opted out. Removed when the person turns WhatsApp on.
|
||||
model WhatsAppOptOut {
|
||||
phone String @id // E.164
|
||||
keyword String
|
||||
source String // the product that received it, or "accounts" (its own webhook)
|
||||
receivedAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model LinkNonce {
|
||||
nonce String @id
|
||||
seenAt DateTime @default(now())
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Loads a demo scenario's church and people into Accounts (1.9.0, docs/APP-1.0-PLAN.md §12).
|
||||
*
|
||||
* npm run demo -- --profile <scenario> [--scenario <scenario>] --force
|
||||
* npm run demo -- --list
|
||||
*
|
||||
* It replaces the church profile and the demo people, so it needs --force. On a server,
|
||||
* `crosscode demo <church> accounts --profile …` runs it (backup first), for the Hub's demo sites;
|
||||
* Accounts loads first in a scenario, then Cross Events, the Website and the App.
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { agent } from '@crosscode/contracts';
|
||||
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||
import { createCtx } from '../src/context.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
import { loadScenario } from '../src/demo/scenario.js';
|
||||
|
||||
const arg = (name: string) => {
|
||||
const i = process.argv.indexOf(`--${name}`);
|
||||
return i > 0 ? process.argv[i + 1] : undefined;
|
||||
};
|
||||
|
||||
if (process.argv.includes('--list')) {
|
||||
for (const s of agent.DEMO_SCENARIOS) console.log(`${s.key.padEnd(18)} ${s.label}`);
|
||||
process.exit(0);
|
||||
}
|
||||
const profile = agent.demoScenarioSchema.safeParse(arg('profile'));
|
||||
if (!profile.success) {
|
||||
console.error(`Usage: npm run demo -- --profile <scenario> --force (one of ${agent.DEMO_SCENARIO_KEYS.join(', ')}; --list)`);
|
||||
process.exit(2);
|
||||
}
|
||||
const scenario = arg('scenario');
|
||||
if (scenario !== undefined && scenario !== profile.data) {
|
||||
console.error(`--scenario ${scenario} loads ${agent.demoScenario(agent.demoScenarioSchema.parse(scenario)).profiles.accounts} in Accounts, not ${profile.data}.`);
|
||||
process.exit(2);
|
||||
}
|
||||
if (!process.argv.includes('--force')) {
|
||||
console.error('This replaces the church profile and the demo people. Add --force to do it (demo sites only).');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const ctx = createCtx(loadConfig(), db);
|
||||
try {
|
||||
const r = await loadScenario(ctx, profile.data);
|
||||
console.log(`${r.church} loaded: ${r.people} people (${r.created} new, ${r.updated} brought back, ${r.removed} from before removed). The linked products are told the church changed.`);
|
||||
} finally {
|
||||
await db.$disconnect();
|
||||
}
|
||||
@@ -44,6 +44,8 @@ export function profileOf(a: Account): Profile {
|
||||
phone_number: a.phone,
|
||||
phone_number_verified: a.phoneVerified,
|
||||
news_consent: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
|
||||
// 1.9.0 (contracts 1.20.0): replied STOP; no product sends them WhatsApp.
|
||||
whatsapp_opted_out: a.whatsappOptedOut,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -112,7 +114,11 @@ export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp
|
||||
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
|
||||
const what = purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
|
||||
const text = `Your code to ${what} at ${churchName} is ${code}. It works for ${CODE_MINUTES} minutes. If you didn't ask for it, you can ignore this message.`;
|
||||
if (method === 'whatsapp' && a.phone) {
|
||||
// 1.9.0: someone who replied STOP gets no WhatsApp, codes included: email instead.
|
||||
if (method === 'whatsapp' && a.phone && a.whatsappOptedOut && purpose !== 'sign_in') {
|
||||
throw new SendError('You turned WhatsApp messages off (you replied STOP). Turn them back on on your account page, or choose another way to get your codes.', 'CODE_NOT_SENT');
|
||||
}
|
||||
if (method === 'whatsapp' && a.phone && !a.whatsappOptedOut) {
|
||||
try {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text });
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'whatsapp') };
|
||||
|
||||
@@ -47,7 +47,7 @@ export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: str
|
||||
const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' });
|
||||
const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site });
|
||||
await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html });
|
||||
if (a.phone && a.phoneVerified && (await ctx.messenger.whatsappReady())) {
|
||||
if (a.phone && a.phoneVerified && !a.whatsappOptedOut && (await ctx.messenger.whatsappReady())) {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text: msg.whatsapp }).catch((e: Error) => console.warn('[sign-in notice] WhatsApp:', e.message));
|
||||
}
|
||||
return 'sent';
|
||||
|
||||
@@ -42,6 +42,7 @@ export async function useRecoveryCode(ctx: Ctx, a: Account, code: unknown, req?:
|
||||
export async function startTwoFactorSetup(ctx: Ctx, a: Account, method: unknown) {
|
||||
if (!METHODS.has(String(method))) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
|
||||
if (method === 'whatsapp' && (!a.phone || !(await ctx.messenger.whatsappReady()))) throw new TwoFactorError('WhatsApp codes need a phone number on your account.', 'BAD_METHOD');
|
||||
if (method === 'whatsapp' && a.whatsappOptedOut) throw new TwoFactorError('You turned WhatsApp messages off (you replied STOP). Turn them back on on your account page first.', 'BAD_METHOD');
|
||||
if (method === 'totp') {
|
||||
const secret = generateSecret();
|
||||
const issuer = (await ctx.settings.json<{ shortName?: string; name?: string }>('church_profile', {}));
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* The WhatsApp opt-out for every product (1.9.0, docs/APP-1.0-PLAN.md §8, decision 11). A STOP to
|
||||
* the church's WhatsApp number reaches Accounts (a product's `whatsapp.optout`, or Accounts' own
|
||||
* webhook for a church without Events). Accounts keeps it: the number in `WhatsAppOptOut`, and
|
||||
* `whatsappOptedOut` on each account with it. Every linked product is told (`user.updated` carries
|
||||
* `whatsapp_opted_out`) and sends that person no WhatsApp of any kind until they turn it back on
|
||||
* on their account page here. Accounts itself sends them none either (codes go by email).
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { Account } from '../generated/prisma/client.js';
|
||||
import { audit, loginEvent } from '../lib/audit.js';
|
||||
import { profileChanged, setNewsConsent } from './service.js';
|
||||
|
||||
/** What counts as STOP in a reply (English and Afrikaans), as Cross Events reads it. */
|
||||
export function isStopKeyword(text: unknown): boolean {
|
||||
return /^\s*(stop|stopp|unsubscribe|stop all|opt out|optout|uitteken)\s*[.!]?\s*$/i.test(String(text ?? ''));
|
||||
}
|
||||
|
||||
/** A WAWP chat id (`27821234567@c.us`) → `+27821234567`; null for groups, channels and LIDs. */
|
||||
export function phoneFromChatId(chatId: unknown): string | null {
|
||||
const m = /^(\d{8,15})@c\.us$/.exec(String(chatId ?? ''));
|
||||
return m ? `+${m[1]}` : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A STOP from `phone` (E.164): keeps the number, opts out every account with it (news on WhatsApp
|
||||
* off too) and tells the products. Returns how many accounts have the number.
|
||||
*/
|
||||
export async function optOutNumber(ctx: Ctx, phone: string, opts: { keyword: string; source: string; receivedAt: Date }): Promise<number> {
|
||||
await ctx.db.whatsAppOptOut.upsert({
|
||||
where: { phone },
|
||||
update: { keyword: opts.keyword, source: opts.source, receivedAt: opts.receivedAt },
|
||||
create: { phone, keyword: opts.keyword, source: opts.source, receivedAt: opts.receivedAt, createdAt: ctx.now() },
|
||||
});
|
||||
const accounts = await ctx.db.account.findMany({ where: { phone, status: { not: 'deleted' } } });
|
||||
for (const a of accounts) await optOut(ctx, a, opts.source);
|
||||
await audit(ctx, { actorId: null, actorRole: 'system', action: 'whatsapp_opt_out', targetType: 'phone', targetId: null, metadata: { source: opts.source, keyword: opts.keyword, accounts: accounts.length } });
|
||||
return accounts.length;
|
||||
}
|
||||
|
||||
async function optOut(ctx: Ctx, a: Account, source: string) {
|
||||
if (!a.whatsappOptedOut) {
|
||||
await ctx.db.account.update({ where: { id: a.id }, data: { whatsappOptedOut: true, whatsappOptedOutAt: ctx.now() } });
|
||||
await loginEvent(ctx, a.id, 'whatsapp_opted_out', undefined, { detail: { source } });
|
||||
}
|
||||
await setNewsConsent(ctx, a, { whatsapp: false }, 'whatsapp_stop');
|
||||
await profileChanged(ctx, a.id);
|
||||
}
|
||||
|
||||
/** The person turns WhatsApp back on (their account page): the number's STOP is forgotten too. */
|
||||
export async function optBackIn(ctx: Ctx, a: Account): Promise<boolean> {
|
||||
if (!a.whatsappOptedOut) return false;
|
||||
await ctx.db.account.update({ where: { id: a.id }, data: { whatsappOptedOut: false, whatsappOptedOutAt: null } });
|
||||
if (a.phone) await ctx.db.whatsAppOptOut.deleteMany({ where: { phone: a.phone } });
|
||||
await loginEvent(ctx, a.id, 'whatsapp_opted_in');
|
||||
await profileChanged(ctx, a.id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After an account's phone number is set or changed: a number that replied STOP starts opted out.
|
||||
* (A number without a STOP never turns an opt-out off: only the person does.) Returns whether it did.
|
||||
*/
|
||||
export async function applyKnownOptOut(ctx: Ctx, accountId: string): Promise<boolean> {
|
||||
const a = await ctx.db.account.findUnique({ where: { id: accountId } });
|
||||
if (!a?.phone || a.whatsappOptedOut) return false;
|
||||
const stop = await ctx.db.whatsAppOptOut.findUnique({ where: { phone: a.phone } });
|
||||
if (!stop) return false;
|
||||
await optOut(ctx, a, 'known_number');
|
||||
return true;
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import { ApiError, handle, limit, sendError } from '../http.js';
|
||||
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
|
||||
import { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js';
|
||||
import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js';
|
||||
import { messagingChanged, messagingParts } from '../links/messaging.js';
|
||||
import { whatsappWebhookUrl } from '../links/whatsappWebhook.js';
|
||||
import { currentSession } from '../oidc/sessions.js';
|
||||
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||
import { recoveryCodesLeft, turnOff } from '../accounts/twoFactor.js';
|
||||
@@ -195,6 +197,8 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
changed.push(key);
|
||||
}
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'settings_changed', targetType: 'setting', metadata: { keys: changed }, ip: clientIp(req) });
|
||||
// 1.9.0: products sending with the church's settings (the App) fetch them again.
|
||||
await messagingChanged(ctx, messagingParts(changed));
|
||||
return { changed };
|
||||
}));
|
||||
|
||||
@@ -209,6 +213,13 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
// 1.9.0: WAWP's webhook address for STOP replies (a church without Cross Events points WAWP here).
|
||||
r.get('/settings/whatsapp-webhook', handle(async (req, res) => {
|
||||
await admin(req, res);
|
||||
const linked = await ctx.db.productLink.findFirst({ where: { product: 'events' } });
|
||||
return { ...(await whatsappWebhookUrl(ctx)), eventsLinked: !!linked };
|
||||
}));
|
||||
|
||||
// 1.2.0: as the test email, for WhatsApp (WAWP), to the admin's own phone.
|
||||
r.post('/settings/test-whatsapp', limit(5), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* /api/self/… the account page's own sign-in
|
||||
* /api/church/v1, /api/links/v1/… for the church's other products
|
||||
* /api/accounts/v1/requests what a linked product asks (import, people.*; contracts 1.8.0)
|
||||
* /api/v2/webhooks/whatsapp WAWP's webhook: STOP replies (1.9.0)
|
||||
* /api/v2/… the pages' API (sign-in steps, account, admin, setup)
|
||||
*/
|
||||
import express from 'express';
|
||||
@@ -19,6 +20,7 @@ import { meRouter } from './me/routes.js';
|
||||
import { LOGOUT_JS } from './oidc/pages.js';
|
||||
import { publicRouter } from './public/routes.js';
|
||||
import { requestsRouter } from './links/requests.js';
|
||||
import { whatsappWebhookRouter } from './links/whatsappWebhook.js';
|
||||
import { setupRouter } from './setup/routes.js';
|
||||
import { health } from './hub/client.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
@@ -50,6 +52,8 @@ export function createApp(ctx: Ctx, provider: Provider) {
|
||||
app.use('/api/self', selfRouter(ctx));
|
||||
app.use('/api', requestsRouter(ctx, provider));
|
||||
app.use('/api', publicRouter(ctx));
|
||||
// 1.9.0: WAWP's webhook (STOP replies), before the pages' API: no same-origin check, its own secret.
|
||||
app.use(whatsappWebhookRouter(ctx));
|
||||
|
||||
const v2 = express.Router();
|
||||
v2.use(express.json({ limit: '64kb' }));
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Accounts' part of a demo scenario (1.9.0, docs/APP-1.0-PLAN.md §12, "Demo scenarios"): the
|
||||
* scenario's church becomes the church profile (its own name, logo, icon, colours, campuses,
|
||||
* service times and contact details), and its people get accounts. Loaded first, so Cross Events,
|
||||
* the Website and the App then build their demo data around the same church and people.
|
||||
*
|
||||
* Only for demo sites (`crosscode demo <church> accounts --profile <scenario>`, which takes a backup
|
||||
* first). People keep the same account id on every load (`demoId`), so products' copies still match.
|
||||
* Demo people from before who aren't in this scenario are anonymised; real people (any address not at
|
||||
* example.com) and Accounts admins are never touched.
|
||||
*/
|
||||
import { agent, DEMO_EMAIL_DOMAIN } from '@crosscode/contracts';
|
||||
import { DEMO_PASSWORD, demoChurch, demoIconSvg, demoLogoSvg, demoPeople } from '@crosscode/demo';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { hashPassword } from '../lib/passwords.js';
|
||||
import { updateProfile } from '../church/profile.js';
|
||||
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
|
||||
/** Where Accounts serves the scenario's logo and icon (`/api/demo-assets/<scenario>/logo.svg`). */
|
||||
export const DEMO_ASSETS_PATH = '/api/demo-assets';
|
||||
const DEMO_ASSET_FILES = { 'logo.svg': demoLogoSvg, 'icon.svg': demoIconSvg } as const;
|
||||
|
||||
/** The SVG for a demo asset, or null for anything else. */
|
||||
export function demoAsset(scenario: string, file: string): string | null {
|
||||
const key = agent.demoScenarioSchema.safeParse(scenario);
|
||||
const draw = (DEMO_ASSET_FILES as Record<string, (s: agent.DemoScenarioKey) => string>)[file];
|
||||
return key.success && draw ? draw(key.data) : null;
|
||||
}
|
||||
|
||||
export interface ScenarioResult { scenario: agent.DemoScenarioKey; church: string; people: number; created: number; updated: number; removed: number }
|
||||
|
||||
const isDemo = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
|
||||
const CHUNK = 500;
|
||||
|
||||
export async function loadScenario(ctx: Ctx, scenario: agent.DemoScenarioKey): Promise<ScenarioResult> {
|
||||
const { profile } = demoChurch(scenario);
|
||||
const assets = `${ctx.config.publicUrl.replace(/\/$/, '')}${DEMO_ASSETS_PATH}/${scenario}`;
|
||||
|
||||
// The church: every shared field replaced, so nothing from the church before is left (tells the products: church.changed).
|
||||
await updateProfile(ctx, {
|
||||
name: profile.name, shortName: profile.shortName, timezone: profile.timezone, locale: profile.locale,
|
||||
branding: { logoUrl: `${assets}/logo.svg`, iconUrl: `${assets}/icon.svg`, colours: profile.colours, style: profile.style },
|
||||
campuses: profile.campuses, serviceTimes: profile.serviceTimes,
|
||||
contact: { ...profile.contact, phone: null, whatsapp: null }, social: profile.social,
|
||||
});
|
||||
|
||||
// The people.
|
||||
const people = demoPeople(scenario);
|
||||
const wanted = new Set(people.map((p) => p.id));
|
||||
const existing = new Map((await ctx.db.account.findMany({ where: { id: { in: [...wanted] } } })).map((a) => [a.id, a]));
|
||||
let removed = 0;
|
||||
for (const a of await ctx.db.account.findMany({ where: { email: { contains: `@${DEMO_EMAIL_DOMAIN}` }, status: { not: 'deleted' } } })) {
|
||||
if (wanted.has(a.id) || !isDemo(a.email) || a.role === 'admin') continue;
|
||||
await ctx.db.oidcPayload.deleteMany({ where: { accountId: a.id } });
|
||||
await anonymise(ctx, a.id);
|
||||
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
|
||||
removed++;
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(DEMO_PASSWORD);
|
||||
const notice = await currentNoticeVersion(ctx);
|
||||
const now = ctx.now();
|
||||
const fields = (p: (typeof people)[number]) => ({
|
||||
name: p.name, givenName: p.givenName, familyName: p.familyName, email: p.email, emailVerified: true,
|
||||
phone: null, phoneVerified: false, passwordHash, role: 'member' as const, status: 'active' as const,
|
||||
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: now,
|
||||
noticeVersionAccepted: notice, failedSignIns: 0, lockedUntil: null, deactivatedAt: null, anonymisedAt: null,
|
||||
whatsappOptedOut: false, whatsappOptedOutAt: null,
|
||||
});
|
||||
let updated = 0;
|
||||
// Already here (this scenario loaded before, or anonymised when another was): brought back as they were.
|
||||
for (const p of people) {
|
||||
const a = existing.get(p.id);
|
||||
if (!a) continue;
|
||||
// Never take over a real person's account, nor an admin's.
|
||||
if (a.role === 'admin' || (a.status !== 'deleted' && !isDemo(a.email))) continue;
|
||||
const other = await ctx.db.account.findUnique({ where: { email: p.email } });
|
||||
if (other && other.id !== p.id) continue;
|
||||
await ctx.db.account.update({ where: { id: p.id }, data: fields(p) });
|
||||
updated++;
|
||||
}
|
||||
// New: in chunks, as the larger scenarios have a couple of thousand people.
|
||||
const taken = new Set((await ctx.db.account.findMany({ where: { email: { in: people.map((p) => p.email) } }, select: { email: true } })).map((a) => a.email));
|
||||
const fresh = people.filter((p) => !existing.has(p.id) && !taken.has(p.email));
|
||||
for (let i = 0; i < fresh.length; i += CHUNK) {
|
||||
await ctx.db.account.createMany({ data: fresh.slice(i, i + CHUNK).map((p) => ({ id: p.id, ...fields(p), createdAt: now })) });
|
||||
}
|
||||
|
||||
await audit(ctx, { actorId: null, actorRole: 'system', action: 'demo_scenario_loaded', targetType: 'setting', targetId: 'church_profile', metadata: { scenario, people: people.length, created: fresh.length, updated, removed } });
|
||||
await ctx.settings.set('demo_scenario', JSON.stringify({ scenario, loadedAt: now.toISOString() }));
|
||||
return { scenario, church: profile.name, people: people.length, created: fresh.length, updated, removed };
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { loginEvent } from '../lib/audit.js';
|
||||
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
|
||||
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
import { applyKnownOptOut } from '../accounts/whatsapp.js';
|
||||
|
||||
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
|
||||
|
||||
@@ -115,7 +116,7 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
|
||||
}
|
||||
if (stage === 'setup_two_factor') {
|
||||
// Only the ways that can deliver a code now (1.2.0): an app always works.
|
||||
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone && !a.whatsappOptedOut ? ['whatsapp'] : [])];
|
||||
extra.why = a.role === 'admin' ? 'admin' : 'product';
|
||||
}
|
||||
if (stage === 'notice') {
|
||||
@@ -177,6 +178,7 @@ export async function signUp(ctx: Ctx, pending: PendingSignIn, input: Record<str
|
||||
await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: notice.version, acceptedAt: ctx.now() } });
|
||||
await setNewsConsent(ctx, a, { email: input.newsEmail === true, whatsapp: input.newsWhatsApp === true && !!phone }, 'sign_up');
|
||||
await loginEvent(ctx, a.id, 'account_created');
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 });
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,8 @@ export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole
|
||||
|
||||
export type LoginEventType =
|
||||
| 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off'
|
||||
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created';
|
||||
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created'
|
||||
| 'whatsapp_opted_out' | 'whatsapp_opted_in';
|
||||
|
||||
export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) {
|
||||
try {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** Encrypted at rest; never sent to the browser. */
|
||||
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']);
|
||||
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks', 'wawp_webhook_secret']);
|
||||
|
||||
/** The settings an admin may read and change through the generic settings API. */
|
||||
export const ADMIN_SETTINGS = new Set([
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/**
|
||||
* Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1`
|
||||
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a
|
||||
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, `church.changed` and (1.9.0) `messaging.changed`. Each is a
|
||||
* `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min,
|
||||
* 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion,
|
||||
* export).
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts';
|
||||
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS, MESSAGING_CHANGED_PATH } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { callSibling, siblingUrl } from './http.js';
|
||||
@@ -14,7 +14,10 @@ import { callSibling, siblingUrl } from './http.js';
|
||||
const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[];
|
||||
export const MAX_ATTEMPTS = RETRY_MS.length + 1;
|
||||
|
||||
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed';
|
||||
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed' | 'messaging.changed';
|
||||
|
||||
/** Where each call goes on the product. 1.9.0 adds messaging.changed (only to products that asked for the settings). */
|
||||
const PATHS: Partial<Record<CallType, string>> = { 'church.changed': CHURCH_PATHS.changed, 'messaging.changed': MESSAGING_CHANGED_PATH };
|
||||
|
||||
/** Queues a call to every linked product (or the ones given). Returns the deliveries made. */
|
||||
export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) {
|
||||
@@ -23,7 +26,7 @@ export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: str
|
||||
for (const link of links) {
|
||||
const callId = crypto.randomUUID();
|
||||
made.push(await ctx.db.delivery.create({
|
||||
data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||
data: { linkId: link.installId, callId, type, path: PATHS[type] ?? ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||
}));
|
||||
}
|
||||
return made;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 4): one set of email and WhatsApp settings per church,
|
||||
* kept here (or copied in from Cross Events). Products that asked for them (`messaging.get`, the
|
||||
* Church App) are sent `messaging.changed` when they change, so they fetch them again.
|
||||
*/
|
||||
import { IDENTITY_REQUEST_SCHEMA, type MessagingChanged } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { queueCall } from './deliveries.js';
|
||||
|
||||
/** The settings that make up the church's email and WhatsApp. */
|
||||
const EMAIL_KEYS = new Set(['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure']);
|
||||
const WHATSAPP_KEYS = new Set(['wawp_access_token', 'wawp_instance_id']);
|
||||
|
||||
/** Which parts the changed setting keys touch. */
|
||||
export function messagingParts(keys: string[]): { email: boolean; whatsapp: boolean } {
|
||||
return { email: keys.some((k) => EMAIL_KEYS.has(k)), whatsapp: keys.some((k) => WHATSAPP_KEYS.has(k)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the change and tells every product that asked for the settings, except the one that
|
||||
* made the change (`exceptLinkId`, e.g. Events saving its own into Accounts).
|
||||
*/
|
||||
export async function messagingChanged(ctx: Ctx, parts: { email: boolean; whatsapp: boolean }, exceptLinkId?: string) {
|
||||
if (!parts.email && !parts.whatsapp) return;
|
||||
const at = ctx.now().toISOString();
|
||||
await ctx.settings.set('messaging_updated_at', at);
|
||||
const wanted = await ctx.db.productLink.findMany({ where: { messagingWantedAt: { not: null } } });
|
||||
const linkIds = wanted.map((l) => l.installId).filter((id) => id !== exceptLinkId);
|
||||
if (!linkIds.length) return;
|
||||
await queueCall(ctx, 'messaging.changed', (): MessagingChanged => ({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: at, ...parts }), { linkIds });
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
|
||||
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
|
||||
} from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import { LINK_HEADERS, openLinkValue, sealLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { ProductLink } from '../generated/prisma/client.js';
|
||||
import { limit } from '../http.js';
|
||||
@@ -32,6 +32,8 @@ import { turnOff } from '../accounts/twoFactor.js';
|
||||
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js';
|
||||
import { applyKnownOptOut, optOutNumber } from '../accounts/whatsapp.js';
|
||||
import { messagingChanged } from './messaging.js';
|
||||
|
||||
/** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */
|
||||
const PROFILE_EDITORS = new Set(['website']);
|
||||
@@ -134,6 +136,7 @@ async function importOne(ctx: Ctx, link: ProductLink, secret: string, p: ImportP
|
||||
for (const c of p.consentChanges) await ctx.db.consentChange.create({ data: { accountId: a.id, channel: c.channel, granted: c.granted, source: 'events_import', createdAt: new Date(c.at) } });
|
||||
await knows(ctx, link.installId, a.id, 'import', { upgrade: true });
|
||||
await loginEvent(ctx, a.id, 'account_created', undefined, { clientId: link.installId, detail: { by: 'import', product: link.product } });
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
}
|
||||
return { id: p.id, outcome: 'created', sub: p.id, reason: null };
|
||||
}
|
||||
@@ -225,6 +228,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
}
|
||||
const a = await ctx.db.account.create({ data: { name: r.name, email, phone: r.phone, passwordHash: null, emailVerified: false } });
|
||||
await knows(ctx, link.installId, a.id, 'ensure');
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
const token = randomToken();
|
||||
// Only the product's own address: never somewhere else.
|
||||
const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url;
|
||||
@@ -259,7 +263,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
if (Object.keys(data).length) {
|
||||
await ctx.db.account.update({ where: { id: a.id }, data });
|
||||
if (data.email) await loginEvent(ctx, a.id, 'email_changed', req, { clientId: link.installId, detail: { by: 'product' } });
|
||||
await profileChanged(ctx, a.id);
|
||||
if (!(data.phone && (await applyKnownOptOut(ctx, a.id)))) await profileChanged(ctx, a.id);
|
||||
}
|
||||
await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) });
|
||||
return reply({ ok: true as const });
|
||||
@@ -323,10 +327,20 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
|
||||
return reply({ people });
|
||||
}
|
||||
// contracts 1.20.0 (APP-1.0-PLAN §8): answered from Accounts 1.9.0.
|
||||
case 'messaging.get':
|
||||
case 'whatsapp.optout':
|
||||
throw new RequestError(`This Accounts doesn't answer ${r.type} yet (Accounts 1.9.0 does).`, 'INVALID_REQUEST', 400);
|
||||
case 'messaging.get': {
|
||||
// 1.9.0 (APP-1.0-PLAN §8, decision 4): the church's one set of email and WhatsApp settings,
|
||||
// secrets sealed with the link's secret. The product is sent messaging.changed from now on.
|
||||
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { messagingWantedAt: ctx.now() } });
|
||||
const out = await messagingSettings(ctx, secret);
|
||||
await logRequest(ctx, link, r, 'messaging_settings_given', null, req, { email: !!out.email, whatsapp: !!out.whatsapp });
|
||||
return reply(out);
|
||||
}
|
||||
case 'whatsapp.optout': {
|
||||
// 1.9.0 (decision 11): a STOP the product received. Kept here for every product.
|
||||
const accounts = await optOutNumber(ctx, r.phone, { keyword: r.keyword, source: link.product, receivedAt: new Date(r.receivedAt) });
|
||||
await logRequest(ctx, link, r, 'whatsapp_stop_from_product', null, req, { accounts });
|
||||
return reply({ accounts });
|
||||
}
|
||||
case 'church.update': {
|
||||
// The product checked the person's role (Accounts doesn't know the Website's); Accounts
|
||||
// checks it's the Website, that the person signs in through it, and audits it as theirs.
|
||||
@@ -386,6 +400,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
|
||||
}
|
||||
}
|
||||
if (save && (email?.saved || whatsapp?.saved)) await messagingChanged(ctx, { email: !!email?.saved, whatsapp: !!whatsapp?.saved }, link.installId);
|
||||
await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } });
|
||||
const status = await messagingStatus(ctx);
|
||||
return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } });
|
||||
@@ -423,7 +438,8 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
|
||||
const out = await handle(ctx, provider, link, secret, request, req);
|
||||
// Checks write nothing, so they needn't be remembered.
|
||||
// people.check (1.5.0) only reads, and its reply holds profiles: never kept.
|
||||
const isCheck = ('check' in request && request.check) || request.type === 'people.check';
|
||||
// messaging.get (1.9.0) carries sealed secrets: never kept either.
|
||||
const isCheck = ('check' in request && request.check) || request.type === 'people.check' || request.type === 'messaging.get';
|
||||
if (!isCheck) {
|
||||
await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {});
|
||||
}
|
||||
@@ -469,6 +485,29 @@ async function messagingStatus(ctx: Ctx) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* messaging.get (1.9.0): what Accounts sends with (its saved settings, else the server's .env),
|
||||
* the password and token sealed with the link's secret. A part that isn't set up is null.
|
||||
*/
|
||||
async function messagingSettings(ctx: Ctx, secret: string) {
|
||||
const s = ctx.settings;
|
||||
const host = (await s.get('smtp_host')) || ctx.config.smtp?.host || null;
|
||||
const port = Number((await s.get('smtp_port')) || ctx.config.smtp?.port || 587);
|
||||
const pass = (await s.get('smtp_pass')) || ctx.config.smtp?.pass || '';
|
||||
const from = (await s.get('smtp_from')) || ctx.config.smtp?.from || '';
|
||||
const email = host && from ? {
|
||||
host, port,
|
||||
secure: (await s.get('smtp_secure')) === 'true' || (ctx.config.smtp?.secure ?? port === 465),
|
||||
user: (await s.get('smtp_user')) || ctx.config.smtp?.user || '',
|
||||
pass: pass ? sealLinkValue(secret, pass) : null,
|
||||
from,
|
||||
} : null;
|
||||
const token = (await s.get('wawp_access_token')) || ctx.config.wawp?.accessToken || null;
|
||||
const instanceId = (await s.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null;
|
||||
const whatsapp = token && instanceId ? { accessToken: sealLinkValue(secret, token), instanceId } : null;
|
||||
return { email, whatsapp, updatedAt: (await s.get('messaging_updated_at')) || null };
|
||||
}
|
||||
|
||||
/** Old remembered requests (the `cleanup` job). */
|
||||
export async function forgetOldRequests(ctx: Ctx) {
|
||||
return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } });
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 11): Accounts takes WAWP's webhook itself, for a church
|
||||
* without Cross Events (a WAWP number sends replies to one address; with Events, Events receives
|
||||
* them and passes a STOP on with `whatsapp.optout`).
|
||||
*
|
||||
* POST /api/v2/webhooks/whatsapp?secret=… (WAWP's `message` event)
|
||||
*
|
||||
* WAWP doesn't sign webhooks, so the address carries a secret only Accounts and WAWP know
|
||||
* (Admin → Email and WhatsApp shows it to paste into WAWP). Always answers 200 quickly, so WAWP
|
||||
* never retries; only a STOP from a phone number is acted on.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { isStopKeyword, optOutNumber, phoneFromChatId } from '../accounts/whatsapp.js';
|
||||
|
||||
export const WHATSAPP_WEBHOOK_PATH = '/api/v2/webhooks/whatsapp';
|
||||
|
||||
/** The secret in the webhook's address, made on first use. */
|
||||
async function webhookSecret(ctx: Ctx): Promise<string> {
|
||||
const saved = await ctx.settings.get('wawp_webhook_secret');
|
||||
if (saved) return saved;
|
||||
const secret = crypto.randomBytes(24).toString('base64url');
|
||||
await ctx.settings.set('wawp_webhook_secret', secret);
|
||||
return secret;
|
||||
}
|
||||
|
||||
/** The address to paste into WAWP's webhook settings (event: message), and when it last called. */
|
||||
export async function whatsappWebhookUrl(ctx: Ctx) {
|
||||
return {
|
||||
url: `${ctx.config.publicUrl.replace(/\/$/, '')}${WHATSAPP_WEBHOOK_PATH}?secret=${encodeURIComponent(await webhookSecret(ctx))}`,
|
||||
lastSeenAt: await ctx.settings.get('wawp_webhook_last_seen'),
|
||||
};
|
||||
}
|
||||
|
||||
function secretMatches(given: string, secret: string) {
|
||||
return given.length === secret.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(secret));
|
||||
}
|
||||
|
||||
export async function handleWhatsappWebhook(ctx: Ctx, query: { secret?: unknown }, body: unknown): Promise<'ignored' | 'seen' | 'stopped'> {
|
||||
const secret = await ctx.settings.get('wawp_webhook_secret');
|
||||
if (!secret || !secretMatches(String(query.secret ?? ''), secret)) return 'ignored';
|
||||
await ctx.settings.set('wawp_webhook_last_seen', ctx.now().toISOString());
|
||||
const payload = ((body as { payload?: Record<string, unknown> })?.payload ?? {}) as { fromMe?: boolean; body?: unknown; from?: unknown };
|
||||
if (payload.fromMe || !isStopKeyword(payload.body)) return 'seen';
|
||||
const phone = phoneFromChatId(payload.from);
|
||||
// Groups, channels and senders WhatsApp only names by a "LID" have no number to opt out.
|
||||
if (!phone) return 'seen';
|
||||
await optOutNumber(ctx, phone, { keyword: String(payload.body).trim().toUpperCase().slice(0, 40), source: 'accounts', receivedAt: ctx.now() });
|
||||
// The one message after a STOP: what it did and how to undo it.
|
||||
const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'the church';
|
||||
await ctx.messenger.whatsapp({ to: phone, text: `You won't get WhatsApp messages from ${church} any more. To turn them back on, go to ${ctx.config.publicUrl.replace(/\/$/, '')}/account.` })
|
||||
.catch((e: Error) => console.warn('[whatsapp webhook] confirmation not sent:', e.message));
|
||||
return 'stopped';
|
||||
}
|
||||
|
||||
export function whatsappWebhookRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
r.post(WHATSAPP_WEBHOOK_PATH, express.json({ limit: '256kb' }), async (req: Request, res: Response) => {
|
||||
try {
|
||||
await handleWhatsappWebhook(ctx, req.query as { secret?: unknown }, req.body);
|
||||
} catch (e) {
|
||||
console.error('[whatsapp webhook]', (e as Error).message);
|
||||
}
|
||||
res.json({ ok: true });
|
||||
});
|
||||
return r;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { requestExport } from '../privacy/export.js';
|
||||
import { requestDeletion } from '../privacy/deletion.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
import { linkedProducts } from '../links/store.js';
|
||||
import { applyKnownOptOut, optBackIn } from '../accounts/whatsapp.js';
|
||||
|
||||
/** 1.3.0: the quick links on the account page. Events' own sign-in, already signed in here, lands on the dashboard. */
|
||||
const APP_NAMES: Record<string, string> = { events: 'Events', website: 'Website', app: 'Church app' };
|
||||
@@ -29,7 +30,9 @@ export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: numbe
|
||||
return {
|
||||
id: a.id, name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified,
|
||||
phone: a.phone, role: a.role, twoFactor: a.twoFactorMethod, recoveryCodesLeft: extra.recoveryCodesLeft,
|
||||
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp }, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
|
||||
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
|
||||
// 1.9.0: replied STOP to the church's WhatsApp number; turned back on here.
|
||||
whatsappOptedOut: a.whatsappOptedOut, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
|
||||
createdAt: a.createdAt, lastSignInAt: a.lastSignInAt,
|
||||
};
|
||||
}
|
||||
@@ -80,7 +83,8 @@ export function meRouter(ctx: Ctx, provider: Provider) {
|
||||
...(phone ? {} : { newsWhatsApp: false }),
|
||||
},
|
||||
});
|
||||
await profileChanged(ctx, s.account.id);
|
||||
// 1.9.0: a number that replied STOP starts opted out (which tells the products itself).
|
||||
if (!(phone !== s.account.phone && (await applyKnownOptOut(ctx, s.account.id)))) await profileChanged(ctx, s.account.id);
|
||||
return view(s);
|
||||
}));
|
||||
|
||||
@@ -175,11 +179,18 @@ export function meRouter(ctx: Ctx, provider: Provider) {
|
||||
|
||||
r.put('/me/news', handle(async (req, res) => {
|
||||
const s = await signedIn(req, res);
|
||||
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone }, 'account_page');
|
||||
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone && !s.account.whatsappOptedOut }, 'account_page');
|
||||
if (changed) await profileChanged(ctx, s.account.id);
|
||||
return view(s);
|
||||
}));
|
||||
|
||||
// 1.9.0: WhatsApp back on after a STOP (every product may send it again; news stays off until chosen).
|
||||
r.post('/me/whatsapp-on', handle(async (req, res) => {
|
||||
const s = await signedIn(req, res);
|
||||
await optBackIn(ctx, s.account);
|
||||
return view(s);
|
||||
}));
|
||||
|
||||
r.get('/me/notice', handle(async (req, res) => {
|
||||
await signedIn(req, res);
|
||||
const n = await currentNotice(ctx);
|
||||
|
||||
@@ -27,7 +27,7 @@ async function ownPart(ctx: Ctx, accountId: string) {
|
||||
return {
|
||||
product: 'accounts',
|
||||
sections: [
|
||||
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
|
||||
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, whatsappOptedOut: a.whatsappOptedOut, whatsappOptedOutAt: a.whatsappOptedOutAt, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
|
||||
{ key: 'news_consent', title: 'News consent', records: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })) },
|
||||
{ key: 'privacy_notice', title: 'Privacy notices accepted', records: notices.map((n) => ({ version: n.version, acceptedAt: n.acceptedAt })) },
|
||||
{ key: 'sign_ins', title: 'Sign-ins and changes', records: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent })) },
|
||||
|
||||
@@ -10,6 +10,7 @@ import { branding, church } from '../church/profile.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js';
|
||||
import { setupNeeded } from '../setup/routes.js';
|
||||
import { currentNotice } from '../privacy/notice.js';
|
||||
import { DEMO_ASSETS_PATH, demoAsset } from '../demo/scenario.js';
|
||||
|
||||
const strip = (p: string) => p.replace(/^\/api/, '');
|
||||
|
||||
@@ -31,6 +32,14 @@ export function publicRouter(ctx: Ctx) {
|
||||
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
|
||||
}));
|
||||
|
||||
// 1.9.0: a demo scenario's logo and icon (drawn for the demo), which its church profile points at.
|
||||
r.get(`${strip(DEMO_ASSETS_PATH)}/:scenario/:file`, limit(600), (req, res) => {
|
||||
const svg = demoAsset(String(req.params.scenario), String(req.params.file));
|
||||
if (!svg) return res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such demo image.' } });
|
||||
res.set({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'" });
|
||||
return res.send(svg);
|
||||
});
|
||||
|
||||
r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => {
|
||||
res.set('Cache-Control', 'public, max-age=60');
|
||||
return church(ctx);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// Accounts 1.9.0: a demo scenario's church and people (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { CHURCH_PATHS, churchSchema } from '@crosscode/contracts';
|
||||
import { demoPeople } from '@crosscode/demo';
|
||||
import { startHarness, type Harness } from './support/harness.js';
|
||||
import { loadScenario } from '../src/demo/scenario.js';
|
||||
import { church } from '../src/church/profile.js';
|
||||
import { verifyPassword } from '../src/lib/passwords.js';
|
||||
|
||||
let h: Harness;
|
||||
before(async () => { h = await startHarness(); });
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
const live = async () => h.db.account.findMany({ where: { status: { not: 'deleted' } } });
|
||||
|
||||
describe('loading a demo scenario', () => {
|
||||
test('the church becomes the scenario\'s, with its own logo and icon, and the products are told', async () => {
|
||||
const real = await h.makeAccount({ email: 'office@hope.test' });
|
||||
const admin = await h.makeAccount({ email: 'admin.demo@example.com', role: 'admin' });
|
||||
const r = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(r.church, 'Acacia Hill Church');
|
||||
const c = await church(h.ctx);
|
||||
assert.ok(churchSchema.safeParse(c).success);
|
||||
assert.equal(c.name, 'Acacia Hill Church');
|
||||
assert.equal(c.shortName, 'Acacia Hill');
|
||||
assert.equal(c.branding.colours.primary, '#2f6f4f');
|
||||
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'soft' });
|
||||
assert.equal(c.branding.logoUrl, `${h.publicUrl}/api/demo-assets/community-family/logo.svg`);
|
||||
assert.equal(c.contact.email, 'office.acaciahill@example.com');
|
||||
assert.ok((await h.db.delivery.findMany({ where: { type: 'church.changed' } })).length >= 1);
|
||||
// Real people and admins are never touched.
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: real.id } }))!.status, 'active');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: admin.id } }))!.status, 'active');
|
||||
});
|
||||
|
||||
test('every person has an account with the id the other products work out, and the demo password', async () => {
|
||||
const people = demoPeople('community-family');
|
||||
const ids = new Set((await live()).map((a) => a.id));
|
||||
for (const p of people) assert.ok(ids.has(p.id), p.email);
|
||||
const pastor = (await h.db.account.findUnique({ where: { id: people[0]!.id } }))!;
|
||||
assert.equal(pastor.name, 'Thabo Nkosi');
|
||||
assert.equal(pastor.emailVerified, true);
|
||||
assert.ok(await verifyPassword('Demo@1234', pastor.passwordHash as string));
|
||||
});
|
||||
|
||||
test('loading it again changes nobody\'s id', async () => {
|
||||
const r = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(r.created, 0);
|
||||
assert.equal(r.removed, 0);
|
||||
assert.equal(r.updated, demoPeople('community-family').length);
|
||||
});
|
||||
|
||||
test('another scenario replaces the demo people; switching back brings them back with the same ids', async () => {
|
||||
const before = demoPeople('community-family');
|
||||
const r = await loadScenario(h.ctx, 'bold-plant');
|
||||
assert.equal(r.church, 'Harbour City Church');
|
||||
assert.equal(r.removed, before.length);
|
||||
assert.equal(r.created, demoPeople('bold-plant').length);
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: before[0]!.id } }))!.status, 'deleted');
|
||||
assert.ok(await h.db.account.findUnique({ where: { email: 'office@hope.test' } }), 'a real person stays');
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'admin.demo@example.com' } }))!.status, 'active', 'an admin stays');
|
||||
|
||||
const back = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(back.updated, before.length);
|
||||
const pastor = (await h.db.account.findUnique({ where: { id: before[0]!.id } }))!;
|
||||
assert.equal(pastor.status, 'active');
|
||||
assert.equal(pastor.email, before[0]!.email);
|
||||
});
|
||||
|
||||
test('a scenario with campuses has them in the profile', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church' }));
|
||||
// Riverside has about 2 450 people; only its profile is checked here.
|
||||
const c = await (async () => { await loadScenario(h.ctx, 'clean-campus'); return church(h.ctx); })();
|
||||
assert.deepEqual(c.campuses.map((x) => x.slug), ['stellenbosch', 'paarl', 'somerset-west']);
|
||||
assert.equal(c.serviceTimes.filter((s) => s.campus === 'stellenbosch').length, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('demo logos', () => {
|
||||
test('served as SVG for a scenario, 404 for anything else', async () => {
|
||||
const res = await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/icon.svg`);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.headers.get('content-type'), 'image/svg+xml; charset=utf-8');
|
||||
assert.match(await res.text(), /^<svg[^>]*>.*#e4572e/);
|
||||
const logo = await (await fetch(`${h.publicUrl}/api/demo-assets/heritage-parish/logo.svg`)).text();
|
||||
assert.match(logo, /St Columba's Church/);
|
||||
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/nowhere/icon.svg`)).status, 404);
|
||||
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/secrets.txt`)).status, 404);
|
||||
assert.equal((await fetch(`${h.publicUrl}${CHURCH_PATHS.profile}`)).status, 200);
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
account: () => ({
|
||||
givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active',
|
||||
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0,
|
||||
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false,
|
||||
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false, whatsappOptedOut: false, whatsappOptedOutAt: null,
|
||||
}),
|
||||
recoveryCode: () => ({ usedAt: null }),
|
||||
pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }),
|
||||
@@ -20,13 +20,13 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }),
|
||||
privacyNotice: () => ({ publishedById: null }),
|
||||
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
||||
productLink: () => ({ connectedById: null, importStartedAt: null }),
|
||||
productLink: () => ({ connectedById: null, importStartedAt: null, messagingWantedAt: null }),
|
||||
oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }),
|
||||
delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }),
|
||||
dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }),
|
||||
deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }),
|
||||
};
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId' };
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId', whatsAppOptOut: 'phone' };
|
||||
const UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] };
|
||||
const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']);
|
||||
|
||||
@@ -117,6 +117,10 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
||||
table().set(row[key], row);
|
||||
return clone(row);
|
||||
},
|
||||
createMany: async ({ data }: { data: Row[] }) => {
|
||||
for (const d of data) await api.create({ data: d });
|
||||
return { count: data.length };
|
||||
},
|
||||
update: async ({ where, data }: { where: Row; data: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
// Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the church's email and WhatsApp settings for a product
|
||||
// that sends with them (messaging.get, messaging.changed), and the WhatsApp opt-out for every
|
||||
// product (whatsapp.optout, Accounts' own WAWP webhook, turning WhatsApp back on).
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import { after, before, beforeEach, describe, test } from 'node:test';
|
||||
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, MESSAGING_CHANGED_PATH, messagingChangedSchema, messagingGetReplySchema, userUpdatedSchema } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, openLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
import { runDue } from '../src/links/deliveries.js';
|
||||
import { messagingChanged } from '../src/links/messaging.js';
|
||||
import { handleWhatsappWebhook, whatsappWebhookUrl } from '../src/links/whatsappWebhook.js';
|
||||
import { isStopKeyword, phoneFromChatId } from '../src/accounts/whatsapp.js';
|
||||
|
||||
let h: Harness;
|
||||
let messenger: MemoryMessenger;
|
||||
|
||||
before(async () => { h = await startHarness(); messenger = h.messenger as MemoryMessenger; });
|
||||
after(async () => { await h.close(); });
|
||||
beforeEach(async () => {
|
||||
h.received.length = 0;
|
||||
messenger.whatsappOn = true;
|
||||
messenger.whatsapps.length = 0;
|
||||
await h.db.delivery.deleteMany({});
|
||||
});
|
||||
|
||||
/** A request from the harness's linked product (signed with its link's secret). */
|
||||
async function ask(body: Record<string, unknown>) {
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, ...body });
|
||||
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: PRODUCT_ID, secret: h.linkSecret, rawBody: raw }) } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const sent = (path: string) => h.received.filter((r) => r.path === path).map((r) => JSON.parse(r.body) as Record<string, unknown>);
|
||||
|
||||
describe('messaging.get', () => {
|
||||
test('nothing set up: both parts null', async () => {
|
||||
const r = await ask({ type: 'messaging.get' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.ok(messagingGetReplySchema.safeParse(r.body).success);
|
||||
assert.equal(r.body.email, null);
|
||||
assert.equal(r.body.whatsapp, null);
|
||||
});
|
||||
|
||||
test('gives the settings with the password and token sealed for this link only, and never keeps the reply', async () => {
|
||||
await h.ctx.settings.setMany({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_user: 'hello@hope.test', smtp_pass: 'mail-pass', smtp_from: 'hello@hope.test', wawp_access_token: 'wa-token', wawp_instance_id: 'HOPE01' });
|
||||
const r = await ask({ type: 'messaging.get' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
const reply = messagingGetReplySchema.parse(r.body);
|
||||
assert.equal(reply.email?.host, 'smtp.hope.test');
|
||||
assert.equal(reply.email?.user, 'hello@hope.test');
|
||||
assert.notEqual(reply.email?.pass, 'mail-pass');
|
||||
assert.equal(openLinkValue(h.linkSecret, reply.email!.pass!), 'mail-pass');
|
||||
assert.equal(openLinkValue(h.linkSecret, reply.whatsapp!.accessToken), 'wa-token');
|
||||
assert.equal(reply.whatsapp?.instanceId, 'HOPE01');
|
||||
assert.doesNotMatch(JSON.stringify(r.body), /mail-pass|wa-token/);
|
||||
const link = await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } });
|
||||
assert.ok(link?.messagingWantedAt, 'remembered as wanting messaging.changed');
|
||||
assert.equal((await h.db.productRequest.findMany({ where: { type: 'messaging.get' } })).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('messaging.changed', () => {
|
||||
test('an admin changing WhatsApp tells the products that asked', async () => {
|
||||
await ask({ type: 'messaging.get' });
|
||||
await messagingChanged(h.ctx, { email: false, whatsapp: true });
|
||||
await runDue(h.ctx);
|
||||
const calls = sent(MESSAGING_CHANGED_PATH);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.ok(messagingChangedSchema.safeParse(calls[0]).success);
|
||||
assert.equal(calls[0]!.whatsapp, true);
|
||||
assert.equal(calls[0]!.email, false);
|
||||
assert.ok(h.received.find((x) => x.path === MESSAGING_CHANGED_PATH && h.signedByLink(x)), 'signed with the link');
|
||||
assert.ok(await h.ctx.settings.get('messaging_updated_at'));
|
||||
});
|
||||
|
||||
test('not to the product that made the change, nor for unrelated settings', async () => {
|
||||
await ask({ type: 'messaging.get' });
|
||||
await messagingChanged(h.ctx, { email: true, whatsapp: false }, PRODUCT_ID);
|
||||
await messagingChanged(h.ctx, { email: false, whatsapp: false });
|
||||
await runDue(h.ctx);
|
||||
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
|
||||
});
|
||||
|
||||
test('a product that never asked isn\'t told', async () => {
|
||||
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { messagingWantedAt: null } });
|
||||
await messagingChanged(h.ctx, { email: true, whatsapp: true });
|
||||
await runDue(h.ctx);
|
||||
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('whatsapp.optout', () => {
|
||||
test('opts out every account with the number, turns WhatsApp news off and tells the products', async () => {
|
||||
const a = await h.makeAccount({ email: 'stop1@hope.test', phone: '+27825550001', phoneVerified: true, newsWhatsApp: true });
|
||||
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550001', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.equal(r.body.accounts, 1);
|
||||
const after = (await h.db.account.findUnique({ where: { id: a.id } }))!;
|
||||
assert.equal(after.whatsappOptedOut, true);
|
||||
assert.equal(after.newsWhatsApp, false);
|
||||
await runDue(h.ctx);
|
||||
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).find((b) => b.type === 'user.updated' && b.sub === a.id);
|
||||
assert.ok(updated, 'user.updated sent');
|
||||
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, true);
|
||||
});
|
||||
|
||||
test('keeps a number without an account: an account made with it later starts opted out', async () => {
|
||||
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550002', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
assert.equal(r.body.accounts, 0);
|
||||
const ensured = await ask({ type: 'people.ensure', name: 'Later Person', email: 'later@hope.test', phone: '+27825550002', returnUrl: `${h.productUrl}/` });
|
||||
assert.equal(ensured.status, 200, JSON.stringify(ensured.body));
|
||||
const a = (await h.db.account.findUnique({ where: { id: ensured.body.sub as string } }))!;
|
||||
assert.equal(a.whatsappOptedOut, true);
|
||||
});
|
||||
|
||||
test('a code for someone who replied STOP goes by email, never WhatsApp', async () => {
|
||||
await h.makeAccount({ email: 'stop3@hope.test', password: 'Correct-horse-1', phone: '+27825550003', twoFactorMethod: 'whatsapp', whatsappOptedOut: true });
|
||||
const r = await h.signIn(new Browser(), 'stop3@hope.test', 'Correct-horse-1');
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.stage, 'two_factor');
|
||||
assert.match(String(r.pending.sentTo), /@hope\.test$/);
|
||||
assert.equal(messenger.whatsapps.filter((w) => w.to === '+27825550003').length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accounts\' own WAWP webhook', () => {
|
||||
const message = (from: string, body: string, fromMe = false) => ({ event: 'message', payload: { from, body, fromMe } });
|
||||
|
||||
test('reads STOP and phone numbers as Cross Events does', () => {
|
||||
for (const s of ['STOP', ' stop ', 'Stop!', 'unsubscribe', 'STOPP', 'opt out']) assert.ok(isStopKeyword(s), s);
|
||||
for (const s of ['stop the music', 'please stop', '', 'STOPPED']) assert.ok(!isStopKeyword(s), s);
|
||||
assert.equal(phoneFromChatId('27825550004@c.us'), '+27825550004');
|
||||
assert.equal(phoneFromChatId('1234567890-123@g.us'), null);
|
||||
assert.equal(phoneFromChatId('12345@lid'), null);
|
||||
});
|
||||
|
||||
test('ignores a call without the secret', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
assert.match(url, /\/api\/v2\/webhooks\/whatsapp\?secret=/);
|
||||
await h.makeAccount({ email: 'stop4@hope.test', phone: '+27825550004' });
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret: 'wrong' }, message('27825550004@c.us', 'STOP')), 'ignored');
|
||||
const res = await fetch(`${h.publicUrl}/api/v2/webhooks/whatsapp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550004@c.us', 'STOP')) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop4@hope.test' } }))!.whatsappOptedOut, false);
|
||||
});
|
||||
|
||||
test('a STOP through the real address opts the number out and answers once', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
await h.makeAccount({ email: 'stop5@hope.test', phone: '+27825550005' });
|
||||
const path = url.slice(url.indexOf('/api/'));
|
||||
const res = await fetch(`${h.publicUrl}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550005@c.us', 'Stop')) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop5@hope.test' } }))!.whatsappOptedOut, true);
|
||||
assert.ok(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550005' } }));
|
||||
const replies = messenger.whatsapps.filter((w) => w.to === '+27825550005');
|
||||
assert.equal(replies.length, 1);
|
||||
assert.match(replies[0]!.text, /won't get WhatsApp messages from Hope Family Church/);
|
||||
assert.ok((await whatsappWebhookUrl(h.ctx)).lastSeenAt);
|
||||
});
|
||||
|
||||
test('other messages, and the church\'s own, change nothing', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
const secret = new URL(url).searchParams.get('secret');
|
||||
await h.makeAccount({ email: 'stop6@hope.test', phone: '+27825550006' });
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'Thanks!')), 'seen');
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'STOP', true)), 'seen');
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop6@hope.test' } }))!.whatsappOptedOut, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('turning WhatsApp back on', () => {
|
||||
test('on the account page: every product may send it again, and the number\'s STOP is forgotten', async () => {
|
||||
await ask({ type: 'whatsapp.optout', phone: '+27825550007', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
const a = await h.makeAccount({ email: 'stop7@hope.test', password: 'Correct-horse-1', phone: '+27825550007', whatsappOptedOut: true, whatsappOptedOutAt: new Date() });
|
||||
const browser = new Browser();
|
||||
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin');
|
||||
const step = await h.api(browser, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'stop7@hope.test', password: 'Correct-horse-1' });
|
||||
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
|
||||
await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||
const me = await h.api(browser, 'GET', '/api/v2/me');
|
||||
assert.equal(me.body.whatsappOptedOut, true);
|
||||
// News on WhatsApp can't be ticked while it's off.
|
||||
await h.api(browser, 'PUT', '/api/v2/me/news', { email: false, whatsapp: true });
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.newsWhatsApp, false);
|
||||
const on = await h.api(browser, 'POST', '/api/v2/me/whatsapp-on');
|
||||
assert.equal(on.status, 200, JSON.stringify(on.body));
|
||||
assert.equal(on.body.whatsappOptedOut, false);
|
||||
assert.equal(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550007' } }), null);
|
||||
await runDue(h.ctx);
|
||||
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).filter((b) => b.type === 'user.updated' && b.sub === a.id).at(-1);
|
||||
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"private": true,
|
||||
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useExternalEffect } from "@/lib/hooks";
|
||||
type Me = {
|
||||
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin";
|
||||
twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
|
||||
whatsappOptedOut?: boolean;
|
||||
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
|
||||
};
|
||||
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
|
||||
@@ -24,6 +25,7 @@ const EVENT: Record<string, string> = {
|
||||
sign_in: "Signed in", sign_in_failed: "Wrong password", locked: "Locked after too many tries", password_reset: "Password reset", password_changed: "Password changed",
|
||||
two_factor_on: "Two-step sign-in turned on", two_factor_off: "Two-step sign-in turned off", recovery_code_used: "Recovery code used", recovery_codes_replaced: "New recovery codes",
|
||||
signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
|
||||
whatsapp_opted_out: "WhatsApp turned off (replied STOP)", whatsapp_opted_in: "WhatsApp turned back on",
|
||||
};
|
||||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||
|
||||
@@ -291,8 +293,17 @@ function Privacy({ me, onDone, onFail }: Props) {
|
||||
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message);
|
||||
}}>
|
||||
<Checkbox name="email" label="Church news by email" defaultChecked={me.news.email} />
|
||||
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} />
|
||||
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone || me.whatsappOptedOut} hint={!me.phone ? "Add your mobile number first." : me.whatsappOptedOut ? "WhatsApp is off: see below." : undefined} />
|
||||
</form>
|
||||
{me.whatsappOptedOut && (
|
||||
<div className="mb-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm">
|
||||
<p className="mb-2">You replied STOP to the church's WhatsApp number, so none of the church's sites send you WhatsApp messages (reminders and codes come by email instead).</p>
|
||||
<Button variant="secondary" onClick={async () => {
|
||||
const r = await call("POST", "/me/whatsapp-on");
|
||||
if (r.ok) onDone("WhatsApp is back on. Church news on WhatsApp stays off until you tick it."); else onFail(r.error.message);
|
||||
}}>Turn WhatsApp back on</Button>
|
||||
</div>
|
||||
)}
|
||||
<p className="mb-4 text-sm"><a href="/privacy" className="text-brand underline">Read the privacy notice</a></p>
|
||||
|
||||
<div className="border-t pt-4">
|
||||
|
||||
@@ -71,6 +71,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
|
||||
{section === "messages" && <>
|
||||
<Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} />
|
||||
<Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} />
|
||||
<WhatsAppReplies />
|
||||
</>}
|
||||
{section === "notice" && <NoticeTab flash={flash} />}
|
||||
{section === "backups" && <Backups flash={flash} />}
|
||||
@@ -446,6 +447,29 @@ function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: strin
|
||||
);
|
||||
}
|
||||
|
||||
/** 1.9.0: where WAWP sends replies, so a STOP reaches Accounts (only needed without Cross Events). */
|
||||
function WhatsAppReplies() {
|
||||
const [data, setData] = useState<{ url: string; lastSeenAt: string | null; eventsLinked: boolean } | null>(null);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<{ url: string; lastSeenAt: string | null; eventsLinked: boolean }>("GET", "/admin/settings/whatsapp-webhook").then((r) => { if (alive && r.ok) setData(r.data); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!data) return null;
|
||||
return (
|
||||
<Card>
|
||||
<Heading icon={<MessageCircle className="h-4 w-4" />} sub="Someone who replies STOP to the church's WhatsApp number gets no WhatsApp from any of the church's sites until they turn it back on on their account page.">WhatsApp replies (STOP)</Heading>
|
||||
{data.eventsLinked
|
||||
? <p className="text-sm text-gray-600">Cross Events receives the replies and passes a STOP on to Accounts. Keep WAWP's webhook pointing at Cross Events.</p>
|
||||
: <>
|
||||
<p className="mb-2 text-sm text-gray-600">In WAWP, set the webhook (event: message) to this address:</p>
|
||||
<input readOnly className="mb-2 w-full rounded border bg-gray-50 px-2 py-1 font-mono text-xs" value={data.url} onFocus={(e) => e.currentTarget.select()} aria-label="Webhook address" />
|
||||
<p className="text-sm text-gray-600">{data.lastSeenAt ? `Last message received: ${new Date(data.lastSeenAt).toLocaleString("en-ZA")}.` : "No message received through it yet."}</p>
|
||||
</>}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Privacy notice, licence, audit ───────────────────────────────────────────
|
||||
|
||||
type NoticeVersion = { version: number; title: string; body: string };
|
||||
|
||||
@@ -13,6 +13,16 @@ 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.7.0
|
||||
|
||||
- **Demo scenarios.** The Hub (2.26.0 and later) can load a whole demo church on a demo client:
|
||||
Accounts first, then Cross Events, the Website and the App, the same church and people in each.
|
||||
It's one job: the server loads **whatever the client has installed** and skips the rest, so a
|
||||
client with only Accounts and the Website gets both. Every product's release is checked first
|
||||
(Accounts 1.9.0, Events 3.8.0, Website 1.8.0); if one fails part-way, the report says which
|
||||
products are out of step. The agent also runs single demo jobs for Accounts and (from App
|
||||
1.0.0) the Church App. Single-product demo data works as before.
|
||||
|
||||
## 1.6.0
|
||||
|
||||
- **Demo data for the Church Website.** The Hub (2.25.0 and later) can load one of the Website's
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.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",
|
||||
|
||||
@@ -58,10 +58,20 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
|
||||
if (job.args.restart) out.push("--restart");
|
||||
return out;
|
||||
}
|
||||
case "seed-demo":
|
||||
case "seed-demo": {
|
||||
// 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] : [])];
|
||||
// 1.7.0: the App's and Accounts' too, and a demo scenario passed on (`--scenario`), so each
|
||||
// product can tell a scenario load from a single one.
|
||||
const a = job.args;
|
||||
const product = a.product && a.product !== "events" ? [a.product] : [];
|
||||
return ["demo", a.church, ...product, "--profile", a.profile,
|
||||
...(a.scenario ? ["--scenario", a.scenario] : []),
|
||||
...(a.adminEmail ? ["--admin-email", a.adminEmail] : [])];
|
||||
}
|
||||
case "seed-scenario":
|
||||
// 1.7.0: a whole demo scenario. No product named: the script loads every product the church
|
||||
// has on this server, Accounts first, and skips the others.
|
||||
return ["demo", job.args.church, "--scenario", job.args.scenario, ...(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];
|
||||
|
||||
@@ -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.6.0";
|
||||
export const AGENT_VERSION = "1.7.0";
|
||||
|
||||
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
|
||||
@@ -52,6 +52,26 @@ describe("crosscode arguments for each job", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "small" } }))).toEqual(["demo", "hope", "--profile", "small"]);
|
||||
});
|
||||
|
||||
it("seed-scenario 1.7.0: one job, no product named, so the server seeds whatever the church has", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "community-family" } }))).toEqual(["demo", "demo2", "--scenario", "community-family"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "bold-youth", adminEmail: "jane@hope.test" } })))
|
||||
.toEqual(["demo", "demo2", "--scenario", "bold-youth", "--admin-email", "jane@hope.test"]);
|
||||
expect(() => parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "bold-youth", products: ["website"] } })).toThrow();
|
||||
});
|
||||
|
||||
it("seed-demo 1.7.0: the App's and Accounts' demos, and a scenario passed on to every product", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "app", profile: "community-family" } }))).toEqual(["demo", "hope", "app", "--profile", "community-family"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "accounts", profile: "bold-youth", scenario: "bold-youth" } })))
|
||||
.toEqual(["demo", "hope", "accounts", "--profile", "bold-youth", "--scenario", "bold-youth"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "clean-campus", scenario: "clean-campus" } })))
|
||||
.toEqual(["demo", "hope", "website", "--profile", "clean-campus", "--scenario", "clean-campus"]);
|
||||
// Events keeps its old form (no product), with the scenario and the admin kept.
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "bold-youth", scenario: "bold-youth", adminEmail: "jane@hope.test" } })))
|
||||
.toEqual(["demo", "hope", "--profile", "bold-youth", "--scenario", "bold-youth", "--admin-email", "jane@hope.test"]);
|
||||
// A scenario's profile must be the scenario's for that product (the contracts refuse the job).
|
||||
expect(() => parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant", scenario: "bold-youth" } })).toThrow();
|
||||
});
|
||||
|
||||
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "env-read", args: { church: "hope", product: "accounts" } }))).toEqual(["env", "hope", "accounts"]);
|
||||
expect(crosscodeArgs(parsed({
|
||||
|
||||
@@ -5,6 +5,36 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.8.0] - 2026-11-30
|
||||
|
||||
Needs contracts 1.21.0 and `@crosscode/demo` 1.1.0 (built with Events; the `crosscode` script on
|
||||
`main` builds it). **One migration** (`20261130120000_whatsapp_stop`): `User.whatsappOptedOut` and a
|
||||
`WhatsAppStop` table. No new settings. Works with any Accounts; the opt-out reaches the church's
|
||||
other products with Accounts 1.9.0. Part of Church App 1.0.0 (docs/APP-1.0-PLAN.md §8 and §12).
|
||||
|
||||
### Changed
|
||||
|
||||
- **STOP stops all WhatsApp** (APP-1.0-PLAN decision 11), not only news: event updates, tickets,
|
||||
kids check-in messages and two-step codes too (codes go by email). Checked before every message
|
||||
(`sendText`, `sendPdf`, `src/utils/whatsappStop.js`), against the numbers that replied STOP here
|
||||
(`WhatsAppStop`) and the accounts Accounts says opted out (`User.whatsappOptedOut`, from
|
||||
`user.updated`'s `whatsapp_opted_out`). News on WhatsApp is turned off as before.
|
||||
- **A STOP received here is passed on to Accounts** (`whatsapp.optout`, contracts 1.20.0), which
|
||||
keeps it for every product. The reply says how to undo it: the account page in Accounts, or,
|
||||
without Accounts, reply START (which turns it back on here). With Accounts, START only answers
|
||||
with the account page; turned back on there, `user.updated` clears this site's STOP for the
|
||||
number too. STOPP and UITTEKEN (Afrikaans) count as STOP.
|
||||
|
||||
### Added
|
||||
|
||||
- **Demo scenarios** (contracts 1.21.0, APP-1.0-PLAN §12): `set-demo.js --profile=<scenario>` for
|
||||
the eight (heritage-parish … clean-campus), each built as one of the four kinds of demo but around
|
||||
the scenario's church from `@crosscode/demo`: its people (the same as in Accounts, the Website and
|
||||
the App; leads become the demo staff and event contacts), and its own campuses with people at
|
||||
their home campus. Accounts' part loads first; the demo then links its people to their accounts
|
||||
and never removes them (`people.removeDemo` skips the scenario's own). A small church's events
|
||||
sell to the people it has (the breakfast isn't sold out at St Columba's). The four demos as before.
|
||||
|
||||
## [3.7.2] - 2026-11-27
|
||||
|
||||
No migrations, no new settings.
|
||||
|
||||
@@ -765,8 +765,11 @@ registered for; always sent) or **News & announcements** (only to people who opt
|
||||
on that channel and haven't unsubscribed). News emails carry an unsubscribe link and
|
||||
one-click `List-Unsubscribe` headers; news WhatsApps end with "Reply STOP" and a link.
|
||||
Event updates say why they were sent and link to the preferences. A STOP reply on
|
||||
WhatsApp turns off WhatsApp news (through WAWP's `message` webhook, checked against a
|
||||
secret in the webhook URL).
|
||||
WhatsApp (through WAWP's `message` webhook, checked against a secret in the webhook URL)
|
||||
**stops every WhatsApp message to that number** from 3.8.0, event updates, tickets and
|
||||
codes included (they go by email), and from the church's other sites too: it's passed on
|
||||
to the church's Accounts, where the person turns WhatsApp back on (without Accounts, by
|
||||
replying START).
|
||||
|
||||
**Privacy notice** (`/legal/privacy`) — edited in **Admin → Privacy (POPIA)**
|
||||
(`/dashboard/admin/privacy`): sections start from the built-in text; drafts, preview,
|
||||
|
||||
@@ -12,6 +12,17 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.8.0
|
||||
|
||||
- **STOP now means no WhatsApp at all.** Someone who replies STOP to your church's WhatsApp number
|
||||
gets no more WhatsApp messages from Cross Events, event updates and tickets included (they come
|
||||
by email instead), and none from your church's other sites either. Before, STOP only stopped news
|
||||
and announcements. They can turn WhatsApp back on from their account page in your church's
|
||||
sign-in (or, if your church doesn't use it, by replying START).
|
||||
- **Demo churches** for Cross Code's demo sites: eight demo churches, each with its own people,
|
||||
staff and campuses, the same as on the demo Church Website and App. Never used on a real
|
||||
church's site.
|
||||
|
||||
## 3.7.2
|
||||
|
||||
- **Fixed: events from your Church Website could show twice** after the website's content was
|
||||
|
||||
@@ -11,7 +11,27 @@ showing it to:
|
||||
| `npm run demo:ministry` | One campus with weekly ministry | The Alpha Course running now (sessions, attendance, late joining, certificates), a finished Marriage Course with certificates, a 3-day conference sold by day, **Kids Church** with families, children, rooms and check-ins, **volunteer rosters**, a **Men's Breakfast series** with followers and a **season pass**, plus a family day, women's conference and carols. |
|
||||
| `npm run demo:multicampus` | A church with several campuses | **Campuses** Central, North and South (switched on), events per campus and church-wide, home campuses, staff limited to a campus (Anri Botha → North, Daniel Pillay → South), the breakfast series moving between campuses, kids church and rosters at two campuses, and all the events-demo events spread over the campuses. |
|
||||
|
||||
`npm run demo:list` prints the same list. Kids church always has a session **today** with
|
||||
**3.8.0: the eight demo scenarios** (docs/APP-1.0-PLAN.md §12). Each is named after its
|
||||
Website demo profile and is one of the churches every product of a demo client shows:
|
||||
|
||||
| Profile | Church | Built as |
|
||||
|---|---|---|
|
||||
| `heritage-parish` | St Columba's Church | small |
|
||||
| `heritage-city` | Grace Cathedral | events |
|
||||
| `bold-youth` | Ignite Church | events |
|
||||
| `bold-plant` | Harbour City Church | small |
|
||||
| `community-family` | Acacia Hill Church (cross-demo2) | ministry |
|
||||
| `community-town` | Karoo Gemeenskapskerk | small |
|
||||
| `clean-modern` | Northpoint Church | ministry |
|
||||
| `clean-campus` | Riverside Church (three campuses) | multicampus |
|
||||
|
||||
They use the church's own people from `@crosscode/demo` (its leads are the staff and the event
|
||||
contacts; the same people, with the same accounts, as in Accounts, the Website and the App) and
|
||||
its own campuses. Load Accounts' part first (`crosscode demo <church> accounts --profile …`), then
|
||||
`npm run set-demo -- --profile=<scenario> --yes` (or `crosscode demo <church> --profile <scenario>`).
|
||||
A small church's events sell only to the people it has.
|
||||
|
||||
`npm run demo:list` prints every profile. Kids church always has a session **today** with
|
||||
children checked in right now, so the kids desk and room screens have something live to
|
||||
show on any day.
|
||||
|
||||
|
||||
@@ -145,7 +145,7 @@ npm run prisma:generate
|
||||
|
||||
### Demo data
|
||||
|
||||
`npm run set-demo -- --profile=<small|events|ministry|multicampus>` wipes the database (keeping site settings and the admin account) and stages demo data for that kind of church; from the repo root it's `npm run demo:<name>` (`npm run demo:list` describes them). See [DEMO_DATA.md](DEMO_DATA.md).
|
||||
`npm run set-demo -- --profile=<small|events|ministry|multicampus|a demo scenario>` (3.8.0: the eight scenarios, e.g. `community-family`) wipes the database (keeping site settings and the admin account) and stages demo data for that kind of church; from the repo root it's `npm run demo:<name>` (`npm run demo:list` describes them). See [DEMO_DATA.md](DEMO_DATA.md).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.7.2",
|
||||
"version": "3.8.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
@@ -25,6 +25,7 @@
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Cross Events 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): STOP to the church's WhatsApp number
|
||||
-- means no WhatsApp from any of its products. Kept per account (from Accounts) and per number.
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "whatsappOptedOut" BOOLEAN NOT NULL DEFAULT false;
|
||||
-- CreateTable
|
||||
CREATE TABLE "WhatsAppStop" (
|
||||
"phone" TEXT NOT NULL,
|
||||
"keyword" TEXT NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"receivedAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "WhatsAppStop_pkey" PRIMARY KEY ("phone")
|
||||
);
|
||||
@@ -95,6 +95,10 @@ model User {
|
||||
newsWhatsApp Boolean @default(false)
|
||||
// When the person last answered the news opt-in question. Null = ask at next login.
|
||||
newsAskedAt DateTime?
|
||||
// 3.8.0: replied STOP to the church's WhatsApp number (here or to another of the church's
|
||||
// products; Accounts keeps it and sends it in user.updated): no WhatsApp of any kind, until
|
||||
// they turn it back on in Accounts. See also WhatsAppStop (by number).
|
||||
whatsappOptedOut Boolean @default(false)
|
||||
// The privacy notice version they last accepted (0 = the built-in notice). Null = never
|
||||
// recorded. Asked again when a version that needs re-acceptance is newer.
|
||||
noticeVersionAccepted Int?
|
||||
@@ -1893,6 +1897,16 @@ model CommunicationConsent {
|
||||
|
||||
// Addresses (email, or phone as 27…) that unsubscribed from news without an account,
|
||||
// e.g. ad-hoc broadcast recipients. News broadcasts skip them.
|
||||
// 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): numbers that replied STOP to the church's WhatsApp
|
||||
// number. Nothing goes to them on WhatsApp (src/utils/whatsappStop.js), with or without an account.
|
||||
model WhatsAppStop {
|
||||
phone String @id // 27821234567
|
||||
keyword String
|
||||
source String // events (this site's webhook) | accounts
|
||||
receivedAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model MessagingOptOut {
|
||||
id String @id @default(uuid())
|
||||
channel String // email | whatsapp
|
||||
|
||||
@@ -16,6 +16,13 @@
|
||||
* campus-limited staff, a series across campuses, kids check-in and rosters at two
|
||||
* campuses.
|
||||
*
|
||||
* 3.8.0: and one per demo scenario (docs/APP-1.0-PLAN.md §12; contracts agent.DEMO_SCENARIOS),
|
||||
* named after it (heritage-parish … clean-campus). A scenario's demo is built from one of the four
|
||||
* kinds above, but around the scenario's own church: its people from @crosscode/demo (the same
|
||||
* people, with the same church accounts, as in Accounts, the Website and the App; leads become the
|
||||
* staff), and its own campuses. Load Accounts first (crosscode demo <church> accounts …), which
|
||||
* makes those people's accounts; the demo then links to them rather than removing them.
|
||||
*
|
||||
* Everything is removed first EXCEPT the site settings (AppSetting) and one admin
|
||||
* account (--admin-email= or DEMO_ADMIN_EMAIL; else joshua@crosscode.co.za, else the oldest admin).
|
||||
* Dates are relative to
|
||||
@@ -58,6 +65,8 @@ const { hashPassword } = require('../src/config/auth');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const { createPrismaClient } = require('../src/config/db');
|
||||
const { applyBundles } = require('../src/utils/bundles');
|
||||
const { agent } = require('@crosscode/contracts');
|
||||
const demo = require('@crosscode/demo');
|
||||
|
||||
const prisma = createPrismaClient();
|
||||
|
||||
@@ -236,7 +245,34 @@ function addUser({ first, last, gender, role = 'user', email }) {
|
||||
return user;
|
||||
}
|
||||
|
||||
/** The name of the nth demo staff member (the contact on events), for every profile. */
|
||||
const staffName = (n) => (staffTeam[n] || staffTeam[0]).name;
|
||||
|
||||
/** The Events roles the scenario's leads get, in this order: the first four are the demo staff. */
|
||||
const STAFF_PARTS = ['pastor', 'office', 'youth', 'worship', 'kids', 'prayer-coordinator'];
|
||||
/** People in a scenario's Events demo besides its leads: not every member uses Events. */
|
||||
const SCENARIO_MEMBERS = 260;
|
||||
|
||||
/** 3.8.0: a scenario's people (@crosscode/demo), as Accounts has them. */
|
||||
function buildScenarioPeople(scenario) {
|
||||
const all = demo.demoPeople(scenario);
|
||||
const leads = all.filter(x => x.part !== 'member');
|
||||
const staff = STAFF_PARTS.map(part => leads.find(x => x.part === part)).filter(Boolean).slice(0, 4);
|
||||
const asUser = (person, role) => {
|
||||
const user = addUser({ first: person.givenName, last: person.familyName, gender: person.gender, role, email: person.email });
|
||||
userMeta.get(user.id).campus = person.campus;
|
||||
return user;
|
||||
};
|
||||
staff.forEach((person, n) => staffTeam.push(asUser(person, n === 0 ? 'supervisor' : 'staff')));
|
||||
const others = leads.filter(x => !staff.includes(x)).concat(all.filter(x => x.part === 'member').slice(0, SCENARIO_MEMBERS));
|
||||
const users = others.map(person => asUser(person, 'user'));
|
||||
const women = users.filter(u => userMeta.get(u.id).gender === 'female');
|
||||
const men = users.filter(u => userMeta.get(u.id).gender === 'male');
|
||||
return { women, men, everyone: women.concat(men) };
|
||||
}
|
||||
|
||||
function buildPeople() {
|
||||
if (profile.scenario) return buildScenarioPeople(profile.scenario);
|
||||
staffTeam.push(
|
||||
addUser({ first: 'Lerato', last: 'Khumalo', gender: 'female', role: 'supervisor', email: 'lerato.khumalo@example.com' }),
|
||||
addUser({ first: 'Sipho', last: 'Dlamini', gender: 'male', role: 'staff', email: 'sipho.dlamini@example.com' }),
|
||||
@@ -259,7 +295,7 @@ function addEvent(data) {
|
||||
goLiveAt: addTime(NOW, -35 * DAY),
|
||||
createdAt: addTime(NOW, -38 * DAY),
|
||||
isActive: true,
|
||||
contactName: 'Lerato Khumalo',
|
||||
contactName: staffName(0),
|
||||
contactEmail: 'events@example.com',
|
||||
contactPhone: '021 555 0142',
|
||||
...data,
|
||||
@@ -539,7 +575,7 @@ function buildMensBreakfast(people) {
|
||||
picture: IMG('photo-1414235077428-338989a2e8c0'),
|
||||
location: 'Church hall',
|
||||
waitlistEnabled: true,
|
||||
contactName: 'Sipho Dlamini',
|
||||
contactName: staffName(1),
|
||||
});
|
||||
const ticket = addOption(event, { name: 'Breakfast ticket', price: 150, stockLimit: 60 });
|
||||
addSection(event, 'Hall entrance', [ticket]);
|
||||
@@ -548,16 +584,17 @@ function buildMensBreakfast(people) {
|
||||
|
||||
const men = shuffle(people.men);
|
||||
let sold = 0;
|
||||
while (sold < 60) {
|
||||
// 3.8.0: a small scenario church has fewer men than seats: sold to all of them, the rest left open.
|
||||
while (sold < 60 && men.length > 7) {
|
||||
const user = men.shift();
|
||||
const quantity = Math.min(chance(0.2) ? 2 : 1, 60 - sold);
|
||||
sold += quantity;
|
||||
addRegistration(event, user, [line(ticket, quantity)], { createdAt: pastDate(28), ...payPlan({ card: 0.65, cash: 0.15, eft: 0.08, none: 0.12 }) });
|
||||
}
|
||||
for (let i = 0; i < 2; i++) {
|
||||
for (let i = 0; i < 2 && men.length; i++) {
|
||||
addRegistration(event, men.shift(), [line(ticket, 1)], { createdAt: pastDate(25, 5), pay: 'cancelled' });
|
||||
}
|
||||
for (let position = 1; position <= 5; position++) {
|
||||
for (let position = 1; position <= 5 && sold >= 60 && men.length; position++) {
|
||||
add('waitlistEntry', {
|
||||
id: uuidv4(), eventId: event.id, eventOptionId: ticket.id, userId: men.shift().id,
|
||||
quantity: position === 3 ? 2 : 1, position, status: 'waiting', createdAt: pastDate(4),
|
||||
@@ -580,7 +617,7 @@ function buildWomensConference(people) {
|
||||
price: 450,
|
||||
picture: IMG('photo-1511632765486-a01980e01a18'),
|
||||
location: 'Main auditorium',
|
||||
contactName: 'Anri Botha',
|
||||
contactName: staffName(2),
|
||||
});
|
||||
const full = addOption(event, { name: 'Full conference (Fri + Sat)', price: 450 });
|
||||
const saturday = addOption(event, { name: 'Saturday only', price: 280 });
|
||||
@@ -659,7 +696,7 @@ function buildYouthCamp(people) {
|
||||
collectGender: true,
|
||||
allowSponsorships: true,
|
||||
sponsorshipGoalSpots: 10,
|
||||
contactName: 'Daniel Pillay',
|
||||
contactName: staffName(3),
|
||||
});
|
||||
const camper = addOption(event, { name: 'Camper (Grade 7–12)', price: 1650, stockLimit: 80 });
|
||||
const hoodie = addOption(event, { name: 'Camp hoodie', price: 380, isMainTicket: false });
|
||||
@@ -798,7 +835,7 @@ function buildMarriageWeekend(people) {
|
||||
price: 3400,
|
||||
picture: IMG('photo-1606800052052-a08af7148866'),
|
||||
location: 'Kloofzicht Lodge, Muldersdrift',
|
||||
contactName: 'Lerato Khumalo',
|
||||
contactName: staffName(0),
|
||||
});
|
||||
const couple = addOption(event, { name: 'Couple package (2 nights)', price: 3400 });
|
||||
const [garden, mountain] = addVariants(couple, [
|
||||
@@ -887,22 +924,26 @@ function buildPastEvent(people, spec) {
|
||||
for (const [label, type, amount, option] of spec.costs(opts)) addCost(event, label, type, amount, option || null);
|
||||
|
||||
const buyers = shuffle(people[spec.pool || 'everyone']);
|
||||
const nextBuyer = () => {
|
||||
if (buyers.length === 0) throw new Error(`Not enough demo people for ${spec.title}`);
|
||||
return buyers.shift();
|
||||
};
|
||||
// 3.8.0: a small scenario church runs out of people before the event fills: the sales stop there.
|
||||
const nextBuyer = () => buyers.shift() || null;
|
||||
const salesFrom = addTime(start, -35 * DAY);
|
||||
const payBy = addTime(start, -HOUR);
|
||||
for (let i = 0; i < spec.online; i++) {
|
||||
const plan = typeof spec.onlinePay === 'function' ? spec.onlinePay() : payPlan(spec.onlinePay);
|
||||
addRegistration(event, nextBuyer(), spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -DAY)), payBy, ...plan });
|
||||
const buyer = nextBuyer();
|
||||
if (!buyer) break;
|
||||
addRegistration(event, buyer, spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -DAY)), payBy, ...plan });
|
||||
}
|
||||
for (let i = 0; i < (spec.refunds || 0); i++) {
|
||||
addRegistration(event, nextBuyer(), spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -10 * DAY)), pay: 'refunded', method: 'card' });
|
||||
const buyer = nextBuyer();
|
||||
if (!buyer) break;
|
||||
addRegistration(event, buyer, spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -10 * DAY)), pay: 'refunded', method: 'card' });
|
||||
}
|
||||
for (let i = 0; i < (spec.door || 0); i++) {
|
||||
const method = weighted(spec.doorPay || { cash: 70, card: 30 });
|
||||
addRegistration(event, nextBuyer(), spec.lines(opts, true), { createdAt: within(addTime(start, -30 * MINUTE), addTime(start, HOUR)), method, atDoor: true });
|
||||
const buyer = nextBuyer();
|
||||
if (!buyer) break;
|
||||
addRegistration(event, buyer, spec.lines(opts, true), { createdAt: within(addTime(start, -30 * MINUTE), addTime(start, HOUR)), method, atDoor: true });
|
||||
}
|
||||
|
||||
const { card = 0, cash = 0, amounts = [] } = spec.donations || {};
|
||||
@@ -1307,6 +1348,23 @@ const PROFILES = {
|
||||
},
|
||||
};
|
||||
|
||||
/** 3.8.0: the kind of demo each scenario is built from (APP-1.0-PLAN §12, the "Events" column). */
|
||||
const SCENARIO_KINDS = {
|
||||
'heritage-parish': 'small', 'heritage-city': 'events', 'bold-youth': 'events', 'bold-plant': 'small',
|
||||
'community-family': 'ministry', 'community-town': 'small', 'clean-modern': 'ministry', 'clean-campus': 'multicampus',
|
||||
};
|
||||
for (const scenario of agent.DEMO_SCENARIOS) {
|
||||
const kind = PROFILES[SCENARIO_KINDS[scenario.key]];
|
||||
const church = demo.demoChurch(scenario.key);
|
||||
PROFILES[scenario.key] = {
|
||||
...kind,
|
||||
scenario: scenario.key,
|
||||
title: `${church.profile.name} — demo scenario (${scenario.label.split(':')[0]})`,
|
||||
about: [scenario.description, `Built as the "${SCENARIO_KINDS[scenario.key]}" demo, with ${church.profile.name}'s own people${kind.campuses ? ' and campuses' : ''}. Load Accounts' part first.`],
|
||||
campuses: church.profile.campuses.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
let profile = PROFILES[PROFILE_NAME];
|
||||
|
||||
const hex = (bytes = 16) => crypto.randomBytes(bytes).toString('hex');
|
||||
@@ -1316,9 +1374,23 @@ let campuses = [];
|
||||
|
||||
function buildCampuses() {
|
||||
const campus = (name, slug, address, colour, defaultLocation, order) => add('campus', {
|
||||
id: uuidv4(), name, slug, address, contactName: 'Lerato Khumalo', contactEmail: `${slug}@example.com`,
|
||||
id: uuidv4(), name, slug, address, contactName: staffName(0), contactEmail: `campus.${slug}@example.com`,
|
||||
colour, defaultLocation, order, createdAt: addTime(NOW, -300 * DAY), updatedAt: NOW,
|
||||
});
|
||||
if (profile.scenario) {
|
||||
// 3.8.0: the scenario church's own campuses, and people at the campus Accounts gives them.
|
||||
const colours = ['#2563eb', '#16a34a', '#ea580c'];
|
||||
campuses = demo.demoChurch(profile.scenario).profile.campuses.map((c, n) => campus(
|
||||
c.name, c.slug, c.address ? [c.address.line1, c.address.suburb, c.address.city].filter(Boolean).join(', ') : null,
|
||||
colours[n % colours.length], n === 0 ? 'Main auditorium' : `${c.name} campus hall`, n,
|
||||
));
|
||||
for (const u of rows.user) {
|
||||
const slug = userMeta.get(u.id)?.campus;
|
||||
const home = campuses.find(c => c.slug === slug);
|
||||
if (u.role === 'user' && home) u.homeCampusId = home.id;
|
||||
}
|
||||
return;
|
||||
}
|
||||
campuses = [
|
||||
campus('Central', 'central', '12 Church Street, Hatfield, Pretoria', '#2563eb', 'Main auditorium', 0),
|
||||
campus('North', 'north', '45 Zambezi Drive, Montana', '#16a34a', 'North campus hall', 1),
|
||||
@@ -1345,9 +1417,10 @@ function assignCampuses() {
|
||||
|
||||
/** Staff limited to one campus (a many-to-many, so it's set after the rows are in). */
|
||||
async function scopeStaff(tx) {
|
||||
const byName = (first) => staffTeam.find(s => s.name.startsWith(first));
|
||||
for (const [first, campusIdx] of [['Anri', 1], ['Daniel', 2]]) {
|
||||
await tx.user.update({ where: { id: byName(first).id }, data: { scopedCampuses: { connect: [{ id: campuses[campusIdx].id }] } } });
|
||||
// The third and fourth demo staff (Anri Botha and Daniel Pillay in the multicampus demo).
|
||||
for (const [staffIdx, campusIdx] of [[2, 1], [3, 2]]) {
|
||||
if (!staffTeam[staffIdx] || !campuses[campusIdx]) continue;
|
||||
await tx.user.update({ where: { id: staffTeam[staffIdx].id }, data: { scopedCampuses: { connect: [{ id: campuses[campusIdx].id }] } } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1363,7 +1436,7 @@ function buildBreakfast(people, { start, title, sold }) {
|
||||
price: 150,
|
||||
picture: IMG('photo-1414235077428-338989a2e8c0'),
|
||||
location: 'Church hall',
|
||||
contactName: 'Sipho Dlamini',
|
||||
contactName: staffName(1),
|
||||
});
|
||||
const ticket = addOption(event, { name: 'Breakfast ticket', price: 150, stockLimit: 60 });
|
||||
addCost(event, 'Breakfast catering', 'per_item', 85, ticket);
|
||||
@@ -1747,8 +1820,8 @@ function buildExtras(people, built) {
|
||||
function listProfiles() {
|
||||
console.log('\nDemo profiles — npm run demo:<name> (from the repo root):\n');
|
||||
for (const [name, p] of Object.entries(PROFILES)) {
|
||||
console.log(` ${name.padEnd(12)} ${p.title}`);
|
||||
for (const line of p.about) console.log(` ${''.padEnd(12)} ${line}`);
|
||||
console.log(` ${name.padEnd(17)} ${p.title}`);
|
||||
for (const line of p.about) console.log(` ${''.padEnd(17)} ${line}`);
|
||||
console.log('');
|
||||
}
|
||||
}
|
||||
@@ -1890,6 +1963,7 @@ async function main() {
|
||||
}
|
||||
|
||||
passwordHash = await hashPassword(DEMO_PASSWORD);
|
||||
const scenarioSubs = new Set(profile.scenario ? demo.demoPeople(profile.scenario).map(x => x.id) : []);
|
||||
const people = buildPeople();
|
||||
if (profile.campuses) buildCampuses();
|
||||
const events = profile.upcoming.map(key => UPCOMING[key](people));
|
||||
@@ -1900,7 +1974,9 @@ async function main() {
|
||||
|
||||
// 3.3.0: the church accounts of the people about to be cleared, so the old demo people leave
|
||||
// Accounts too (only demo addresses; Accounts checks).
|
||||
const oldSubs = (await prisma.user.findMany({ where: { id: { not: admin.id }, accountId: { not: null } }, select: { accountId: true } })).map(u => u.accountId);
|
||||
const oldSubs = (await prisma.user.findMany({ where: { id: { not: admin.id }, accountId: { not: null } }, select: { accountId: true } })).map(u => u.accountId)
|
||||
// 3.8.0: a scenario's people belong to Accounts' part of the scenario (loaded first): linked again, never removed.
|
||||
.filter(sub => !scenarioSubs.has(sub));
|
||||
const cleared = await prisma.$transaction(async (tx) => {
|
||||
const result = await clearData(tx);
|
||||
for (const model of INSERT_ORDER) {
|
||||
|
||||
@@ -29,6 +29,7 @@ const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: stri
|
||||
const { requiresTwoFactor } = require('../utils/twoFactor') as { requiresTwoFactor(u: { role: string }): boolean };
|
||||
const { logSecurityEvent } = require('../utils/securityEvents') as { logSecurityEvent(e: object): Promise<void> };
|
||||
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string | null };
|
||||
const whatsappStop = require('../utils/whatsappStop') as { clearStop(phone: string): Promise<string | null> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const PENDING_COOKIE = 'ev_signin';
|
||||
@@ -107,7 +108,7 @@ export async function userForClaims(claims: IdentityClaims): Promise<{ user: Eve
|
||||
}
|
||||
|
||||
/** Keeps Events' copy of the profile (for lists and messages) as Accounts has it. */
|
||||
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor'] }) {
|
||||
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor']; whatsapp_opted_out?: boolean }) {
|
||||
const data: Record<string, unknown> = {
|
||||
name: profile.name,
|
||||
// The 2FA method, for admins' list of staff (2.3.0); Accounts' `totp` is Events' `authenticator`.
|
||||
@@ -125,7 +126,15 @@ export async function updateLocalCopy(userId: string, profile: Pick<IdentityClai
|
||||
} else {
|
||||
data.phoneNumber = null;
|
||||
}
|
||||
// 3.8.0: the WhatsApp opt-out Accounts keeps for every product (absent from an Accounts before 1.9.0).
|
||||
if (profile.whatsapp_opted_out !== undefined) data.whatsappOptedOut = profile.whatsapp_opted_out;
|
||||
const before = profile.whatsapp_opted_out === false ? await prisma.user.findUnique({ where: { id: userId }, select: { whatsappOptedOut: true, phoneNumber: true } }) : null;
|
||||
await prisma.user.update({ where: { id: userId }, data });
|
||||
// Turned back on in Accounts: this site's own STOP for the number goes too.
|
||||
if (before?.whatsappOptedOut) {
|
||||
const phone = (data.phoneNumber as string | null | undefined) ?? before.phoneNumber;
|
||||
if (phone) await whatsappStop.clearStop(phone);
|
||||
}
|
||||
}
|
||||
|
||||
async function startSignIn(req: Request, res: Response) {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): a STOP this site's WhatsApp webhook received is
|
||||
* passed on to the church's Accounts (`whatsapp.optout`, contracts 1.20.0), which keeps the opt-out
|
||||
* for every product (the App, the Website, Accounts' own codes) and tells them all. Never fails the
|
||||
* STOP itself: it's kept here either way.
|
||||
*/
|
||||
import { accounts, accountsLink } from './client';
|
||||
import { viaAccounts } from './mode';
|
||||
|
||||
/** Passes a STOP on to Accounts; returns whether it did. `phone`: 27821234567. */
|
||||
export async function stopInAccounts(phone: string, keyword: string): Promise<boolean> {
|
||||
try {
|
||||
if (!(await viaAccounts())) return false;
|
||||
await (await accounts()).request({
|
||||
type: 'whatsapp.optout', actor: null, phone: `+${phone.replace(/^\+/, '')}`,
|
||||
receivedAt: new Date().toISOString(), keyword: String(keyword || 'STOP').trim().toUpperCase().slice(0, 40) || 'STOP',
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.warn('[accounts] WhatsApp STOP not passed on:', (e as Error).message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Where someone turns WhatsApp back on: their account page in the church's Accounts. */
|
||||
export async function accountPageUrl(): Promise<string | null> {
|
||||
try {
|
||||
if (!(await viaAccounts())) return null;
|
||||
const link = await accountsLink();
|
||||
return link ? `${link.url.replace(/\/$/, '')}/account` : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -214,9 +214,11 @@ const handleWebhook = async (req, res) => {
|
||||
|
||||
/**
|
||||
* An incoming WhatsApp message (WAWP `message` event). The only thing we act on is an
|
||||
* opt-out reply — "STOP" — which stops News & announcements on WhatsApp for that number
|
||||
* (event updates still go out). Only trusted when the URL carries our webhook secret,
|
||||
* since WAWP doesn't sign webhooks.
|
||||
* opt-out reply — "STOP". 3.8.0 (APP-1.0-PLAN decision 11): it stops all WhatsApp to that number
|
||||
* from every one of the church's products, event updates and codes included: kept here
|
||||
* (utils/whatsappStop), news turned off, and passed on to the church's Accounts, which tells the
|
||||
* others. Turned back on in Accounts; a site without Accounts takes a "START" reply. Only trusted
|
||||
* when the URL carries our webhook secret, since WAWP doesn't sign webhooks.
|
||||
*/
|
||||
async function handleIncomingMessage(req) {
|
||||
const crypto = require('crypto');
|
||||
@@ -236,16 +238,35 @@ async function handleIncomingMessage(req) {
|
||||
prisma.appSetting.upsert({ where: { key: 'wawp_webhook_last_seen' }, update: { value: now }, create: { key: 'wawp_webhook_last_seen', value: now } }).catch(() => {});
|
||||
|
||||
const payload = req.body?.payload || {};
|
||||
if (payload.fromMe || !isStopKeyword(payload.body)) return;
|
||||
if (payload.fromMe) return;
|
||||
const stop = isStopKeyword(payload.body);
|
||||
const { isStartKeyword, recordStop, clearStop } = require('../utils/whatsappStop');
|
||||
const { stopInAccounts, accountPageUrl } = require('../accounts/whatsappOptOut');
|
||||
if (!stop && !isStartKeyword(payload.body)) return;
|
||||
const phone = phoneFromChatId(payload.from);
|
||||
if (!phone) {
|
||||
// Groups, channels, and senders WhatsApp only identifies by a "LID" (no phone number).
|
||||
console.warn('[whatsapp webhook] STOP from a sender without a phone number:', payload.from);
|
||||
return;
|
||||
}
|
||||
const result = await whatsAppStop(phone);
|
||||
if (!result) return;
|
||||
await sendText(phone, "You won't get news and announcements from us on WhatsApp any more. You'll still get messages about events you've registered for.").catch(() => {});
|
||||
const { getSettingSync } = require('../utils/settingsCache');
|
||||
const church = getSettingSync('org_name', process.env.ORG_NAME || 'us');
|
||||
const accountPage = await accountPageUrl();
|
||||
if (!stop) {
|
||||
// START: only without Accounts (with it, Accounts keeps the opt-out: turned back on there).
|
||||
if (accountPage) {
|
||||
await sendText(phone, `To get WhatsApp messages from ${church} again, turn them back on on your account page: ${accountPage}`, { evenIfStopped: true }).catch(() => {});
|
||||
return;
|
||||
}
|
||||
await clearStop(phone);
|
||||
await sendText(phone, `WhatsApp messages from ${church} are back on. Reply STOP at any time to stop them.`).catch(() => {});
|
||||
return;
|
||||
}
|
||||
await recordStop(phone, { keyword: payload.body, source: 'events' });
|
||||
await whatsAppStop(phone);
|
||||
await stopInAccounts(phone, payload.body);
|
||||
const undo = accountPage ? `To turn them back on, go to ${accountPage}` : 'Reply START to turn them back on.';
|
||||
await sendText(phone, `You won't get WhatsApp messages from ${church} any more (event updates and codes come by email). ${undo}`, { evenIfStopped: true }).catch(() => {});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -270,7 +270,8 @@ function whatsAppNewsFooter(recipient) {
|
||||
|
||||
/** Recognises an opt-out reply ("STOP", "stop.", "Unsubscribe"). */
|
||||
function isStopKeyword(text) {
|
||||
return /^\s*(stop|unsubscribe|stop all|opt out|optout)\s*[.!]?\s*$/i.test(String(text || ''));
|
||||
// 3.8.0: STOPP and UITTEKEN (Afrikaans) too, as the church's Accounts reads them.
|
||||
return /^\s*(stop|stopp|unsubscribe|stop all|opt out|optout|uitteken)\s*[.!]?\s*$/i.test(String(text || ''));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -186,6 +186,8 @@ async function deliverCode(user, method, code, { allowFallback = true } = {}) {
|
||||
try {
|
||||
// sendText silently no-ops when WhatsApp isn't set up, so check first.
|
||||
if (!isValidZAPhone(user.phoneNumber) || !(await isConfigured())) throw new Error('WhatsApp unavailable');
|
||||
// 3.8.0: they replied STOP, so no WhatsApp: the code goes by email.
|
||||
if (await require('./whatsappStop').isWhatsAppStopped(user.phoneNumber)) throw new Error('WhatsApp turned off (STOP)');
|
||||
await sendText(user.phoneNumber, buildWATwoFactorCode({ name: user.name, code }));
|
||||
return { method: 'whatsapp', destination: maskPhone(user.phoneNumber) };
|
||||
} catch (e) {
|
||||
|
||||
@@ -222,10 +222,18 @@ async function requestPairingCode(phoneNumber) {
|
||||
|
||||
// ─── Messaging ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function sendText(toPhone, message) {
|
||||
/**
|
||||
* 3.8.0: nothing goes to a number that replied STOP (utils/whatsappStop.js), unless `evenIfStopped`
|
||||
* (only the one reply that confirms the STOP). Returns false when it skipped.
|
||||
*/
|
||||
async function sendText(toPhone, message, { evenIfStopped = false } = {}) {
|
||||
if (!(await isConfigured())) return;
|
||||
const chatId = toChatId(toPhone);
|
||||
if (!chatId) { console.warn('[whatsapp] Invalid phone, skipping text:', toPhone); return; }
|
||||
if (!evenIfStopped && (await require('./whatsappStop').isWhatsAppStopped(toPhone))) {
|
||||
console.info('[whatsapp] Not sent: the number replied STOP.');
|
||||
return false;
|
||||
}
|
||||
const { token, instanceId } = await getConfig();
|
||||
try {
|
||||
await axios.post(`${BASE}/send/text`, {
|
||||
@@ -251,6 +259,10 @@ async function sendPdf(toPhone, localPdfPath, filename, caption) {
|
||||
if (!(await isConfigured())) return;
|
||||
const chatId = toChatId(toPhone);
|
||||
if (!chatId) { console.warn('[whatsapp] Invalid phone, skipping PDF:', toPhone); return; }
|
||||
if (await require('./whatsappStop').isWhatsAppStopped(toPhone)) {
|
||||
console.info('[whatsapp] PDF not sent: the number replied STOP.');
|
||||
return false;
|
||||
}
|
||||
|
||||
const tempDir = path.join(__dirname, '../../public/uploads/tickets-temp');
|
||||
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): a STOP to the church's WhatsApp number means no
|
||||
* WhatsApp from any of the church's products, event updates and codes included, until the person
|
||||
* turns it back on (in the church's Accounts; or, without Accounts, by replying START here).
|
||||
*
|
||||
* Two records, either of which stops a message:
|
||||
* - `WhatsAppStop`, by number: STOPs this site's webhook received (with or without an account).
|
||||
* - `User.whatsappOptedOut`: from Accounts (`user.updated` carries `whatsapp_opted_out`), so a STOP
|
||||
* another product received reaches Events too.
|
||||
*
|
||||
* `sendText` / `sendPdf` (utils/whatsapp.js) check `isWhatsAppStopped` before every message.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const prisma = require('../config/db');
|
||||
|
||||
function normalise(raw) {
|
||||
return require('./whatsapp').normalizeZAPhone(raw);
|
||||
}
|
||||
|
||||
/** The ways a number may be stored on an account: 27821234567, +27821234567, 0821234567. */
|
||||
function storedForms(n) {
|
||||
return [n, `+${n}`, `0${n.slice(2)}`];
|
||||
}
|
||||
|
||||
/** Whether nothing may go to this number on WhatsApp. */
|
||||
async function isWhatsAppStopped(rawPhone) {
|
||||
const n = normalise(rawPhone);
|
||||
if (!n) return false;
|
||||
if (await prisma.whatsAppStop.findUnique({ where: { phone: n } })) return true;
|
||||
const user = await prisma.user.findFirst({ where: { whatsappOptedOut: true, phoneNumber: { in: storedForms(n) } }, select: { id: true } });
|
||||
return !!user;
|
||||
}
|
||||
|
||||
/** A STOP from this number: kept, and every account with it opted out. Returns the number (27…) or null. */
|
||||
async function recordStop(rawPhone, { keyword, source = 'events' }) {
|
||||
const n = normalise(rawPhone);
|
||||
if (!n) return null;
|
||||
const word = String(keyword || 'STOP').trim().toUpperCase().slice(0, 40);
|
||||
await prisma.whatsAppStop.upsert({
|
||||
where: { phone: n },
|
||||
update: { keyword: word, source, receivedAt: new Date() },
|
||||
create: { phone: n, keyword: word, source, receivedAt: new Date() },
|
||||
});
|
||||
await prisma.user.updateMany({ where: { phoneNumber: { in: storedForms(n) } }, data: { whatsappOptedOut: true } });
|
||||
return n;
|
||||
}
|
||||
|
||||
/** WhatsApp back on for this number (Accounts said so, or a START here without Accounts). */
|
||||
async function clearStop(rawPhone) {
|
||||
const n = normalise(rawPhone);
|
||||
if (!n) return null;
|
||||
await prisma.whatsAppStop.deleteMany({ where: { phone: n } });
|
||||
await prisma.user.updateMany({ where: { phoneNumber: { in: storedForms(n) } }, data: { whatsappOptedOut: false } });
|
||||
return n;
|
||||
}
|
||||
|
||||
/** "START" (or "BEGIN", Afrikaans "BEGIN"/"AAN"): WhatsApp back on, for a site without Accounts. */
|
||||
function isStartKeyword(text) {
|
||||
return /^\s*(start|unstop|begin|aan)\s*[.!]?\s*$/i.test(String(text || ''));
|
||||
}
|
||||
|
||||
module.exports = { isWhatsAppStopped, recordStop, clearStop, isStartKeyword, storedForms };
|
||||
@@ -0,0 +1,42 @@
|
||||
// 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): the WhatsApp opt-out Accounts keeps for every
|
||||
// product reaches Events in user.updated (`whatsapp_opted_out`), both ways.
|
||||
const mockUpdates: { id: string; data: Record<string, unknown> }[] = [];
|
||||
let mockBefore: { whatsappOptedOut: boolean; phoneNumber: string | null } | null = null;
|
||||
|
||||
jest.mock('../src/config/db', () => ({
|
||||
user: {
|
||||
findFirst: async () => null,
|
||||
findUnique: async () => mockBefore,
|
||||
update: async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => { mockUpdates.push({ id: where.id, data }); return {}; },
|
||||
},
|
||||
}));
|
||||
jest.mock('../src/utils/whatsappStop', () => ({ clearStop: jest.fn().mockResolvedValue('27821234567') }));
|
||||
|
||||
import { updateLocalCopy } from '../src/accounts/signin';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const { clearStop } = require('../src/utils/whatsappStop') as { clearStop: jest.Mock };
|
||||
|
||||
const profile = (over: Record<string, unknown> = {}) => ({
|
||||
name: 'Thandi Example', email: 'thandi@hope.test', phone_number: '+27821234567', news_consent: { email: true, whatsapp: false }, ...over,
|
||||
});
|
||||
|
||||
beforeEach(() => { mockUpdates.length = 0; mockBefore = null; clearStop.mockClear(); });
|
||||
|
||||
test('opted out in Accounts: no WhatsApp here either', async () => {
|
||||
await updateLocalCopy('u1', profile({ whatsapp_opted_out: true }));
|
||||
expect(mockUpdates[0]!.data.whatsappOptedOut).toBe(true);
|
||||
expect(clearStop).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('turned back on in Accounts: on here, and this site\'s own STOP for the number goes', async () => {
|
||||
mockBefore = { whatsappOptedOut: true, phoneNumber: '+27821234567' };
|
||||
await updateLocalCopy('u1', profile({ whatsapp_opted_out: false }));
|
||||
expect(mockUpdates[0]!.data.whatsappOptedOut).toBe(false);
|
||||
expect(clearStop).toHaveBeenCalledWith('+27821234567');
|
||||
});
|
||||
|
||||
test('an Accounts before 1.9.0 (no field) changes nothing about it', async () => {
|
||||
await updateLocalCopy('u1', profile());
|
||||
expect('whatsappOptedOut' in mockUpdates[0]!.data).toBe(false);
|
||||
});
|
||||
@@ -78,6 +78,7 @@ jest.mock('../src/utils/email', () => ({
|
||||
buildTwoFactorCodeEmail: ({ code }) => ({ text: `code:${code}`, html: '' }),
|
||||
}));
|
||||
jest.mock('../src/utils/waMessages', () => ({ buildWATwoFactorCode: ({ code }) => `code:${code}` }));
|
||||
jest.mock('../src/utils/whatsappStop', () => ({ isWhatsAppStopped: async () => false }));
|
||||
jest.mock('../src/utils/whatsapp', () => ({
|
||||
isValidZAPhone: (p) => /^27\d{9}$/.test(String(p || '')),
|
||||
isConfigured: async () => mockWhatsApp.configured,
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): STOP to the church's WhatsApp number means no
|
||||
// WhatsApp from any of its products: kept by number and per account, checked before every send,
|
||||
// passed on to Accounts, and turned back on there (or by START without Accounts).
|
||||
jest.mock('../src/config/db', () => ({
|
||||
user: { findFirst: jest.fn(), updateMany: jest.fn() },
|
||||
whatsAppStop: { findUnique: jest.fn(), upsert: jest.fn(), deleteMany: jest.fn() },
|
||||
appSetting: {
|
||||
findMany: jest.fn().mockResolvedValue([{ key: 'WAWP_ACCESS_TOKEN', value: 'token' }, { key: 'WAWP_INSTANCE_ID', value: 'HOPE01' }]),
|
||||
findUnique: jest.fn().mockResolvedValue({ value: 's3cret' }),
|
||||
upsert: jest.fn().mockResolvedValue({}),
|
||||
},
|
||||
}));
|
||||
jest.mock('axios', () => ({ post: jest.fn().mockResolvedValue({ data: {} }) }));
|
||||
jest.mock('../src/accounts/whatsappOptOut', () => ({ stopInAccounts: jest.fn().mockResolvedValue(true), accountPageUrl: jest.fn() }));
|
||||
jest.mock('../src/utils/settingsCache', () => ({ getSettingSync: () => 'Hope Family Church' }));
|
||||
jest.mock('../src/utils/privacy', () => ({ ...jest.requireActual('../src/utils/privacy'), whatsAppStop: jest.fn().mockResolvedValue('account') }));
|
||||
jest.mock('../src/utils/encryption', () => ({ encrypt: (v) => v, decrypt: (v) => v }));
|
||||
|
||||
const prisma = require('../src/config/db');
|
||||
const axios = require('axios');
|
||||
const { stopInAccounts, accountPageUrl } = require('../src/accounts/whatsappOptOut');
|
||||
const privacy = require('../src/utils/privacy');
|
||||
const stop = require('../src/utils/whatsappStop');
|
||||
const { sendText } = require('../src/utils/whatsapp');
|
||||
const { handleWebhook } = require('../src/controllers/whatsappController');
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
prisma.whatsAppStop.findUnique.mockResolvedValue(null);
|
||||
prisma.user.findFirst.mockResolvedValue(null);
|
||||
accountPageUrl.mockResolvedValue('https://accounts.hope.test/account');
|
||||
});
|
||||
|
||||
const res = () => ({ status() { return this; }, json() { return this; } });
|
||||
/** WAWP's message event, through the real handler (which answers first, then works). */
|
||||
async function wawp(body, from = '27821234567@c.us', secret = 's3cret') {
|
||||
await handleWebhook({ query: { secret }, body: { event: 'message', payload: { from, body, fromMe: false } } }, res());
|
||||
}
|
||||
const sentTexts = () => axios.post.mock.calls.filter(([url]) => url.endsWith('/send/text')).map(([, b]) => ({ to: b.chatId, text: b.message }));
|
||||
|
||||
describe('isWhatsAppStopped', () => {
|
||||
test('a number that replied STOP here', async () => {
|
||||
prisma.whatsAppStop.findUnique.mockResolvedValueOnce({ phone: '27821234567' });
|
||||
expect(await stop.isWhatsAppStopped('082 123 4567')).toBe(true);
|
||||
expect(prisma.whatsAppStop.findUnique).toHaveBeenCalledWith({ where: { phone: '27821234567' } });
|
||||
});
|
||||
|
||||
test('an account Accounts says opted out, however its number is written', async () => {
|
||||
prisma.user.findFirst.mockResolvedValueOnce({ id: 'u1' });
|
||||
expect(await stop.isWhatsAppStopped('+27821234567')).toBe(true);
|
||||
expect(prisma.user.findFirst.mock.calls[0][0].where).toEqual({ whatsappOptedOut: true, phoneNumber: { in: ['27821234567', '+27821234567', '0821234567'] } });
|
||||
});
|
||||
|
||||
test('anyone else, and numbers WhatsApp can\'t reach', async () => {
|
||||
expect(await stop.isWhatsAppStopped('0821234567')).toBe(false);
|
||||
expect(await stop.isWhatsAppStopped('not a number')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('every send checks it', () => {
|
||||
test('nothing goes to a stopped number', async () => {
|
||||
prisma.whatsAppStop.findUnique.mockResolvedValue({ phone: '27821234567' });
|
||||
expect(await sendText('0821234567', 'Reminder: Youth Camp starts tomorrow')).toBe(false);
|
||||
expect(axios.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('other numbers are sent to as before', async () => {
|
||||
await sendText('0829999999', 'Hello');
|
||||
expect(sentTexts()).toEqual([{ to: '27829999999@c.us', text: 'Hello' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a STOP reply', () => {
|
||||
test('is kept, turns news off, goes to Accounts, and is answered once with how to undo it', async () => {
|
||||
await wawp('Stop');
|
||||
expect(prisma.whatsAppStop.upsert.mock.calls[0][0].create).toMatchObject({ phone: '27821234567', keyword: 'STOP', source: 'events' });
|
||||
expect(prisma.user.updateMany).toHaveBeenCalledWith({ where: { phoneNumber: { in: ['27821234567', '+27821234567', '0821234567'] } }, data: { whatsappOptedOut: true } });
|
||||
expect(privacy.whatsAppStop).toHaveBeenCalledWith('27821234567');
|
||||
expect(stopInAccounts).toHaveBeenCalledWith('27821234567', 'Stop');
|
||||
const [reply] = sentTexts();
|
||||
expect(reply.to).toBe('27821234567@c.us');
|
||||
expect(reply.text).toMatch(/won't get WhatsApp messages from Hope Family Church/);
|
||||
expect(reply.text).toContain('https://accounts.hope.test/account');
|
||||
});
|
||||
|
||||
test('Afrikaans STOPP and UITTEKEN count; other messages, groups and a wrong secret don\'t', async () => {
|
||||
await wawp('STOPP');
|
||||
await wawp('uitteken');
|
||||
expect(stopInAccounts).toHaveBeenCalledTimes(2);
|
||||
jest.clearAllMocks();
|
||||
await wawp('Thanks for the reminder!');
|
||||
await wawp('STOP', '1203630@g.us');
|
||||
await wawp('STOP', '27821234567@c.us', 'wrong');
|
||||
expect(prisma.whatsAppStop.upsert).not.toHaveBeenCalled();
|
||||
expect(stopInAccounts).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('START', () => {
|
||||
test('without Accounts: WhatsApp back on for the number', async () => {
|
||||
accountPageUrl.mockResolvedValue(null);
|
||||
await wawp('START');
|
||||
expect(prisma.whatsAppStop.deleteMany).toHaveBeenCalledWith({ where: { phone: '27821234567' } });
|
||||
expect(prisma.user.updateMany).toHaveBeenCalledWith({ where: { phoneNumber: { in: ['27821234567', '+27821234567', '0821234567'] } }, data: { whatsappOptedOut: false } });
|
||||
expect(sentTexts()[0].text).toMatch(/back on/);
|
||||
});
|
||||
|
||||
test('with Accounts: only a pointer to the account page (Accounts keeps the opt-out)', async () => {
|
||||
await wawp('start');
|
||||
expect(prisma.whatsAppStop.deleteMany).not.toHaveBeenCalled();
|
||||
expect(sentTexts()[0].text).toContain('https://accounts.hope.test/account');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,11 @@
|
||||
# Handover — where things stand and how to carry on
|
||||
|
||||
> **2026-11-30:** Events is now at **3.8.0** (released, not deployed; 3.7.2 is rolled out). Where
|
||||
> it stands and what's next is kept in the root [HANDOVER.md](../../../docs/HANDOVER.md) and
|
||||
> [VERSIONS.md](../../../docs/VERSIONS.md); this file keeps the "where the code lives" notes.
|
||||
> Changed since the note below: STOP stops all WhatsApp (see "Where WhatsApp STOP lives (3.8.0)")
|
||||
> and the demo has the eight demo scenarios (see "Demo data").
|
||||
|
||||
Last updated: 2026-11-18, after **2.3.1** (Next.js 16.4.6 for security advisories, on top of 2.3.0;
|
||||
released, not deployed yet; servers still run 2.1.1 until they're adopted, see the root
|
||||
[ROLLOUT-1.0.md](../../../docs/ROLLOUT-1.0.md)).
|
||||
@@ -263,7 +269,8 @@ Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md
|
||||
`CommunicationConsent`), unsubscribe tokens (HMAC with `JWT_SECRET`, never expire),
|
||||
`filterRecipients` (every bulk send goes through it: `kind` 'update' passes, 'news' only to
|
||||
opted-in accounts and not to `MessagingOptOut` addresses), email/WhatsApp footers, STOP
|
||||
handling, data requests, `deletionBlockers`, `anonymiseUser`, `exportUserData` + PDF.
|
||||
handling (news off; from 3.8.0 all WhatsApp too, below), data requests, `deletionBlockers`,
|
||||
`anonymiseUser`, `exportUserData` + PDF.
|
||||
Tests: `backend/tests/privacy.test.js`; e2e: `e2e/privacy.spec.ts`.
|
||||
- `controllers/privacyController.js` + `routes/privacyRoutes.js` (`/api/privacy`).
|
||||
- Bulk sends: `broadcastController`, `whatsappBroadcastController`, and `emailEventAttendees` /
|
||||
@@ -472,6 +479,22 @@ Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md
|
||||
- Frontend: `components/admin/WebhooksTab.tsx`. Tests: `tests/webhooks.test.js`, e2e
|
||||
`webhooks.spec.ts` (runs a receiver on localhost:5199; e2e backend has `WEBHOOKS_ALLOW_PRIVATE`).
|
||||
|
||||
## Where WhatsApp STOP lives (3.8.0)
|
||||
|
||||
- APP-1.0-PLAN decision 11: STOP to the church's WhatsApp number stops **all** WhatsApp from every
|
||||
one of the church's products (event updates, tickets, kids messages, 2FA codes), not only news.
|
||||
- `src/utils/whatsappStop.js`: `isWhatsAppStopped` (by number in `WhatsAppStop`, or an account with
|
||||
`User.whatsappOptedOut`, set from Accounts' `user.updated` `whatsapp_opted_out`), `recordStop`,
|
||||
`clearStop`, `isStartKeyword`. `sendText` / `sendPdf` (`utils/whatsapp.js`) check it before every
|
||||
message; only the reply that confirms a STOP is sent anyway (`evenIfStopped`). 2FA codes for a
|
||||
stopped number go by email (`utils/twoFactor.js`).
|
||||
- The webhook (`handleIncomingMessage`): STOP → kept, news off (`privacy.whatsAppStop`), passed on to
|
||||
Accounts (`src/accounts/whatsappOptOut.ts`, `whatsapp.optout`); the reply links Accounts' account
|
||||
page. START turns it back on only without Accounts (with Accounts it's turned on there, and
|
||||
`updateLocalCopy` clears this site's STOP for the number).
|
||||
- **Anything new that sends WhatsApp** goes through `sendText` / `sendPdf`, never WAWP directly.
|
||||
- Tests: `tests/whatsappStop.test.js`, `tests/accountsWhatsappOptOut.test.ts`.
|
||||
|
||||
## Demo data (1.48.2)
|
||||
|
||||
- `backend/scripts/set-demo.js` builds everything in memory and writes it with `createMany` in one
|
||||
@@ -486,6 +509,14 @@ Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md
|
||||
- Tried by seeding all four into a throwaway database and calling the API (events, series page and
|
||||
report, season pass, kids board, roster, attendance registers, certificate check, cashups, campus
|
||||
scoping).
|
||||
- **3.8.0, the demo scenarios** (APP-1.0-PLAN §12): `PROFILES` also has one per scenario
|
||||
(`agent.DEMO_SCENARIOS`), each a copy of one of the four kinds (`SCENARIO_KINDS`) built around
|
||||
the scenario's church from `@crosscode/demo`: its people (`buildScenarioPeople`: leads become the
|
||||
staff, at most 260 members), its campuses (`buildCampuses`), its staff as event contacts
|
||||
(`staffName`). Builders stop when a small church runs out of people (`nextBuyer` returns null),
|
||||
so don't add one that needs a fixed number of people without the same guard. The scenario's
|
||||
own people are never sent to `people.removeDemo` (Accounts loaded them first). All eight and
|
||||
the four were loaded into a throwaway PostgreSQL 18 database before release.
|
||||
|
||||
## Where the dashboard and palette live (1.49.0)
|
||||
|
||||
@@ -745,6 +776,10 @@ Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md
|
||||
into WAWP (events `message` + `session.status`), and only for senders WhatsApp identifies by
|
||||
phone number — a sender known only by a "LID" is logged and ignored (they can still use the
|
||||
link in the message).
|
||||
- (3.8.0) No test yet for a 2FA code falling back to email for a number that replied STOP.
|
||||
- (3.8.0) The demo scenarios reuse the four demos' events: a scenario's own events (Grace
|
||||
Cathedral's concert series, Ignite's youth conference) and Afrikaans content for Karoo
|
||||
Gemeenskapskerk aren't built yet.
|
||||
- There's no log of individual messages sent, so "Download my data" can't include "messages
|
||||
sent to you" yet.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.7.2",
|
||||
"version": "3.8.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -1,5 +1,31 @@
|
||||
# Changelog — Church Website
|
||||
|
||||
## [1.8.0] — 2026-11-30
|
||||
|
||||
No migration, no new environment settings. The backend now uses `@crosscode/demo` (built by
|
||||
`crosscode deploy` with the other shared packages).
|
||||
|
||||
### Added
|
||||
|
||||
- **Demo scenarios** (APP-1.0-PLAN §12): `npm run demo -- --profile <p> --scenario <p>` (the
|
||||
scenario must be the profile of the same name) loads a profile as part of the scenario, so the
|
||||
Website shows the same church as Accounts, Cross Events and the App.
|
||||
- **Leaders:** each profile's `scenarioTeam` (`src/demo/seeds.ts`) names four parts, roles and
|
||||
portraits, the pastor first; the names are the scenario's people from `demoPeople`. The pastor
|
||||
is the home page's pastor and the messages' speaker, and every portrait's alt text is the new
|
||||
name. None of the profile's own leader names is left.
|
||||
- **Events:** with a linked Cross Events, a scenario load makes no simple events of its own (and
|
||||
no pictures for them), turns on that link's **Show events from** and fetches Events' whole
|
||||
feed at once (`syncLink`, full), so Events' events show, never copied. If Events can't be
|
||||
reached the load still succeeds and says so; the 15-minute sync catches up. Without Events, the
|
||||
profile's own three events, as before.
|
||||
- On a site with no church profile at all, a scenario saves the scenario's church (from
|
||||
`@crosscode/demo`) instead of Acacia Hill.
|
||||
- `crosscode demo <church> website --profile <p> --scenario <p>` passes `--scenario` on (agent
|
||||
1.7.0 sends it for the Hub's **Load a demo scenario**) and refuses a release before 1.8.0;
|
||||
`packages/demo` joins the Website's shared packages (`website_shared_packages`,
|
||||
`website_build`).
|
||||
|
||||
## [1.7.1] — 2026-11-28
|
||||
|
||||
One migration (`20261128000000_photo_framing`: a nullable `framing` column on `Ministry`,
|
||||
|
||||
@@ -3,6 +3,12 @@
|
||||
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.8.0
|
||||
|
||||
- Behind the scenes, Cross Code's demonstration websites can now be loaded as part of a whole demo
|
||||
church, with the same people and events as its Accounts, Events site and App. Nothing changes on
|
||||
your own website.
|
||||
|
||||
## 1.7.1
|
||||
|
||||
- **Move and zoom now works for ministries, your team and events too**, not only for page
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.7.1",
|
||||
"version": "1.8.0",
|
||||
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -20,6 +20,7 @@
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"cron-parser": "^5.10.2",
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
* 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 -- --profile <profile> --scenario <profile> [--force] 1.8.0: as part of that demo scenario
|
||||
* (its people lead; with Cross Events
|
||||
* linked, Events' events through the feed)
|
||||
* npm run demo -- --list the profiles
|
||||
*
|
||||
* It replaces the site's content, so a site that has been published needs --force. On a server,
|
||||
@@ -22,7 +25,7 @@ const arg = (name: string) => {
|
||||
const i = process.argv.indexOf(`--${name}`);
|
||||
return i > 0 ? process.argv[i + 1] : undefined;
|
||||
};
|
||||
const usage = 'Usage: npm run demo -- --template heritage|bold|community|clean | --profile <profile> [--force] | --list';
|
||||
const usage = 'Usage: npm run demo -- --template heritage|bold|community|clean | --profile <profile> [--scenario <profile>] [--force] | --list';
|
||||
|
||||
if (process.argv.includes('--list')) {
|
||||
for (const s of demoSeeds()) console.log(`${s.id.padEnd(18)} ${s.label}`);
|
||||
@@ -35,6 +38,18 @@ if (!what.success) {
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// A demo scenario loads the profile of the same name (contracts agent.DEMO_SCENARIOS).
|
||||
const scenarioArg = arg('scenario');
|
||||
const scenario = scenarioArg !== undefined ? agent.demoScenarioSchema.safeParse(scenarioArg) : null;
|
||||
if (scenario && !scenario.success) {
|
||||
console.error(`Unknown scenario "${scenarioArg}" (npm run demo -- --list).`);
|
||||
process.exit(2);
|
||||
}
|
||||
if (scenario && scenario.data !== profileArg) {
|
||||
console.error(`The ${scenario.data} scenario loads the ${scenario.data} profile: --profile ${scenario.data} --scenario ${scenario.data}.`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const ctx = createCtx(loadConfig(), db);
|
||||
const published = await db.siteVersion.findFirst({ where: { NOT: { publishedBy: 'demo' } } });
|
||||
@@ -43,6 +58,9 @@ if (published && !process.argv.includes('--force')) {
|
||||
await db.$disconnect();
|
||||
process.exit(1);
|
||||
}
|
||||
const version = await loadDemo(ctx, what.data);
|
||||
console.log(`Demo ${what.data} loaded and published (version ${version.number}).`);
|
||||
const version = await loadDemo(ctx, what.data, { scenario: scenario?.data });
|
||||
console.log(`Demo ${what.data}${scenario ? ' (demo scenario)' : ''} loaded and published (version ${version.number}).`);
|
||||
const sync = version.eventsSync;
|
||||
if (sync?.ok) console.log(`Showing Cross Events' events: ${sync.imported} fetched.`);
|
||||
else if (sync) console.warn(`Cross Events' events couldn't be fetched yet (${sync.error}); the next sync, within 15 minutes, brings them.`);
|
||||
await db.$disconnect();
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
* 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.
|
||||
*
|
||||
* 1.8.0: a demo scenario (`--scenario`, APP-1.0-PLAN §12) loads a profile as part of the same
|
||||
* church in every product: the leaders are the scenario's people (`@crosscode/demo`), and with a
|
||||
* linked Cross Events the site shows Events' events through the feed instead of making its own.
|
||||
*
|
||||
* It replaces the Website's content (never the admins), so the script refuses on a site that has
|
||||
* been published unless told otherwise.
|
||||
*/
|
||||
@@ -18,12 +22,13 @@ import { fileURLToPath } from 'node:url';
|
||||
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 { markRemoved, notifyLinks } from '../feed/feed.js';
|
||||
import { demoChurch, demoParts, demoPeople } from '@crosscode/demo';
|
||||
import { markRemoved, notifyLinks, syncLink, type SyncResult } from '../feed/feed.js';
|
||||
import type { SectionData } from '../site/sections.js';
|
||||
import { publish } from '../site/snapshot.js';
|
||||
import { TEMPLATE_HEADERS, TEMPLATE_VARIANTS, SECTION_TYPES, defaultDesign, type SiteDesign } from '../site/variants.js';
|
||||
import { MAX_WIDTH, WIDTHS, processImage, type Sizes } from '../admin/media.js';
|
||||
import { DEMO_SEEDS, type DemoPhotos, type DemoSeed } from './seeds.js';
|
||||
import { DEMO_SEEDS, type DemoPhotos, type DemoSeed, type ProfileSeed } from './seeds.js';
|
||||
|
||||
export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' };
|
||||
|
||||
@@ -57,6 +62,41 @@ export function demoProfile(publicUrl: string): Church {
|
||||
} as Church;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1.8.0: a scenario's church as a profile, for a scenario loaded on a site that has no profile at
|
||||
* all (Accounts normally has it first and the site reads it from there).
|
||||
*/
|
||||
export function scenarioProfile(publicUrl: string, scenario: agent.DemoScenarioKey): Church {
|
||||
const p = demoChurch(scenario).profile;
|
||||
const base = demoProfile(publicUrl);
|
||||
return {
|
||||
...base,
|
||||
name: p.name, shortName: p.shortName, timezone: p.timezone, locale: p.locale, campuses: p.campuses, serviceTimes: p.serviceTimes, social: p.social,
|
||||
branding: { ...base.branding, colours: p.colours, style: p.style },
|
||||
contact: { ...p.contact, phone: null, whatsapp: null },
|
||||
links: { ...base.links, accounts: `https://example.com/accounts/${demoChurch(scenario).slug}` },
|
||||
} as Church;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1.8.0: a profile's seed with the scenario's people as its leaders (`scenarioTeam`), the pastor
|
||||
* first, each with the portrait chosen for them.
|
||||
*/
|
||||
export function scenarioSeed(seed: ProfileSeed, scenario: agent.DemoScenarioKey): DemoSeed {
|
||||
const parts = demoParts(scenario);
|
||||
const leads = demoPeople(scenario).filter((p) => parts.has(p.email));
|
||||
const team = seed.scenarioTeam.map(([part, role, photo]) => {
|
||||
const person = leads.find((p) => parts.get(p.email)!.includes(part));
|
||||
if (!person) throw new Error(`The ${scenario} scenario has no one who is ${part}.`);
|
||||
return { name: person.name, role, photo };
|
||||
});
|
||||
return {
|
||||
...seed,
|
||||
leaders: team.map((l) => [l.name, l.role]),
|
||||
photos: { ...seed.photos, pastor: team[0]!.photo, team: [team[1]!.photo, team[2]!.photo, team[3]!.photo] },
|
||||
};
|
||||
}
|
||||
|
||||
/** Hills, a sun and a path in the church's colours (SVG): what stands in for a demo photo that is missing. */
|
||||
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'];
|
||||
@@ -132,14 +172,14 @@ async function demoAsset(ctx: Ctx, uploadDir: string, key: string, alt: string,
|
||||
}
|
||||
|
||||
/** The demo's pictures by slot (hero, collage2, collage3, welcome, pastor, invite, and the four ministries). */
|
||||
async function demoMedia(ctx: Ctx, uploadDir: string, photos: DemoPhotos, pastorName: string, team: string[], colours: { primary: string; accent: string }): Promise<Ids> {
|
||||
async function demoMedia(ctx: Ctx, uploadDir: string, photos: DemoPhotos, pastorName: string, team: string[], colours: { primary: string; accent: string }, withEvents: boolean): Promise<Ids> {
|
||||
const slots: [string, string, string | null][] = [
|
||||
['hero', photos.hero, null], ['collage2', photos.collage[0], null], ['collage3', photos.collage[1], null],
|
||||
['welcome', photos.welcome, null], ['pastor', photos.pastor, pastorName], ['invite', photos.invite, null],
|
||||
...photos.ministries.map((p, i) => [`ministry${i}`, p, null] as [string, string, string | null]),
|
||||
...photos.team.map((p, i) => [`team${i}`, p, team[i] ?? null] as [string, string, string | null]),
|
||||
...photos.messages.map((p, i) => [`message${i}`, p, null] as [string, string, string | null]),
|
||||
...photos.events.map((p, i) => [`event${i}`, p, null] as [string, string, string | null]),
|
||||
...(withEvents ? photos.events : []).map((p, i) => [`event${i}`, p, null] as [string, string, string | null]),
|
||||
];
|
||||
fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true });
|
||||
const ids: Ids = {};
|
||||
@@ -224,18 +264,27 @@ export const isDemoTemplate = (v: string): v is WebsiteTemplate => (WEBSITE_TEMP
|
||||
* 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).
|
||||
*
|
||||
* `scenario` (1.8.0): part of loading that demo scenario, whose church the profile is (the same
|
||||
* name: the script refuses any other). The leaders are the scenario's people, and with a linked
|
||||
* Cross Events the site makes no events of its own: it shows Events' through the feed.
|
||||
*/
|
||||
export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDemoProfile, opts: { uploadDir?: string; publishedBy?: string } = {}) {
|
||||
export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDemoProfile, opts: { uploadDir?: string; publishedBy?: string; scenario?: agent.DemoScenarioKey } = {}) {
|
||||
const db = ctx.db;
|
||||
const uploadDir = opts.uploadDir ?? ctx.config.uploadDir ?? defaultUploadDir();
|
||||
const classic = isDemoTemplate(what);
|
||||
const seed: DemoSeed = classic ? { ...CLASSIC, template: what } : DEMO_SEEDS[what];
|
||||
const scenario = opts.scenario ?? null;
|
||||
if (scenario && scenario !== what) throw new Error(`The ${scenario} scenario loads the ${scenario} profile, not ${what}.`);
|
||||
const seed: DemoSeed = classic ? { ...CLASSIC, template: what } : scenario ? scenarioSeed(DEMO_SEEDS[what], scenario) : DEMO_SEEDS[what];
|
||||
const extra = classic ? CLASSIC : null;
|
||||
// A scenario's events are Cross Events' when the church has it: shown through the feed, never copied.
|
||||
const eventsLink = scenario ? await db.productLink.findFirst({ where: { product: 'events' } }) : null;
|
||||
|
||||
// The church: Acacia Hill for a template; else whoever the site belongs to.
|
||||
// The church: Acacia Hill for a template; else whoever the site belongs to (in a scenario,
|
||||
// Accounts has the scenario's church by now).
|
||||
let church = classic ? null : await churchProfile(ctx);
|
||||
if (!church) {
|
||||
church = demoProfile(ctx.config.publicUrl);
|
||||
church = scenario ? scenarioProfile(ctx.config.publicUrl, scenario) : demoProfile(ctx.config.publicUrl);
|
||||
await ctx.settings.set('church_profile_local', JSON.stringify(church));
|
||||
}
|
||||
const name = church.name;
|
||||
@@ -261,7 +310,7 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe
|
||||
const [pastorName] = seed.leaders[0]!;
|
||||
const ministryNames = seed.ministries.map(([, n]) => t(n));
|
||||
const speaker = extra?.pastorName ?? pastorName;
|
||||
const img = await demoMedia(ctx, uploadDir, seed.photos, speaker, seed.leaders.slice(1).map(([name]) => name), colours);
|
||||
const img = await demoMedia(ctx, uploadDir, seed.photos, speaker, seed.leaders.slice(1).map(([name]) => name), colours, !eventsLink);
|
||||
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 } });
|
||||
|
||||
@@ -330,12 +379,18 @@ export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDe
|
||||
}
|
||||
n = 0;
|
||||
const made: string[] = [];
|
||||
for (const [slug, title, inDays, description] of seed.events) {
|
||||
for (const [slug, title, inDays, description] of eventsLink ? [] : seed.events) {
|
||||
const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3);
|
||||
made.push((await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: t(seed.venue), description: t(description), imageId: img[`event${n++}`] ?? null, publishedAt: now } })).id);
|
||||
}
|
||||
const version = await publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, classic ? `Demo church on ${seed.template}` : `Demo: ${seed.label}`);
|
||||
// Linked products fetch the feed now, not at their next poll (one try; the poll catches up).
|
||||
await notifyLinks(ctx, [...gone, ...made]).catch(() => {});
|
||||
return version;
|
||||
let eventsSync: SyncResult | null = null;
|
||||
if (eventsLink) {
|
||||
// Show Events' events (the scenario loaded them just before), the whole list at once.
|
||||
const link = await db.productLink.update({ where: { installId: eventsLink.installId }, data: { showEvents: true } });
|
||||
eventsSync = await syncLink(ctx, link, { full: true });
|
||||
}
|
||||
return { ...version, eventsSync };
|
||||
}
|
||||
|
||||
@@ -8,9 +8,15 @@
|
||||
* profile of each template starts on the template's other recommended variants and header, so the
|
||||
* eight show every recommended look.
|
||||
*
|
||||
* 1.8.0: a profile is also a demo scenario's church (contracts `agent.DEMO_SCENARIOS`, APP-1.0-PLAN
|
||||
* §12). Loaded as part of the scenario (`--scenario`), its leaders are the scenario's people from
|
||||
* `@crosscode/demo` (`scenarioTeam`: their part, role and portrait), the same people as in Accounts,
|
||||
* Cross Events and the App.
|
||||
*
|
||||
* Every person and place in here is made up. A profile id never changes once released.
|
||||
*/
|
||||
import { agent, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { DemoPart } from '@crosscode/demo';
|
||||
|
||||
type WebsiteDemoProfile = agent.WebsiteDemoProfile;
|
||||
|
||||
@@ -36,6 +42,11 @@ export type DemoSeed = {
|
||||
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][];
|
||||
/**
|
||||
* 1.8.0, a scenario load: four leaders as [part, role, portrait], the pastor first. Their names
|
||||
* are the scenario's people with that part (`demoPeople`); the portraits suit them (photos.json).
|
||||
*/
|
||||
scenarioTeam?: [DemoPart, string, string][];
|
||||
series: [string, string];
|
||||
/** Three: [slug, title, days ago, passage]. */
|
||||
messages: [string, string, number, string][];
|
||||
@@ -68,7 +79,10 @@ export type DemoPhotos = {
|
||||
|
||||
const visitButton: Button = { label: 'Plan your visit', href: '/visit' };
|
||||
|
||||
export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
/** A demo profile: one of the eight, each also a demo scenario's church. */
|
||||
export type ProfileSeed = DemoSeed & { id: WebsiteDemoProfile; scenarioTeam: [DemoPart, string, string][] };
|
||||
|
||||
export const DEMO_SEEDS: Record<WebsiteDemoProfile, ProfileSeed> = {
|
||||
'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 },
|
||||
@@ -95,6 +109,7 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
['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']],
|
||||
scenarioTeam: [['pastor', 'Rector', 'pastor-margaret'], ['worship', 'Director of music', 'team-sipho'], ['kids', 'Sunday school', 'team-anne'], ['prayer-coordinator', 'Prayer coordinator', 'team-david']],
|
||||
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: [
|
||||
@@ -131,6 +146,7 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
['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']],
|
||||
scenarioTeam: [['pastor', 'Vicar', 'pastor-peter'], ['prayer-coordinator', 'Prayer coordinator', 'team-claire'], ['worship', 'Organist', 'team-nomsa'], ['youth', 'Students and young adults', 'team-tom']],
|
||||
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: [
|
||||
@@ -167,6 +183,7 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
['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']],
|
||||
scenarioTeam: [['pastor', 'Lead pastor', 'team-kagiso'], ['youth', 'Youth pastor', 'team-ayesha'], ['worship', 'Worship pastor', 'team-megan'], ['prayer-coordinator', 'Prayer and connect groups', 'team-ruan']],
|
||||
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: [
|
||||
@@ -203,6 +220,7 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
['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']],
|
||||
scenarioTeam: [['pastor', 'Church planter', 'team-sipho'], ['kids', 'Kids', 'team-ayesha'], ['worship', 'Music', 'team-ruan'], ['prayer-coordinator', 'Prayer and community', 'team-lerato']],
|
||||
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: [
|
||||
@@ -239,6 +257,7 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
['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']],
|
||||
scenarioTeam: [['pastor', 'Senior pastor', 'pastor-andile'], ['kids', 'Children\'s pastor', 'team-michelle'], ['prayer-coordinator', 'Prayer coordinator', 'team-lerato'], ['youth', 'Youth', 'team-johan']],
|
||||
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: [
|
||||
@@ -275,6 +294,7 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
['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']],
|
||||
scenarioTeam: [['pastor', 'Minister', 'pastor-willem'], ['kids', 'Sunday school', 'team-elsie'], ['worship', 'Music', 'team-pieter'], ['prayer-coordinator', 'Prayer', 'team-marie']],
|
||||
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: [
|
||||
@@ -311,6 +331,7 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
['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']],
|
||||
scenarioTeam: [['pastor', 'Pastor', 'pastor-daniel'], ['kids', 'Kids', 'team-bongani'], ['worship', 'Music', 'team-nadia'], ['prayer-coordinator', 'Prayer', 'team-refilwe']],
|
||||
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: [
|
||||
@@ -347,6 +368,7 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
['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']],
|
||||
scenarioTeam: [['pastor', 'Pastor', 'pastor-ian'], ['youth', 'Students', 'team-thabo'], ['worship', 'Music', 'team-lisa'], ['prayer-coordinator', 'Prayer', 'team-priya']],
|
||||
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: [
|
||||
@@ -360,4 +382,4 @@ export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
|
||||
};
|
||||
|
||||
/** The profiles in the contracts' order (what the Hub offers). */
|
||||
export const demoSeeds = (): DemoSeed[] => agent.WEBSITE_DEMO_PROFILES.map((id: WebsiteDemoProfile) => DEMO_SEEDS[id]);
|
||||
export const demoSeeds = (): ProfileSeed[] => agent.WEBSITE_DEMO_PROFILES.map((id: WebsiteDemoProfile) => DEMO_SEEDS[id]);
|
||||
|
||||
@@ -3,9 +3,13 @@ import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import { WEBSITE_TEMPLATES, agent } from '@crosscode/contracts';
|
||||
import { demoProfile, loadDemo, seedDesign } from '../src/demo/demoChurch.js';
|
||||
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, WEBSITE_TEMPLATES, agent } from '@crosscode/contracts';
|
||||
import { demoChurch, demoParts, demoPeople } from '@crosscode/demo';
|
||||
import { demoProfile, loadDemo, scenarioProfile, seedDesign } from '../src/demo/demoChurch.js';
|
||||
import { DEMO_SEEDS, demoSeeds } from '../src/demo/seeds.js';
|
||||
import { messageThumbnail, siteContent, spotifyEmbed, youtubeId } from '../src/site/content.js';
|
||||
import { buildPalette, contrast, hexToRgb } from '../src/site/palette.js';
|
||||
@@ -208,6 +212,82 @@ describe('the public site\'s content', () => {
|
||||
assert.ok(c.mode === 'published' && JSON.stringify(c.snapshot).includes('Welcome to Acacia Hill'));
|
||||
});
|
||||
|
||||
for (const profile of agent.WEBSITE_DEMO_PROFILES) {
|
||||
it(`1.8.0: the ${profile} scenario's people lead the ${profile} profile`, async () => {
|
||||
const scenario = profile as agent.DemoScenarioKey;
|
||||
const h = await harness({ linked: false });
|
||||
const dir = tmp();
|
||||
await h.ctx.settings.set('church_profile_local', JSON.stringify(scenarioProfile('http://x.test', scenario)));
|
||||
await loadDemo(h.ctx, profile, { uploadDir: dir, scenario });
|
||||
const c = await siteContent(h.ctx);
|
||||
assert.ok(c.mode === 'published');
|
||||
const seed = DEMO_SEEDS[profile];
|
||||
const parts = demoParts(scenario);
|
||||
const leads = demoPeople(scenario).filter((p) => parts.has(p.email));
|
||||
const expected = seed.scenarioTeam.map(([part, role]) => [leads.find((p) => parts.get(p.email)!.includes(part))!.name, role]);
|
||||
assert.deepEqual(c.snapshot.leaders.map((l) => [l.name, l.role]), expected, 'the scenario\'s people, the pastor first');
|
||||
assert.equal(new Set(expected.map(([name]) => name)).size, 4, 'four different people');
|
||||
for (const [i, l] of c.snapshot.leaders.entries()) assert.equal(l.photo?.alt, expected[i]![0], `${l.name}'s portrait is named for them`);
|
||||
assert.ok(fs.existsSync(path.join(dir, 'demo', `${seed.scenarioTeam[0]![2]}.webp`)), 'the pastor\'s portrait chosen for them');
|
||||
const welcome = c.snapshot.pages[0]!.sections.find((s) => s.type === 'welcome')!.data as { pastor: { name: string; role: string } };
|
||||
assert.deepEqual([welcome.pastor.name, welcome.pastor.role], expected[0]);
|
||||
for (const m of c.messages) assert.equal(m.speaker, expected[0]![0], 'the pastor preaches');
|
||||
const all = JSON.stringify(c.snapshot);
|
||||
for (const [name] of seed.leaders) if (!expected.some(([n]) => n === name)) assert.ok(!all.includes(name), `none of the profile's own leaders (${name})`);
|
||||
assert.equal(c.church?.name, demoChurch(scenario).profile.name);
|
||||
assert.equal(c.events.length, 3, 'without Cross Events, the profile\'s own events');
|
||||
});
|
||||
}
|
||||
|
||||
it('1.8.0: a scenario on a site with no church profile saves the scenario\'s church, not Acacia Hill', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
await loadDemo(h.ctx, 'bold-plant', { uploadDir: tmp(), scenario: 'bold-plant' });
|
||||
const c = await siteContent(h.ctx);
|
||||
assert.equal(c.church?.name, demoChurch('bold-plant').profile.name);
|
||||
assert.ok(c.mode === 'published' && !JSON.stringify(c.snapshot).includes('Acacia'));
|
||||
});
|
||||
|
||||
it('1.8.0: a scenario loads only the profile of the same name', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
await assert.rejects(loadDemo(h.ctx, 'bold-plant', { uploadDir: tmp(), scenario: 'bold-youth' }), /bold-youth profile/);
|
||||
assert.equal(await h.db.siteVersion.count(), 0, 'nothing changed');
|
||||
});
|
||||
|
||||
it('1.8.0: with Cross Events linked, a scenario shows Events\' events through the feed and makes none of its own', async () => {
|
||||
const eventsId = '5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e';
|
||||
const start = new Date(Date.now() + 9 * 864e5);
|
||||
const event = {
|
||||
schema: EVENT_SCHEMA, id: '6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', origin: { product: 'events', installId: eventsId, url: 'https://events.ignite.test/events/conf' },
|
||||
status: 'published', updatedAt: new Date().toISOString(), title: 'Ignite youth conference', summary: null, description: null, imageUrl: null, timezone: 'Africa/Johannesburg',
|
||||
startsAt: start.toISOString(), endsAt: new Date(start.getTime() + 3600e3).toISOString(), allDay: false, sessions: [], location: { name: 'The auditorium', address: null, onlineUrl: null },
|
||||
campus: null, series: null, tags: [], registration: { mode: 'origin', url: 'https://events.ignite.test/events/conf', status: 'open', opensAt: null, closesAt: null, priceFrom: null },
|
||||
};
|
||||
const fake = express();
|
||||
fake.get('/api/feed/v1/events', (_req, res) => { res.json({ schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [event] }); });
|
||||
fake.post('/api/feed/v1/changed', (_req, res) => { res.status(202).json({ accepted: true }); });
|
||||
const server = http.createServer(fake);
|
||||
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
|
||||
try {
|
||||
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
|
||||
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
await h.db.productLink.create({ data: { installId: eventsId, product: 'events', url, publicKey: 'x', secret: h.ctx.secrets.encrypt('events-link-secret-0123456789abcdef'), connectedAt: new Date(), showEvents: false } });
|
||||
const version = await loadDemo(h.ctx, 'bold-youth', { uploadDir: tmp(), scenario: 'bold-youth' });
|
||||
assert.equal(version.eventsSync?.ok, true, version.eventsSync?.error);
|
||||
assert.equal(await h.db.simpleEvent.count(), 0, 'no events of its own');
|
||||
assert.equal((await h.db.productLink.findUnique({ where: { installId: eventsId } }))?.showEvents, true, 'Show events from Cross Events');
|
||||
const c = await siteContent(h.ctx);
|
||||
assert.ok(c.mode === 'published');
|
||||
assert.deepEqual(c.events.map((e) => [e.title, e.from]), [['Ignite youth conference', 'events']]);
|
||||
assert.equal(await h.db.mediaAsset.count(), 16, 'no pictures for events it doesn\'t make');
|
||||
|
||||
// A single profile load (no scenario) still makes its own, as before.
|
||||
await loadDemo(h.ctx, 'bold-youth', { uploadDir: tmp() });
|
||||
assert.equal(await h.db.simpleEvent.count(), 3);
|
||||
} finally {
|
||||
await new Promise((r) => server.close(r));
|
||||
}
|
||||
});
|
||||
|
||||
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 } });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "1.7.1",
|
||||
"version": "1.8.0",
|
||||
"private": true,
|
||||
"description": "Church Website: the church's public site in its template, and the admin",
|
||||
"scripts": {
|
||||
|
||||
+100
-55
@@ -28,20 +28,26 @@ look comes from the church profile (colours, logo, fonts, corners) and it shares
|
||||
links with the Website and Cross Events, so the three feel like one church.
|
||||
|
||||
**Where things stand:** every earlier phase is released and rolled out, including the Church Website
|
||||
at Hope Family Church and a second church (confirmed by Joshua 2026-11-30).
|
||||
at Hope Family Church and a second church (confirmed by Joshua 2026-11-30). **Phase 6 progress
|
||||
(2026-11-30):** `contracts@1.20.0` to `1.23.0`, `accounts@1.9.0`, `events@3.8.0`, `website@1.8.0` and
|
||||
`agent@1.7.0` released (not deployed yet), with the new shared package `@crosscode/demo` 1.1.0 (§12, "Demo scenarios").
|
||||
The Bible publishers' terms were checked ([BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)): 1.0
|
||||
uses only the free translations, the KJV and the Berean Standard Bible (decision 14, contracts 1.22.0).
|
||||
Next: Hub `v2.26.0`, then `app@1.0.0` (§15).
|
||||
|
||||
**Who uses 1.0:** the demo church (cross-demo2, Acacia Hill) first, then Hope Family Church. Then
|
||||
it goes on sale (crosscode-site, ROADMAP §9).
|
||||
|
||||
**Done when:**
|
||||
|
||||
- `app@1.0.0`, `contracts@1.20.0` (released 2026-11-30), `contracts@1.21.0` (released 2026-11-30), `accounts@1.9.0`,
|
||||
`events@3.8.0`, `website@1.8.0`, `agent@1.7.0` and Hub `v2.26.0` are tagged; the Hub installs
|
||||
- `app@1.0.0`, `contracts@1.20.0` (released 2026-11-30), `contracts@1.21.0` (released 2026-11-30), `contracts@1.22.0` (released 2026-11-30), `accounts@1.9.0`
|
||||
(released 2026-11-30), `events@3.8.0` (released 2026-11-30), `website@1.8.0` (released 2026-11-30), `agent@1.7.0` (released 2026-11-30) and Hub `v2.26.0` are tagged; the Hub installs
|
||||
the App from New install (after Accounts) and lists its releases.
|
||||
- On a demo client, **Load a demo scenario** in the Hub loads Accounts, Events, the Website and
|
||||
the App with the same church, people and events, in one step (§12, "Demo scenarios").
|
||||
- The Hub holds 3 months of Cross Code devotionals (written or imported from CSV), and an App set to
|
||||
"From Cross Code" shows and sends them.
|
||||
- The Hub holds 3 months of Cross Code devotionals (written or imported from CSV) in the free
|
||||
translations (KJV, BSB; decision 14), and an App set to "From Cross Code" shows and sends them
|
||||
with the translation's notice.
|
||||
- A member can add the App to their home screen (Android and iPhone), sign in once, book a one-off
|
||||
or recurring prayer slot, get its reminder by email or WhatsApp, and change or cancel it within
|
||||
the rules.
|
||||
@@ -263,30 +269,45 @@ Decision 1: **two sources**, chosen in Settings → Devotionals:
|
||||
devotional, with its translation and copyright line, and **Read in YouVersion** opens it at
|
||||
`bible.com` (the passage in that translation; YouVersion's app opens instead where it's
|
||||
installed). The YouVersion link is built from the reference and the translation's YouVersion id.
|
||||
- **Translations** (decision 10): each devotional, from Cross Code or the church's own, picks one
|
||||
of seven:
|
||||
- **Translations** (decisions 10 and 14): **App 1.0 offers only the free (public-domain)
|
||||
translations**, for Cross Code's devotionals and a church's own alike:
|
||||
|
||||
| Id | Translation | Language |
|
||||
|---|---|---|
|
||||
| `NLT` | New Living Translation | English |
|
||||
| `ESV` | English Standard Version | English |
|
||||
| `NIV` | New International Version | English |
|
||||
| `NKJV` | New King James Version | English |
|
||||
| `KJV` | King James Version | English |
|
||||
| `AFR53` | Afrikaans 1933/1953-vertaling | Afrikaans |
|
||||
| `AFR83` | Afrikaans 1983-vertaling | Afrikaans |
|
||||
| Id | Translation | Language | In 1.0 |
|
||||
|---|---|---|---|
|
||||
| `KJV` | King James Version | English | ✅ public domain |
|
||||
| `BSB` | Berean Standard Bible (modern English; public domain since 30 April 2023) | English | ✅ public domain |
|
||||
| `NLT` | New Living Translation | English | later, with Tyndale's permission |
|
||||
| `ESV` | English Standard Version | English | later, with Crossway's permission |
|
||||
| `NIV` | New International Version | English | later, with Biblica's permission |
|
||||
| `NKJV` | New King James Version | English | later, with HarperCollins Christian's permission |
|
||||
| `AFR53` | Afrikaans 1933/1953-vertaling | Afrikaans | later, with the Bible Society's permission |
|
||||
| `AFR83` | Afrikaans 1983/1992-vertaling (1983 with the 1992 rewordings) | Afrikaans | later, with the Bible Society's permission |
|
||||
|
||||
The list lives in the contracts with each one's YouVersion id and copyright line, so the Hub,
|
||||
the App and the CSV import agree; an id never changes once released, and more can be added.
|
||||
The Afrikaans pair is the proposal (the 2020-vertaling or the Nuwe Lewende Vertaling could
|
||||
replace one).
|
||||
- **Licensing:** every one but the KJV is under copyright (the Afrikaans ones with the Bible
|
||||
Society of South Africa). Each publisher lets its text be quoted within limits (a number of
|
||||
verses, never a whole book, with its notice), so a devotional quotes **the passage it's about,
|
||||
not whole chapters**, and the App always shows that translation's copyright line under the
|
||||
verse. The Hub and the App warn when a passage is longer than 25 verses. Before Cross Code's
|
||||
devotionals go out to churches, check each publisher's terms for use in an app (or ask for
|
||||
permission); the church is responsible for its own.
|
||||
The list lives in the contracts with each one's YouVersion id, notices and `licence`, so the Hub,
|
||||
the App and the CSV import agree; an id never changes once released, and more can be added. The
|
||||
Hub and the App offer `FREE_BIBLE_TRANSLATION_IDS` only, and the CSV import refuses any other
|
||||
(`checkDevotionalCsv(…, { translations })`, naming the publisher to ask). A translation joins
|
||||
when its publisher gives written permission (a contracts release moves it to `public-domain`
|
||||
or a new `licensed` value, and the Hub and the App offer it from their next release). **There
|
||||
is no free Afrikaans translation** (the Bible Society holds both, and eBible lists none), so an
|
||||
Afrikaans church's devotionals are written in Afrikaans and quote the KJV or BSB until one is
|
||||
cleared.
|
||||
- **Licensing** (checked 2026-11-30, [BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)): every
|
||||
translation but the KJV and BSB is under copyright. Each publisher allows **500 verses** without
|
||||
asking, counted across the whole work (Biblica: the whole app), never a whole book, with its
|
||||
notice. **Daily devotionals pass that in two or three months, and the App is sold**, so using
|
||||
them needs each publisher's **written permission**. Decision 14: 1.0 doesn't wait for it; the
|
||||
requests are drafted in BIBLE-PERMISSIONS.md for when Cross Code wants a translation. A
|
||||
devotional quotes **the passage it's about, not whole chapters**; the Hub and the App warn when
|
||||
a passage is longer than 25 verses.
|
||||
- **Notices** (contracts 1.22.0): the translation's `copyright` line under every quoted passage
|
||||
(screen, email and WhatsApp) and an **Acknowledgements** page (linked from the footer and the
|
||||
devotional) with each used translation's `acknowledgement`. Not required for the KJV and BSB,
|
||||
but shown anyway (the Berean translators ask for it). A translation added later brings its
|
||||
publisher's exact wording, and for the Bible Society's their `disclaimer` with every devotional.
|
||||
- **No AI on Bible text:** Crossway (ESV) and Biblica (NIV) forbid it without a separate licence,
|
||||
so no AI feature reads, writes, translates or summarises a devotional's passage (§4 already keeps
|
||||
AI away from prayer).
|
||||
- **The Hub** (Hub 2.26.0, decision 1): a **Devotionals** page to write and schedule Cross Code's
|
||||
devotionals **up to 3 months ahead**, with a calendar showing which days are filled, and an
|
||||
**Import CSV** button: upload, a preview with every row checked (date, required fields, a
|
||||
@@ -419,8 +440,8 @@ the band in Settings → Licence. Visitors browsing signed out never count.
|
||||
**renewal check** (the tier is checked once a year at renewal, ROADMAP §10) that flags an install
|
||||
whose band is above its tier; the FastPanel email for `app.`; the App in Jobs' product filter
|
||||
(already) and demo data; and **Devotionals** (§6): write and schedule up to 3 months ahead, the
|
||||
calendar, Import CSV with its preview, and `GET /api/v2/devotionals` for App installs (licence
|
||||
token, App licences only).
|
||||
calendar, Import CSV with its preview (the free translations only, §6), and
|
||||
`GET /api/v2/devotionals` for App installs (licence token, App licences only).
|
||||
- **Contracts 1.20.0:** `app` in `DEMO_PRODUCTS`; the `app` section of the church export; the
|
||||
App's modules list (`APP_MODULES`); `crosscode.devotional/1` and the devotionals reply; the CSV
|
||||
columns and row checks (shared by the Hub and the App); `messaging.get` for the App (§8); the
|
||||
@@ -454,9 +475,11 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
Website's demo keeps the profile and only uses the church's name). It's a demo client, so nothing
|
||||
real is lost; the profile before the load goes in the backup taken first. Each scenario has:
|
||||
- a name, short name and a **logo and icon** of its own (made for the demo, a simple mark and
|
||||
wordmark per church, never a real church's), in `apps/accounts/backend/demo-assets/<scenario>/`
|
||||
with a credits file. Accounts serves them itself (`/demo-assets/…`), since its profile holds
|
||||
addresses, not uploads;
|
||||
wordmark per church, never a real church's), drawn as SVG by `@crosscode/demo` (Accounts
|
||||
1.9.0). Accounts serves them itself (`/api/demo-assets/<scenario>/logo.svg`, `icon.svg`), since
|
||||
its profile holds addresses, not uploads;
|
||||
- its people, also in `@crosscode/demo` (`demoPeople`), with the same account id in every
|
||||
product (`demoId`), so each product's loader builds around the same people;
|
||||
- colours, font pairing, corners and the Website template's style that suit it;
|
||||
- a street address, campuses, service times, phone, email (`@example.com`) and social links
|
||||
(to `example.com` addresses), a timezone, and the product links to the client's installs;
|
||||
@@ -478,12 +501,12 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
|
||||
| Scenario | Church | Website | Events (built from) | App |
|
||||
|---|---|---|---|---|
|
||||
| `heritage-parish` | **St Columba's**: a 120-year-old parish church, small and older, Sunday 09:00 | `heritage-parish` | `small`: carol service, harvest festival, a funeral-tea roster | a quiet wall (about 10 of 24 hours), Cross Code's devotionals in NKJV, a Lent campaign |
|
||||
| `heritage-parish` | **St Columba's**: a 120-year-old parish church, small and older, Sunday 09:00 | `heritage-parish` | `small`: carol service, harvest festival, a funeral-tea roster | a quiet wall (about 10 of 24 hours), Cross Code's devotionals in the KJV, a Lent campaign |
|
||||
| `heritage-city` | **Grace Cathedral**: city centre, three Sunday services, lunchtime prayer | `heritage-city` | `events`: a concert series, ticketed Easter services | full in office hours with gaps at night, a weekday lunchtime focus, announcements per service |
|
||||
| `bold-youth` | **Ignite Church**: young and music-led | `bold-youth` | `events`: a youth conference with paid registration, a worship night | a 21-day campaign before the conference, testimonies, WhatsApp reminders, NLT devotionals |
|
||||
| `bold-youth` | **Ignite Church**: young and music-led | `bold-youth` | `events`: a youth conference with paid registration, a worship night | a 21-day campaign before the conference, testimonies, WhatsApp reminders, BSB devotionals |
|
||||
| `bold-plant` | **Harbour City**: a 2-year-old plant in a school hall | `bold-plant` | `small`: launch Sunday, a newcomers' lunch | a wall still filling up (the admin's setup checklist half done), the pastor's own devotionals |
|
||||
| `community-family` | **Acacia Hill**: a family church (cross-demo2, the mockup's church) | `community-family` | `ministry`: kids' club, Alpha, family camp, volunteer rosters | full with a few gaps (as in the mockup), a 21-day campaign, members' requests waiting for approval |
|
||||
| `community-town` | **Karoo Gemeenskapskerk**: a country-town church, mostly Afrikaans | `community-town` | `small`: a bazaar, a prayer breakfast | AFR83 devotionals of its own, 30-minute slots, the area's emergency numbers |
|
||||
| `community-town` | **Karoo Gemeenskapskerk**: a country-town church, mostly Afrikaans | `community-town` | `small`: a bazaar, a prayer breakfast | Afrikaans devotionals of its own (quoting the BSB until an Afrikaans translation is cleared), 30-minute slots, the area's emergency numbers |
|
||||
| `clean-modern` | **Northpoint**: a contemporary church of about 600 | `clean-modern` | `ministry`: courses, groups launch, serve teams | every hour covered, target 2 per slot, Cross Code's devotionals, announcements by WhatsApp |
|
||||
| `clean-campus` | **Riverside**: three campuses near the university | `clean-campus` | `multicampus`: student welcome week at one campus, a combined worship night | one wall for three campuses, announcements per campus, students on the 02:00 slots |
|
||||
|
||||
@@ -494,15 +517,24 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
profile it uses for each product (`accounts`, `events`, `website`, `app`), so the Hub and the
|
||||
agent agree; a test checks every profile it names exists. `seed-demo` takes an optional
|
||||
`scenario`, and `accounts` joins `DEMO_PRODUCTS` (its demo is the church profile and the people).
|
||||
- **Agent 1.7.0:** runs `crosscode demo <church> <product> --profile <p> [--scenario <s>]` for
|
||||
every product, so a product can tell a scenario load from a single one.
|
||||
- **Agent 1.7.0** (released 2026-11-30): runs `crosscode demo <church> <product> --profile <p>
|
||||
[--scenario <s>]` for every product, so a product can tell a scenario load from a single one,
|
||||
and the whole scenario in **one `seed-scenario` job** (contracts 1.23.0, Joshua 2026-11-30):
|
||||
`crosscode demo <church> --scenario <s>` **seeds whatever the church has installed** on that
|
||||
server, Accounts first, then Events, the Website and the App, and skips the products it doesn't
|
||||
have (a client with only Accounts and the Website gets both). Every installed release is
|
||||
checked against `DEMO_SCENARIO_MIN_VERSIONS` before anything changes; the first failure stops
|
||||
the rest and names the products now out of step (the report's `loaded` and `skipped`).
|
||||
Each product also works without the others: the Website without Accounts uses the scenario's
|
||||
own church profile, without Events its own events; the App without Events its own events.
|
||||
- **Hub 2.26.0:** on a demo client (every install marked as a demo site), **Load a demo
|
||||
scenario**: pick one from the list, see which installs it will replace (and any product the
|
||||
client has that the scenario doesn't cover), type the client's short name once, and the Hub
|
||||
queues one batch in order: **Accounts first** (profile and people), then **Events**, the
|
||||
**Website** and the **App**, each job starting only after the one before it succeeded; a failure
|
||||
stops the rest and says which product is now out of step. At the end the products sync the
|
||||
event feed, and one email reports the whole batch. The client page shows the scenario last
|
||||
sends **one `seed-scenario` job** to the client's server (agent 1.7.0+). The server loads every
|
||||
product the client has there, **Accounts first** (profile and people), then **Events**, the
|
||||
**Website** and the **App**, skipping what isn't installed; a failure stops the rest and the
|
||||
report says which products are now out of step. The Website and the App fetch Events' feed as
|
||||
they load, and one email reports the job. The client page shows the scenario last
|
||||
loaded and when. Loading one product's demo on its own stays (as now), marked "out of step with
|
||||
the scenario" until a scenario is loaded again. The Hub refuses a scenario when an install
|
||||
needs a newer release (each scenario lists the minimum versions it needs).
|
||||
@@ -519,14 +551,17 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
| `crosscode-platform` `apps/app` | New (§1–§12), with `CHANGELOG.md`, `WHATS-NEW.md`, `env.template.json`, e2e, demo data | `app@1.0.0` |
|
||||
| `crosscode-platform` `packages/contracts` | `app` in `DEMO_PRODUCTS`, `APP_MODULES`, the `app` part of the church export, `crosscode.devotional/1` and its CSV rules, the translations, `messaging.get`, `whatsapp.optout` | `contracts@1.20.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `packages/contracts` | `agent.DEMO_SCENARIOS`, `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS` | `contracts@1.21.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/accounts` | `messaging.get` for linked products, a hint when the messaging settings change, the WhatsApp opt-out for every product; demo data (the scenario's church profile with its logo and icon, and its people) | `accounts@1.9.0` |
|
||||
| `crosscode-platform` `apps/events` | STOP replies passed to Accounts; the opt-out read from Accounts; demo profiles reworked to the scenarios | `events@3.8.0` |
|
||||
| `crosscode-platform` `apps/website` | Demo profiles take the scenario's people and events (`--scenario`) | `website@1.8.0` |
|
||||
| `crosscode-platform` `apps/agent` | `seed-demo` for `app` and `accounts`, `--scenario` passed on | `agent@1.7.0` |
|
||||
| `crosscode-platform` `packages/contracts` | The free translations only in 1.0 (`licence`, `FREE_BIBLE_TRANSLATION_IDS`, the CSV `translations` option), the Berean Standard Bible (`BSB`) added; the publishers' exact notices (`copyright`, `acknowledgement`, the Bible Society's `disclaimer`), `publisher` and `permissionsUrl`, `FREE_QUOTE_VERSES`, `quotedVerses`; `AFR83` named "Afrikaans 1983/1992-vertaling" | `contracts@1.22.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `packages/contracts` | `seed-scenario`: a whole demo scenario in one job, on whatever the church has installed (`SEED_SCENARIO_JOB_MIN_AGENT`) | `contracts@1.23.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/accounts` | `messaging.get` for linked products, a hint when the messaging settings change, the WhatsApp opt-out for every product; demo data (the scenario's church profile with its logo and icon, and its people) | `accounts@1.9.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/events` | STOP stops all WhatsApp, passed to Accounts; the opt-out read from Accounts; a demo profile per scenario (its four kept) | `events@3.8.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/website` | Demo profiles take the scenario's people and events (`--scenario`) | `website@1.8.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/agent` | `seed-demo` for `app` and `accounts`, `--scenario` passed on; `seed-scenario` (the whole scenario on what's installed) | `agent@1.7.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `packages/demo` | New: the scenarios' churches, people (`gender` from 1.1.0) and SVG logos | `@crosscode/demo` 1.1.0 (workspace, **released with Accounts 1.9.0 / Events 3.8.0**) |
|
||||
| `crosscode-platform` `packages/ui` | The tab bar and bottom sheet, if worth sharing; otherwise nothing | workspace |
|
||||
| `crosscode-platform` `packages/seo` | `Article` builder for devotionals and announcements; the icon generator for the manifest | workspace |
|
||||
| `crosscode-platform` `scripts/` | `products/app.sh`, `app.env.template.json`, bats tests | — |
|
||||
| `events-hub` | App in New install, its releases, env template, billing on the band, renewal check, FastPanel email, Devotionals (write, schedule 3 months ahead, Import CSV, the endpoint for Apps), **Load a demo scenario** on a demo client (vendored contracts 1.21.0) | Hub `v2.26.0` |
|
||||
| `events-hub` | App in New install, its releases, env template, billing on the band, renewal check, FastPanel email, Devotionals (write, schedule 3 months ahead, Import CSV in the free translations, the endpoint for Apps), **Load a demo scenario** on a demo client (one `seed-scenario` job; vendored contracts 1.23.0) | Hub `v2.26.0` |
|
||||
| `crosscode-site` | Church App on sale (ROADMAP §9): its page, the active-member tiers, House of Prayer screenshots, the bundle examples (§10), FAQ, `SoftwareApplication` JSON-LD | `v1.10.0` |
|
||||
|
||||
## 14. Testing
|
||||
@@ -539,9 +574,10 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
Member, the 8-day sign-in renewed up to 90 days, active-member counting and the band, the export
|
||||
and delete hooks, the devotional CSV checks (a bad date, a missing field, a reference YouVersion
|
||||
can't open, a day already filled), the YouVersion links, the nightly Cross Code fetch (and the
|
||||
last copy kept when the Hub is down), `messaging.get`.
|
||||
- **Hub:** the Devotionals page, Import CSV with its preview, the 3-month limit, and the endpoint
|
||||
refusing anything but an App licence.
|
||||
last copy kept when the Hub is down), `messaging.get`, the notice under every quoted passage
|
||||
(screen, email, WhatsApp), only the free translations offered and imported.
|
||||
- **Hub:** the Devotionals page, Import CSV with its preview, the 3-month limit, a translation that isn't
|
||||
free refused, and the endpoint refusing anything but an App licence.
|
||||
- **Playwright** (phone, tablet and desktop): browse signed out; sign in from a slot and land back
|
||||
on it with the sheet open (through 2FA); book once, weekly and daily; skip, change and cancel;
|
||||
the 8-hour rule; two browsers, one books, the other's view updates live (and with the stream
|
||||
@@ -562,11 +598,12 @@ data that describes **the same church**, so a demo shows the three products work
|
||||
## 15. Releasing and rolling it out
|
||||
|
||||
1. `contracts@1.20.0` (**released 2026-11-30**), then `accounts@1.9.0` (`messaging.get`, the
|
||||
WhatsApp opt-out) and `events@3.8.0` (STOP passed to Accounts), rolled out to every church.
|
||||
WhatsApp opt-out) and `events@3.8.0` (STOP passed to Accounts), **both released 2026-11-30**,
|
||||
rolled out to every church (not yet).
|
||||
2. `contracts@1.21.0` (demo scenarios, **released 2026-11-30**), with the scenario demo loaders in Accounts 1.9.0, Events
|
||||
3.8.0, `website@1.8.0`, and `agent@1.7.0`.
|
||||
3. Hub `v2.26.0` (vendored contracts 1.21.0) deployed, and the first 3 months of Cross Code
|
||||
devotionals written or imported.
|
||||
3.8.0, `website@1.8.0` and `agent@1.7.0` (**both released 2026-11-30**).
|
||||
3. Hub `v2.26.0` (vendored contracts 1.23.0) deployed, and the first 3 months of Cross Code
|
||||
devotionals written or imported, in the KJV or BSB (decision 14).
|
||||
4. `app@1.0.0` tagged after the e2e and Lighthouse runs.
|
||||
5. **cross-demo2** (Acacia Hill): New install → App, every demo scenario loaded once, the
|
||||
throwaway test above.
|
||||
@@ -598,6 +635,7 @@ Made by Joshua on 2026-11-30, after the first draft and the mockup:
|
||||
panels and stat cards), not a new style (§10; mockup redrawn).
|
||||
10. **Each devotional uses one of NLT, ESV, NIV, NKJV, KJV or two Afrikaans translations**
|
||||
(proposed: 1933/1953 and 1983), quoting only the passage, with its copyright line (§6).
|
||||
Narrowed by decision 14: only the free ones (KJV, BSB) in 1.0.
|
||||
11. **Accounts keeps the WhatsApp opt-out for every product,** so a STOP to the shared number
|
||||
reaches the App, Events and Accounts alike (§8). Adds Events 3.8.0.
|
||||
12. **Home shows today's prayer clock** in small, as the House of Prayer does (mockup redrawn).
|
||||
@@ -606,6 +644,10 @@ Made by Joshua on 2026-11-30, after the first draft and the mockup:
|
||||
contracts 1.21.0, agent 1.7.0 and Website 1.8.0, and demo data in Accounts 1.9.0. Eight
|
||||
scenarios, one per Website demo profile, each its own church: a scenario load replaces the
|
||||
church profile with its own name, logo, icon, colours and details.
|
||||
14. **Only free Bible translations in 1.0** (added later on 2026-11-30, after the publishers'
|
||||
terms were checked: none covers a sold app past 500 verses): the KJV and the Berean Standard
|
||||
Bible. The others stay in the contracts and join when a publisher gives written permission;
|
||||
that doesn't hold up this plan (§6, [BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)).
|
||||
|
||||
The other proposals as first written, confirmed:
|
||||
|
||||
@@ -641,6 +683,9 @@ for a group; an app-store release; moving to the church's own domain (as the Web
|
||||
## Still open
|
||||
|
||||
- ~~Which two Afrikaans translations~~: 1933/1953 and 1983, confirmed by Joshua 2026-11-30 (YouVersion ids checked, contracts 1.20.0).
|
||||
- **The publishers' terms** for quoting each translation in an app (§6), checked before Cross
|
||||
Code's devotionals go out; ask for permission where the terms don't cover it.
|
||||
- ~~The publishers' terms~~: checked 2026-11-30 ([BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)).
|
||||
None covers a sold app past 500 verses, so 1.0 uses only the free translations (decision 14).
|
||||
The permission requests are drafted for later; nothing in this plan waits for them.
|
||||
- **An Afrikaans translation** (1.x): none is free. Ask the Bible Society when an Afrikaans church
|
||||
needs one (the request is drafted in BIBLE-PERMISSIONS.md).
|
||||
- ~~The demo scenarios~~: eight, one per Website demo profile, each its own church with its own logo and details; Acacia Hill is `community-family` (Joshua, 2026-11-30).
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
# Bible translations: permissions for the Church App
|
||||
|
||||
Written 2026-11-30 for [APP-1.0-PLAN.md](./APP-1.0-PLAN.md) §6 (decisions 5 and 10), which said:
|
||||
"before Cross Code's devotionals go out to churches, check each publisher's terms for use in an
|
||||
app". This file holds what each publisher allows, where each request stands and the requests
|
||||
themselves. **Update the status table when a publisher answers.**
|
||||
|
||||
Sources, read 2026-11-30: crossway.org/permissions, harpercollinschristian.com (Sales and rights →
|
||||
Permissions), the Bible Society of South Africa's *Copyright Policy 2022* (updated 18 July 2022,
|
||||
linked from biblesociety.co.za → Copyright and permissions), and Tyndale's and Biblica's
|
||||
permissions pages (copied by Joshua into `temp/`, as their sites refuse automated reading).
|
||||
|
||||
## Decision: only free translations in App 1.0
|
||||
|
||||
**Joshua, 2026-11-30:** App 1.0 and the Hub use only the free, public-domain translations: the
|
||||
**KJV** and the **Berean Standard Bible** (BSB, dedicated to the public domain under CC0 on
|
||||
30 April 2023, berean.bible/terms.htm; bible.com version 3034). The others stay in the contracts
|
||||
and join when a publisher gives written permission; **nothing in APP-1.0-PLAN waits for that**.
|
||||
The requests below are drafted for when Cross Code wants a translation, and aren't sent yet.
|
||||
|
||||
There is **no free Afrikaans translation**: the Bible Society holds the 1933/1953, 1983/1992 and
|
||||
2020 translations, and eBible lists none. The World English Bible is also public domain but was
|
||||
left out (its own copyright page was gone when checked, and the BSB covers modern English).
|
||||
|
||||
## The short answer
|
||||
|
||||
**No publisher's free allowance covers Cross Code's devotionals.** Every one but the KJV allows
|
||||
about **500 verses** without asking, but:
|
||||
|
||||
1. **The 500 count across the whole work**, not per devotional. Biblica says so outright: on a
|
||||
website or app "the General Use Guidelines apply to the entire platform". A daily devotional of
|
||||
5–10 verses passes 500 within two or three months; a year is about 2 000–3 500 verses.
|
||||
2. **The App is commercial.** Churches pay for it (a subscription by active-member band). The Bible
|
||||
Society's policy calls anything "subject to a sale, lease or trade agreement" commercial; Biblica's
|
||||
free "Express Licensing" for apps excludes "sales, subscriptions"; Tyndale's free allowance
|
||||
covers only "print or eBook" use.
|
||||
|
||||
So Cross Code needs **written permission from each publisher** whose translation its devotionals
|
||||
use, hence the decision above.
|
||||
|
||||
A church's own devotionals are limited to the free translations too in 1.0. When a translation
|
||||
needing permission is added later, `quotedVerses` and `FREE_QUOTE_VERSES` (contracts 1.22.0) let
|
||||
the Hub and the App count verses against the allowance.
|
||||
|
||||
## Status
|
||||
|
||||
| Translation | Publisher | Free use | Our use | Request | Status |
|
||||
|---|---|---|---|---|---|
|
||||
| `KJV` | none (public domain; Crown rights in the UK only) | everything | covered | none needed | ✅ In 1.0 |
|
||||
| `BSB` | none (public domain, CC0, since 2023-04-30) | everything; attribution "appreciated but not required", the Berean name only for the verbatim text | covered | none needed | ✅ In 1.0 |
|
||||
| `NLT` | Tyndale House Publishers | 500 verses, **print or eBook only** | not covered (an app, past 500, commercial) | [Tyndale](#tyndale-nlt) | Later (not sent) |
|
||||
| `ESV` | Crossway | 500 verses (print, digital, audio); its API free for non-commercial use only | not covered (past 500, commercial app) | [Crossway](#crossway-esv) | Later (not sent) |
|
||||
| `NIV` | Biblica, Inc. (South Africa is "rest of the world") | 500 verses **across the whole platform**; Express Licensing only for non-commercial apps without AI | not covered | [Biblica](#biblica-niv) | Later (not sent) |
|
||||
| `NKJV` | HarperCollins Christian Publishing (Thomas Nelson) | 500 verses in any form; apps: "contact our licensing department" | not covered | [HarperCollins](#harpercollins-christian-nkjv) | Later (not sent; 6–8 weeks to answer) |
|
||||
| `AFR53`, `AFR83` | Bible Society of South Africa | 500 verses, plus a copy of the work couriered to them | not covered (past 500, commercial) | [Bible Society](#bible-society-of-south-africa-afr53-afr83) | Later (not sent) |
|
||||
|
||||
When a request is answered, record here the date, any fee, the conditions (a verse cap, a notice,
|
||||
reporting) and where the letter is kept, then release contracts with the translation's `licence`
|
||||
changed, so the Hub and the App offer it (APP-1.0-PLAN §6).
|
||||
|
||||
## What each publisher requires
|
||||
|
||||
### Every translation
|
||||
|
||||
- **The exact notice, under every quote.** The texts are in `packages/contracts/src/bible.ts`
|
||||
(`copyright` under the verse, `acknowledgement` for the App's **Acknowledgements** page). Copy
|
||||
them from the publisher; never reword them.
|
||||
- **Quote exactly**, punctuation and capitals included (Tyndale, Crossway, Biblica), from the latest
|
||||
edition (Biblica: only its latest editions; Crossway: ESV Text Edition 2025).
|
||||
- **Never a whole book**, and quotes under 25% of the work (the devotionals are mostly the writer's
|
||||
text, so this holds; the Hub and App warn past 25 verses in one passage).
|
||||
- **No AI on Bible text.** Crossway: the ESV text may not be "used, accessed, or processed by any
|
||||
AI system". Biblica: any use "in connection with artificial intelligence, machine learning, large
|
||||
language models, chatbots" needs a separate licence. So **no AI feature may ever read, write,
|
||||
translate or summarise a devotional's passage** (Events' AI buttons, anything added to the Hub
|
||||
or the App later). The App already keeps AI away from prayer (§4); this extends it to devotionals.
|
||||
- **Permission is for the use asked for and isn't passed on** (Tyndale: "you may not pass permission
|
||||
on to another person"). So each request names the whole chain: Cross Code writes, the Hub
|
||||
distributes to each church's App, the App shows it and sends it by email and WhatsApp.
|
||||
|
||||
### Tyndale (NLT)
|
||||
|
||||
- Free: up to 500 verses "in any print or eBook form", under 25% of the work, never a complete book.
|
||||
Online sermons and posts have their own limits (50 or 250 verses per recording, non-commercial).
|
||||
**Apps aren't covered at all.**
|
||||
- Notice (only the NLT): "Scripture quotations are taken from the Holy Bible, New Living
|
||||
Translation, copyright © 1996, 2004, 2015 by Tyndale House Ministries. Used by permission. All
|
||||
rights reserved." With several translations: "Scripture quotations marked (NLT) are taken from…".
|
||||
(Our 1.20.0 notice still said "Tyndale House Foundation … Carol Stream, Illinois"; fixed in
|
||||
contracts 1.22.0.)
|
||||
- Ask: permission@tyndale.com or the Permissions Questionnaire on tyndale.com/permissions.
|
||||
|
||||
### Crossway (ESV)
|
||||
|
||||
- Free: up to 500 verses in print, digital or audio, under half of any book and under 25% of the
|
||||
work, not in a commentary. Websites, blogs and social media are listed as covered uses.
|
||||
- The ESV API (api.esv.org) is free "for non-commercial use" only.
|
||||
- Notice: "Scripture quotations are from the ESV® Bible (The Holy Bible, English Standard
|
||||
Version®), © 2001 by Crossway, a publishing ministry of Good News Publishers. ESV Text Edition:
|
||||
2025. …" with the Creative Commons and translation clauses, ending "Used by permission. All
|
||||
rights reserved." **Check the text in `bible.ts` against crossway.org/permissions word for word
|
||||
before the App ships**: the page reader could only confirm its clauses and their order.
|
||||
- "ESV" and "English Standard Version" are trademarks: fine to label a quote, not for branding.
|
||||
- No AI (above).
|
||||
- Ask: the Digital form at crossway.org/permissions/digital/.
|
||||
|
||||
### Biblica (NIV)
|
||||
|
||||
- Outside North America, the UK and Europe, Biblica itself handles every commercial use "including
|
||||
non-print and audio". South Africa is in that group.
|
||||
- Free: 500 verses or fewer **in total**, never a complete book, under 25% of the "product,
|
||||
publication, or platform", with the notice; on a website or app, for the whole platform.
|
||||
- **Express Licensing** (free, through api.bible or platform.youversion.com) is only for apps that
|
||||
are "truly non-commercial (no sales, subscriptions, …)" and have no AI features. The App is sold,
|
||||
so it doesn't qualify.
|
||||
- Licences for a full Bible or New Testament only go to registered legal entities (not our case,
|
||||
but the request comes from Cross Code as a company).
|
||||
- Notice: Biblica offers to provide the correct one. Ours ("Scripture quotations taken from The
|
||||
Holy Bible, New International Version® NIV®. Copyright © 1973, 1978, 1984, 2011 by Biblica,
|
||||
Inc.™ Used by permission. All rights reserved worldwide.") is the one Biblica has long asked for;
|
||||
**ask them to confirm it** in the request.
|
||||
- No AI (above).
|
||||
- Ask: the Permission Request Form on biblica.com/permissions.
|
||||
|
||||
### HarperCollins Christian (NKJV)
|
||||
|
||||
- Free: up to 500 verses "in any form (written, visual, electronic, or audio)", under 25% of the
|
||||
work, under half of any book, not in a commentary, properly cited.
|
||||
- Apps: "for a smartphone app or other digital product … contact our licensing department".
|
||||
- Notice (ours is right): "Scripture taken from the New King James Version®. Copyright © 1982 by
|
||||
Thomas Nelson. Used by permission. All rights reserved."
|
||||
- Ask: the HarperCollins Christian Permission Request Form
|
||||
(cognitoforms.com/HarperCollinsChristianPublishing/PermissionsForm); questions to
|
||||
HCCPpermissions@HarperCollins.com. **6–8 weeks** on average; no phone calls, no duplicate
|
||||
requests, incomplete requests are ignored.
|
||||
|
||||
### Bible Society of South Africa (AFR53, AFR83)
|
||||
|
||||
- Both are theirs: "Bybel in Afrikaans 1933/1953-vertaling" and "Bybel in Afrikaans 1983-vertaling
|
||||
met herformulerings tot en met 1992" (policy §3 a and c). "Ou Vertaling" and "Nuwe Vertaling"
|
||||
are not official names and may not be used (§6).
|
||||
- Free (§4): up to 500 verses, under 50% of a book and under 25% of the work, with a notice, **and
|
||||
one copy of the work couriered** to the Copyright Officer (134 Edward Street, Bellville 7530) with
|
||||
an email to copyright@biblesociety.co.za. For an app, ask what they want instead.
|
||||
- Past that, or commercial (§5): a formal application, made **during planning, before release**.
|
||||
Two copies of a commercial product are due after publication. A fee may be set case by case
|
||||
(§7.2); they may require a **text release** (their files, for this use only, never passed on;
|
||||
§7.3). Permission is per edition (§7.1).
|
||||
- Apps (§3): a complete Bible text in "mobile application software" needs written permission (we
|
||||
quote passages only). Social media: one verse at a time (§6.2); media and "social media
|
||||
campaigns" go to biblia@biblesociety.co.za (§5.3). Name WhatsApp and email sends in the request.
|
||||
- Notices (§6.2, digital): the short form on every screen with the text, the full form in an
|
||||
acknowledgements section, and **the disclaimer** with them whenever their text is next to
|
||||
content they haven't approved (§6.4), which is every devotional. All three are in `bible.ts`. Our
|
||||
copy of the Afrikaans disclaimer reads "beskou kan word" where the policy has the typo "can word".
|
||||
- Ask: copyright@biblesociety.co.za (the application form for legal entities is linked from their
|
||||
page), 021 910 8777. Post: PO Box 5500, Tyger Valley 7536.
|
||||
|
||||
## The requests
|
||||
|
||||
Fill in the bracketed details before sending. Each describes the same use, so the answers can be
|
||||
compared. Send them from Cross Code's address, not a personal one, and keep the replies (and any
|
||||
licence) with the company's records; note where in the status table.
|
||||
|
||||
**The use, in one paragraph** (paste into each form's description field):
|
||||
|
||||
> Cross Code [company name and registration number], South Africa, makes the Church App, a web app
|
||||
> that churches in South Africa subscribe to (priced by how many members use it). Each church has
|
||||
> its own App at its own address. Cross Code writes a daily devotional that churches can choose to
|
||||
> show: each quotes one Bible passage (usually 3–10 verses, never more than 25, never a whole
|
||||
> chapter's worth of a short book), shown in full above the devotional with your copyright notice
|
||||
> under it, followed by the devotional (about 300–600 words of our own) and a prayer. The
|
||||
> devotional is shown in the App (public pages, as text, not downloadable), kept by the App for
|
||||
> offline reading on the member's phone, and sent at the member's request by email and WhatsApp
|
||||
> (the title, the passage and a link to the App). A "Read in YouVersion" link opens the passage on
|
||||
> bible.com. We expect about [365] devotionals a year in [translation], about [2 500] verses a
|
||||
> year, the same for every church that chooses them; we start with [N] churches and expect
|
||||
> [N] within a year. No AI is used with the Bible text. We would like permission for this use,
|
||||
> and to know any fee, the notice you want and any conditions.
|
||||
|
||||
### Tyndale (NLT)
|
||||
|
||||
To: permission@tyndale.com (or the Permissions Questionnaire)
|
||||
Subject: Permission request: NLT in a church devotional app (South Africa)
|
||||
|
||||
> Dear Permissions team,
|
||||
>
|
||||
> We would like permission to quote the New Living Translation in daily devotionals in a church
|
||||
> app. Your fair-use guideline covers print and eBook use up to 500 verses; ours is an app, sold to
|
||||
> churches by subscription, and goes past 500 verses within a few months.
|
||||
>
|
||||
> [The use, in one paragraph.]
|
||||
>
|
||||
> We would show the notice "Scripture quotations are taken from the Holy Bible, New Living
|
||||
> Translation, copyright © 1996, 2004, 2015 by Tyndale House Ministries. Used by permission. All
|
||||
> rights reserved." under every passage. Since each church's App shows the devotionals Cross Code
|
||||
> writes, please let us know whether your permission to Cross Code covers their display in every
|
||||
> subscribing church's App.
|
||||
>
|
||||
> Kind regards,
|
||||
> [name], Cross Code
|
||||
> [email, phone, address]
|
||||
|
||||
### Crossway (ESV)
|
||||
|
||||
Form: crossway.org/permissions/digital/ (description field):
|
||||
|
||||
> [The use, in one paragraph.] We would show your full ESV notice (ESV Text Edition: 2025) under
|
||||
> every passage and quote the current ESV text exactly. We understand the ESV API's free terms
|
||||
> are for non-commercial use; we would like to know whether we may use the API or must supply
|
||||
> the text ourselves, and any fee. The ESV text will not be processed by any AI system.
|
||||
|
||||
### Biblica (NIV)
|
||||
|
||||
Form: Permission Request Form on biblica.com/permissions (rest of the world, digital, commercial):
|
||||
|
||||
> [The use, in one paragraph.] We understand your General Use Guidelines apply to the whole
|
||||
> platform and that Express Licensing is for non-commercial apps only, so we are asking for
|
||||
> permission. We would quote the latest NIV text exactly and show this notice under every passage;
|
||||
> please confirm it is the one you want: "Scripture quotations taken from The Holy Bible, New
|
||||
> International Version® NIV®. Copyright © 1973, 1978, 1984, 2011 by Biblica, Inc.™ Used by
|
||||
> permission. All rights reserved worldwide." The App has no AI or machine-learning features that
|
||||
> use the Bible text. Cross Code is a registered company ([registration number]).
|
||||
|
||||
### HarperCollins Christian (NKJV)
|
||||
|
||||
Form: HarperCollins Christian Permission Request Form (fill in every field; incomplete requests
|
||||
aren't considered):
|
||||
|
||||
> [The use, in one paragraph.] We would show "Scripture taken from the New King James Version®.
|
||||
> Copyright © 1982 by Thomas Nelson. Used by permission. All rights reserved." under every
|
||||
> passage. Your page asks smartphone apps and other digital products to contact the licensing
|
||||
> department; please pass this on if that is the right place.
|
||||
|
||||
### Bible Society of South Africa (AFR53, AFR83)
|
||||
|
||||
To: copyright@biblesociety.co.za, with the application form for legal entities
|
||||
Subject: Aansoek om kopiereg-toestemming: Bybel in Afrikaans 1933/1953 en 1983/1992 in 'n kerk-app
|
||||
(Application for copyright permission: the Afrikaans 1933/1953 and 1983/1992 Bibles in a church app)
|
||||
|
||||
> Geagte Regspraktisyn en Kopieregbeampte / Dear Legal Practitioner and Copyright Officer,
|
||||
>
|
||||
> We apply, in the planning phase as your Copyright Policy 2022 asks, for permission to quote
|
||||
> the Bybel in Afrikaans 1933/1953-vertaling and the Bybel in Afrikaans 1983-vertaling met
|
||||
> herformulerings tot en met 1992 in daily devotionals in a church app. The use is commercial as
|
||||
> your policy defines it (churches subscribe to the App) and will pass 500 verses a year.
|
||||
>
|
||||
> [The use, in one paragraph.]
|
||||
>
|
||||
> We would show your digital short notice under every passage, the full notice on the App's
|
||||
> Acknowledgements page, and your disclaimer with every devotional (policy §6.2 and §6.4). The
|
||||
> devotionals are also sent by email and WhatsApp to members who ask for them; please tell us
|
||||
> whether that needs your Communications and Marketing department (§5.3). As an app has no
|
||||
> physical copy to courier, please tell us what you would like instead (for example, access to a
|
||||
> demonstration App). We would also like to know any fee, and whether you require a text release.
|
||||
>
|
||||
> Churches in the App can also write their own devotionals; they would apply to you themselves.
|
||||
>
|
||||
> Vriendelike groete / Kind regards,
|
||||
> [name], Cross Code
|
||||
> [email, phone, address]
|
||||
+71
-11
@@ -16,7 +16,7 @@ every release).
|
||||
|
||||
| Repo | What |
|
||||
|------|------|
|
||||
| `joshua/crosscode-platform` (this one) | Contracts, the apps (Events from 2.2.0; Accounts, Website and App to come), shared packages, the `crosscode` script (`scripts/`), the server agent (`apps/agent`), and these docs |
|
||||
| `joshua/crosscode-platform` (this one) | Contracts, the apps (Events, Accounts, the Website; the App in phase 6), shared packages (`contracts`, `auth-client`, `seo`, `ui`, `demo`), the `crosscode` script (`scripts/`), the server agent (`apps/agent`), and these docs |
|
||||
| `joshua/hope-events` | Cross Events up to 2.1.x. Frozen; archived once every install is adopted (EVENTS-2.2-PLAN §7) |
|
||||
| `joshua/events-hub` | Cross Code Hub. Its own server, its own `scripts/deploy.sh` |
|
||||
| `joshua/crosscode-site` | crosscode.co.za. Updated at the end of every phase that changes what it says (ROADMAP §9) |
|
||||
@@ -25,19 +25,37 @@ every release).
|
||||
|
||||
| Phase | What | State |
|
||||
|-------|------|-------|
|
||||
| 0 | contracts 1.0.0 → 1.17.0 | **Released and in use.** Not published to a registry (decision 22): the Hub gets a packed release committed to its repo (`backend/vendor/`) |
|
||||
| 0 | contracts 1.0.0 → 1.21.0 | **Released and in use.** Not published to a registry (decision 22): the Hub gets a packed release committed to its repo (`backend/vendor/`) |
|
||||
| 1 | Hub 2.0 → 2.20.0 | **Released, deployed and tested** (Hub `v2.20.0`) |
|
||||
| 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released, rolled out and tested.** Every install adopted onto the monorepo |
|
||||
| 1c | Cross Events 2.3.x: authenticator app 2FA | **Released and rolled out** (carried into Accounts in phase 4) |
|
||||
| 1d | Agent 1.x + Hub 2.1+ | **Released, rolled out and tested** (agent `1.5.0` on every server: from 1.4.0 the Hub reads and changes frps's / frpc's config and probes ports before an install; from 1.5.0 one product of a church can be uninstalled, exported or purged) |
|
||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | **Released, rolled out and tested** ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)) |
|
||||
| 3 | Accounts 1.0.0 | **Released, rolled out and tested** (now `accounts@1.6.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)) |
|
||||
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (now `events@3.7.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
|
||||
| 3 | Accounts 1.0.0 | **Released, rolled out and tested** (`accounts@1.8.0` rolled out; `1.9.0` released 2026-11-30 for phase 6, not deployed; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)) |
|
||||
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (`events@3.7.2` rolled out; `3.8.0` released 2026-11-30 for phase 6, not deployed; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
|
||||
| 4+ | Running it: jobs from the dashboard, styled emails, .env from the Hub, sign-in health, the nightly people check; then frp config and one-product uninstalls, and the Hub's popups, pickers and port list | **Released, deployed and tested** 2026-11-20 and 2026-11-23 (below) |
|
||||
| 5 | Church Website 1.0.0 | **Released 2026-11-26** (planned 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md), all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, the Hub deployed 2026-11-26. **`website@1.0.0` and `1.0.1` released 2026-11-26**, crosscode-site `v1.7.0` (the Website on sale) released 2026-11-26. **Done** (confirmed by Joshua 2026-11-30): crosscode-site deployed, Hope Family Church and a second church live, the remaining release checks finished. Now `website@1.7.1` (VERSIONS.md) |
|
||||
| 6 | Church App 1.0.0 | **Being planned** (2026-11-30): [APP-1.0-PLAN.md](./APP-1.0-PLAN.md), decisions confirmed 2026-11-30 (two left in "Still open"); mockup on the Design canvas "Church App 1.0 mockup" |
|
||||
| 5 | Church Website 1.0.0 | **Released 2026-11-26** (planned 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md), all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, the Hub deployed 2026-11-26. **`website@1.0.0` and `1.0.1` released 2026-11-26**, crosscode-site `v1.7.0` (the Website on sale) released 2026-11-26. **Done** (confirmed by Joshua 2026-11-30): crosscode-site deployed, Hope Family Church and a second church live, the remaining release checks finished. Now `website@1.8.0` (VERSIONS.md) |
|
||||
| 6 | Church App 1.0.0 | **Under way** (planned and started 2026-11-30): [APP-1.0-PLAN.md](./APP-1.0-PLAN.md), decisions confirmed 2026-11-30 (decision 13, the demo scenarios, added the same day); mockup on the Design canvas "Church App 1.0 mockup". Released 2026-11-30, not deployed: `contracts@1.20.0` to `1.23.0`, `accounts@1.9.0`, `events@3.8.0`, `website@1.8.0`, `agent@1.7.0` (below). Next: Hub 2.26.0, `app@1.0.0` |
|
||||
| 7 | App 1.x | Not started |
|
||||
|
||||
## Released 2026-11-30 (phase 6, first steps)
|
||||
|
||||
Tagged and pushed on 2026-11-30, **not deployed yet** (Accounts and Events have one migration each; the Website and the agent none). Details in
|
||||
[VERSIONS.md](./VERSIONS.md), [CHANGELOG.md](../CHANGELOG.md) and the apps' CHANGELOGs.
|
||||
|
||||
| Release | What |
|
||||
|---------|------|
|
||||
| `contracts@1.20.0` | The App's contracts: `crosscode.devotional/1` and the devotionals CSV checks (shared by the Hub and the App), the Bible books and seven translations with YouVersion ids, `messaging.get` / `messaging.changed`, `whatsapp.optout` and `whatsapp_opted_out`, `APP_MODULES`, the `app` part of the church export |
|
||||
| `contracts@1.21.0` | `agent.DEMO_SCENARIOS`: the eight demo churches, one per Website demo profile; `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS` |
|
||||
| `accounts@1.9.0`, `@crosscode/demo` 1.0.0 | `messaging.get` for the App; the WhatsApp opt-out for every product (STOP kept per number and account, Accounts' own WAWP webhook, "Turn WhatsApp back on"); a scenario's church profile, SVG logo and icon, and people (`crosscode demo <church> accounts --profile <scenario>`) |
|
||||
| `contracts@1.22.0` | Only free Bible translations in 1.0 (KJV and the new BSB: `licence`, `FREE_BIBLE_TRANSLATION_IDS`, the CSV `translations` option); the publishers' exact notices (NLT, ESV and the Afrikaans ones were out of date), the Bible Society's disclaimer, an `acknowledgement` per translation, who to ask, `FREE_QUOTE_VERSES` and `quotedVerses` ([BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)) |
|
||||
| `events@3.8.0`, `@crosscode/demo` 1.1.0 | STOP stops all WhatsApp (not only news), checked before every message and passed on to Accounts; the eight scenarios as Events demo profiles, around each church's own people and campuses |
|
||||
| `contracts@1.23.0`, `agent@1.7.0` | `seed-scenario`: a whole demo scenario in one job, on whatever the church has installed (Accounts first, the rest skipped, every release checked first); `seed-demo` for Accounts and the App, and `--scenario` passed on to every product |
|
||||
| `website@1.8.0` | A profile loaded with `--scenario` takes the scenario's people as its leaders and, with a linked Cross Events, shows Events' events through the feed instead of its own; `crosscode demo <church> website --scenario`; `packages/demo` built with the Website. No migration |
|
||||
|
||||
All four were checked on PostgreSQL 18 (local, details in `temp/`, never committed): migrations,
|
||||
scenario loads, the opt-out.
|
||||
|
||||
## Released 2026-11-23
|
||||
|
||||
All tagged, pushed and deployed on 2026-11-23. Details in [VERSIONS.md](./VERSIONS.md) and the Hub's
|
||||
@@ -100,11 +118,32 @@ Everything up to and including phase 5 (the Church Website) is released and roll
|
||||
Family Church and a second church are live on the Website, crosscode-site sells it (confirmed by
|
||||
Joshua 2026-11-30; VERSIONS.md, "Deployed / rolled out").
|
||||
|
||||
1. **Phase 6, Church App 1.0.0** (ROADMAP §7, §9). Planned in [APP-1.0-PLAN.md](./APP-1.0-PLAN.md)
|
||||
(2026-11-30, decisions confirmed): contracts 1.20.0 → Accounts 1.9.0 (shared email and
|
||||
WhatsApp for the App, the WhatsApp opt-out for every product) and Events 3.8.0 (STOP passed to
|
||||
Accounts) → Hub 2.26.0 (with Cross Code devotionals) → `app@1.0.0` → cross-demo2 (with a throwaway install from the Hub) → Hope Family
|
||||
Church → crosscode-site 1.10.0 (the App on sale).
|
||||
1. **Phase 6, Church App 1.0.0** (ROADMAP §7, §9), [APP-1.0-PLAN.md](./APP-1.0-PLAN.md) §15.
|
||||
**Done 2026-11-30 (released, not deployed):** contracts 1.20.0 to 1.23.0, Accounts
|
||||
1.9.0, Events 3.8.0, Website 1.8.0, agent 1.7.0. The Bible publishers' terms checked: none covers a sold app, so **1.0 uses only the
|
||||
free translations, the KJV and the Berean Standard Bible** (APP-1.0-PLAN decision 14); the
|
||||
permission requests for the others are drafted in [BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)
|
||||
for later, and nothing waits for them. **Next:**
|
||||
1. ~~**Website 1.8.0**~~: **released 2026-11-30** (not deployed). A profile loaded with
|
||||
`--scenario` takes the scenario's people as leaders (`scenarioTeam` in `src/demo/seeds.ts`)
|
||||
and, with a linked Cross Events, shows Events' events through the feed; `crosscode demo
|
||||
<church> website --scenario`; the Website builds `packages/demo`.
|
||||
2. ~~**Agent 1.7.0**~~ and **contracts 1.23.0**: **released 2026-11-30** (not rolled out).
|
||||
`seed-demo` for `app` and `accounts`, `--scenario` passed on; the new `seed-scenario` job
|
||||
(`crosscode demo <church> --scenario <s>`) loads the scenario on every product the church
|
||||
has installed, skipping the rest, every release checked first; `crosscode demo <church> app` refused clearly until
|
||||
App 1.0.0 brings `scripts/products/app.sh` and the App's demo.
|
||||
3. **Hub 2.26.0** (vendored contracts 1.23.0): the App in New install and releases, billing on
|
||||
the active-member band, **Load a demo scenario** on a demo client (one `seed-scenario` job,
|
||||
agent 1.7.0+: the server seeds whatever the client has installed, Accounts first; show the
|
||||
report's `loaded` / `skipped`), the **Devotionals** page
|
||||
(3 months ahead, Import CSV, the free translations only: KJV and BSB) and
|
||||
`GET /api/v2/devotionals`. Then write or import the first 3
|
||||
months of Cross Code devotionals.
|
||||
4. **`app@1.0.0`** → cross-demo2 (every scenario loaded, the throwaway install from the Hub) →
|
||||
Hope Family Church → crosscode-site 1.10.0 (the App on sale).
|
||||
Deploying Accounts 1.9.0, Events 3.8.0 and Website 1.8.0 to the churches can happen any time before the App;
|
||||
a church without Cross Events gives WAWP the address in Accounts → Admin → Email and WhatsApp.
|
||||
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
|
||||
before Hub 2.10.0, and the Hub's own site, has `location ^~ /api/`.
|
||||
|
||||
@@ -148,6 +187,22 @@ rollout.
|
||||
- **Demo data:** Hub → the install's page → Mark as a demo site → Load demo data (Hub 2.4.0, agent
|
||||
1.2.0; `crosscode demo <church> --profile …` on the server). By hand, run `npm run demo:*` as the
|
||||
site's user (`sudo -u cc-<church> …`): only that user can read the `.env`.
|
||||
- **Demo scenarios** (APP-1.0-PLAN §12, from 2026-11-30): eight preset churches, the list in
|
||||
contracts `agent.DEMO_SCENARIOS`, each church's profile, people and logo in `packages/demo`
|
||||
(`@crosscode/demo`, built by every product that uses it). **Accounts loads first**
|
||||
(`crosscode demo <church> accounts --profile <scenario>`: profile, logo, people), then Events,
|
||||
the Website and the App with the same profile name. People keep the same account id everywhere
|
||||
and on every load (`demoId`); everything is at example.com with no phone numbers. A new demo
|
||||
feature that should look the same in every product goes in `packages/demo`, not in one app.
|
||||
- **WhatsApp STOP** (APP-1.0-PLAN decision 11, from Accounts 1.9.0 / Events 3.8.0): STOP means no
|
||||
WhatsApp from any product, of any kind. Accounts keeps it (`whatsapp_opted_out` in
|
||||
`user.updated`); every product checks it before sending (Events: `utils/whatsappStop.js`), and
|
||||
whichever product receives a STOP passes it on with `whatsapp.optout`. The App and the Website
|
||||
must do the same.
|
||||
- **Bible text** (BIBLE-PERMISSIONS.md, from contracts 1.22.0): the Hub and the App offer only
|
||||
`FREE_BIBLE_TRANSLATION_IDS` (KJV, BSB). Any other needs its publisher's written permission
|
||||
first, then brings its exact `copyright` line (and the Bible Society's `disclaimer` for
|
||||
AFR53/AFR83), copied from the publisher, never reworded. **No AI on Bible text**, ever: Crossway and Biblica forbid it.
|
||||
- **A new Events install never takes over an existing database**: moving an existing site is
|
||||
`adopt`, not a New install pointed at the old database.
|
||||
- **Prisma in the monorepo:** each app other than Events sets its own generator `output`, so
|
||||
@@ -168,6 +223,11 @@ rollout.
|
||||
address there doesn't change the Hub's domain for the install or FastPanel.
|
||||
- **Demo data keeps the links** to the church's other products (`KEEP_TABLES` in
|
||||
`apps/events/backend/scripts/set-demo.js`). Anything that must survive a demo load goes there.
|
||||
- **A local PostgreSQL** is on the dev machine (`temp/database details.txt`, git-ignored; the user is
|
||||
`postgres`, the file says `postges`). Use a throwaway database per check (`cc_<app>_<version>_check`),
|
||||
run `prisma migrate deploy` and `prisma migrate diff --from-config-datasource --to-schema …`, and drop
|
||||
it afterwards. Never print the password. Events' database has an older drift on
|
||||
`_EventNotifyRecipients` (an index Prisma now wants as a primary key), not from 3.8.0.
|
||||
- **Releasing:** branch → merge → tag (`<product>@<version>` here, `v<version>` in events-hub and
|
||||
crosscode-site) → push, with a CHANGELOG entry, and `npm run check` first. Pushes to c-git often
|
||||
fail authentication the first time; retry once. A push can also hang waiting on a login prompt
|
||||
|
||||
+2
-2
@@ -641,8 +641,8 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short:
|
||||
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned and built 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat); not tagged yet | Small; ready for when the Website exists |
|
||||
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script. [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md) (with contracts 1.5.0, `packages/auth-client`, Hub 2.3.0). **Released 2026-11-18** (`accounts@1.0.0`, 1.0.1 on 2026-11-19); the VM test and a run on real Postgres are still to do before a church gets it | Every later product signs in through it |
|
||||
| 4 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide. **Planned 2026-11-19:** [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md) (with contracts 1.8.0, Accounts 1.1.0, Hub 2.5.0; decisions confirmed 2026-11-19) | Breaking change, so a major version. **Moved before the Website on 2026-11-19** (decision 38): Events is the product churches use today, so Accounts is proven on real users first, and the Website then starts with a church whose people already have accounts |
|
||||
| 5 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats. **Planned 2026-11-21:** [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (with contracts 1.17.0, Accounts 1.7.0, Events 3.7.0 for the shared fonts and footer, Hub 2.21.0) | More churches need a website than an app; it also covers the "website only" case. Built on Accounts from day one |
|
||||
| 6 | **Church App 1.0.0** | Foundation (PWA, branding, Accounts), House of Prayer, announcements, devotionals, events (simple + feed) | Starts with shared users and the feed already in place |
|
||||
| 5 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats. **Planned 2026-11-21:** [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (with contracts 1.17.0, Accounts 1.7.0, Events 3.7.0 for the shared fonts and footer, Hub 2.21.0). **Released 2026-11-26, done 2026-11-30** (Hope Family Church and a second church live, crosscode-site sells it) | More churches need a website than an app; it also covers the "website only" case. Built on Accounts from day one |
|
||||
| 6 | **Church App 1.0.0** | Foundation (PWA, branding, Accounts), House of Prayer, announcements, devotionals, events (simple + feed). **Planned 2026-11-30:** [APP-1.0-PLAN.md](./APP-1.0-PLAN.md) (with contracts 1.20.0 and 1.21.0, Accounts 1.9.0, Events 3.8.0, Website 1.8.0, agent 1.7.0, Hub 2.26.0; also **demo scenarios**: eight preset churches loaded into every product of a demo client). contracts 1.20.0 / 1.21.0, Accounts 1.9.0 and Events 3.8.0 **released 2026-11-30** | Starts with shared users and the feed already in place |
|
||||
| 7 | Church App 1.x | Reading plans, sermons, groups, pastoral care, serving, giving links, directory | After House of Prayer is in use |
|
||||
|
||||
Each phase adds help content, audit log entries, tests, a CHANGELOG entry and updates to the
|
||||
|
||||
+48
-6
@@ -10,14 +10,14 @@ separately below; the two often differ.
|
||||
|
||||
| What | Repo | Latest | Tag | Released |
|
||||
|------|------|--------|-----|----------|
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.2** | `events@3.7.2` | 2026-11-27 |
|
||||
| Church Website | `crosscode-platform` (`apps/website`) | **1.7.1** | `website@1.7.1` | 2026-11-28 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 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.21.0** | `contracts@1.21.0` | 2026-11-30 |
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.8.0** | `events@3.8.0` | 2026-11-30 |
|
||||
| Church Website | `crosscode-platform` (`apps/website`) | **1.8.0** | `website@1.8.0` | 2026-11-30 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.9.0** | `accounts@1.9.0` | 2026-11-30 |
|
||||
| Server agent | `crosscode-platform` (`apps/agent`) | **1.7.0** | `agent@1.7.0` | 2026-11-30 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.23.0** | `contracts@1.23.0` | 2026-11-30 |
|
||||
| Cross Code Hub | `events-hub` | **2.25.1** | `v2.25.1` | 2026-11-27 |
|
||||
| crosscode.co.za | `crosscode-site` | **1.9.1** | `v1.9.1` | 2026-11-27 |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-27 (last change: an uninstall keeps the Website's backup snapshots shared, `rsync -aH`) |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-30 (last change: `crosscode demo <church> --scenario <s>` loads a whole scenario on whatever is installed; `crosscode demo <church> app` refused clearly until App 1.0.0; `--scenario` passed on to the Website's demo, the Website builds `packages/demo`; before that Events takes the demo scenarios as profiles, `crosscode demo <church> accounts`, Accounts and Events build `packages/demo`) |
|
||||
|
||||
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
|
||||
@@ -28,6 +28,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
|
||||
| What | Where | Version in package.json |
|
||||
|------|-------|-------------------------|
|
||||
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
|
||||
| `@crosscode/demo` | `packages/demo` | 1.1.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0, Events 3.8.0 and Website 1.8.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.7.1 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.7.0 on 2026-11-27, 1.7.1 on 2026-11-28; installed for the demo church cross-demo2 (1.7.1) only, Hope Family Church next) |
|
||||
@@ -38,6 +39,47 @@ need their own tags until something outside this repo depends on them.
|
||||
|
||||
## What each latest release was for
|
||||
|
||||
- **Server agent 1.7.0 + contracts 1.23.0 + crosscode script (2026-11-30):** demo scenarios
|
||||
(APP-1.0-PLAN §12): the `seed-scenario` job, one per scenario load, which the server runs on
|
||||
**whatever the client has installed** (Accounts first, the rest skipped, every release checked
|
||||
first, the first failure naming what's out of step); `seed-demo` for Accounts and the App, and
|
||||
`--scenario` passed on to every product. For the Hub 2.26.0's **Load a demo scenario** (it
|
||||
vendors contracts 1.23.0). Checked: contracts (340), the agent's tests (60, the two version
|
||||
numbers match), the script's demo bats (21), `npm run check`. Not rolled out yet (Update
|
||||
agent from the Hub).
|
||||
- **Church Website 1.8.0 + crosscode script (2026-11-30):** demo scenarios (APP-1.0-PLAN §12): a
|
||||
profile loaded with `--scenario` takes the scenario's people as its leaders (the pastor first,
|
||||
each with a portrait chosen for them) and, with a linked Cross Events, shows Events' events
|
||||
through the feed instead of making its own. `crosscode demo <church> website --scenario`; the
|
||||
Website builds `packages/demo`. **No migration.** Checked: the Website's backend tests (147), the
|
||||
script's bats (demo and website), `npm run check`, and on PostgreSQL 18 scenario and profile loads
|
||||
(with an unreachable Events link too: the load succeeds and says the feed will catch up). Not
|
||||
deployed yet.
|
||||
- **Contracts 1.22.0 (2026-11-30):** only free Bible translations in App 1.0 (KJV and the new
|
||||
Berean Standard Bible, `licence`, `FREE_BIBLE_TRANSLATION_IDS`, the CSV import's `translations`);
|
||||
the Bible publishers' exact notices for the Church App's
|
||||
devotionals (NLT, ESV, AFR53 and AFR83 corrected; `AFR83` named "Afrikaans 1983/1992-vertaling"),
|
||||
the Bible Society's disclaimer, an `acknowledgement`, `publisher` and `permissionsUrl` per
|
||||
translation, `FREE_QUOTE_VERSES` and `quotedVerses` ([BIBLE-PERMISSIONS.md](./BIBLE-PERMISSIONS.md)).
|
||||
Nothing uses them yet: the Hub 2.26.0 and the App 1.0.0 will. Checked: `npm run check`.
|
||||
- **Cross Events 3.8.0 + `@crosscode/demo` 1.1.0 + crosscode script (2026-11-30):** STOP to the
|
||||
church's WhatsApp number stops all WhatsApp from Events (event updates, tickets and codes too;
|
||||
codes by email), checked before every message, passed on to Accounts and read back from it
|
||||
(`whatsapp_opted_out`); START without Accounts. The eight demo scenarios as Events demo profiles,
|
||||
built around each church's own people and campuses. **One migration.** Checked: Events' tests
|
||||
(814), the script's bats (demo and events, 17), typecheck and lint, and on PostgreSQL 18 the
|
||||
migration and every scenario and demo profile loaded. The database also shows an older, unrelated
|
||||
drift on `_EventNotifyRecipients` (an index Prisma now wants as a primary key), there before 3.8.0.
|
||||
Not deployed yet.
|
||||
- **Accounts 1.9.0 + `@crosscode/demo` 1.0.0 + crosscode script (2026-11-30):** Church App
|
||||
groundwork (APP-1.0-PLAN §8, §12): `messaging.get` and `messaging.changed`; the WhatsApp opt-out
|
||||
for every product (`whatsapp.optout`, Accounts' own WAWP webhook, `whatsapp_opted_out`, "Turn
|
||||
WhatsApp back on"); a demo scenario's church profile, SVG logo and icon, and people
|
||||
(`crosscode demo <church> accounts --profile <scenario>`). **One migration.** Needs contracts
|
||||
1.21.0 and `packages/demo` (the `crosscode` script on `main` installs and builds it). Checked:
|
||||
Accounts' tests (99), `@crosscode/demo`'s (8), the script's bats (111), the workspace typecheck
|
||||
and lint, and on PostgreSQL 18 the migrations, scenario loads (2 457 people in 3.4 s), the
|
||||
opt-out and `npm run demo`. Not deployed yet.
|
||||
- **Contracts 1.21.0 (2026-11-30):** demo scenarios (APP-1.0-PLAN §12): `agent.DEMO_SCENARIOS`,
|
||||
eight fictional churches, one per Website demo profile, that load Accounts, Events, the Website
|
||||
and the App alike; `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS`, a profile per
|
||||
|
||||
Generated
+23
-8
@@ -51,10 +51,11 @@
|
||||
},
|
||||
"apps/accounts/backend": {
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
@@ -88,7 +89,7 @@
|
||||
},
|
||||
"apps/accounts/frontend": {
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
@@ -114,7 +115,7 @@
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
@@ -133,12 +134,13 @@
|
||||
},
|
||||
"apps/events/backend": {
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.7.2",
|
||||
"version": "3.8.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
@@ -183,7 +185,7 @@
|
||||
},
|
||||
"apps/events/frontend": {
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.7.2",
|
||||
"version": "3.8.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
@@ -360,11 +362,12 @@
|
||||
},
|
||||
"apps/website/backend": {
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.7.1",
|
||||
"version": "1.8.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"cron-parser": "^5.10.2",
|
||||
@@ -389,7 +392,7 @@
|
||||
},
|
||||
"apps/website/frontend": {
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "1.7.1",
|
||||
"version": "1.8.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
@@ -1066,6 +1069,10 @@
|
||||
"resolved": "packages/contracts",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@crosscode/demo": {
|
||||
"resolved": "packages/demo",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@crosscode/events-backend": {
|
||||
"resolved": "apps/events/backend",
|
||||
"link": true
|
||||
@@ -23185,7 +23192,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.21.0",
|
||||
"version": "1.23.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
@@ -23219,6 +23226,14 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"packages/demo": {
|
||||
"name": "@crosscode/demo",
|
||||
"version": "1.1.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*"
|
||||
}
|
||||
},
|
||||
"packages/seo": {
|
||||
"name": "@crosscode/seo",
|
||||
"version": "1.0.0",
|
||||
|
||||
@@ -16,7 +16,7 @@ Events and the Hub, uses it, so the key fields are the same in every product's J
|
||||
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
|
||||
| Env template | `crosscode.env-template/1` | Each product's `.env` variables by layer; `missingRequired` and, from 1.6.0, `checkEnvValue` / `invalidValues` (values an app can't start with, e.g. `TRUST_PROXY=TRUE`), which the Hub checks before a job | `src/agent.ts` (exported as `agent`) |
|
||||
| Devotional | `crosscode.devotional/1` | From 1.20.0: one day's devotional for the Church App (Cross Code's from the Hub at `GET /api/v2/devotionals`, or the church's own), the CSV import's columns and row checks (`checkDevotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`), shared by the Hub and the App | `src/devotional.ts` |
|
||||
| Bible passages | — | From 1.20.0: the 66 books (USFM codes, English and Afrikaans names), the seven translations with their YouVersion ids and copyright lines, `parseBibleReference`, `formatBibleReference`, `youVersionUrl` | `src/bible.ts` |
|
||||
| Bible passages | — | From 1.20.0: the 66 books (USFM codes, English and Afrikaans names), the seven translations with their YouVersion ids and copyright lines, `parseBibleReference`, `formatBibleReference`, `youVersionUrl`. From 1.22.0: the Berean Standard Bible, `licence` and `FREE_BIBLE_TRANSLATION_IDS` (only those in App 1.0), each publisher's exact notices (`copyright` under the verse, `acknowledgement`, the Bible Society's `disclaimer`), who to ask (`publisher`, `permissionsUrl`), `FREE_QUOTE_VERSES` and `quotedVerses` (docs/BIBLE-PERMISSIONS.md) | `src/bible.ts` |
|
||||
| Demo scenarios | — | From 1.21.0: `agent.DEMO_SCENARIOS`, eight preset churches that load every product of a demo client alike (Accounts first, `DEMO_SCENARIO_ORDER`), each product's profiles, the minimum releases and agent; `seed-demo` takes `scenario` | `src/agent.ts` (exported as `agent`) |
|
||||
| Signing | — | HMAC request signing for the Hub and for product links (Node only) | `src/signing.ts` (`@crosscode/contracts/signing`) |
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.21.0",
|
||||
"version": "1.23.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",
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
"passage": {
|
||||
"reference": "1 Corinthians 13:4–7",
|
||||
"location": { "book": "1CO", "chapter": 13, "verse": 4, "endChapter": 13, "endVerse": 7 },
|
||||
"translation": "NLT",
|
||||
"text": "Love is patient and kind. Love is not jealous or boastful or proud or rude. It does not demand its own way. It is not irritable, and it keeps no record of being wronged. It does not rejoice about injustice but rejoices whenever the truth wins out. Love never gives up, never loses faith, is always hopeful, and endures through every circumstance."
|
||||
"translation": "BSB",
|
||||
"text": "Love is patient, love is kind. It does not envy, it does not boast, it is not proud. It is not rude, it is not self-seeking, it is not easily angered, it keeps no account of wrongs. Love takes no pleasure in evil, but rejoices in the truth. It bears all things, believes all things, hopes all things, endures all things."
|
||||
},
|
||||
"body": "Paul wrote these words to a church that was proud of its gifts.\n\nLove is the gift that makes the others worth having.",
|
||||
"prayer": "Lord, teach me to love the way you love me.",
|
||||
@@ -25,14 +25,14 @@
|
||||
"id": "4c5d6e7f-8a9b-4c0d-9e1f-3a4b5c6d7e8f",
|
||||
"source": "crosscode",
|
||||
"date": "2027-01-06",
|
||||
"title": "Die Here is my herder",
|
||||
"title": "The Lord is my shepherd",
|
||||
"passage": {
|
||||
"reference": "Psalms 23:1–3",
|
||||
"location": { "book": "PSA", "chapter": 23, "verse": 1, "endChapter": 23, "endVerse": 3 },
|
||||
"translation": "AFR83",
|
||||
"text": "Die Here is my herder, ek kom niks kort nie. Hy laat my rus in groen weivelde. Hy bring my by waters waar daar vrede is. Hy gee my nuwe krag. Hy lei my op die regte paaie tot eer van sy Naam."
|
||||
"translation": "KJV",
|
||||
"text": "The LORD is my shepherd; I shall not want. He maketh me to lie down in green pastures: he leadeth me beside the still waters. He restoreth my soul: he leadeth me in the paths of righteousness for his name's sake."
|
||||
},
|
||||
"body": "Vandag herinner Dawid ons dat ons nie alleen loop nie.",
|
||||
"body": "Today David reminds us that we never walk alone.",
|
||||
"prayer": null,
|
||||
"author": null,
|
||||
"updatedAt": "2026-12-01T10:00:00.000Z"
|
||||
|
||||
@@ -914,6 +914,121 @@
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.agent-job/1"
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^job_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"serverId": {
|
||||
"type": "string",
|
||||
"pattern": "^srv_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"config": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"alg": {
|
||||
"type": "string",
|
||||
"const": "x25519-hkdf-sha256-aes-256-gcm"
|
||||
},
|
||||
"epk": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{43}$"
|
||||
},
|
||||
"iv": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{16}$"
|
||||
},
|
||||
"ciphertext": {
|
||||
"type": "string",
|
||||
"maxLength": 200000,
|
||||
"pattern": "^[A-Za-z0-9_-]+$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"alg",
|
||||
"epk",
|
||||
"iv",
|
||||
"ciphertext"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"notBefore": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"expiresAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"signature": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{86}$"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "seed-scenario"
|
||||
},
|
||||
"args": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"church": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9-]{1,30}$"
|
||||
},
|
||||
"scenario": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"heritage-parish",
|
||||
"heritage-city",
|
||||
"bold-youth",
|
||||
"bold-plant",
|
||||
"community-family",
|
||||
"community-town",
|
||||
"clean-modern",
|
||||
"clean-campus"
|
||||
]
|
||||
},
|
||||
"adminEmail": {
|
||||
"type": "string",
|
||||
"maxLength": 254,
|
||||
"format": "email",
|
||||
"pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"church",
|
||||
"scenario"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"id",
|
||||
"serverId",
|
||||
"notBefore",
|
||||
"expiresAt",
|
||||
"signature",
|
||||
"type",
|
||||
"args"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"adopt-undo",
|
||||
"restart",
|
||||
"seed-demo",
|
||||
"seed-scenario",
|
||||
"env-read",
|
||||
"env-set",
|
||||
"export",
|
||||
|
||||
@@ -1965,7 +1965,8 @@
|
||||
"NKJV",
|
||||
"KJV",
|
||||
"AFR53",
|
||||
"AFR83"
|
||||
"AFR83",
|
||||
"BSB"
|
||||
]
|
||||
},
|
||||
"text": {
|
||||
|
||||
@@ -133,7 +133,8 @@
|
||||
"NKJV",
|
||||
"KJV",
|
||||
"AFR53",
|
||||
"AFR83"
|
||||
"AFR83",
|
||||
"BSB"
|
||||
]
|
||||
},
|
||||
"text": {
|
||||
|
||||
@@ -153,7 +153,8 @@
|
||||
"NKJV",
|
||||
"KJV",
|
||||
"AFR53",
|
||||
"AFR83"
|
||||
"AFR83",
|
||||
"BSB"
|
||||
]
|
||||
},
|
||||
"text": {
|
||||
|
||||
@@ -169,7 +169,7 @@ export const DEMO_SCENARIOS: readonly DemoScenario[] = [
|
||||
}),
|
||||
scenario("community-town", {
|
||||
church: "Karoo Gemeenskapskerk", label: "Community: Karoo Gemeenskapskerk, a country-town church",
|
||||
description: "Mostly Afrikaans. A bazaar and a prayer breakfast, its own AFR83 devotionals, 30-minute prayer slots.",
|
||||
description: "Mostly Afrikaans. A bazaar and a prayer breakfast, its own Afrikaans devotionals, 30-minute prayer slots.",
|
||||
campuses: 1, language: "af", appActiveMembers: "101–300",
|
||||
}),
|
||||
scenario("clean-modern", {
|
||||
@@ -203,6 +203,9 @@ export const SEED_APP_DEMO_MIN_AGENT = "1.7.0";
|
||||
/** 1.21.0: the first agent that runs `seed-demo` for Accounts and with a `scenario` (passed on as `--scenario`). */
|
||||
export const SEED_SCENARIO_MIN_AGENT = "1.7.0";
|
||||
|
||||
/** 1.23.0: the first agent that runs `seed-scenario` jobs (a whole scenario on whatever the church has installed). */
|
||||
export const SEED_SCENARIO_JOB_MIN_AGENT = "1.7.0";
|
||||
|
||||
/** The first agent that runs a product's `seed-demo` jobs. */
|
||||
export const SEED_DEMO_MIN_AGENT_BY_PRODUCT: Record<DemoProduct, string> = {
|
||||
events: SEED_DEMO_MIN_AGENT, website: SEED_WEBSITE_DEMO_MIN_AGENT, app: SEED_APP_DEMO_MIN_AGENT, accounts: SEED_SCENARIO_MIN_AGENT,
|
||||
@@ -305,6 +308,17 @@ export const jobArgsSchemas = {
|
||||
ctx.addIssue({ code: "custom", path: ["profile"], message: `the ${a.scenario} scenario loads ${demoScenario(a.scenario).profiles[product]} in ${DEMO_PRODUCT_NAMES[product]}` });
|
||||
}
|
||||
}),
|
||||
/**
|
||||
* 1.23.0: `crosscode demo <church> --scenario <s> [--admin-email <email>] --json`: a whole demo
|
||||
* scenario in one job, on **every product the church has on that server**, in
|
||||
* `DEMO_SCENARIO_ORDER` (Accounts first); products it doesn't have are skipped, so a demo client
|
||||
* with only Accounts and the Website gets both. The script checks every installed product's
|
||||
* release (`DEMO_SCENARIO_MIN_VERSIONS`) before changing anything, and stops at the first
|
||||
* failure, naming the products now out of step. The report's `result`: `loaded` and `skipped`
|
||||
* (products, space-separated). `adminEmail`: Events' account kept, as in `seed-demo`.
|
||||
* Agent 1.7.0+ (`SEED_SCENARIO_JOB_MIN_AGENT`).
|
||||
*/
|
||||
"seed-scenario": z.strictObject({ church: shortNameSchema, scenario: demoScenarioSchema, adminEmail: z.email().max(254).optional() }),
|
||||
/**
|
||||
* `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}.
|
||||
@@ -380,7 +394,7 @@ export const CENTRAL_JOB_TYPES: readonly JobType[] = ["check-ports", "status", "
|
||||
|
||||
/** Time limits per job type, in minutes (§3). A job past it is stopped and reported as failed. */
|
||||
export const JOB_TIME_LIMIT_MINUTES: Record<JobType, number> = {
|
||||
install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, "seed-demo": 15, "env-read": 2, "env-set": 20, export: 20,
|
||||
install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, "seed-demo": 15, "seed-scenario": 45, "env-read": 2, "env-set": 20, export: 20,
|
||||
uninstall: 20, purge: 10, "update-agent": 15, "check-ports": 2, status: 3,
|
||||
"frp-read": 2, "frp-write": 5, "probe-ports": 2,
|
||||
};
|
||||
@@ -425,7 +439,7 @@ function jobOf<T extends JobType>(type: T) {
|
||||
}
|
||||
|
||||
export const agentJobSchema = z.discriminatedUnion("type", [
|
||||
jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"), jobOf("seed-demo"),
|
||||
jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"), jobOf("seed-demo"), jobOf("seed-scenario"),
|
||||
jobOf("env-read"), jobOf("env-set"), jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"),
|
||||
jobOf("frp-read"), jobOf("frp-write"), jobOf("probe-ports"),
|
||||
]);
|
||||
|
||||
@@ -14,37 +14,85 @@ import { z } from "zod";
|
||||
/**
|
||||
* The translations a devotional can use. An id never changes once released; more can be added.
|
||||
* `youVersionId` is the version's number on bible.com (`bible.com/bible/<id>/JHN.3.16.<abbr>`).
|
||||
* `copyright` is shown under the verse wherever it's quoted. Check each publisher's terms for use
|
||||
* in an app before Cross Code's devotionals go out (APP-1.0-PLAN, "Still open").
|
||||
*
|
||||
* The notices are the publishers' own wording (checked 2026-11-30, docs/BIBLE-PERMISSIONS.md):
|
||||
* - `copyright` is shown under the verse, wherever it's quoted.
|
||||
* - `acknowledgement` is the full notice, for the App's Acknowledgements page (the Bible Society
|
||||
* asks for the long form there and allows the short one next to the text).
|
||||
* - `disclaimer`, where not null, goes with the notice whenever the translation is quoted next to
|
||||
* content the publisher hasn't approved, which is every devotional (Bible Society, §6.4).
|
||||
* - `publisher` and `permissionsUrl`: who to ask past the free allowance (`FREE_QUOTE_VERSES`).
|
||||
* - `licence`: "public-domain" may be used freely; "permission" needs the publisher's written
|
||||
* permission for our use. **App 1.0 and the Hub offer only the public-domain ones**
|
||||
* (`FREE_BIBLE_TRANSLATION_IDS`, decided by Joshua 2026-11-30); the others stay in the list,
|
||||
* ids unchanged, for when a publisher says yes.
|
||||
*
|
||||
* None of these lets Cross Code quote past that allowance: that needs each publisher's written
|
||||
* permission (docs/BIBLE-PERMISSIONS.md). Never send a passage's text to an AI feature: Crossway
|
||||
* (ESV) and Biblica (NIV) forbid it outright without a separate licence.
|
||||
*/
|
||||
const BIBLE_SOCIETY_DISCLAIMER_AF =
|
||||
"Die Bybelgenootskap van Suid-Afrika verklaar hiermee dat die mening, sienings en teologiese standpunte in die bykomende materiaal in hierdie publikasie nie noodwendig dié van die Bybelgenootskap van Suid-Afrika weerspieël nie. Die Bybelgenootskap van Suid-Afrika onderskryf nie die gebruik van Bybelteks op enige manier of op enige platform wat moontlik as antichristelik beskou kan word of wat onwettige aktiwiteite bevorder.";
|
||||
const BIBLE_SOCIETY = { licence: "permission", publisher: "Bible Society of South Africa", permissionsUrl: "https://biblesociety.co.za/index/copyright-and-permissions/" } as const;
|
||||
|
||||
export const BIBLE_TRANSLATIONS = [
|
||||
{
|
||||
id: "NLT", name: "New Living Translation", language: "en", youVersionId: 116,
|
||||
copyright: "Scripture quotations are taken from the Holy Bible, New Living Translation, copyright © 1996, 2004, 2015 by Tyndale House Foundation. Used by permission of Tyndale House Publishers, Carol Stream, Illinois 60188. All rights reserved.",
|
||||
copyright: "Scripture quotations are taken from the Holy Bible, New Living Translation, copyright © 1996, 2004, 2015 by Tyndale House Ministries. Used by permission. All rights reserved.",
|
||||
acknowledgement: "Scripture quotations marked (NLT) are taken from the Holy Bible, New Living Translation, copyright © 1996, 2004, 2015 by Tyndale House Ministries. Used by permission. All rights reserved.",
|
||||
disclaimer: null,
|
||||
licence: "permission", publisher: "Tyndale House Publishers", permissionsUrl: "https://www.tyndale.com/permissions",
|
||||
},
|
||||
{
|
||||
id: "ESV", name: "English Standard Version", language: "en", youVersionId: 59,
|
||||
copyright: "Scripture quotations are from the ESV® Bible (The Holy Bible, English Standard Version®), © 2001 by Crossway, a publishing ministry of Good News Publishers. Used by permission. All rights reserved.",
|
||||
copyright: "Scripture quotations are from the ESV® Bible (The Holy Bible, English Standard Version®), © 2001 by Crossway, a publishing ministry of Good News Publishers. ESV Text Edition: 2025. The ESV text may not be quoted in any publication made available to the public by a Creative Commons license. The ESV may not be translated in whole or in part into any other language. Used by permission. All rights reserved.",
|
||||
acknowledgement: "Scripture quotations marked (ESV) are from the ESV® Bible (The Holy Bible, English Standard Version®), © 2001 by Crossway, a publishing ministry of Good News Publishers. ESV Text Edition: 2025. The ESV text may not be quoted in any publication made available to the public by a Creative Commons license. The ESV may not be translated in whole or in part into any other language. Used by permission. All rights reserved.",
|
||||
disclaimer: null,
|
||||
licence: "permission", publisher: "Crossway", permissionsUrl: "https://www.crossway.org/permissions/digital/",
|
||||
},
|
||||
{
|
||||
id: "NIV", name: "New International Version", language: "en", youVersionId: 111,
|
||||
copyright: "Scripture quotations taken from The Holy Bible, New International Version® NIV®. Copyright © 1973, 1978, 1984, 2011 by Biblica, Inc.™ Used by permission. All rights reserved worldwide.",
|
||||
acknowledgement: "Scripture quotations marked (NIV) are taken from The Holy Bible, New International Version® NIV®. Copyright © 1973, 1978, 1984, 2011 by Biblica, Inc.™ Used by permission. All rights reserved worldwide.",
|
||||
disclaimer: null,
|
||||
licence: "permission", publisher: "Biblica, Inc.", permissionsUrl: "https://www.biblica.com/permissions/",
|
||||
},
|
||||
{
|
||||
id: "NKJV", name: "New King James Version", language: "en", youVersionId: 114,
|
||||
copyright: "Scripture taken from the New King James Version®. Copyright © 1982 by Thomas Nelson. Used by permission. All rights reserved.",
|
||||
acknowledgement: "Scripture marked (NKJV) taken from the New King James Version®. Copyright © 1982 by Thomas Nelson. Used by permission. All rights reserved.",
|
||||
disclaimer: null,
|
||||
licence: "permission", publisher: "HarperCollins Christian Publishing (Thomas Nelson)", permissionsUrl: "https://www.harpercollinschristian.com/sales-and-rights/permissions/",
|
||||
},
|
||||
{
|
||||
id: "KJV", name: "King James Version", language: "en", youVersionId: 1,
|
||||
copyright: "King James Version. Public domain.",
|
||||
acknowledgement: "Scripture quotations marked (KJV) are from the King James Version, which is in the public domain.",
|
||||
disclaimer: null,
|
||||
licence: "public-domain", publisher: null, permissionsUrl: null,
|
||||
},
|
||||
{
|
||||
id: "AFR53", name: "Afrikaans 1933/1953-vertaling", language: "af", youVersionId: 5,
|
||||
copyright: "Die Bybel in Afrikaans, 1933/1953-vertaling. © Bybelgenootskap van Suid-Afrika. Gebruik met toestemming.",
|
||||
copyright: "Bybel in Afrikaans 1933/1953-vertaling © Bybelgenootskap van Suid-Afrika 1933, 1953. Digitale Weergawe © Bybelgenootskap van Suid-Afrika 2012. Alle regte voorbehou. www.biblesociety.co.za / www.biblesa.co.za.",
|
||||
acknowledgement: "Skrifaanhalings geneem uit die Bybel in Afrikaans 1933/1953-vertaling © Bybelgenootskap van Suid-Afrika 1933, 1953. Digitale Weergawe © Bybelgenootskap van Suid-Afrika 2012. Gebruik met toestemming. Alle regte voorbehou. www.biblesociety.co.za / www.biblesa.co.za. Kontak: copyright@biblesociety.co.za",
|
||||
disclaimer: BIBLE_SOCIETY_DISCLAIMER_AF,
|
||||
...BIBLE_SOCIETY,
|
||||
},
|
||||
{
|
||||
id: "AFR83", name: "Afrikaans 1983-vertaling", language: "af", youVersionId: 6,
|
||||
copyright: "Die Bybel in Afrikaans, 1983-vertaling. © Bybelgenootskap van Suid-Afrika 1983. Gebruik met toestemming.",
|
||||
id: "AFR83", name: "Afrikaans 1983/1992-vertaling", language: "af", youVersionId: 6,
|
||||
copyright: "Bybel in Afrikaans 1983-vertaling met herformulerings tot en met 1992 © Bybelgenootskap van Suid-Afrika 1983, 1992. Alle regte voorbehou. www.biblesociety.co.za / www.biblesa.co.za.",
|
||||
acknowledgement: "Skrifaanhalings geneem uit die Bybel in Afrikaans 1983-vertaling met herformulerings tot en met 1992 © Bybelgenootskap van Suid-Afrika 1983, 1992. Gebruik met toestemming. Alle regte voorbehou. www.biblesociety.co.za / www.biblesa.co.za. Kontak: copyright@biblesociety.co.za",
|
||||
disclaimer: BIBLE_SOCIETY_DISCLAIMER_AF,
|
||||
...BIBLE_SOCIETY,
|
||||
},
|
||||
{
|
||||
// Dedicated to the public domain (CC0) on 30 April 2023 (berean.bible/terms.htm). The
|
||||
// attribution is "appreciated but not required"; the Berean name only for the verbatim text.
|
||||
id: "BSB", name: "Berean Standard Bible", language: "en", youVersionId: 3034,
|
||||
copyright: "Berean Standard Bible (BSB). Public domain.",
|
||||
acknowledgement: "The Holy Bible, Berean Standard Bible, BSB is produced in cooperation with Bible Hub, Discovery Bible, OpenBible.com, and the Berean Bible Translation Committee. This text of God's Word has been dedicated to the public domain.",
|
||||
disclaimer: null,
|
||||
licence: "public-domain", publisher: null, permissionsUrl: null,
|
||||
},
|
||||
] as const;
|
||||
|
||||
@@ -53,6 +101,9 @@ export const BIBLE_TRANSLATION_IDS = BIBLE_TRANSLATIONS.map((t) => t.id) as [Bib
|
||||
export const bibleTranslationIdSchema = z.enum(BIBLE_TRANSLATION_IDS);
|
||||
export type BibleTranslationId = z.infer<typeof bibleTranslationIdSchema>;
|
||||
|
||||
/** The translations anyone may quote freely: the only ones the Hub and App 1.0 offer. */
|
||||
export const FREE_BIBLE_TRANSLATION_IDS: readonly BibleTranslationId[] = BIBLE_TRANSLATIONS.filter((t) => t.licence === "public-domain").map((t) => t.id);
|
||||
|
||||
export function bibleTranslation(id: BibleTranslationId): BibleTranslation {
|
||||
return BIBLE_TRANSLATIONS.find((t) => t.id === id)!;
|
||||
}
|
||||
@@ -60,6 +111,14 @@ export function bibleTranslation(id: BibleTranslationId): BibleTranslation {
|
||||
/** A passage longer than this gets a warning: quote the passage, not whole chapters (§6). */
|
||||
export const PASSAGE_WARN_VERSES = 25;
|
||||
|
||||
/**
|
||||
* What every publisher but the KJV's lets anyone quote without asking, counted across the whole
|
||||
* work (Biblica: across a whole app or website), with the quotes under 25% of it and never a whole
|
||||
* book. Cross Code's devotionals, and a church's own, pass it within a few months, so each needs
|
||||
* the publisher's written permission (docs/BIBLE-PERMISSIONS.md).
|
||||
*/
|
||||
export const FREE_QUOTE_VERSES = 500;
|
||||
|
||||
// ─── Books ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -83,6 +83,30 @@ export function devotionalCopyright(passage: Pick<DevotionalPassage, "translatio
|
||||
return bibleTranslation(passage.translation).copyright;
|
||||
}
|
||||
|
||||
/** The publisher's disclaimer shown with the copyright line, or null (Bible Society translations only). */
|
||||
export function devotionalDisclaimer(passage: Pick<DevotionalPassage, "translation">): string | null {
|
||||
return bibleTranslation(passage.translation).disclaimer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verses quoted per translation, for the free allowance (`FREE_QUOTE_VERSES`, counted across the
|
||||
* whole App). A passage across chapters can't be counted (verse counts per chapter aren't kept)
|
||||
* and goes in `uncounted`, so a warning can say the total is at least this.
|
||||
*/
|
||||
export function quotedVerses(passages: readonly Pick<DevotionalPassage, "location" | "translation">[]): {
|
||||
verses: Partial<Record<BibleTranslationId, number>>;
|
||||
uncounted: Partial<Record<BibleTranslationId, number>>;
|
||||
} {
|
||||
const verses: Partial<Record<BibleTranslationId, number>> = {};
|
||||
const uncounted: Partial<Record<BibleTranslationId, number>> = {};
|
||||
for (const p of passages) {
|
||||
const n = passageVerseCount(p.location);
|
||||
if (n === null) uncounted[p.translation] = (uncounted[p.translation] ?? 0) + 1;
|
||||
else verses[p.translation] = (verses[p.translation] ?? 0) + n;
|
||||
}
|
||||
return { verses, uncounted };
|
||||
}
|
||||
|
||||
// ─── CSV import ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** The columns, in this order in the template. A file may order them differently. */
|
||||
@@ -158,6 +182,8 @@ export interface DevotionalCsvOptions {
|
||||
taken?: Iterable<string>;
|
||||
/** The last date allowed (the Hub: 3 months from today). Later dates are errors. */
|
||||
latestDate?: string;
|
||||
/** The translations allowed (the Hub and App 1.0: `FREE_BIBLE_TRANSLATION_IDS`). Any by default. */
|
||||
translations?: readonly BibleTranslationId[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -211,7 +237,10 @@ export function checkDevotionalCsv(text: string, options: DevotionalCsvOptions =
|
||||
|
||||
const translationText = required("translation", "The translation");
|
||||
const translation = BIBLE_TRANSLATION_IDS.find((id) => id === translationText.toUpperCase().replace(/\s/g, "")) as BibleTranslationId | undefined;
|
||||
if (translationText && !translation) errors.push({ column: "translation", message: `"${translationText}" isn't one of ${BIBLE_TRANSLATION_IDS.join(", ")}` });
|
||||
if (translationText && !translation) errors.push({ column: "translation", message: `"${translationText}" isn't one of ${(options.translations ?? BIBLE_TRANSLATION_IDS).join(", ")}` });
|
||||
else if (translation && options.translations && !options.translations.includes(translation)) {
|
||||
errors.push({ column: "translation", message: `${translation} needs ${bibleTranslation(translation).publisher ?? "the publisher"}'s permission; use ${options.translations.join(" or ")}` });
|
||||
}
|
||||
|
||||
const reference = required("passage", "The passage");
|
||||
const parsed = reference ? parseBibleReference(reference) : null;
|
||||
@@ -265,8 +294,8 @@ export const DEVOTIONAL_CSV_TEMPLATE = devotionalCsv([{
|
||||
date: "2027-01-05",
|
||||
title: "Love that never gives up",
|
||||
passage: "1 Corinthians 13:4-7",
|
||||
translation: "NLT",
|
||||
passage_text: "Love is patient and kind. Love is not jealous or boastful or proud or rude. It does not demand its own way. It is not irritable, and it keeps no record of being wronged. It does not rejoice about injustice but rejoices whenever the truth wins out. Love never gives up, never loses faith, is always hopeful, and endures through every circumstance.",
|
||||
translation: "BSB",
|
||||
passage_text: "Love is patient, love is kind. It does not envy, it does not boast, it is not proud. It is not rude, it is not self-seeking, it is not easily angered, it keeps no account of wrongs. Love takes no pleasure in evil, but rejoices in the truth. It bears all things, believes all things, hopes all things, endures all things.",
|
||||
body: "Paul wrote these words to a church that was proud of its gifts...\n\nA second paragraph after a blank line.",
|
||||
prayer: "Lord, teach me to love the way you love me.",
|
||||
author: "Cross Code",
|
||||
|
||||
@@ -230,6 +230,23 @@ describe("demo scenarios (1.21.0)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("seed-scenario jobs (1.23.0)", () => {
|
||||
const args = (a: Record<string, unknown>) => agent.jobArgsSchemas["seed-scenario"].safeParse(a).success;
|
||||
|
||||
it("takes a church and a scenario (the products are whatever the church has installed)", () => {
|
||||
expect(args({ church: "demo2", scenario: "community-family" })).toBe(true);
|
||||
expect(args({ church: "demo2", scenario: "community-family", adminEmail: "jane@hope.test" })).toBe(true);
|
||||
expect(args({ church: "demo2", scenario: "nowhere" })).toBe(false);
|
||||
expect(args({ church: "demo2" })).toBe(false);
|
||||
expect(args({ church: "demo2", scenario: "bold-youth", products: ["website"] })).toBe(false);
|
||||
expect(args({ church: "demo2", scenario: "bold-youth", adminEmail: "x; rm -rf /" })).toBe(false);
|
||||
expect(agent.JOB_TYPES).toContain("seed-scenario");
|
||||
expect(agent.CENTRAL_JOB_TYPES).not.toContain("seed-scenario");
|
||||
expect(agent.JOB_TIME_LIMIT_MINUTES["seed-scenario"]).toBeGreaterThanOrEqual(agent.JOB_TIME_LIMIT_MINUTES["seed-demo"] * 3);
|
||||
expect(agent.SEED_SCENARIO_JOB_MIN_AGENT).toBe("1.7.0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("env-read and env-set jobs (1.12.0)", () => {
|
||||
const set = (a: Record<string, unknown>) => agent.jobArgsSchemas["env-set"].safeParse({ church: "hope", product: "events", file: "backend/.env", set: {}, unset: [], restart: true, ...a });
|
||||
it("read one product", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
BIBLE_BOOKS, BIBLE_TRANSLATIONS, DEVOTIONAL_CSV_COLUMNS, DEVOTIONAL_CSV_TEMPLATE, checkDevotionalCsv, devotionalCsv,
|
||||
devotionalsReplySchema, findBibleBook, formatBibleReference, parseBibleReference, parseCsv, passageVerseCount, youVersionUrl,
|
||||
BIBLE_BOOKS, BIBLE_TRANSLATIONS, DEVOTIONAL_CSV_COLUMNS, FREE_BIBLE_TRANSLATION_IDS, FREE_QUOTE_VERSES, DEVOTIONAL_CSV_TEMPLATE, checkDevotionalCsv, devotionalCsv,
|
||||
devotionalDisclaimer, devotionalsReplySchema, findBibleBook, quotedVerses, formatBibleReference, parseBibleReference, parseCsv, passageVerseCount, youVersionUrl,
|
||||
type PassageLocation,
|
||||
} from "../src";
|
||||
import { sample } from "./helpers";
|
||||
@@ -33,11 +33,47 @@ describe("Bible books and translations", () => {
|
||||
expect(findBibleBook("Nowhere")).toBeNull();
|
||||
});
|
||||
|
||||
it("has the seven translations, with unique ids and YouVersion numbers", () => {
|
||||
expect(BIBLE_TRANSLATIONS.map((t) => t.id)).toEqual(["NLT", "ESV", "NIV", "NKJV", "KJV", "AFR53", "AFR83"]);
|
||||
expect(new Set(BIBLE_TRANSLATIONS.map((t) => t.youVersionId)).size).toBe(7);
|
||||
it("has the eight translations, with unique ids and YouVersion numbers", () => {
|
||||
expect(BIBLE_TRANSLATIONS.map((t) => t.id)).toEqual(["NLT", "ESV", "NIV", "NKJV", "KJV", "AFR53", "AFR83", "BSB"]);
|
||||
expect(new Set(BIBLE_TRANSLATIONS.map((t) => t.youVersionId)).size).toBe(8);
|
||||
for (const t of BIBLE_TRANSLATIONS) expect(t.copyright.length).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it("carries each publisher's notices, with a publisher to ask for all but the public-domain ones", () => {
|
||||
expect(FREE_BIBLE_TRANSLATION_IDS).toEqual(["KJV", "BSB"]);
|
||||
for (const t of BIBLE_TRANSLATIONS) {
|
||||
const free = FREE_BIBLE_TRANSLATION_IDS.includes(t.id);
|
||||
expect(t.licence).toBe(free ? "public-domain" : "permission");
|
||||
expect(t.acknowledgement.length).toBeGreaterThan(t.id === "KJV" ? 10 : 50);
|
||||
expect(t.publisher === null).toBe(free);
|
||||
expect(t.permissionsUrl === null).toBe(free);
|
||||
}
|
||||
expect(youVersionUrl(ok("John 3:16"), "BSB")).toBe("https://www.bible.com/bible/3034/JHN.3.16.BSB");
|
||||
expect(BIBLE_TRANSLATIONS.find((t) => t.id === "NLT")!.copyright).toContain("Tyndale House Ministries");
|
||||
expect(BIBLE_TRANSLATIONS.find((t) => t.id === "ESV")!.copyright).toContain("ESV Text Edition: 2025");
|
||||
expect(FREE_QUOTE_VERSES).toBe(500);
|
||||
});
|
||||
|
||||
it("gives the Bible Society's translations their disclaimer and official names", () => {
|
||||
for (const t of BIBLE_TRANSLATIONS) {
|
||||
expect(t.disclaimer !== null).toBe(t.language === "af");
|
||||
expect(t.acknowledgement).not.toMatch(/Ou Vertaling|Nuwe Vertaling/);
|
||||
}
|
||||
expect(devotionalDisclaimer({ translation: "AFR83" })).toContain("Bybelgenootskap van Suid-Afrika verklaar");
|
||||
expect(devotionalDisclaimer({ translation: "NIV" })).toBeNull();
|
||||
expect(BIBLE_TRANSLATIONS.find((t) => t.id === "AFR83")!.copyright).toContain("1983-vertaling met herformulerings tot en met 1992");
|
||||
});
|
||||
|
||||
it("counts the verses quoted per translation, passages across chapters apart", () => {
|
||||
const r = quotedVerses([
|
||||
{ location: ok("John 3:16-18"), translation: "NIV" },
|
||||
{ location: ok("Ps 23:1-6"), translation: "NIV" },
|
||||
{ location: ok("Rom 8:38-9:2"), translation: "NIV" },
|
||||
{ location: ok("Gen 1:1"), translation: "KJV" },
|
||||
]);
|
||||
expect(r.verses).toEqual({ NIV: 9, KJV: 1 });
|
||||
expect(r.uncounted).toEqual({ NIV: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseBibleReference", () => {
|
||||
@@ -118,7 +154,15 @@ describe("checkDevotionalCsv", () => {
|
||||
expect(r.fileError).toBeNull();
|
||||
expect(r.rows).toHaveLength(1);
|
||||
expect(r.rows[0]!.errors).toEqual([]);
|
||||
expect(r.rows[0]!.devotional?.passage).toMatchObject({ reference: "1 Corinthians 13:4–7", translation: "NLT" });
|
||||
expect(r.rows[0]!.devotional?.passage).toMatchObject({ reference: "1 Corinthians 13:4–7", translation: "BSB" });
|
||||
expect(checkDevotionalCsv(DEVOTIONAL_CSV_TEMPLATE, { translations: FREE_BIBLE_TRANSLATION_IDS }).rows[0]!.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses a translation that isn't allowed, naming the publisher to ask", () => {
|
||||
const r = checkDevotionalCsv(devotionalCsv([row({ translation: "NIV" }), row({ date: "2027-01-06", translation: "kjv" })]), { translations: FREE_BIBLE_TRANSLATION_IDS });
|
||||
expect(r.rows[0]!.devotional).toBeNull();
|
||||
expect(r.rows[0]!.errors).toEqual([{ column: "translation", message: "NIV needs Biblica, Inc.'s permission; use KJV or BSB" }]);
|
||||
expect(r.rows[1]!.devotional?.passage.translation).toBe("KJV");
|
||||
});
|
||||
|
||||
it("turns a good row into a devotional, in the translation's language, empty optional fields null", () => {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# @crosscode/demo
|
||||
|
||||
The demo scenarios' churches and people (docs/APP-1.0-PLAN.md §12, "Demo scenarios"). Loading a
|
||||
scenario on a demo client puts the same church into every product: Accounts takes the church
|
||||
profile, logo, icon and people from here, and Cross Events, the Church Website and the App build
|
||||
their demo data around the same people (same `sub` in every product: `demoId`).
|
||||
|
||||
- `DEMO_CHURCHES`, `demoChurch(scenario)`: each church's profile (name, colours, font pairing,
|
||||
corners, campuses, service times, contact, social links) and the mark its logo is drawn with.
|
||||
- `demoPeople(scenario)`: the leads (pastor, office, prayer coordinator…) and members, enough for
|
||||
the scenario's App active-member band, each with a `gender` (1.1.0, for Events' gendered events)
|
||||
and a campus where the church has campuses. `demoParts(scenario)`: what each lead does.
|
||||
- `demoIconSvg`, `demoLogoSvg`: the logo and icon, drawn for the demo.
|
||||
|
||||
Everything is fictional: people and church addresses are at `example.com`, there are no phone
|
||||
numbers, and the password is `Demo@1234`. Ships inside the apps that use it (not tagged): Accounts
|
||||
1.9.0 and Events 3.8.0 so far; the Website and the App next. Each product's install script builds it.
|
||||
@@ -0,0 +1,7 @@
|
||||
module.exports = {
|
||||
testEnvironment: "node",
|
||||
testMatch: ["<rootDir>/tests/**/*.test.ts"],
|
||||
transform: { "^.+\\.ts$": ["ts-jest", { tsconfig: { module: "commonjs", moduleResolution: "node", isolatedModules: true } }] },
|
||||
moduleFileExtensions: ["ts", "js", "json"],
|
||||
modulePathIgnorePatterns: ["<rootDir>/dist/"],
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@crosscode/demo",
|
||||
"version": "1.1.0",
|
||||
"private": true,
|
||||
"description": "The demo scenarios' churches and people (APP-1.0-PLAN §12): the same church in Accounts, Cross Events, the Church Website and the App. Fictional only.",
|
||||
"license": "UNLICENSED",
|
||||
"type": "commonjs",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"sideEffects": false,
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "jest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import type { BrandStyle, Church, agent } from "@crosscode/contracts";
|
||||
|
||||
/**
|
||||
* Each demo scenario's church (APP-1.0-PLAN §12, "Demo scenarios"; the list is
|
||||
* `agent.DEMO_SCENARIOS` in the contracts). Loading a scenario puts this profile into Accounts, so
|
||||
* Cross Events, the Website and the App all show the same church. Every name, address and number is
|
||||
* made up: contact addresses are at example.com, social links at example.com, and there are no
|
||||
* phone numbers (nothing a demo sends can reach a real person).
|
||||
*/
|
||||
|
||||
/** The simple mark each church's logo and icon are drawn with (`./logo`). */
|
||||
export type DemoMark = "arch" | "cross" | "flame" | "wave" | "tree" | "sun" | "north" | "river";
|
||||
|
||||
/** The profile fields Accounts takes from a scenario (it fills in the rest: ids, links, logo addresses). */
|
||||
export type DemoChurchProfile = Pick<Church, "name" | "shortName" | "timezone" | "locale" | "campuses" | "serviceTimes" | "social"> & {
|
||||
colours: { primary: string; accent: string };
|
||||
style: { fontPairing: NonNullable<BrandStyle["fontPairing"]>; corners: NonNullable<BrandStyle["corners"]> };
|
||||
contact: Omit<Church["contact"], "phone" | "whatsapp">;
|
||||
};
|
||||
|
||||
export interface DemoChurch {
|
||||
scenario: agent.DemoScenarioKey;
|
||||
/** Used in demo addresses: `office.<slug>@example.com`. */
|
||||
slug: string;
|
||||
mark: DemoMark;
|
||||
profile: DemoChurchProfile;
|
||||
}
|
||||
|
||||
const ZA = "Africa/Johannesburg";
|
||||
const address = (line1: string, suburb: string | null, city: string, province: string, postalCode: string) =>
|
||||
({ line1, line2: null, suburb, city, province, postalCode, country: "ZA", geo: null });
|
||||
const social = (slug: string, networks: ("facebook" | "instagram" | "youtube" | "spotify")[]) =>
|
||||
networks.map((network) => ({ network, url: `https://example.com/${network}/${slug}` }));
|
||||
const contact = (slug: string, addr: ReturnType<typeof address>) => ({ email: `office.${slug}@example.com`, address: addr });
|
||||
|
||||
export const DEMO_CHURCHES: readonly DemoChurch[] = [
|
||||
{
|
||||
scenario: "heritage-parish", slug: "stcolumbas", mark: "arch",
|
||||
profile: {
|
||||
name: "St Columba's Church", shortName: "St Columba's", timezone: ZA, locale: "en-ZA",
|
||||
colours: { primary: "#5b2333", accent: "#c9a227" }, style: { fontPairing: "classic", corners: "sharp" },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: "sunday", time: "09:00", label: "Sung Eucharist", campus: null, note: "Sunday school in the hall during the service" },
|
||||
{ day: "wednesday", time: "10:00", label: "Midweek communion", campus: null, note: null },
|
||||
],
|
||||
contact: contact("stcolumbas", address("3 Glebe Lane", "Old Town", "Grahamstown", "Eastern Cape", "6139")),
|
||||
social: social("stcolumbas", ["facebook"]),
|
||||
},
|
||||
},
|
||||
{
|
||||
scenario: "heritage-city", slug: "gracecathedral", mark: "cross",
|
||||
profile: {
|
||||
name: "Grace Cathedral", shortName: "Grace", timezone: ZA, locale: "en-ZA",
|
||||
colours: { primary: "#1d3557", accent: "#e09f3e" }, style: { fontPairing: "editorial", corners: "sharp" },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: "sunday", time: "07:30", label: "Early communion", campus: null, note: null },
|
||||
{ day: "sunday", time: "09:30", label: "Cathedral Eucharist", campus: null, note: "Choir and children's church" },
|
||||
{ day: "sunday", time: "18:00", label: "Choral evensong", campus: null, note: null },
|
||||
{ day: "wednesday", time: "12:30", label: "Lunchtime prayer", campus: null, note: "Thirty minutes, then soup in the crypt" },
|
||||
],
|
||||
contact: contact("gracecathedral", address("1 Cathedral Square", "City Centre", "Cape Town", "Western Cape", "8001")),
|
||||
social: social("gracecathedral", ["facebook", "youtube", "spotify"]),
|
||||
},
|
||||
},
|
||||
{
|
||||
scenario: "bold-youth", slug: "ignite", mark: "flame",
|
||||
profile: {
|
||||
name: "Ignite Church", shortName: "Ignite", timezone: ZA, locale: "en-ZA",
|
||||
colours: { primary: "#e4572e", accent: "#17bebb" }, style: { fontPairing: "impact", corners: "round" },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: "sunday", time: "10:00", label: "Sunday gathering", campus: null, note: "Kids zone for ages 3 to 11" },
|
||||
{ day: "sunday", time: "17:30", label: "Ignite Night", campus: null, note: "Worship night for students and young adults" },
|
||||
{ day: "friday", time: "19:00", label: "Youth", campus: null, note: "Grades 8 to 12" },
|
||||
],
|
||||
contact: contact("ignite", address("48 Factory Road", "Maboneng", "Johannesburg", "Gauteng", "2094")),
|
||||
social: social("ignite", ["instagram", "youtube", "spotify"]),
|
||||
},
|
||||
},
|
||||
{
|
||||
scenario: "bold-plant", slug: "harbourcity", mark: "wave",
|
||||
profile: {
|
||||
name: "Harbour City Church", shortName: "Harbour City", timezone: ZA, locale: "en-ZA",
|
||||
colours: { primary: "#0b6e99", accent: "#f4b942" }, style: { fontPairing: "contemporary", corners: "round" },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: "sunday", time: "09:30", label: "Sunday service", campus: null, note: "In the hall of Seaview Primary School" },
|
||||
],
|
||||
contact: contact("harbourcity", address("Seaview Primary School, 12 Marine Drive", "Humewood", "Gqeberha", "Eastern Cape", "6001")),
|
||||
social: social("harbourcity", ["instagram", "facebook"]),
|
||||
},
|
||||
},
|
||||
{
|
||||
scenario: "community-family", slug: "acaciahill", mark: "tree",
|
||||
profile: {
|
||||
name: "Acacia Hill Church", shortName: "Acacia Hill", timezone: ZA, locale: "en-ZA",
|
||||
colours: { primary: "#2f6f4f", accent: "#e9a23b" }, style: { fontPairing: "warm", corners: "soft" },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: "sunday", time: "08:30", label: "Early service", campus: null, note: null },
|
||||
{ day: "sunday", time: "10:30", label: "Family service", campus: null, note: "Kids' church for ages 2 to 12" },
|
||||
{ day: "wednesday", time: "18:30", label: "Prayer evening", campus: null, note: null },
|
||||
],
|
||||
contact: contact("acaciahill", address("27 Acacia Avenue", "Lynnwood", "Pretoria", "Gauteng", "0081")),
|
||||
social: social("acaciahill", ["facebook", "instagram", "youtube"]),
|
||||
},
|
||||
},
|
||||
{
|
||||
scenario: "community-town", slug: "karoo", mark: "sun",
|
||||
profile: {
|
||||
name: "Karoo Gemeenskapskerk", shortName: "Karoo Kerk", timezone: ZA, locale: "af-ZA",
|
||||
colours: { primary: "#9c4a1a", accent: "#d9b44a" }, style: { fontPairing: "friendly", corners: "soft" },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: "sunday", time: "09:00", label: "Erediens", campus: null, note: "Kinderkerk tydens die diens" },
|
||||
{ day: "sunday", time: "18:00", label: "Aanddiens (English)", campus: null, note: null },
|
||||
{ day: "wednesday", time: "19:00", label: "Bidstond", campus: null, note: null },
|
||||
],
|
||||
contact: contact("karoo", address("14 Kerkstraat", null, "Graaff-Reinet", "Eastern Cape", "6280")),
|
||||
social: social("karoo", ["facebook"]),
|
||||
},
|
||||
},
|
||||
{
|
||||
scenario: "clean-modern", slug: "northpoint", mark: "north",
|
||||
profile: {
|
||||
name: "Northpoint Church", shortName: "Northpoint", timezone: ZA, locale: "en-ZA",
|
||||
colours: { primary: "#22313f", accent: "#3fb68b" }, style: { fontPairing: "modern", corners: "soft" },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: "sunday", time: "08:30", label: "First service", campus: null, note: null },
|
||||
{ day: "sunday", time: "10:30", label: "Second service", campus: null, note: "Kids and youth during the service" },
|
||||
{ day: "sunday", time: "18:00", label: "Evening service", campus: null, note: null },
|
||||
],
|
||||
contact: contact("northpoint", address("200 Northpoint Boulevard", "Umhlanga Ridge", "Durban", "KwaZulu-Natal", "4319")),
|
||||
social: social("northpoint", ["facebook", "instagram", "youtube", "spotify"]),
|
||||
},
|
||||
},
|
||||
{
|
||||
scenario: "clean-campus", slug: "riverside", mark: "river",
|
||||
profile: {
|
||||
name: "Riverside Church", shortName: "Riverside", timezone: ZA, locale: "en-ZA",
|
||||
colours: { primary: "#264653", accent: "#2a9d8f" }, style: { fontPairing: "modern", corners: "sharp" },
|
||||
campuses: [
|
||||
{ slug: "stellenbosch", name: "Stellenbosch", address: address("5 Riverbank Road", "Die Boord", "Stellenbosch", "Western Cape", "7600") },
|
||||
{ slug: "paarl", name: "Paarl", address: address("88 Main Road", "Paarl Central", "Paarl", "Western Cape", "7646") },
|
||||
{ slug: "somerset-west", name: "Somerset West", address: address("12 Lourens Street", null, "Somerset West", "Western Cape", "7130") },
|
||||
],
|
||||
serviceTimes: [
|
||||
{ day: "sunday", time: "09:00", label: "Morning service", campus: "stellenbosch", note: null },
|
||||
{ day: "sunday", time: "18:30", label: "Students' service", campus: "stellenbosch", note: "Supper afterwards in the courtyard" },
|
||||
{ day: "sunday", time: "09:30", label: "Morning service", campus: "paarl", note: "Kids' church during the service" },
|
||||
{ day: "sunday", time: "10:00", label: "Morning service", campus: "somerset-west", note: null },
|
||||
],
|
||||
contact: contact("riverside", address("5 Riverbank Road", "Die Boord", "Stellenbosch", "Western Cape", "7600")),
|
||||
social: social("riverside", ["instagram", "youtube"]),
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export function demoChurch(scenario: agent.DemoScenarioKey): DemoChurch {
|
||||
const c = DEMO_CHURCHES.find((x) => x.scenario === scenario);
|
||||
if (!c) throw new Error(`No demo church for ${scenario}`);
|
||||
return c;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* @crosscode/demo: the demo scenarios' churches and people (docs/APP-1.0-PLAN.md §12, "Demo
|
||||
* scenarios"), so Accounts, Cross Events, the Church Website and the App load the same church.
|
||||
* The scenario list itself is `agent.DEMO_SCENARIOS` in @crosscode/contracts. Fictional only.
|
||||
*/
|
||||
export * from "./churches";
|
||||
export * from "./people";
|
||||
export * from "./logo";
|
||||
@@ -0,0 +1,47 @@
|
||||
import { FONT_PAIRINGS, type agent } from "@crosscode/contracts";
|
||||
import { demoChurch, type DemoMark } from "./churches";
|
||||
|
||||
/**
|
||||
* Each demo church's logo and icon, drawn for the demo (never a real church's): a simple mark in
|
||||
* white on the church's colour, and the mark beside the church's name. SVG, so they're crisp at
|
||||
* any size; Accounts serves them (`/api/demo-assets/<scenario>/icon.svg`, `logo.svg`).
|
||||
*/
|
||||
|
||||
/** The marks, drawn in white on a 512 × 512 square. */
|
||||
const MARKS: Record<DemoMark, string> = {
|
||||
// A church window: a pointed arch with a sill.
|
||||
arch: '<path d="M176 400V236c0-56 36-100 80-124 44 24 80 68 80 124v164z" fill="none" stroke="#fff" stroke-width="28" stroke-linejoin="round"/><path d="M256 168v232M176 272h160" stroke="#fff" stroke-width="20"/>',
|
||||
cross: '<rect x="232" y="96" width="48" height="320" rx="6" fill="#fff"/><rect x="152" y="176" width="208" height="48" rx="6" fill="#fff"/>',
|
||||
flame: '<path d="M256 88c24 72 104 112 104 200a104 104 0 0 1-208 0c0-48 24-80 48-104 0 40 16 64 40 72-8-64 0-112 16-168z" fill="#fff"/>',
|
||||
wave: '<path d="M96 300c40-40 80-40 120 0s80 40 120 0 80-40 80 0M96 372c40-40 80-40 120 0s80 40 120 0 80-40 80 0" fill="none" stroke="#fff" stroke-width="28" stroke-linecap="round"/><path d="M256 108v120M216 148h80" stroke="#fff" stroke-width="24" stroke-linecap="round"/>',
|
||||
// An acacia: a flat crown on a thin trunk.
|
||||
tree: '<path d="M112 220c0-36 64-64 144-64s144 28 144 64-64 44-144 44-144-8-144-44z" fill="#fff"/><path d="M256 260v156M256 316l-56-52M256 300l52-40" stroke="#fff" stroke-width="22" stroke-linecap="round"/>',
|
||||
sun: '<circle cx="256" cy="300" r="72" fill="#fff"/><path d="M256 156v-48M156 204l-34-34M356 204l34-34M120 300H72M392 300h48" stroke="#fff" stroke-width="24" stroke-linecap="round"/><path d="M96 404h320" stroke="#fff" stroke-width="24" stroke-linecap="round"/>',
|
||||
// A compass point.
|
||||
north: '<path d="M256 88l88 296-88-56-88 56z" fill="#fff"/><circle cx="256" cy="420" r="16" fill="#fff"/>',
|
||||
// A river through three points (three campuses).
|
||||
river: '<path d="M120 120c120 40 40 140 136 168s48 112 136 104" fill="none" stroke="#fff" stroke-width="32" stroke-linecap="round"/><circle cx="148" cy="360" r="28" fill="#fff"/><circle cx="380" cy="160" r="28" fill="#fff"/><circle cx="256" cy="200" r="20" fill="#fff"/>',
|
||||
};
|
||||
|
||||
const escapeXml = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
||||
|
||||
/** The square icon (app icon, favicon): the mark on the church's primary colour. */
|
||||
export function demoIconSvg(scenario: agent.DemoScenarioKey): string {
|
||||
const c = demoChurch(scenario);
|
||||
const radius = c.profile.style.corners === "sharp" ? 48 : c.profile.style.corners === "round" ? 160 : 96;
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="${escapeXml(c.profile.name)}"><rect width="512" height="512" rx="${radius}" fill="${c.profile.colours.primary}"/>${MARKS[c.mark]}</svg>`;
|
||||
}
|
||||
|
||||
/** The logo: the icon and the church's name in its heading font (a font stack, with a fallback). */
|
||||
export function demoLogoSvg(scenario: agent.DemoScenarioKey): string {
|
||||
const c = demoChurch(scenario);
|
||||
const pairing = FONT_PAIRINGS[c.profile.style.fontPairing];
|
||||
const font = `${pairing.heading.family}, ${pairing.heading.category === "serif" ? "Georgia, serif" : "Helvetica, Arial, sans-serif"}`;
|
||||
const name = c.profile.name;
|
||||
const size = name.length > 20 ? 64 : 76;
|
||||
const width = Math.round(240 + name.length * size * 0.56);
|
||||
const icon = demoIconSvg(scenario).replace(/^<svg[^>]*>/, "").replace(/<\/svg>$/, "");
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} 200" width="${width}" height="200" role="img" aria-label="${escapeXml(name)}">`
|
||||
+ `<svg x="16" y="16" width="168" height="168" viewBox="0 0 512 512">${icon}</svg>`
|
||||
+ `<text x="208" y="${100 + size * 0.35}" font-family="${escapeXml(font)}" font-size="${size}" font-weight="700" fill="${c.profile.colours.primary}">${escapeXml(name)}</text></svg>`;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { agent, DEMO_EMAIL_DOMAIN } from "@crosscode/contracts";
|
||||
import { demoChurch } from "./churches";
|
||||
|
||||
/**
|
||||
* Each scenario's people (APP-1.0-PLAN §12): a handful with parts to play in every product (the
|
||||
* pastor, the office, the prayer coordinator…) and members enough to put the App in the scenario's
|
||||
* active-member band. All at example.com (`DEMO_EMAIL_DOMAIN`, reserved: no real person has one), no
|
||||
* phone numbers, password `Demo@1234`. Ids are worked out from the email, so a person keeps the
|
||||
* same account (`sub`) every time a scenario is loaded, in every product.
|
||||
*/
|
||||
|
||||
export const DEMO_PASSWORD = "Demo@1234";
|
||||
|
||||
/** What someone does at the church; each product turns it into its own roles. */
|
||||
export const DEMO_PARTS = ["pastor", "office", "prayer-coordinator", "devotional-writer", "worship", "kids", "youth", "member"] as const;
|
||||
export type DemoPart = (typeof DEMO_PARTS)[number];
|
||||
|
||||
export interface DemoPerson {
|
||||
/** The account id (`sub`): the same on every load. */
|
||||
id: string;
|
||||
name: string;
|
||||
givenName: string;
|
||||
familyName: string;
|
||||
email: string;
|
||||
part: DemoPart;
|
||||
/** 1.1.0: for products that seat or group people (Cross Events' men's breakfast, camp cabins). */
|
||||
gender: "female" | "male";
|
||||
/** The campus they belong to (multi-campus scenarios), or null. */
|
||||
campus: string | null;
|
||||
}
|
||||
|
||||
type Lead = [part: DemoPart, given: string, family: string];
|
||||
|
||||
/** The people with parts, per scenario. */
|
||||
const LEADS: Record<agent.DemoScenarioKey, Lead[]> = {
|
||||
"heritage-parish": [["pastor", "Margaret", "Ashworth"], ["office", "Gillian", "Fortuin"], ["prayer-coordinator", "Desmond", "Botha"], ["devotional-writer", "Rosemary", "Kleinhans"], ["worship", "Edward", "Mbeki"], ["kids", "Joyce", "Petersen"]],
|
||||
"heritage-city": [["pastor", "Jonathan", "Hartley"], ["office", "Nomvula", "Dube"], ["prayer-coordinator", "Abigail", "Jacobs"], ["devotional-writer", "Samuel", "Okafor"], ["worship", "Clara", "Van Wyk"], ["kids", "Thembeka", "Mthembu"], ["youth", "Daniel", "Pillay"]],
|
||||
"bold-youth": [["pastor", "Kagiso", "Molefe"], ["office", "Zinhle", "Khumalo"], ["prayer-coordinator", "Liam", "Fourie"], ["devotional-writer", "Ayanda", "Ngcobo"], ["worship", "Jade", "Adams"], ["kids", "Precious", "Mokoena"], ["youth", "Tumi", "Sithole"]],
|
||||
"bold-plant": [["pastor", "Sipho", "Mahlangu"], ["office", "Megan", "Coetzee"], ["prayer-coordinator", "Lerato", "Mashaba"], ["devotional-writer", "Sipho", "Mahlangu"], ["worship", "Ruan", "Steyn"], ["kids", "Amahle", "Zulu"]],
|
||||
"community-family": [["pastor", "Thabo", "Nkosi"], ["office", "Linda", "Venter"], ["prayer-coordinator", "Lindiwe", "Mabaso"], ["devotional-writer", "Grace", "Naidoo"], ["worship", "Pieter", "Du Toit"], ["kids", "Naledi", "Radebe"], ["youth", "Johan", "Botes"]],
|
||||
"community-town": [["pastor", "Hendrik", "Lombard"], ["office", "Annatjie", "Smit"], ["prayer-coordinator", "Magda", "Vermeulen"], ["devotional-writer", "Hendrik", "Lombard"], ["worship", "Wilhelm", "Kruger"], ["kids", "Elize", "Nel"], ["youth", "Dewald", "Jansen"]],
|
||||
"clean-modern": [["pastor", "Michael", "Reddy"], ["office", "Sarah", "Govender"], ["prayer-coordinator", "Nandi", "Cele"], ["devotional-writer", "Chris", "Marais"], ["worship", "Kayla", "Moodley"], ["kids", "Bongani", "Shabalala"], ["youth", "Ethan", "Brink"]],
|
||||
"clean-campus": [["pastor", "David", "Le Roux"], ["office", "Palesa", "Mofokeng"], ["prayer-coordinator", "Hannah", "Swart"], ["devotional-writer", "Lwazi", "Mkhize"], ["worship", "Mia", "Engelbrecht"], ["kids", "Refilwe", "Tau"], ["youth", "Josh", "Pretorius"]],
|
||||
};
|
||||
|
||||
/** How many members each scenario has besides its leads: inside its App band (`appActiveMembers`). */
|
||||
const MEMBERS: Record<agent.DemoScenarioKey, number> = {
|
||||
"heritage-parish": 48, "heritage-city": 520, "bold-youth": 1180, "bold-plant": 64,
|
||||
"community-family": 210, "community-town": 160, "clean-modern": 610, "clean-campus": 2450,
|
||||
};
|
||||
|
||||
const GIVEN = ["Aisha", "Andile", "Anele", "Bianca", "Busisiwe", "Carel", "Charlotte", "Craig", "Dineo", "Elias", "Emma", "Fatima", "Francois", "Gugu", "Hlengiwe", "Imran", "Isabel", "Jabu", "Jacques", "Karabo", "Keegan", "Lebo", "Lize", "Lungile", "Marco", "Mpho", "Nadia", "Neo", "Nicole", "Olwethu", "Pumla", "Riaan", "Sanele", "Shaun", "Simone", "Tarryn", "Thandeka", "Unathi", "Vusi", "Zanele"];
|
||||
const FAMILY = ["Abrahams", "Bester", "Cloete", "Daniels", "Dlamini", "Erasmus", "February", "Gumede", "Hendricks", "Isaacs", "Joubert", "Kekana", "Lategan", "Maseko", "Moloi", "Ndlovu", "Ntuli", "Olivier", "Phiri", "Qwabe", "Roberts", "Snyman", "Tshabalala", "Uys", "Viljoen", "Williams", "Xaba", "Yende", "Zondo", "Van der Merwe"];
|
||||
|
||||
/** The given names that are women's; every other given name here is a man's. */
|
||||
const FEMALE = new Set([
|
||||
"Margaret", "Gillian", "Rosemary", "Joyce", "Nomvula", "Abigail", "Clara", "Thembeka", "Zinhle", "Ayanda", "Jade", "Precious", "Tumi",
|
||||
"Megan", "Lerato", "Amahle", "Linda", "Lindiwe", "Grace", "Naledi", "Annatjie", "Magda", "Elize", "Sarah", "Nandi", "Kayla", "Palesa",
|
||||
"Hannah", "Mia", "Refilwe",
|
||||
"Aisha", "Anele", "Bianca", "Busisiwe", "Charlotte", "Dineo", "Emma", "Fatima", "Gugu", "Hlengiwe", "Isabel", "Karabo", "Lebo", "Lize",
|
||||
"Lungile", "Mpho", "Nadia", "Nicole", "Olwethu", "Pumla", "Simone", "Tarryn", "Thandeka", "Unathi", "Zanele",
|
||||
]);
|
||||
const genderOf = (given: string): "female" | "male" => (FEMALE.has(given) ? "female" : "male");
|
||||
|
||||
const slugOf = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "");
|
||||
|
||||
/**
|
||||
* A UUID worked out from text (FNV-1a over 128 bits, shaped as version 5), so a demo person's id
|
||||
* is the same in every product and on every load, without Node's crypto (it runs in browsers too).
|
||||
*/
|
||||
export function demoId(text: string): string {
|
||||
let h = 0x6c62272e07bb014262b821756295c58dn;
|
||||
const prime = 0x0000000001000000000000000000013bn;
|
||||
const mask = (1n << 128n) - 1n;
|
||||
for (const byte of new TextEncoder().encode(`crosscode-demo:${text}`)) h = ((h ^ BigInt(byte)) * prime) & mask;
|
||||
const hex = h.toString(16).padStart(32, "0").split("");
|
||||
hex[12] = "5";
|
||||
hex[16] = ((parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16);
|
||||
const s = hex.join("");
|
||||
return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
|
||||
}
|
||||
|
||||
function person(scenario: agent.DemoScenarioKey, part: DemoPart, givenName: string, familyName: string, email: string, campus: string | null): DemoPerson {
|
||||
return { id: demoId(`${scenario}:${email}`), name: `${givenName} ${familyName}`, givenName, familyName, email, part, gender: genderOf(givenName), campus };
|
||||
}
|
||||
|
||||
/** Everyone in a scenario: the leads first, then the members (deterministic: the same every time). */
|
||||
export function demoPeople(scenario: agent.DemoScenarioKey): DemoPerson[] {
|
||||
const church = demoChurch(scenario);
|
||||
const campuses = church.profile.campuses.map((c) => c.slug);
|
||||
const campusFor = (n: number) => (campuses.length ? campuses[n % campuses.length]! : null);
|
||||
const seen = new Set<string>();
|
||||
const out: DemoPerson[] = [];
|
||||
LEADS[scenario].forEach(([part, given, family], n) => {
|
||||
const email = `${slugOf(given)}.${slugOf(family)}.${church.slug}@${DEMO_EMAIL_DOMAIN}`;
|
||||
// One person can have two parts (the pastor who writes the devotionals): one account.
|
||||
const existing = out.find((p) => p.email === email);
|
||||
if (existing) return;
|
||||
seen.add(email);
|
||||
out.push(person(scenario, part, given, family, email, campusFor(n)));
|
||||
});
|
||||
for (let n = 0; n < MEMBERS[scenario]; n++) {
|
||||
const given = GIVEN[n % GIVEN.length]!;
|
||||
const family = FAMILY[Math.floor(n / GIVEN.length) % FAMILY.length]!;
|
||||
const email = `${slugOf(given)}.${slugOf(family)}.${n + 1}.${church.slug}@${DEMO_EMAIL_DOMAIN}`;
|
||||
if (seen.has(email)) continue;
|
||||
seen.add(email);
|
||||
out.push(person(scenario, "member", given, family, email, campusFor(n)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The parts each lead plays (a person may have two: the pastor who writes the devotionals). */
|
||||
export function demoParts(scenario: agent.DemoScenarioKey): Map<string, DemoPart[]> {
|
||||
const church = demoChurch(scenario);
|
||||
const parts = new Map<string, DemoPart[]>();
|
||||
for (const [part, given, family] of LEADS[scenario]) {
|
||||
const email = `${slugOf(given)}.${slugOf(family)}.${church.slug}@${DEMO_EMAIL_DOMAIN}`;
|
||||
parts.set(email, [...(parts.get(email) ?? []), part]);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** Whether an address belongs to a demo person (any scenario). */
|
||||
export const isDemoAddress = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
|
||||
|
||||
/** The scenarios in the contracts' order. */
|
||||
export const DEMO_SCENARIO_KEYS = agent.DEMO_SCENARIO_KEYS;
|
||||
@@ -0,0 +1,90 @@
|
||||
import { agent, churchObjectSchema, DEMO_EMAIL_DOMAIN, hub } from "@crosscode/contracts";
|
||||
import { DEMO_CHURCHES, demoChurch, demoIconSvg, demoId, demoLogoSvg, demoParts, demoPeople } from "../src";
|
||||
|
||||
describe("demo churches", () => {
|
||||
it("has one per scenario, with unique names, slugs and shapes the profile accepts", () => {
|
||||
expect(DEMO_CHURCHES.map((c) => c.scenario)).toEqual([...agent.DEMO_SCENARIO_KEYS]);
|
||||
expect(new Set(DEMO_CHURCHES.map((c) => c.slug)).size).toBe(8);
|
||||
expect(new Set(DEMO_CHURCHES.map((c) => c.profile.name)).size).toBe(8);
|
||||
for (const c of DEMO_CHURCHES) {
|
||||
const { colours, style, contact, ...rest } = c.profile;
|
||||
const profile = { ...rest, branding: { logoUrl: null, iconUrl: null, colours, style }, contact: { ...contact, phone: null, whatsapp: null } };
|
||||
const check = churchObjectSchema.omit({ schema: true, customerId: true, updatedAt: true, links: true }).safeParse(profile);
|
||||
expect(check.success ? [] : check.error.issues).toEqual([]);
|
||||
expect(contact.email!.endsWith(`@${DEMO_EMAIL_DOMAIN}`)).toBe(true);
|
||||
for (const s of c.profile.social) expect(s.url.startsWith("https://example.com/")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("matches the contracts' scenario (church name, campuses, language)", () => {
|
||||
for (const s of agent.DEMO_SCENARIOS) {
|
||||
const c = demoChurch(s.key);
|
||||
expect(c.profile.name.startsWith(s.church)).toBe(true);
|
||||
expect(Math.max(1, c.profile.campuses.length)).toBe(s.campuses);
|
||||
expect(c.profile.locale.startsWith(s.language)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("demo people", () => {
|
||||
it("are at example.com, unique, with ids that stay the same", () => {
|
||||
for (const key of agent.DEMO_SCENARIO_KEYS) {
|
||||
const people = demoPeople(key);
|
||||
expect(new Set(people.map((p) => p.email)).size).toBe(people.length);
|
||||
expect(new Set(people.map((p) => p.id)).size).toBe(people.length);
|
||||
for (const p of people) expect(p.email.endsWith(`@${DEMO_EMAIL_DOMAIN}`)).toBe(true);
|
||||
expect(demoPeople(key).map((p) => p.id)).toEqual(people.map((p) => p.id));
|
||||
}
|
||||
});
|
||||
|
||||
it("put the App in the scenario's band", () => {
|
||||
for (const s of agent.DEMO_SCENARIOS) expect(hub.activeMemberBand(demoPeople(s.key).length)).toBe(s.appActiveMembers);
|
||||
});
|
||||
|
||||
it("have a pastor and a prayer coordinator; a person with two parts has one account", () => {
|
||||
for (const key of agent.DEMO_SCENARIO_KEYS) {
|
||||
const people = demoPeople(key);
|
||||
expect(people.filter((p) => p.part === "pastor")).toHaveLength(1);
|
||||
expect(people.filter((p) => p.part === "prayer-coordinator")).toHaveLength(1);
|
||||
}
|
||||
const plant = demoParts("bold-plant");
|
||||
expect([...plant.values()].some((parts) => parts.includes("pastor") && parts.includes("devotional-writer"))).toBe(true);
|
||||
});
|
||||
|
||||
it("spread a multi-campus church's members over its campuses", () => {
|
||||
const campuses = new Set(demoPeople("clean-campus").map((p) => p.campus));
|
||||
expect(campuses).toEqual(new Set(["stellenbosch", "paarl", "somerset-west"]));
|
||||
expect(new Set(demoPeople("community-family").map((p) => p.campus))).toEqual(new Set([null]));
|
||||
});
|
||||
|
||||
it("demoId is a stable version-5 UUID", () => {
|
||||
expect(demoId("a")).toBe(demoId("a"));
|
||||
expect(demoId("a")).not.toBe(demoId("b"));
|
||||
expect(demoId("a")).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("logos", () => {
|
||||
it("are SVG in the church's colour, with its name", () => {
|
||||
for (const c of DEMO_CHURCHES) {
|
||||
const icon = demoIconSvg(c.scenario);
|
||||
const logo = demoLogoSvg(c.scenario);
|
||||
expect(icon.startsWith("<svg")).toBe(true);
|
||||
expect(icon).toContain(c.profile.colours.primary);
|
||||
expect(logo).toContain(c.profile.name.replace(/'/g, "'"));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("genders (1.1.0)", () => {
|
||||
it("every scenario has women and men among its leads and members", () => {
|
||||
for (const key of agent.DEMO_SCENARIO_KEYS) {
|
||||
const people = demoPeople(key);
|
||||
const women = people.filter((p) => p.gender === "female").length;
|
||||
expect(women).toBeGreaterThan(people.length * 0.3);
|
||||
expect(people.length - women).toBeGreaterThan(people.length * 0.2);
|
||||
}
|
||||
expect(demoPeople("community-family").find((p) => p.part === "pastor")?.gender).toBe("male");
|
||||
expect(demoPeople("heritage-parish").find((p) => p.part === "pastor")?.gender).toBe("female");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"types": ["node", "jest"]
|
||||
},
|
||||
"include": ["src", "tests", "tsup.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
// CommonJS for the Events backend, ESM for the Next.js apps, types for both (as contracts).
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["cjs", "esm"],
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
target: "es2022",
|
||||
external: ["@crosscode/contracts"],
|
||||
outExtension: ({ format }) => ({ js: format === "esm" ? ".mjs" : ".js" }),
|
||||
});
|
||||
+155
-9
@@ -8,14 +8,28 @@ manage_usage() {
|
||||
crosscode restart <church> [events] reload the products' PM2 processes
|
||||
crosscode demo <church> --profile <profile> [--admin-email <email>]
|
||||
replace Cross Events' data with a demo set
|
||||
(small, events, ministry, multicampus); a backup
|
||||
(small, events, ministry, multicampus, or from
|
||||
3.8.0 a demo scenario's church); a backup
|
||||
is taken first, one admin account is kept
|
||||
crosscode demo <church> website --profile <profile>
|
||||
crosscode demo <church> website --profile <profile> [--scenario <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
|
||||
first; the church's profile, settings and admins stay;
|
||||
from 1.8.0, --scenario: the scenario's people lead,
|
||||
and a linked Cross Events' events show instead
|
||||
crosscode demo <church> accounts --profile <scenario> [--scenario <scenario>]
|
||||
a demo scenario's church (profile, logo, icon) and
|
||||
people in Accounts (the eight scenarios, as the
|
||||
Website's profiles); a backup is taken first;
|
||||
real people and admins stay
|
||||
crosscode demo <church> --scenario <scenario> [--admin-email <email>]
|
||||
a whole demo scenario on every product the church
|
||||
has here, Accounts first (then Events, the Website,
|
||||
the App); products it doesn't have are skipped.
|
||||
Every release is checked first; it stops at the
|
||||
first failure and says what's out of step
|
||||
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
|
||||
@@ -88,35 +102,70 @@ cmd_restart() {
|
||||
done
|
||||
}
|
||||
|
||||
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"
|
||||
# Events' (contracts EVENTS_DEMO_PROFILES): its four, and from 3.8.0 one per demo scenario.
|
||||
DEMO_PROFILES="small events ministry multicampus $WEBSITE_DEMO_PROFILES"
|
||||
# The demo scenarios (contracts agent.DEMO_SCENARIO_KEYS, 1.21.0): one per Website profile. Accounts'
|
||||
# profiles are the scenarios themselves.
|
||||
DEMO_SCENARIOS="$WEBSITE_DEMO_PROFILES"
|
||||
|
||||
# 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).
|
||||
# `crosscode demo <church> accounts --profile <scenario>`: a scenario's church and people (cmd_demo_accounts).
|
||||
# `--scenario <s>` (agent 1.7.0): part of loading that scenario; the profile must be the scenario's.
|
||||
# `--scenario <s>` with no product and no profile (the Hub's seed-scenario job): the whole scenario
|
||||
# on every product the church has (cmd_demo_scenario).
|
||||
cmd_demo() {
|
||||
local church="" product="events" profile="" email="" dir user app
|
||||
local church="" product="" profile="" email="" scenario=""
|
||||
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 ;;
|
||||
--scenario) [ $# -ge 2 ] || die "--scenario needs a value."; scenario="$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 ;;
|
||||
events|website|accounts|app) [ -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 [ -n "$scenario" ] && [ -z "$product" ] && [ -z "$profile" ]; then
|
||||
[[ " $DEMO_SCENARIOS " == *" $scenario "* ]] || die "--scenario: one of $DEMO_SCENARIOS."
|
||||
[ -z "$email" ] || [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || die "--admin-email: not an email address."
|
||||
cmd_demo_scenario "$church" "$scenario" "$email"
|
||||
return
|
||||
fi
|
||||
product="${product:-events}"
|
||||
if [ -n "$scenario" ]; then
|
||||
[[ " $DEMO_SCENARIOS " == *" $scenario "* ]] || die "--scenario: one of $DEMO_SCENARIOS."
|
||||
# Every product loads the profile named after the scenario (contracts DEMO_SCENARIOS).
|
||||
[ "$profile" = "$scenario" ] || die "--scenario $scenario loads the $scenario profile in $product, not $profile."
|
||||
fi
|
||||
# Agent 1.7.0 sends the App's demo jobs; the App and its demo come with App 1.0.0.
|
||||
[ "$product" != app ] || die "The Church App's demo data comes with App 1.0.0 (this crosscode has none yet)."
|
||||
if [ "$product" = accounts ]; then
|
||||
[[ " $DEMO_SCENARIOS " == *" $profile "* ]] || die "--profile: one of $DEMO_SCENARIOS."
|
||||
[ -z "$email" ] || die "--admin-email: Accounts' demo keeps every admin."
|
||||
cmd_demo_accounts "$church" "$profile"
|
||||
return
|
||||
fi
|
||||
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"
|
||||
cmd_demo_website "$church" "$profile" "$scenario"
|
||||
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."
|
||||
cmd_demo_events "$church" "$profile" "$email"
|
||||
}
|
||||
|
||||
# Events' demo data (set-demo.js): backup, the profile as the site's user, reload.
|
||||
cmd_demo_events() {
|
||||
local church="$1" profile="$2" email="${3:-}" dir user app
|
||||
require_root
|
||||
load_church "$church"
|
||||
church_has_product events || die "$church has no Cross Events."
|
||||
@@ -144,11 +193,102 @@ cmd_demo() {
|
||||
die "Events didn't answer after the reload (sudo -u $user pm2 logs)."
|
||||
}
|
||||
|
||||
# The first release of each product that loads a demo scenario (contracts DEMO_SCENARIO_MIN_VERSIONS).
|
||||
scenario_min_version() {
|
||||
case "$1" in accounts) echo 1.9.0 ;; events) echo 3.8.0 ;; website) echo 1.8.0 ;; app) echo 1.0.0 ;; esac
|
||||
}
|
||||
|
||||
product_title() {
|
||||
case "$1" in accounts) echo Accounts ;; events) echo "Cross Events" ;; website) echo "The Website" ;; app) echo "The App" ;; *) echo "$1" ;; esac
|
||||
}
|
||||
|
||||
# A whole demo scenario (contracts seed-scenario, agent 1.7.0): every product the church has on this
|
||||
# server, in deploy order (Accounts first: the others read its profile and people; Events before the
|
||||
# Website and the App, which show its events through the feed). Products it doesn't have are
|
||||
# skipped, so a client with only Accounts and the Website gets both. Every product's release is
|
||||
# checked before anything changes; each product takes its own backup; the first failure stops the
|
||||
# rest and says which products are now out of step.
|
||||
cmd_demo_scenario() {
|
||||
local church="$1" scenario="$2" email="${3:-}" p q v min seen
|
||||
local -a todo=() skipped=() loaded=() behind=()
|
||||
require_root
|
||||
load_church "$church"
|
||||
for p in "${PRODUCT_ORDER[@]}"; do
|
||||
if church_has_product "$p"; then todo+=("$p"); else skipped+=("$p"); fi
|
||||
done
|
||||
[ "${#todo[@]}" -gt 0 ] || die "$church has no products on this server."
|
||||
|
||||
step "Demo scenario $scenario: checking ${todo[*]}"
|
||||
[ "${#skipped[@]}" -eq 0 ] || info "Not installed, so skipped: ${skipped[*]}"
|
||||
for p in "${todo[@]}"; do
|
||||
# The App and its demo come with App 1.0.0 (scripts/products/app.sh).
|
||||
[ "$p" != app ] || die "The Church App's demo data comes with App 1.0.0 (this crosscode has none yet). Nothing was changed."
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/$p.sh"
|
||||
v="$("${p}_expected_version" "$(pvar "$p" DIR)" 2>/dev/null || true)"
|
||||
min="$(scenario_min_version "$p")"
|
||||
version_ge "${v:-0.0.0}" "$min" ||
|
||||
die "$(product_title "$p") is ${v:-unknown} here: a demo scenario needs $min or later. Deploy it first; nothing was changed."
|
||||
done
|
||||
|
||||
for p in "${todo[@]}"; do
|
||||
# Each in a subshell: its die stops only that product, so the summary below can say what's
|
||||
# out of step.
|
||||
if ! (
|
||||
case "$p" in
|
||||
accounts) cmd_demo_accounts "$church" "$scenario" ;;
|
||||
events) cmd_demo_events "$church" "$scenario" "$email" ;;
|
||||
website) cmd_demo_website "$church" "$scenario" "$scenario" ;;
|
||||
esac
|
||||
); then
|
||||
seen=0
|
||||
for q in "${todo[@]}"; do [ "$q" = "$p" ] && seen=1; [ "$seen" = 1 ] && behind+=("$q"); done
|
||||
report_result loaded "${loaded[*]}"
|
||||
report_result skipped "${skipped[*]}"
|
||||
die "$(product_title "$p")'s demo failed (see above), so the scenario stopped. Loaded: ${loaded[*]:-none}. Out of step with $scenario: ${behind[*]}. Load the scenario again once it's fixed."
|
||||
fi
|
||||
loaded+=("$p")
|
||||
done
|
||||
report_result loaded "${loaded[*]}"
|
||||
report_result skipped "${skipped[*]}"
|
||||
step "Demo scenario $scenario loaded: ${loaded[*]}${skipped[*]:+ (not installed: ${skipped[*]})}"
|
||||
}
|
||||
|
||||
# Accounts' part of a demo scenario (Accounts 1.9.0+, backend/scripts/demo.ts): the scenario's
|
||||
# church profile (with its logo and icon) and its people; real people and admins stay. Backup first;
|
||||
# Accounts tells the linked products the church changed. Loaded before the other products'.
|
||||
cmd_demo_accounts() {
|
||||
local church="$1" profile="$2" dir user app
|
||||
require_root
|
||||
load_church "$church"
|
||||
church_has_product accounts || die "$church has no Accounts."
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/accounts.sh"
|
||||
dir="$(pvar accounts DIR)"
|
||||
user="$(pvar accounts USER)"
|
||||
app="$(accounts_app "$dir")"
|
||||
[ -f "$app/backend/scripts/demo.ts" ] || die "This release of Accounts ($(checkout_ref "$dir" accounts)) has no demo scenarios (1.9.0 or later has)."
|
||||
|
||||
step "Accounts: backup first"
|
||||
accounts_backup "$dir" "$user" || die "The backup failed, so the demo wasn't loaded."
|
||||
|
||||
step "Accounts: demo scenario ($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 data from before."
|
||||
|
||||
step "Accounts: reloading PM2"
|
||||
accounts_reload "$dir" "$user"
|
||||
step "Accounts: waiting for it to answer"
|
||||
wait_for_version "$(accounts_health_url)" "$(accounts_expected_version "$dir")" 60 ||
|
||||
die "Accounts 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
|
||||
local church="$1" profile="$2" scenario="${3:-}" dir user app
|
||||
local -a scenario_args=()
|
||||
require_root
|
||||
load_church "$church"
|
||||
church_has_product website || die "$church has no Church Website."
|
||||
@@ -158,12 +298,18 @@ cmd_demo_website() {
|
||||
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)."
|
||||
if [ -n "$scenario" ]; then
|
||||
# 1.8.0: the scenario's people lead, and Cross Events' events show through the feed.
|
||||
grep -q scenarioTeam "$app/backend/src/demo/seeds.ts" ||
|
||||
die "This release of the Website ($(checkout_ref "$dir" website)) has no demo scenarios (1.8.0 or later has)."
|
||||
scenario_args=(--scenario "$scenario")
|
||||
fi
|
||||
|
||||
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 ||
|
||||
run_as "$user" "$app/backend" npm run --silent demo -- --profile "$profile" "${scenario_args[@]+"${scenario_args[@]}"}" --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"
|
||||
|
||||
@@ -17,10 +17,11 @@ accounts_expected_version() {
|
||||
node -p 'require(process.argv[1]).version' "$(accounts_app "$1")/backend/package.json"
|
||||
}
|
||||
|
||||
# The shared packages Accounts is built with (contracts, auth-client for its tests, ui for its pages).
|
||||
# The shared packages Accounts is built with (contracts, auth-client for its tests, ui for its pages,
|
||||
# 1.9.0: demo for the demo scenarios).
|
||||
accounts_shared_packages() {
|
||||
local p
|
||||
for p in packages/contracts packages/ui packages/auth-client; do
|
||||
for p in packages/contracts packages/ui packages/auth-client packages/demo; do
|
||||
[ -f "$1/$p/package.json" ] && printf '%s\n' "$p"
|
||||
done
|
||||
}
|
||||
@@ -54,7 +55,7 @@ accounts_migrate() {
|
||||
|
||||
accounts_build() {
|
||||
local p
|
||||
for p in packages/contracts packages/auth-client; do
|
||||
for p in packages/contracts packages/auth-client packages/demo; do
|
||||
[ ! -f "$1/$p/package.json" ] || run_as "$2" "$1/$p" npm run build || return 1
|
||||
done
|
||||
run_as "$2" "$(accounts_app "$1")/backend" npm run build &&
|
||||
|
||||
@@ -32,11 +32,12 @@ events_backup() {
|
||||
}
|
||||
|
||||
# The shared packages this checkout's Events uses (from 2.4.0: contracts and seo; from 3.0.0:
|
||||
# auth-client, built after contracts, which it uses), built before it.
|
||||
# auth-client, built after contracts, which it uses; from 3.8.0: demo, the demo scenarios), built
|
||||
# before it.
|
||||
# Only the ones in the checkout, so going back to an older tag still installs and builds.
|
||||
events_shared_packages() {
|
||||
local p
|
||||
for p in packages/contracts packages/auth-client packages/seo; do
|
||||
for p in packages/contracts packages/auth-client packages/seo packages/demo; do
|
||||
if [ -f "$1/$p/package.json" ] && grep -q "\"@crosscode/${p#packages/}\"" "$1/apps/events/backend/package.json" "$1/apps/events/frontend/package.json" 2>/dev/null; then
|
||||
printf '%s\n' "$p"
|
||||
fi
|
||||
|
||||
@@ -17,10 +17,11 @@ website_expected_version() {
|
||||
node -p 'require(process.argv[1]).version' "$(website_app "$1")/backend/package.json"
|
||||
}
|
||||
|
||||
# The shared packages the Website is built with (contracts, auth-client for signing in, ui and seo for its pages).
|
||||
# The shared packages the Website is built with (contracts, auth-client for signing in, ui and seo for its pages,
|
||||
# 1.8.0: demo for the demo scenarios).
|
||||
website_shared_packages() {
|
||||
local p
|
||||
for p in packages/contracts packages/ui packages/auth-client packages/seo; do
|
||||
for p in packages/contracts packages/ui packages/auth-client packages/seo packages/demo; do
|
||||
[ -f "$1/$p/package.json" ] && printf '%s\n' "$p"
|
||||
done
|
||||
}
|
||||
@@ -54,7 +55,7 @@ website_migrate() {
|
||||
|
||||
website_build() {
|
||||
local p
|
||||
for p in packages/contracts packages/auth-client packages/seo; do
|
||||
for p in packages/contracts packages/auth-client packages/seo packages/demo; do
|
||||
[ ! -f "$1/$p/package.json" ] || run_as "$2" "$1/$p" npm run build || return 1
|
||||
done
|
||||
run_as "$2" "$(website_app "$1")/backend" npm run build &&
|
||||
|
||||
+128
-6
@@ -18,28 +18,38 @@ setup() {
|
||||
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"
|
||||
echo "scenarioTeam" > "$TMP/sites/hope/website/apps/website/backend/src/demo/seeds.ts"
|
||||
mkdir -p "$TMP/sites/hope/accounts/apps/accounts/backend/scripts"
|
||||
touch "$TMP/sites/hope/accounts/apps/accounts/backend/scripts/demo.ts"
|
||||
cat > "$CROSSCODE_HOME/products/accounts.sh" <<EOF3
|
||||
accounts_app() { printf '%s/apps/accounts' "\$1"; }
|
||||
accounts_backup() { echo "backup \$2" >> "$CALLS"; [ -z "\${FAIL_BACKUP:-}" ]; }
|
||||
accounts_reload() { echo "reload \$2" >> "$CALLS"; }
|
||||
accounts_health_url() { echo http://127.0.0.1:5200/api/health; }
|
||||
accounts_expected_version() { echo \${ACCOUNTS_VERSION:-1.9.0}; }
|
||||
EOF3
|
||||
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; }
|
||||
website_expected_version() { echo \${WEBSITE_VERSION:-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:-}" ]; }
|
||||
events_reload() { echo "reload \$2" >> "$CALLS"; }
|
||||
events_health_url() { echo http://127.0.0.1:20001/health; }
|
||||
events_expected_version() { echo 2.4.1; }
|
||||
events_expected_version() { echo \${EVENTS_VERSION:-2.4.1}; }
|
||||
EOF
|
||||
require_root() { :; }
|
||||
load_church() { [ "$1" = hope ] || die "There's no church $1 here."; }
|
||||
church_has_product() { [ "$1" = events ] || [ "$1" = website ]; }
|
||||
HAS="${HAS:-events website accounts}"
|
||||
church_has_product() { [[ " $HAS " == *" $1 "* ]]; }
|
||||
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:-}" ]; }
|
||||
run_as() { local user="$1" dir="$2"; shift 2; echo "run $user ${dir#"$TMP"/} $*" >> "$CALLS"; [ -z "${FAIL_SEED:-}" ] && [ "$user" != "${FAIL_USER:-}" ]; }
|
||||
}
|
||||
|
||||
@test "the profile and admin email are checked before anything else" {
|
||||
@@ -106,7 +116,7 @@ wait 1.3.0" ]
|
||||
[[ "$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
|
||||
run cmd_demo hope --profile clean-campus --admin-email not-an-email
|
||||
[ "$status" -eq 1 ]
|
||||
rm "$TMP/sites/hope/website/apps/website/backend/src/demo/seeds.ts"
|
||||
run cmd_demo hope website --profile clean-campus
|
||||
@@ -114,3 +124,115 @@ wait 1.3.0" ]
|
||||
[[ "$output" == *"no demo profiles"* ]]
|
||||
[ ! -s "$CALLS" ]
|
||||
}
|
||||
|
||||
@test "accounts: backup, then the scenario's church and people as the site's user, then a reload" {
|
||||
run cmd_demo hope accounts --profile community-family --scenario community-family
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(cat "$CALLS")" = "backup cc-hope-accounts
|
||||
run cc-hope-accounts sites/hope/accounts/apps/accounts/backend npm run --silent demo -- --profile community-family --force
|
||||
reload cc-hope-accounts
|
||||
wait 1.9.0" ]
|
||||
}
|
||||
|
||||
@test "accounts: only a scenario, no admin email, and only a release that has scenarios" {
|
||||
run cmd_demo hope accounts --profile small
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"clean-campus"* ]]
|
||||
run cmd_demo hope accounts --profile bold-youth --admin-email jane@hope.test
|
||||
[ "$status" -eq 1 ]
|
||||
rm "$TMP/sites/hope/accounts/apps/accounts/backend/scripts/demo.ts"
|
||||
run cmd_demo hope accounts --profile bold-youth
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"no demo scenarios"* ]]
|
||||
[ ! -s "$CALLS" ]
|
||||
}
|
||||
|
||||
@test "--scenario: a known one, and the profile must be the scenario's" {
|
||||
run cmd_demo hope website --profile bold-plant --scenario bold-youth
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"loads the bold-youth profile"* ]]
|
||||
run cmd_demo hope accounts --profile bold-youth --scenario nowhere
|
||||
[ "$status" -eq 1 ]
|
||||
run cmd_demo hope website --profile bold-youth --scenario bold-youth
|
||||
[ "$status" -eq 0 ]
|
||||
}
|
||||
|
||||
@test "website 1.8.0: --scenario is passed on, and only to a release that has scenarios" {
|
||||
run cmd_demo hope website --profile bold-youth --scenario bold-youth
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$(cat "$CALLS")" == *"npm run --silent demo -- --profile bold-youth --scenario bold-youth --force"* ]]
|
||||
: > "$CALLS"
|
||||
: > "$TMP/sites/hope/website/apps/website/backend/src/demo/seeds.ts"
|
||||
run cmd_demo hope website --profile bold-youth --scenario bold-youth
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"no demo scenarios"* ]]
|
||||
[ ! -s "$CALLS" ]
|
||||
run cmd_demo hope website --profile bold-youth
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$(cat "$CALLS")" == *"demo -- --profile bold-youth --force"* ]]
|
||||
}
|
||||
|
||||
@test "the App's demo (agent 1.7.0 sends it) is refused clearly until App 1.0.0" {
|
||||
run cmd_demo hope app --profile community-family --scenario community-family
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"comes with App 1.0.0"* ]]
|
||||
[ ! -s "$CALLS" ]
|
||||
}
|
||||
|
||||
@test "a failed Accounts demo isn't followed by a reload" {
|
||||
FAIL_SEED=1 run cmd_demo hope accounts --profile clean-modern
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$(cat "$CALLS")" != *"reload"* ]]
|
||||
}
|
||||
|
||||
@test "events 3.8.0: a demo scenario's church is an Events profile too" {
|
||||
run cmd_demo hope --profile clean-campus --scenario clean-campus
|
||||
[ "$status" -eq 0 ]
|
||||
[[ "$(cat "$CALLS")" == *"node scripts/set-demo.js --profile=clean-campus --yes"* ]]
|
||||
}
|
||||
|
||||
@test "seed-scenario: only Accounts and the Website installed, both loaded in order, the rest skipped" {
|
||||
HAS="accounts website" WEBSITE_VERSION=1.8.0 run cmd_demo hope --scenario bold-youth
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(grep '^run' "$CALLS")" = "run cc-hope-accounts sites/hope/accounts/apps/accounts/backend npm run --silent demo -- --profile bold-youth --force
|
||||
run cc-hope-website sites/hope/website/apps/website/backend npm run --silent demo -- --profile bold-youth --scenario bold-youth --force" ]
|
||||
[[ "$output" == *"Not installed, so skipped: events app"* ]]
|
||||
[[ "$(cat "$CALLS")" != *"cc-hope-events"* ]]
|
||||
}
|
||||
|
||||
@test "seed-scenario: every product the church has, Accounts, Events, then the Website" {
|
||||
EVENTS_VERSION=3.8.0 WEBSITE_VERSION=1.8.0 run cmd_demo hope --scenario clean-campus --admin-email jane@hope.test
|
||||
[ "$status" -eq 0 ]
|
||||
[ "$(grep '^run' "$CALLS" | cut -d' ' -f2)" = "cc-hope-accounts
|
||||
cc-hope-events
|
||||
cc-hope-website" ]
|
||||
[[ "$(cat "$CALLS")" == *"DEMO_ADMIN_EMAIL=jane@hope.test node scripts/set-demo.js --profile=clean-campus --yes"* ]]
|
||||
}
|
||||
|
||||
@test "seed-scenario: a release too old for scenarios stops it before anything changes" {
|
||||
EVENTS_VERSION=3.7.2 WEBSITE_VERSION=1.8.0 run cmd_demo hope --scenario bold-plant
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"Cross Events is 3.7.2 here: a demo scenario needs 3.8.0 or later"* ]]
|
||||
[ ! -s "$CALLS" ]
|
||||
}
|
||||
|
||||
@test "seed-scenario: the first failure stops the rest and says what's out of step" {
|
||||
EVENTS_VERSION=3.8.0 WEBSITE_VERSION=1.8.0 FAIL_USER=cc-hope-events run cmd_demo hope --scenario bold-plant
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"Cross Events's demo failed"* ]]
|
||||
[[ "$output" == *"Loaded: accounts. Out of step with bold-plant: events website"* ]]
|
||||
[[ "$(cat "$CALLS")" != *"cc-hope-website"* ]]
|
||||
}
|
||||
|
||||
@test "seed-scenario: an App installed is refused (its demo comes with App 1.0.0), nothing changed" {
|
||||
HAS="accounts app" run cmd_demo hope --scenario bold-plant
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"comes with App 1.0.0"* ]]
|
||||
[ ! -s "$CALLS" ]
|
||||
}
|
||||
|
||||
@test "seed-scenario: a known scenario only" {
|
||||
run cmd_demo hope --scenario nowhere
|
||||
[ "$status" -eq 1 ]
|
||||
[ ! -s "$CALLS" ]
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user