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>
This commit is contained in:
2026-11-30 11:42:17 +02:00
co-authored by Claude Opus 5.5
parent 5b9dc559b6
commit 49153e6f07
26 changed files with 549 additions and 48 deletions
+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) {