diff --git a/CHANGELOG.md b/CHANGELOG.md index 2207b05..226cc7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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=`), 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 diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index c2af9d1..a005d98 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -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=` 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. diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index cda3a27..c681d99 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -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 diff --git a/apps/events/backend/package.json b/apps/events/backend/package.json index 7b6c6d3..ca7656d 100644 --- a/apps/events/backend/package.json +++ b/apps/events/backend/package.json @@ -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", diff --git a/apps/events/backend/prisma/migrations/20261130120000_whatsapp_stop/migration.sql b/apps/events/backend/prisma/migrations/20261130120000_whatsapp_stop/migration.sql new file mode 100644 index 0000000..56d5fdb --- /dev/null +++ b/apps/events/backend/prisma/migrations/20261130120000_whatsapp_stop/migration.sql @@ -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") +); diff --git a/apps/events/backend/prisma/schema.prisma b/apps/events/backend/prisma/schema.prisma index a5e9532..1bd4d9a 100644 --- a/apps/events/backend/prisma/schema.prisma +++ b/apps/events/backend/prisma/schema.prisma @@ -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 diff --git a/apps/events/backend/scripts/set-demo.js b/apps/events/backend/scripts/set-demo.js index a795e92..66b05ba 100644 --- a/apps/events/backend/scripts/set-demo.js +++ b/apps/events/backend/scripts/set-demo.js @@ -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 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: (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) { diff --git a/apps/events/backend/src/accounts/signin.ts b/apps/events/backend/src/accounts/signin.ts index c029a4a..2ed2ccc 100644 --- a/apps/events/backend/src/accounts/signin.ts +++ b/apps/events/backend/src/accounts/signin.ts @@ -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 }; const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string | null }; +const whatsappStop = require('../utils/whatsappStop') as { clearStop(phone: string): Promise }; /* 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 & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor'] }) { +export async function updateLocalCopy(userId: string, profile: Pick & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor']; whatsapp_opted_out?: boolean }) { const data: Record = { 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 { + 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 { + try { + if (!(await viaAccounts())) return null; + const link = await accountsLink(); + return link ? `${link.url.replace(/\/$/, '')}/account` : null; + } catch { + return null; + } +} diff --git a/apps/events/backend/src/controllers/whatsappController.js b/apps/events/backend/src/controllers/whatsappController.js index f109e1f..04ea9ef 100644 --- a/apps/events/backend/src/controllers/whatsappController.js +++ b/apps/events/backend/src/controllers/whatsappController.js @@ -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 = { diff --git a/apps/events/backend/src/utils/privacy.js b/apps/events/backend/src/utils/privacy.js index f10bbc0..4c923d9 100644 --- a/apps/events/backend/src/utils/privacy.js +++ b/apps/events/backend/src/utils/privacy.js @@ -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 || '')); } /** diff --git a/apps/events/backend/src/utils/twoFactor.js b/apps/events/backend/src/utils/twoFactor.js index 560237e..80315c3 100644 --- a/apps/events/backend/src/utils/twoFactor.js +++ b/apps/events/backend/src/utils/twoFactor.js @@ -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) { diff --git a/apps/events/backend/src/utils/whatsapp.js b/apps/events/backend/src/utils/whatsapp.js index 31a5d0c..530a04a 100644 --- a/apps/events/backend/src/utils/whatsapp.js +++ b/apps/events/backend/src/utils/whatsapp.js @@ -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 }); diff --git a/apps/events/backend/src/utils/whatsappStop.js b/apps/events/backend/src/utils/whatsappStop.js new file mode 100644 index 0000000..954e33e --- /dev/null +++ b/apps/events/backend/src/utils/whatsappStop.js @@ -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 }; diff --git a/apps/events/backend/tests/accountsWhatsappOptOut.test.ts b/apps/events/backend/tests/accountsWhatsappOptOut.test.ts new file mode 100644 index 0000000..20c8acc --- /dev/null +++ b/apps/events/backend/tests/accountsWhatsappOptOut.test.ts @@ -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 }[] = []; +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 }) => { 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 = {}) => ({ + 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); +}); diff --git a/apps/events/backend/tests/twoFactorFlow.test.js b/apps/events/backend/tests/twoFactorFlow.test.js index 2520ef2..683f321 100644 --- a/apps/events/backend/tests/twoFactorFlow.test.js +++ b/apps/events/backend/tests/twoFactorFlow.test.js @@ -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, diff --git a/apps/events/backend/tests/whatsappStop.test.js b/apps/events/backend/tests/whatsappStop.test.js new file mode 100644 index 0000000..c3fd040 --- /dev/null +++ b/apps/events/backend/tests/whatsappStop.test.js @@ -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'); + }); +}); diff --git a/apps/events/frontend/package.json b/apps/events/frontend/package.json index 4b483c5..6715bd9 100644 --- a/apps/events/frontend/package.json +++ b/apps/events/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events-frontend", - "version": "3.7.2", + "version": "3.8.0", "private": true, "scripts": { "dev": "next dev", diff --git a/docs/VERSIONS.md b/docs/VERSIONS.md index e41c25a..c7676d5 100644 --- a/docs/VERSIONS.md +++ b/docs/VERSIONS.md @@ -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 accounts --profile `, `--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 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 diff --git a/package-lock.json b/package-lock.json index 39f892b..94dadec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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": "*" diff --git a/packages/demo/package.json b/packages/demo/package.json index e8f7e81..cc775dd 100644 --- a/packages/demo/package.json +++ b/packages/demo/package.json @@ -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", diff --git a/packages/demo/src/people.ts b/packages/demo/src/people.ts index c623ab4..72cdba3 100644 --- a/packages/demo/src/people.ts +++ b/packages/demo/src/people.ts @@ -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 = { 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). */ diff --git a/packages/demo/tests/demo.test.ts b/packages/demo/tests/demo.test.ts index 8c66afb..ddf8eb7 100644 --- a/packages/demo/tests/demo.test.ts +++ b/packages/demo/tests/demo.test.ts @@ -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"); + }); +}); diff --git a/scripts/lib/manage.sh b/scripts/lib/manage.sh index c2d9bab..25480fb 100644 --- a/scripts/lib/manage.sh +++ b/scripts/lib/manage.sh @@ -8,7 +8,8 @@ manage_usage() { crosscode restart [events] reload the products' PM2 processes crosscode demo --profile [--admin-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 website --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" diff --git a/scripts/products/events.sh b/scripts/products/events.sh index cb28df9..6706a8a 100644 --- a/scripts/products/events.sh +++ b/scripts/products/events.sh @@ -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 diff --git a/scripts/tests/demo.bats b/scripts/tests/demo.bats index 726940c..4bce6a3 100644 --- a/scripts/tests/demo.bats +++ b/scripts/tests/demo.bats @@ -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"* ]] +}