Compare commits

...
4 Commits
Author SHA1 Message Date
joshua dfd7278f7b Merge branch 'docs/phase6-progress' 2026-11-30 11:47:31 +02:00
joshuaandClaude Opus 5.5 aacfd228a6 docs: phase 6 progress in every handover, README and plan
HANDOVER (phase table, released 2026-11-30, next steps, demo scenarios, WhatsApp
STOP rule, local PostgreSQL), ROADMAP phase 5/6, APP-1.0-PLAN status, the root
README's folders, Events' handover / FEATURES / DEMO_DATA / README for STOP and
the scenarios, Accounts' and @crosscode/demo's READMEs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:47:29 +02:00
joshua e32d9ecb09 Merge branch 'feat/events-3.8' 2026-11-30 11:42:19 +02:00
joshuaandClaude Opus 5.5 49153e6f07 Events 3.8.0, @crosscode/demo 1.1.0: STOP stops all WhatsApp, demo scenarios
Events 3.8.0 (one migration):
- STOP to the church's WhatsApp number stops all WhatsApp, not only news:
  checked before every sendText/sendPdf against WhatsAppStop (by number) and
  User.whatsappOptedOut (from Accounts' user.updated); 2FA codes go by email
- a STOP received here is passed on to Accounts (whatsapp.optout); START turns
  it back on without Accounts; Accounts turning it back on clears it here
- the eight demo scenarios as set-demo profiles, around each church's own
  people (@crosscode/demo, same accounts as Accounts) and campuses; the
  scenario's people are never removed from Accounts

@crosscode/demo 1.1.0: each person's gender.
crosscode script: scenarios as Events demo profiles; Events builds packages/demo.

Checked on PostgreSQL 18: the migration and every scenario loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:42:17 +02:00
36 changed files with 705 additions and 85 deletions
+13
View File
@@ -2,6 +2,19 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## 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
+20 -12
View File
@@ -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,10 @@ 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 |
## Rules (ROADMAP-v3 §1)
+4
View File
@@ -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
+30
View File
@@ -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.
+5 -2
View File
@@ -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,
+11
View File
@@ -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
+21 -1
View File
@@ -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.
+1 -1
View File
@@ -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).
---
+2 -1
View File
@@ -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")
);
+14
View File
@@ -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
+99 -23
View File
@@ -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) {
+10 -1
View File
@@ -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 = {
+2 -1
View File
@@ -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) {
+13 -1
View File
@@ -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');
});
});
+36 -1
View File
@@ -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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.7.2",
"version": "3.8.0",
"private": true,
"scripts": {
"dev": "next dev",
+11 -6
View File
@@ -28,15 +28,18 @@ 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` and `1.21.0`, `accounts@1.9.0` and `events@3.8.0` released
(not deployed yet), with the new shared package `@crosscode/demo` 1.1.0 (§12, "Demo scenarios").
Next: `website@1.8.0`, `agent@1.7.0`, 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), `accounts@1.9.0`
(released 2026-11-30), `events@3.8.0` (released 2026-11-30), `website@1.8.0`, `agent@1.7.0` 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").
@@ -521,10 +524,11 @@ 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/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` |
| `crosscode-platform` `apps/agent` | `seed-demo` for `app` and `accounts`, `--scenario` passed on | `agent@1.7.0` |
| `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 | — |
@@ -564,7 +568,8 @@ 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
+52 -10
View File
@@ -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,34 @@ 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" |
| 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` and `1.21.0`, `accounts@1.9.0`, `events@3.8.0` (below). Next: Website 1.8.0, agent 1.7.0, 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** (each app has one migration). 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>`) |
| `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 |
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 +115,21 @@ 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 and 1.21.0, Accounts 1.9.0,
Events 3.8.0. **Next:**
1. **Website 1.8.0:** its eight demo profiles take each scenario church's people (leaders,
pastor) from `@crosscode/demo` and accept `--scenario`; the Website builds `packages/demo`.
2. **Agent 1.7.0:** `seed-demo` for `app` and `accounts`, `--scenario` passed on
(`SEED_SCENARIO_MIN_AGENT`; bump `AGENT_VERSION` too).
3. **Hub 2.26.0** (vendored contracts 1.21.0): the App in New install and releases, billing on
the active-member band, **Load a demo scenario** on a demo client, the **Devotionals** page
(3 months ahead, Import CSV) 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 and Events 3.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 +173,18 @@ 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.
- **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 +205,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
View File
@@ -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
+12 -3
View File
@@ -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 |
| Cross Events | `crosscode-platform` (`apps/events`) | **3.8.0** | `events@3.8.0` | 2026-11-30 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.7.1** | `website@1.7.1` | 2026-11-28 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.9.0** | `accounts@1.9.0` | 2026-11-30 |
| 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 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-30 (last change: `crosscode demo <church> accounts --profile <scenario>`, `--scenario` on every demo, Accounts builds `packages/demo`) |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-30 (last change: Events takes the demo scenarios as profiles, `crosscode demo <church> accounts`, `--scenario` on every demo, 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,7 +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.0.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0) |
| `@crosscode/demo` | `packages/demo` | 1.1.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0 and Events 3.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) |
@@ -39,6 +39,15 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **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
+4 -3
View File
@@ -134,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",
@@ -184,7 +185,7 @@
},
"apps/events/frontend": {
"name": "@crosscode/events-frontend",
"version": "3.7.2",
"version": "3.8.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
@@ -23226,7 +23227,7 @@
},
"packages/demo": {
"name": "@crosscode/demo",
"version": "1.0.0",
"version": "1.1.0",
"license": "UNLICENSED",
"dependencies": {
"@crosscode/contracts": "*"
+4 -2
View File
@@ -8,8 +8,10 @@ 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. `demoParts(scenario)`: what each lead does.
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).
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.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/demo",
"version": "1.0.0",
"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",
+13 -1
View File
@@ -23,6 +23,8 @@ export interface DemoPerson {
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;
}
@@ -50,6 +52,16 @@ const MEMBERS: Record<agent.DemoScenarioKey, number> = {
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, "");
/**
@@ -69,7 +81,7 @@ export function demoId(text: string): string {
}
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, campus };
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). */
+13
View File
@@ -75,3 +75,16 @@ describe("logos", () => {
}
});
});
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");
});
});
+4 -2
View File
@@ -8,7 +8,8 @@ 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>
replace the Website's content with a demo church
@@ -93,9 +94,10 @@ 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"
+3 -2
View File
@@ -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
+7 -1
View File
@@ -115,7 +115,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
@@ -161,3 +161,9 @@ wait 1.9.0" ]
[ "$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"* ]]
}