From acd3b259a1633db5c4ac57135723ac4affa361f5 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Tue, 1 Dec 2026 15:43:48 +0200 Subject: [PATCH] =?UTF-8?q?app:=20the=20demo=20scenarios=20(APP-1.0-PLAN?= =?UTF-8?q?=20=C2=A712)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit npm run demo loads Acacia Hill; --profile/--scenario any of the eight demo churches, around @crosscode/demo's people (the same account ids as Accounts), in the scenario's active-member band: a prayer wall with three months of commitments and the scenario's gaps, a campaign, testimonies, prayer requests, announcements, the church's own devotionals or Cross Code's from the Hub, and events (Cross Events' or the Website's through the feed when linked, else the App's own). The devotionals' passages are copied word for word from the public- domain KJV and BSB by scripts/demo-passages.ts (no Bible text written by hand). The sender never sends anything to a demo person. Co-Authored-By: Claude Opus 5.5 --- apps/app/backend/package.json | 4 +- apps/app/backend/scripts/demo-passages.ts | 168 ++++++++++ apps/app/backend/scripts/demo.ts | 68 ++++ apps/app/backend/src/demo/devotionals.ts | 155 +++++++++ apps/app/backend/src/demo/load.ts | 358 +++++++++++++++++++++ apps/app/backend/src/demo/passages.ts | 31 ++ apps/app/backend/src/demo/scenarios.ts | 282 ++++++++++++++++ apps/app/backend/src/messaging/send.ts | 8 +- apps/app/backend/tests/demo.test.ts | 134 ++++++++ apps/app/backend/tests/support/memoryDb.ts | 7 +- package-lock.json | 1 + 11 files changed, 1213 insertions(+), 3 deletions(-) create mode 100644 apps/app/backend/scripts/demo-passages.ts create mode 100644 apps/app/backend/scripts/demo.ts create mode 100644 apps/app/backend/src/demo/devotionals.ts create mode 100644 apps/app/backend/src/demo/load.ts create mode 100644 apps/app/backend/src/demo/passages.ts create mode 100644 apps/app/backend/src/demo/scenarios.ts create mode 100644 apps/app/backend/tests/demo.test.ts diff --git a/apps/app/backend/package.json b/apps/app/backend/package.json index 1efd3d2..867cf61 100644 --- a/apps/app/backend/package.json +++ b/apps/app/backend/package.json @@ -14,11 +14,13 @@ "postinstall": "prisma generate", "prisma:generate": "prisma generate", "prisma:deploy": "prisma migrate deploy && prisma generate", - "prisma:status": "prisma migrate status" + "prisma:status": "prisma migrate status", + "demo": "tsx scripts/demo.ts" }, "dependencies": { "@crosscode/auth-client": "*", "@crosscode/contracts": "*", + "@crosscode/demo": "*", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "cron-parser": "^5.10.2", diff --git a/apps/app/backend/scripts/demo-passages.ts b/apps/app/backend/scripts/demo-passages.ts new file mode 100644 index 0000000..06d1f4c --- /dev/null +++ b/apps/app/backend/scripts/demo-passages.ts @@ -0,0 +1,168 @@ +/** + * Copies the demo devotionals' Bible passages, word for word, out of the two public-domain Bibles + * into src/demo/passages.ts (APP-1.0-PLAN §6, §12). Bible text is never typed or written by anyone + * or anything else: "No AI on Bible text, ever" (BIBLE-PERMISSIONS.md). Run it again after adding a + * devotional to src/demo/devotionals.ts: + * + * npx tsx scripts/demo-passages.ts --kjv --bsb + * + * The KJV is the plain-text edition (books in order, `CHAPTER n` / `PSALM n`, verses as + * ` n text`, Latin-1 with ¶ marks); the BSB is Bible Hub's Word edition (verse numbers in the + * `reftext1` style, chapter numbers as a paragraph of their own, footnote marks as links). Both + * files stay out of the repo (temp/); only the verses the demo quotes are kept. + */ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { fileURLToPath } from 'node:url'; +import { BIBLE_BOOKS, parseBibleReference, type BibleBookCode, type PassageLocation } from '@crosscode/contracts'; +import { DEMO_DEVOTIONAL_PASSAGES } from '../src/demo/devotionals.js'; + +type Verses = Map; // `${book}.${chapter}.${verse}` → text +const key = (book: string, chapter: number, verse: number) => `${book}.${chapter}.${verse}`; +const tidy = (s: string) => s.replace(/\s+/g, ' ').trim(); + +/** The KJV text file: every book's chapters restart at 1, so a `CHAPTER 1` (or `PSALM 1`) is the next book. */ +export function readKjv(text: string): Verses { + const verses: Verses = new Map(); + let book = -1; + let chapter = 0; + let last: string | null = null; + for (const raw of text.split(/\r?\n/)) { + const line = raw.replace(/¶/g, ''); + const ch = /^(?:CHAPTER|PSALM) (\d+)\s*$/.exec(line); + if (ch) { + chapter = Number(ch[1]); + if (chapter === 1) book++; + last = null; + continue; + } + const v = /^\s+(\d+)\s+(\S.*)$/.exec(line); + if (v && book >= 0 && chapter > 0) { + last = key(BIBLE_BOOKS[book]!.code, chapter, Number(v[1])); + verses.set(last, tidy(v[2]!)); + continue; + } + if (!line.trim()) last = null; + } + if (book !== BIBLE_BOOKS.length - 1) throw new Error(`The KJV file has ${book + 1} books, not ${BIBLE_BOOKS.length}.`); + return verses; +} + +/** One file out of a .docx (a zip), without a zip library. */ +function unzip(file: Buffer, name: string): string { + const end = file.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06])); + if (end < 0) throw new Error('Not a .docx (no zip directory).'); + let at = file.readUInt32LE(end + 16); + const count = file.readUInt16LE(end + 10); + for (let i = 0; i < count; i++) { + const method = file.readUInt16LE(at + 10); + const size = file.readUInt32LE(at + 20); + const nameLen = file.readUInt16LE(at + 28); + const extra = file.readUInt16LE(at + 30); + const comment = file.readUInt16LE(at + 32); + const local = file.readUInt32LE(at + 42); + if (file.toString('utf8', at + 46, at + 46 + nameLen) === name) { + const start = local + 30 + file.readUInt16LE(local + 26) + file.readUInt16LE(local + 28); + const data = file.subarray(start, start + size); + return (method === 0 ? data : zlib.inflateRawSync(data)).toString('utf8'); + } + at += 46 + nameLen + extra + comment; + } + throw new Error(`${name} isn't in the .docx.`); +} + +const unxml = (s: string) => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); + +/** Paragraph styles that hold no Bible text: headings, superscriptions' cross references, front matter. */ +const NOT_TEXT = new Set(['', 'NormalWeb', 'hdg', 'subhdg', 'ihdg', 'pshdg', 'inscrip', 'acrostic']); + +/** The BSB Word file: a book starts at a plain paragraph with its name; chapters at a paragraph that is only a number. */ +export function readBsb(docx: Buffer): Verses { + const xml = unzip(docx, 'word/document.xml').replace(//g, ''); + const verses: Verses = new Map(); + let book: BibleBookCode | null = null; + let chapter = 0; + let verse = 0; + const add = (t: string) => { + if (!book || !chapter || !verse) return; + const k = key(book, chapter, verse); + verses.set(k, (verses.get(k) ?? '') + t); + }; + for (const p of xml.split(/]/).slice(1)) { + const style = /]/).slice(1)) { + const t = [...r.matchAll(/]*)?>([^<]*)<\/w:t>/g)].map((m) => unxml(m[1]!)).join(''); + if (t) runs.push([/ t).join('')); + if (style === '') { + const psalm = /^Psalm (\d+)$/.exec(text); + if (psalm && book === 'PSA') { chapter = Number(psalm[1]); verse = 1; continue; } + const named = BIBLE_BOOKS.find((b) => b.en === text || (b.code === 'PSA' && text === 'Psalms')); + if (named) { book = named.code; chapter = 0; verse = 0; } + continue; + } + if (NOT_TEXT.has(style)) continue; + if (/^\d+$/.test(text) && runs.every(([s]) => s !== 'reftext1')) { + chapter = Number(text); + verse = 1; + continue; + } + for (const [s, t] of runs) { + if (s === 'reftext1') { + if (/^\d+$/.test(t.trim())) verse = Number(t.trim()); + continue; + } + if (s === 'cross1') continue; + add(t); + } + add(' '); + } + for (const [k, t] of verses) verses.set(k, tidy(t)); + return verses; +} + +/** A passage's verses joined with spaces; throws when one is missing (better no demo than a wrong verse). */ +export function passageText(verses: Verses, p: PassageLocation): string { + if (p.endChapter !== p.chapter) throw new Error('The demo quotes passages within one chapter.'); + const out: string[] = []; + for (let v = p.verse; v <= p.endVerse; v++) { + const t = verses.get(key(p.book, p.chapter, v)); + if (!t) throw new Error(`${p.book} ${p.chapter}:${v} isn't in the file.`); + out.push(t); + } + return out.join(' '); +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const arg = (name: string) => { + const i = process.argv.indexOf(`--${name}`); + const v = i > 0 ? process.argv[i + 1] : undefined; + if (!v) { console.error('Usage: npx tsx scripts/demo-passages.ts --kjv --bsb '); process.exit(2); } + return v; + }; + const bibles = { KJV: readKjv(fs.readFileSync(arg('kjv'), 'latin1')), BSB: readBsb(fs.readFileSync(arg('bsb'))) }; + const entries: [string, string][] = []; + for (const { reference, translation } of DEMO_DEVOTIONAL_PASSAGES) { + const parsed = parseBibleReference(reference); + if (!parsed.ok) throw new Error(`${reference}: ${parsed.error}`); + const text = passageText(bibles[translation], parsed.passage); + // A quotation that runs on past the passage would show a stray “ or ”: pick other verses. + if ((text.match(/“/g) ?? []).length !== (text.match(/”/g) ?? []).length) throw new Error(`${translation} ${reference}: a quotation starts or ends outside the passage.`); + entries.push([`${translation} ${reference}`, text]); + } + const out = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'demo', 'passages.ts'); + const body = entries.sort(([a], [b]) => a.localeCompare(b)).map(([k, t]) => ` ${JSON.stringify(k)}: ${JSON.stringify(t)},`).join('\n'); + fs.writeFileSync(out, `/** + * The demo devotionals' passages, copied word for word from the KJV and the Berean Standard Bible + * (both public domain) by scripts/demo-passages.ts. Never edit by hand: change + * src/demo/devotionals.ts and run the script again. "No AI on Bible text, ever." + */ +export const DEMO_PASSAGES: Record = { +${body} +}; +`); + console.log(`${entries.length} passages written to ${path.relative(process.cwd(), out)}.`); +} diff --git a/apps/app/backend/scripts/demo.ts b/apps/app/backend/scripts/demo.ts new file mode 100644 index 0000000..5369aa5 --- /dev/null +++ b/apps/app/backend/scripts/demo.ts @@ -0,0 +1,68 @@ +/** + * Loads a demo scenario into the App (APP-1.0-PLAN §12, src/demo/load.ts). + * + * npm run demo Acacia Hill (community-family), for development + * npm run demo -- --profile [--force] one of the eight demo churches + * npm run demo -- --profile --scenario --force as part of loading that scenario (the Hub, the agent) + * npm run demo -- --list the scenarios + * + * It replaces the App's content and its demo members, so an App with real members (any address not + * at example.com) needs --force. On a server, `crosscode demo app --profile …` runs it as + * the App's user, after a backup. + */ +import 'dotenv/config'; +import { PrismaPg } from '@prisma/adapter-pg'; +import { agent, DEMO_EMAIL_DOMAIN } from '@crosscode/contracts'; +import { PrismaClient } from '../src/generated/prisma/client.js'; +import { createCtx } from '../src/context.js'; +import { loadConfig } from '../src/lib/config.js'; +import { loadDemo } from '../src/demo/load.js'; + +const arg = (name: string) => { + const i = process.argv.indexOf(`--${name}`); + return i > 0 ? process.argv[i + 1] : undefined; +}; + +if (process.argv.includes('--list')) { + for (const s of agent.DEMO_SCENARIOS) console.log(`${s.key.padEnd(18)} ${s.label}`); + process.exit(0); +} +const profile = agent.appDemoProfileSchema.safeParse(arg('profile') ?? 'community-family'); +if (!profile.success) { + console.error(`Unknown profile "${arg('profile')}" (npm run demo -- --list).`); + process.exit(2); +} +// A demo scenario loads the profile of the same name (contracts agent.DEMO_SCENARIOS). +const scenarioArg = arg('scenario'); +if (scenarioArg !== undefined && scenarioArg !== profile.data) { + console.error(agent.demoScenarioSchema.safeParse(scenarioArg).success + ? `The ${scenarioArg} scenario loads the ${scenarioArg} profile: --profile ${scenarioArg} --scenario ${scenarioArg}.` + : `Unknown scenario "${scenarioArg}" (npm run demo -- --list).`); + process.exit(2); +} + +const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) }); +const ctx = createCtx(loadConfig(), db); +// Real members (the Hub's first Owner, say) are kept; what they made isn't. +const real = (await db.member.findMany({ where: { NOT: { email: { endsWith: `@${DEMO_EMAIL_DOMAIN}` } } }, select: { id: true } })).map((m) => m.id); +const where = { memberId: { in: real } }; +const made = (await db.prayerCommitment.count({ where })) + (await db.prayerRequest.count({ where })) + (await db.testimony.count({ where })); +if (made > 0 && !process.argv.includes('--force')) { + console.error(`Real members have prayed, asked or shared in this App (${made} in all): loading the demo replaces the prayer wall, requests, announcements and events. Add --force to do it anyway.`); + await db.$disconnect(); + process.exit(1); +} +try { + const r = await loadDemo(ctx, profile.data); + console.log(`Demo ${r.scenario} loaded: ${r.church}, ${r.members} members, ${r.commitments} prayer commitments.`); + const d = r.devotionals; + if (d.source === 'church') console.log(`The church's own devotionals: ${d.saved}.`); + else if (d.error) console.warn(`Cross Code's devotionals weren't fetched (${d.error}); the nightly fetch brings them.`); + else console.log(`Cross Code's devotionals fetched from the Hub: ${d.saved} days.`); + const e = r.events; + if (e.from === 'app') console.log(`The App's own events: ${e.made}.`); + else if (e.sync?.ok) console.log(`Showing ${e.from === 'events' ? 'Cross Events\'' : 'the Website\'s'} events: ${e.sync.imported} fetched.`); + else console.warn(`${e.from === 'events' ? 'Cross Events\'' : 'The Website\'s'} events couldn't be fetched yet (${e.sync?.error}); the next sync, within 15 minutes, brings them.`); +} finally { + await db.$disconnect(); +} diff --git a/apps/app/backend/src/demo/devotionals.ts b/apps/app/backend/src/demo/devotionals.ts new file mode 100644 index 0000000..acfa9d8 --- /dev/null +++ b/apps/app/backend/src/demo/devotionals.ts @@ -0,0 +1,155 @@ +/** + * The demo churches' own devotionals (APP-1.0-PLAN §6, §12): the three scenarios whose church writes + * its own (St Columba's in the KJV, Harbour City's pastor, Karoo Gemeenskapskerk in Afrikaans, + * quoting the BSB until an Afrikaans translation is cleared). The others show Cross Code's, fetched + * from the Hub. + * + * Only the reference and the translation are written here: the passage itself is copied word for + * word from the public-domain Bibles into passages.ts by scripts/demo-passages.ts. Fictional writers, + * the scenario's devotional writer; eight days each, from five days ago to two days ahead. + */ +import type { agent } from '@crosscode/contracts'; + +export type DemoDevotional = { title: string; reference: string; body: string; prayer: string }; +export type DemoDevotionalSet = { translation: 'KJV' | 'BSB'; days: DemoDevotional[] }; + +export const DEMO_DEVOTIONALS: Partial> = { + 'heritage-parish': { + translation: 'KJV', + days: [ + { + title: 'A very present help', reference: 'Psalm 46:1', + body: 'The psalmist does not promise that trouble will stay away. He promises that God will be near when it comes. The words have been said in this church at weddings and at gravesides for more than a hundred years, and they have not worn thin.\n\nWhatever you carry into this week, carry it to the One who is present already.', + prayer: 'Lord, be my refuge and my strength today, and teach me to run to you first.', + }, + { + title: 'New every morning', reference: 'Lamentations 3:22-23', + body: 'These verses were written among ruins, not in comfortable times. Jeremiah looked at a broken city and still found mercy waiting for him each morning.\n\nBefore the post arrives or the telephone rings, stop for a moment and receive today\'s portion of God\'s faithfulness. It was not used up yesterday.', + prayer: 'Faithful God, thank you that your compassions do not fail. Let me begin this day in your mercy.', + }, + { + title: 'Wings for the weary', reference: 'Isaiah 40:31', + body: 'Waiting upon the Lord is not idleness. It is the patient trust of those who know their strength comes from elsewhere.\n\nMany of us are not as quick on our feet as we once were. Isaiah speaks to us too: the promise is to walk and not faint, and that is a gift for every age.', + prayer: 'Lord, renew my strength as I wait upon you, and help me walk faithfully today.', + }, + { + title: 'Lifting our eyes', reference: 'Psalm 121:1-2', + body: 'Pilgrims on the road to Jerusalem sang this psalm as the hills came into view. The hills were beautiful, and they were also where danger hid. So the singer looks past them to the Maker of heaven and earth.\n\nLook up from the worry in front of you, and remember who made the hills.', + prayer: 'Maker of heaven and earth, my help comes from you. Keep my going out and my coming in.', + }, + { + title: 'Sufficient unto the day', reference: 'Matthew 6:34', + body: 'Jesus does not tell us that tomorrow will be easy. He tells us that tomorrow belongs to him as surely as today does.\n\nWrite down the one thing today asks of you, and do it gladly. Leave the rest of the list with the Lord until morning.', + prayer: 'Lord Jesus, lift from me the weight of tomorrow, and help me be faithful in today.', + }, + { + title: 'Peace not as the world gives', reference: 'John 14:27', + body: 'Jesus spoke these words on the night before he died. His peace was not the absence of trouble but the gift of his presence in it.\n\nAt the Eucharist we pass the peace to one another. Today, receive it from him first, and then pass it on to someone who needs it.', + prayer: 'Lord, give me your peace, and let my heart be neither troubled nor afraid.', + }, + { + title: 'All things together', reference: 'Romans 8:28', + body: 'Paul does not say that all things are good. He says that God works all things together for good for those who love him.\n\nThink back over the years and you may see threads you could not see at the time. Trust the same hands with what you cannot yet understand.', + prayer: 'Father, I trust you with the parts of my life I do not understand. Work them together for good.', + }, + { + title: 'Careful for nothing', reference: 'Philippians 4:6-7', + body: 'Paul wrote these words from prison. His remedy for anxiety is not to stop caring but to turn every care into prayer, with thanksgiving.\n\nName your worries to God one by one this morning, and thank him for one thing beside each.', + prayer: 'God of peace, I bring you every care. Keep my heart and mind in Christ Jesus.', + }, + ], + }, + 'bold-plant': { + translation: 'BSB', + days: [ + { + title: 'Who builds the house', reference: 'Psalm 127:1', + body: 'Two years into planting Harbour City, I still need this verse every Monday. Setting up chairs in a school hall, planning Sundays, praying for new people: none of it lasts unless the Lord is the builder.\n\nWhat are you building this week? Ask him to build it with you.', + prayer: 'Lord, build our church and my life. Without you we labour in vain.', + }, + { + title: 'God gives the growth', reference: '1 Corinthians 3:6-7', + body: 'Some of us plant, some of us water, and all of us are tempted to measure ourselves by how quickly things grow. Paul reminds the church in Corinth that growth is God\'s work.\n\nBe faithful with your seed today and leave the harvest to him.', + prayer: 'Father, make us faithful planters and patient waterers, and give the growth.', + }, + { + title: 'Members of one household', reference: 'Ephesians 2:19-20', + body: 'A church plant can feel like a group of strangers who happen to meet in the same hall. Paul says otherwise: in Christ we are fellow citizens and family, built on one foundation.\n\nSay hello to someone new on Sunday as if they were family, because they are.', + prayer: 'Jesus, thank you for making strangers into family. Help us welcome as you welcome.', + }, + { + title: 'What they devoted themselves to', reference: 'Acts 2:42', + body: 'The first church had no building and no budget. They had teaching, fellowship, bread and prayer.\n\nThose four things are still the heart of a church, in a cathedral or a school hall. Which of them have you neglected this week? Pick one and give it your attention.', + prayer: 'Holy Spirit, make us devoted to the things that matter most.', + }, + { + title: 'One body, many parts', reference: 'Romans 12:4-5', + body: 'In a young church everyone can see the gaps: no one on sound, no one to run kids\' church, no one to make the coffee. That is not a problem to hide. It is an invitation.\n\nYou belong to this body, and you have a part to play in it.', + prayer: 'Lord, show me my part in your body, and give me joy in doing it.', + }, + { + title: 'Spurring one another on', reference: 'Hebrews 10:24-25', + body: 'Meeting together is easy to drop when life is busy. The writer of Hebrews knew it, and called the church to keep gathering and to encourage one another.\n\nWho could you send a message of encouragement to today?', + prayer: 'God of love, help me spur someone on today and keep meeting with your people.', + }, + { + title: 'Something new', reference: 'Isaiah 43:19', + body: 'Every church plant has days when it looks unfinished, and so does every life. Isaiah spoke to people who could only see wilderness, and God promised them a way through it and streams in the desert.\n\nLook for one new thing God is doing around you this week.', + prayer: 'Lord of new beginnings, open my eyes to what you are doing, and make a way where I see none.', + }, + { + title: 'God\'s temple', reference: '1 Corinthians 3:16', + body: 'We do not have a building of our own yet, and Paul would say that is fine: God lives among his people, not in bricks.\n\nWherever you are today, at work, at school or at home, you carry his presence with you.', + prayer: 'Holy Spirit, make your home in us, and let our church be a place where you are known.', + }, + ], + }, + 'community-town': { + translation: 'BSB', + days: [ + { + title: 'Ek kyk op na die berge', reference: 'Psalm 121:1-2', + body: 'In die Karoo kyk ons elke dag op na die berge. Hulle is mooi, maar hulle kan nie help as die droogte aanhou nie. Die psalmdigter kyk verder, na die Here wat hemel en aarde gemaak het.\n\nWaarheen kyk jy vandag vir hulp?', + prayer: 'Here, my hulp kom van U. Hou my vandag in U hand.', + }, + { + title: 'U sorg vir die aarde', reference: 'Psalm 65:9', + body: 'Ons wat op droë grond woon, weet hoe kosbaar reën is. Die psalm herinner ons dat die Here self die aarde besoek en dit natmaak.\n\nBid vandag vir die boere in ons distrik, en dank die Here vir elke druppel wat val.', + prayer: 'Vader, besoek ons land met reën, en laat ons U dank vir alles wat groei.', + }, + { + title: 'Die woestyn sal bloei', reference: 'Isaiah 35:1', + body: 'Na \'n goeie reën blom die Karoo in kleure wat niemand verwag het nie. Jesaja gebruik daardie beeld vir wat God met sy volk doen.\n\nIs daar \'n droë plek in jou lewe? Die Here kan dit laat bloei.', + prayer: 'Here, laat die droë plekke in my lewe weer blom.', + }, + { + title: 'Elke môre nuut', reference: 'Lamentations 3:22-23', + body: 'Jeremia het hierdie woorde tussen puin geskryf. Tog het hy elke oggend die Here se trou gevind.\n\nVoor die werk begin, staan \'n oomblik stil en ontvang vandag se deel van God se goedheid.', + prayer: 'Getroue God, dankie dat U genade elke môre nuut is.', + }, + { + title: 'Die Here is my herder', reference: 'Psalm 23:1-3', + body: 'Ons ken skape in hierdie wêreld. Hulle dwaal, hulle raak dors, hulle het \'n herder nodig. Dawid sê die Here is so \'n herder vir ons.\n\nLaat Hom jou vandag na rustige water lei.', + prayer: 'Herder van my lewe, lei my vandag en verkwik my siel.', + }, + { + title: 'Geduld soos \'n boer', reference: 'James 5:7', + body: 'Elke boer weet: jy plant, en dan wag jy. Jy kan nie die reën haastig maak nie. Jakobus vra ons om net so geduldig te wees tot die Here kom.\n\nWaarvoor wag jy vandag? Wag met hoop.', + prayer: 'Here, gee my die geduld van \'n boer en die hoop van \'n gelowige.', + }, + { + title: 'Bevestig die werk van ons hande', reference: 'Psalm 90:17', + body: 'Of ons in die winkel werk, op die plaas, of in die kombuis van die kerksaal: Moses bid dat die Here die werk van ons hande sal bevestig.\n\nVra vandag die Here se seën oor jou werk.', + prayer: 'Here, laat U goedheid op ons rus, en bevestig die werk van ons hande.', + }, + { + title: 'Moenie moeg word nie', reference: 'Galatians 6:9', + body: 'Goed doen is soms moeg werk: die basaar, die sop vir die skool, die besoeke by die ouetehuis. Paulus sê ons moet nie moedeloos word nie, want die oes kom.\n\nHou aan, en vertrou die Here met die oes.', + prayer: 'Vader, gee my krag om aan te hou met goed doen.', + }, + ], + }, +}; + +/** Every passage the demo quotes, for scripts/demo-passages.ts. */ +export const DEMO_DEVOTIONAL_PASSAGES = Object.values(DEMO_DEVOTIONALS).flatMap((set) => set!.days.map((d) => ({ reference: d.reference, translation: set!.translation }))); diff --git a/apps/app/backend/src/demo/load.ts b/apps/app/backend/src/demo/load.ts new file mode 100644 index 0000000..808ccfb --- /dev/null +++ b/apps/app/backend/src/demo/load.ts @@ -0,0 +1,358 @@ +/** + * The App's demo (APP-1.0-PLAN §12): one of the eight demo scenarios, built around the same church + * and people as Accounts, Cross Events and the Website (`@crosscode/demo`). `npm run demo` loads + * Acacia Hill (`community-family`); `crosscode demo app --profile --scenario ` loads + * one on a demo server (backup first), and the Hub's "Load a demo scenario" does it for every product. + * + * - **The church:** Accounts' profile, which the scenario loaded first; without a link to Accounts + * (local development) the scenario's church is saved as the App's own profile. + * - **The people:** every person in the scenario becomes a member (the same account id as in + * Accounts, so their sign-in finds them), active in the last 90 days, so the App's active-member + * band is the scenario's. The leads get their roles. Demo members of an earlier scenario go; real + * members (any address not at example.com) and their roles stay. + * - **The content** is replaced: the prayer wall (three months of commitments, with gaps where the + * scenario has them), the campaign and testimonies, prayer requests, announcements, the church's + * own devotionals and events. Cross Code's devotionals are fetched from the Hub; events come from + * Cross Events (or else the Website) through the feed when the church has one, never copied. + * - **Nothing is sent:** demo people are at example.com, and the sender skips them (messaging/send.ts). + */ +import crypto from 'node:crypto'; +import { CHURCH_SCHEMA, DEMO_EMAIL_DOMAIN, parseBibleReference, type agent, type Church } from '@crosscode/contracts'; +import { demoChurch, demoParts, demoPeople, type DemoPart, type DemoPerson } from '@crosscode/demo'; +import type { Ctx } from '../context.js'; +import type { AppRole } from '../generated/prisma/client.js'; +import { accountsLink } from '../auth/accounts.js'; +import { churchChanged, churchProfile } from '../church/profile.js'; +import { setDevotionalSource, syncCrosscode } from '../content/devotionals.js'; +import { markRemoved, notifyLinks, syncLink, type SyncResult } from '../events/feed.js'; +import { audit } from '../lib/audit.js'; +import { addDays, addMonths, localDate, weekday, zonedTime } from '../lib/zoned.js'; +import { DEFAULT_WALL } from '../prayer/rules.js'; +import { DEFAULT_REQUEST_SETTINGS } from '../requests/settings.js'; +import { DEMO_DEVOTIONALS } from './devotionals.js'; +import { DEMO_PASSAGES } from './passages.js'; +import { APP_SCENARIOS, DEMO_REQUESTS, DEMO_TESTIMONIES, easterSunday, type AppScenario } from './scenarios.js'; + +const DAY = 864e5; +/** How far back the wall goes: three months of commitments. */ +const HISTORY_DAYS = 91; +/** "I prayed" marked on about this share of the last three weeks' slots. */ +const PRAYED_SHARE = 0.65; + +/** The roles each part plays in the App (§10). Every role needs 2FA when they sign in. */ +const ROLES: Record = { + pastor: ['owner', 'pastoral_care'], + office: ['church_admin', 'content_admin'], + 'prayer-coordinator': ['prayer_coordinator'], + 'devotional-writer': ['devotional_writer'], + worship: [], kids: [], youth: [], member: [], +}; + +/** A steady number in [0, 1) for a piece of text (FNV-1a): the same demo every time. */ +export function steady(text: string): number { + let h = 0x811c9dc5; + for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193); + return (h >>> 0) / 2 ** 32; +} + +/** The scenario's church as the App's own profile, for an App not linked to Accounts. */ +export function scenarioProfile(publicUrl: string, scenario: agent.DemoScenarioKey): Church { + const c = demoChurch(scenario); + const p = c.profile; + return { + schema: CHURCH_SCHEMA, + customerId: '00000000-0000-4000-8000-000000000001', + updatedAt: '2026-12-01T08:00:00.000Z', + name: p.name, shortName: p.shortName, timezone: p.timezone, locale: p.locale, + branding: { logoUrl: null, iconUrl: null, colours: p.colours, style: p.style }, + campuses: p.campuses, serviceTimes: p.serviceTimes, + contact: { ...p.contact, phone: null, whatsapp: null }, + social: p.social, + links: { website: null, events: null, app: publicUrl, accounts: `https://example.com/accounts/${c.slug}` }, + } as Church; +} + +export type DemoResult = { + scenario: agent.DemoScenarioKey; + church: string; + members: number; + commitments: number; + devotionals: { source: 'crosscode' | 'church'; saved: number; error?: string }; + events: { from: 'app' | 'events' | 'website'; made: number; sync?: SyncResult }; +}; + +export async function loadDemo(ctx: Ctx, scenario: agent.DemoScenarioKey): Promise { + const db = ctx.db; + const s = APP_SCENARIOS[scenario]; + const now = ctx.now(); + + // The church: Accounts' (the scenario loaded it first), else the scenario's as the App's own. + const linked = await accountsLink(ctx).catch(() => null); + if (linked) churchChanged(ctx); + else await ctx.settings.set('church_profile_local', JSON.stringify(scenarioProfile(ctx.config.publicUrl, scenario))); + const church = (linked ? await churchProfile(ctx) : null) ?? scenarioProfile(ctx.config.publicUrl, scenario); + const tz = church.timezone || ctx.config.timezone; + const today = localDate(now, tz); + + // The content goes; published events are listed as removed, so linked products drop their copies. + const gone = (await db.simpleEvent.findMany({ where: { publishedAt: { not: null } }, select: { id: true } })).map((e) => e.id); + for (const id of gone) await markRemoved(ctx, id, true); + await db.simpleEvent.deleteMany({}); + await db.prayedMark.deleteMany({}); + await db.prayerSkip.deleteMany({}); + await db.prayerCommitment.deleteMany({}); + await db.testimony.deleteMany({}); + await db.prayerCampaign.deleteMany({}); + await db.requestPrayer.deleteMany({}); + await db.prayerRequestUpdate.deleteMany({}); + await db.prayerRequest.deleteMany({}); + await db.announcement.deleteMany({}); + await db.devotional.deleteMany({ where: { source: 'church' } }); + await db.outboxMessage.deleteMany({}); + + // The people: demo members from before go (with their sessions); real members stay as they are. + await db.member.deleteMany({ where: { email: { endsWith: `@${DEMO_EMAIL_DOMAIN}` } } }); + const people = demoPeople(scenario); + const parts = demoParts(scenario); + const taken = new Set((await db.member.findMany({ select: { id: true, email: true } })).flatMap((m) => [m.id, m.email.toLowerCase()])); + const joining = people.filter((p) => !taken.has(p.id) && !taken.has(p.email.toLowerCase())); + const rolesOf = (p: DemoPerson) => [...new Set((parts.get(p.email) ?? []).flatMap((part) => ROLES[part]))]; + const activeAt = (p: DemoPerson, n: number) => new Date(now.getTime() - Math.floor(steady(`${p.id}:active`) * (n < 12 ? 3 : 80)) * DAY - 3600e3); + for (let i = 0; i < joining.length; i += 500) { + await db.member.createMany({ + data: joining.slice(i, i + 500).map((p, n) => { + const at = activeAt(p, i + n); + return { + id: p.id, name: p.name, email: p.email, phone: null, roles: rolesOf(p), + newsEmail: steady(`${p.id}:news`) < 0.4, newsWhatsApp: false, + lastActiveAt: at, lastSignInAt: at, createdAt: new Date(now.getTime() - (HISTORY_DAYS + 30) * DAY), + }; + }), + }); + } + const leads = people.filter((p) => parts.has(p.email)); + const lead = (part: DemoPart) => leads.find((p) => parts.get(p.email)!.includes(part))!; + const pastor = lead('pastor'); + const coordinator = lead('prayer-coordinator'); + const writer = lead('devotional-writer'); + const office = lead('office'); + const members = people.filter((p) => !parts.has(p.email)); + // Leads who chose to get the devotional (the rest of the App's choices stay at their defaults). + for (const p of leads) await db.notificationSettings.create({ data: { memberId: p.id, devotional: 'email', devotionalOfferedAt: now, announcements: 'email' } }); + + // Settings. + const wall = s.wall ? { ...DEFAULT_WALL, ...s.wall, coordinator: { name: coordinator.name, contact: `${coordinator.email}` } } : null; + await ctx.settings.setMany({ + modules: null, + prayer_wall: wall ? JSON.stringify(wall) : null, + prayer_requests: JSON.stringify({ ...DEFAULT_REQUEST_SETTINGS, anonymousAllowed: s.anonymousAllowed }), + app_shared_at: s.shared ? new Date(now.getTime() - 20 * DAY).toISOString() : null, + }); + await setDevotionalSource(ctx, s.devotionals); + + const commitments = await prayerWall(ctx, scenario, s, { tz, today, slotMinutes: wall?.slotMinutes ?? DEFAULT_WALL.slotMinutes, members, coordinator, pastor }); + await campaign(ctx, s, today, members, coordinator); + await requests(ctx, scenario, s, members, coordinator, now); + await announcements(ctx, s, office, now); + const own = await ownDevotionals(ctx, scenario, today, writer); + + // Events: Cross Events' when the church has it, else the Website's, else the App's own. + const links = await db.productLink.findMany({ where: { product: { in: ['events', 'website'] } } }); + const source = links.find((l) => l.product === 'events') ?? links.find((l) => l.product === 'website') ?? null; + const made: string[] = []; + if (!source) { + for (const [slug, title, inDays, time, hours, location, description] of s.events) { + const date = inDays === 'easter' ? nextEaster(today) : addDays(today, inDays); + const [hh, mm] = time.split(':').map(Number); + const startsAt = zonedTime(date, hh! * 60 + mm!, tz) ?? new Date(`${date}T08:00:00Z`); + made.push((await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + hours * 3600e3), timezone: tz, location, description, publishedAt: now, updatedBy: office.id } })).id); + } + } + await audit(ctx, { actorId: null, actorRole: 'system', action: 'demo.load', targetType: 'app', metadata: { scenario } }); + await notifyLinks(ctx, [...gone, ...made]).catch(() => {}); + let sync: SyncResult | undefined; + for (const l of links) { + // Only the one shown: the other's events would be the same events twice. + const show = l.installId === source?.installId; + const link = await db.productLink.update({ where: { installId: l.installId }, data: { showEvents: show } }); + const r = await syncLink(ctx, link, { full: true }); + if (show) sync = r; + } + + let devotionals: DemoResult['devotionals'] = { source: s.devotionals, saved: own }; + if (s.devotionals === 'crosscode') { + try { + devotionals = { source: 'crosscode', saved: (await syncCrosscode(ctx)).saved }; + } catch (e) { + devotionals = { source: 'crosscode', saved: 0, error: (e as Error).message }; + } + } + return { + scenario, church: church.name, members: people.length, commitments, devotionals, + events: { from: source ? (source.product as 'events' | 'website') : 'app', made: made.length, ...(sync ? { sync } : {}) }, + }; +} + +const nextEaster = (today: string) => { + const year = Number(today.slice(0, 4)); + const easter = easterSunday(year); + return easter >= today ? easter : easterSunday(year + 1); +}; + +type WallArgs = { tz: string; today: string; slotMinutes: number; members: DemoPerson[]; coordinator: DemoPerson; pastor: DemoPerson }; + +/** + * The prayer wall: weekly commitments for every slot the scenario fills, started up to three months + * ago and running on for most of a year (a few end soon, so renewals show), plus the coordinator's + * daily hour, a few bookings for this week only, a few skips that open gaps, and "I prayed" on most + * of the last three weeks. Rules, not rows (§3): a commitment is one row however long it runs. + */ +async function prayerWall(ctx: Ctx, scenario: agent.DemoScenarioKey, s: AppScenario, a: WallArgs): Promise { + const { today, slotMinutes, members } = a; + type Row = { id: string; memberId: string; startDate: string; startMinute: number; durationMinutes: number; recurrence: 'once' | 'daily' | 'weekly'; endDate: string; reminder: 'none' | 'hour1'; channel: 'email' | 'whatsapp'; createdAt: Date }; + const rows: Row[] = []; + let next = 0; + const who = () => members[next++ % members.length]!; + const created = (date: string) => new Date(`${date}T10:00:00Z`); + const first = addDays(today, -HISTORY_DAYS); + for (let day = 0; day < 7; day++) { + for (let minute = 0; minute < 1440; minute += slotMinutes) { + const n = s.coverage(day, minute, steady(`${scenario}:${day}:${minute}`)); + for (let i = 0; i < n; i++) { + const h = steady(`${scenario}:${day}:${minute}:${i}`); + // Most began three months ago; some joined since. + const joined = h < 0.6 ? first : addDays(today, -[63, 35, 14, 7][Math.floor(h * 10) % 4]!); + const startDate = addDays(joined, (day - weekday(joined) + 7) % 7); + // A few end in the next fortnight (renewals due); the rest a year after they began. + const endDate = h > 0.94 ? addDays(today, 3 + Math.floor(h * 100) % 10) : addDays(addMonths(startDate, 12), -1); + const member = who(); + const whatsapp = s.whatsappReminders && h < 0.3; + rows.push({ id: crypto.randomUUID(), memberId: member.id, startDate, startMinute: minute, durationMinutes: slotMinutes, recurrence: 'weekly', endDate, reminder: 'none', channel: whatsapp ? 'whatsapp' : 'email', createdAt: created(startDate) }); + } + } + } + // The coordinator's daily hour at 06:00, and the pastor's Sunday 05:00. + rows.push({ id: crypto.randomUUID(), memberId: a.coordinator.id, startDate: first, startMinute: 360, durationMinutes: slotMinutes, recurrence: 'daily', endDate: addDays(addMonths(first, 12), -1), reminder: 'hour1', channel: 'email', createdAt: created(first) }); + const sunday = addDays(first, (7 - weekday(first)) % 7); + rows.push({ id: crypto.randomUUID(), memberId: a.pastor.id, startDate: sunday, startMinute: 300, durationMinutes: slotMinutes, recurrence: 'weekly', endDate: addDays(addMonths(sunday, 12), -1), reminder: 'hour1', channel: 'email', createdAt: created(sunday) }); + // A few booked for this week only, in the small hours that need them. + for (let i = 0; i < 4; i++) { + const date = addDays(today, 1 + i); + rows.push({ id: crypto.randomUUID(), memberId: who().id, startDate: date, startMinute: (2 + i) * 60, durationMinutes: slotMinutes, recurrence: 'once', endDate: date, reminder: 'none', channel: 'email', createdAt: created(today) }); + } + for (let i = 0; i < rows.length; i += 500) await ctx.db.prayerCommitment.createMany({ data: rows.slice(i, i + 500) }); + + // Skips: three weekly ones in the coming week ("away that week"), so even a full wall has a gap or two. + const tomorrow = addDays(today, 1); + const skipped = rows.filter((r) => r.recurrence === 'weekly' && r.startDate <= today && r.endDate > addDays(today, 7)) + .sort((x, y) => steady(`${scenario}:skip:${x.startDate}:${x.startMinute}`) - steady(`${scenario}:skip:${y.startDate}:${y.startMinute}`)).slice(0, 3); + for (const r of skipped) { + const date = addDays(tomorrow, (weekday(r.startDate) - weekday(tomorrow) + 7) % 7); + await ctx.db.prayerSkip.create({ data: { commitmentId: r.id, date } }); + } + + // "I prayed" on most of the last three weeks' occurrences. + const marks: { commitmentId: string; memberId: string; date: string }[] = []; + for (let back = 1; back <= 21; back++) { + const date = addDays(today, -back); + for (const r of rows) { + if (date < r.startDate || date > r.endDate) continue; + if (r.recurrence === 'weekly' && weekday(date) !== weekday(r.startDate)) continue; + if (r.recurrence === 'once' && date !== r.startDate) continue; + if (steady(`${r.id}:${date}`) < PRAYED_SHARE) marks.push({ commitmentId: r.id, memberId: r.memberId, date }); + } + } + for (let i = 0; i < marks.length; i += 1000) await ctx.db.prayedMark.createMany({ data: marks.slice(i, i + 1000) }); + return rows.length; +} + +async function campaign(ctx: Ctx, s: AppScenario, today: string, members: DemoPerson[], coordinator: DemoPerson) { + const c = s.campaign; + let id: string | null = null; + if (c) { + let startDate: string; + if (c.start === 'lent') { + const year = Number(today.slice(0, 4)); + const ash = (y: number) => addDays(easterSunday(y), -46); + startDate = addDays(easterSunday(year), -1) >= today ? ash(year) : ash(year + 1); + } else { + startDate = addDays(today, c.start); + } + const endDate = addDays(startDate, c.days - 1); + id = (await ctx.db.prayerCampaign.create({ data: { title: c.title, description: c.description, goal: c.goal, targetPerSlot: c.targetPerSlot ?? null, startDate, endDate, createdById: coordinator.id } })).id; + } + const running = c && c.start !== 'lent' && c.start <= 0; + const pool = DEMO_TESTIMONIES[s.language]; + for (const [i, t] of pool.entries()) { + const by = members[(i * 7 + 3) % members.length]!; + const ago = 2 + i * 3; + const at = new Date(ctx.now().getTime() - ago * DAY); + await ctx.db.testimony.create({ + data: { + memberId: by.id, campaignId: running && i % 2 === 0 ? id : null, text: t.text, showName: t.showName, + status: t.pending ? 'pending' : 'approved', moderatedById: t.pending ? null : coordinator.id, moderatedAt: t.pending ? null : at, createdAt: at, + }, + }); + } +} + +async function requests(ctx: Ctx, scenario: agent.DemoScenarioKey, s: AppScenario, members: DemoPerson[], coordinator: DemoPerson, now: Date) { + const pool = DEMO_REQUESTS[s.language]; + let pending = s.pendingRequests; + for (const [i, r] of pool.entries()) { + const by = members[(i * 11 + 5) % members.length]!; + const createdAt = new Date(now.getTime() - r.ago * DAY); + // The newest shared ones wait for approval, as many as the scenario has. + const waiting = r.visibility === 'members' && !r.closed && !r.answered && pending > 0 && r.ago <= 5 ? (pending--, true) : false; + const moderation = r.visibility === 'team' ? 'none' : waiting ? 'pending' : 'approved'; + const req = await ctx.db.prayerRequest.create({ + data: { + memberId: by.id, text: r.text, visibility: r.visibility, showName: !!r.showName, moderation, + moderatedById: moderation === 'approved' ? coordinator.id : null, moderatedAt: moderation === 'approved' ? new Date(createdAt.getTime() + 3 * 3600e3) : null, + closesAt: new Date(createdAt.getTime() + DEFAULT_REQUEST_SETTINGS.closeAfterDays * DAY), + closedAt: r.closed ? new Date(createdAt.getTime() + DEFAULT_REQUEST_SETTINGS.closeAfterDays * DAY) : null, + createdAt, + }, + }); + if (moderation === 'approved') { + const count = 3 + Math.floor(steady(`${scenario}:req:${i}`) * 25); + const prayed = members.filter((m) => m.id !== by.id).slice((i * 31) % Math.max(members.length - count, 1)).slice(0, count); + if (prayed.length) await ctx.db.requestPrayer.createMany({ data: prayed.map((m) => ({ requestId: req.id, memberId: m.id })) }); + } + if (r.answered) await ctx.db.prayerRequestUpdate.create({ data: { requestId: req.id, author: 'submitter', authorId: by.id, text: r.answered, createdAt: new Date(now.getTime() - DAY) } }); + if (r.reply) await ctx.db.prayerRequestUpdate.create({ data: { requestId: req.id, author: 'team', authorId: coordinator.id, text: r.reply, createdAt: new Date(createdAt.getTime() + 6 * 3600e3) } }); + } +} + +async function announcements(ctx: Ctx, s: AppScenario, office: DemoPerson, now: Date) { + for (const a of s.announcements) { + await ctx.db.announcement.create({ + data: { + slug: a.slug, title: a.title, body: a.body, pinned: !!a.pinned, audience: a.audience ?? 'everyone', campus: a.campus ?? null, + publishAt: new Date(now.getTime() - a.ago * DAY), endsAt: a.ends !== undefined ? new Date(now.getTime() + a.ends * DAY) : null, + buttonLabel: a.button?.[0] ?? null, buttonUrl: a.button?.[1] ?? null, createdById: office.id, + // Never sent: a demo's announcements were "sent" before it was loaded. + sentAt: a.ago > 0 ? now : null, + }, + }); + } +} + +/** The church's own devotionals: five days ago to two days ahead, in the writer's name. */ +async function ownDevotionals(ctx: Ctx, scenario: agent.DemoScenarioKey, today: string, writer: DemoPerson): Promise { + const set = DEMO_DEVOTIONALS[scenario]; + if (!set) return 0; + for (const [i, d] of set.days.entries()) { + const parsed = parseBibleReference(d.reference); + const text = DEMO_PASSAGES[`${set.translation} ${d.reference}`]; + if (!parsed.ok || !text) throw new Error(`The demo devotional "${d.title}" has no passage (run scripts/demo-passages.ts).`); + await ctx.db.devotional.create({ + data: { + source: 'church', date: addDays(today, i - 5), title: d.title, reference: d.reference, location: parsed.passage as never, + translation: set.translation, passageText: text, body: d.body, prayer: d.prayer, author: writer.name, createdById: writer.id, + }, + }); + } + return set.days.length; +} + diff --git a/apps/app/backend/src/demo/passages.ts b/apps/app/backend/src/demo/passages.ts new file mode 100644 index 0000000..48f1749 --- /dev/null +++ b/apps/app/backend/src/demo/passages.ts @@ -0,0 +1,31 @@ +/** + * The demo devotionals' passages, copied word for word from the KJV and the Berean Standard Bible + * (both public domain) by scripts/demo-passages.ts. Never edit by hand: change + * src/demo/devotionals.ts and run the script again. "No AI on Bible text, ever." + */ +export const DEMO_PASSAGES: Record = { + "BSB 1 Corinthians 3:16": "Do you not know that you yourselves are God’s temple, and that God’s Spirit dwells in you?", + "BSB 1 Corinthians 3:6-7": "I planted the seed and Apollos watered it, but God made it grow. So neither he who plants nor he who waters is anything, but only God, who makes things grow.", + "BSB Acts 2:42": "They devoted themselves to the apostles’ teaching and to the fellowship, to the breaking of bread and to prayer.", + "BSB Ephesians 2:19-20": "Therefore you are no longer strangers and foreigners, but fellow citizens with the saints and members of God’s household, built on the foundation of the apostles and prophets, with Christ Jesus Himself as the cornerstone.", + "BSB Galatians 6:9": "Let us not grow weary in well-doing, for in due time we will reap a harvest if we do not give up.", + "BSB Hebrews 10:24-25": "And let us consider how to spur one another on to love and good deeds. Let us not neglect meeting together, as some have made a habit, but let us encourage one another, and all the more as you see the Day approaching.", + "BSB Isaiah 35:1": "The wilderness and the dry land will be glad; the desert will rejoice and blossom like a rose.", + "BSB Isaiah 43:19": "Behold, I am about to do something new; even now it is coming. Do you not see it? Indeed, I will make a way in the wilderness and streams in the desert.", + "BSB James 5:7": "Be patient, then, brothers, until the Lord’s coming. See how the farmer awaits the precious fruit of the soil—how patient he is for the fall and spring rains.", + "BSB Lamentations 3:22-23": "Because of the loving devotion of the LORD we are not consumed, for His mercies never fail. They are new every morning; great is Your faithfulness!", + "BSB Psalm 121:1-2": "I lift up my eyes to the hills. From where does my help come? My help comes from the LORD, the Maker of heaven and earth.", + "BSB Psalm 127:1": "Unless the LORD builds the house, its builders labor in vain; unless the LORD protects the city, its watchmen stand guard in vain.", + "BSB Psalm 23:1-3": "The LORD is my shepherd; I shall not want. He makes me lie down in green pastures; He leads me beside quiet waters. He restores my soul; He guides me in the paths of righteousness for the sake of His name.", + "BSB Psalm 65:9": "You attend to the earth and water it; with abundance You enrich it. The streams of God are full of water, for You prepare our grain by providing for the earth.", + "BSB Psalm 90:17": "May the favor of the Lord our God rest upon us; establish for us the work of our hands— yes, establish the work of our hands!", + "BSB Romans 12:4-5": "Just as each of us has one body with many members, and not all members have the same function, so in Christ we who are many are one body, and each member belongs to one another.", + "KJV Isaiah 40:31": "But they that wait upon the LORD shall renew their strength; they shall mount up with wings as eagles; they shall run, and not be weary; and they shall walk, and not faint.", + "KJV John 14:27": "Peace I leave with you, my peace I give unto you: not as the world giveth, give I unto you. Let not your heart be troubled, neither let it be afraid.", + "KJV Lamentations 3:22-23": "It is of the LORD'S mercies that we are not consumed, because his compassions fail not. They are new every morning: great is thy faithfulness.", + "KJV Matthew 6:34": "Take therefore no thought for the morrow: for the morrow shall take thought for the things of itself. Sufficient unto the day is the evil thereof.", + "KJV Philippians 4:6-7": "Be careful for nothing; but in every thing by prayer and supplication with thanksgiving let your requests be made known unto God. And the peace of God, which passeth all understanding, shall keep your hearts and minds through Christ Jesus.", + "KJV Psalm 121:1-2": "I will lift up mine eyes unto the hills, from whence cometh my help. My help cometh from the LORD, which made heaven and earth.", + "KJV Psalm 46:1": "God is our refuge and strength, a very present help in trouble.", + "KJV Romans 8:28": "And we know that all things work together for good to them that love God, to them who are the called according to his purpose.", +}; diff --git a/apps/app/backend/src/demo/scenarios.ts b/apps/app/backend/src/demo/scenarios.ts new file mode 100644 index 0000000..bd03812 --- /dev/null +++ b/apps/app/backend/src/demo/scenarios.ts @@ -0,0 +1,282 @@ +/** + * What the App shows in each demo scenario (APP-1.0-PLAN §12, the table's App column): the prayer + * wall's rules and how full it is, a campaign, announcements, events (only when the church has no + * Cross Events or Website to show them from), and the tone of its prayer requests and testimonies. + * The church itself (name, colours, campuses) and the people are `@crosscode/demo`'s, the same in + * every product. Every name here is fictional; days are counted from the day the demo is loaded. + */ +import type { agent } from '@crosscode/contracts'; +import type { WallSettings } from '../prayer/rules.js'; + +/** How many people pray in a slot each week: `weekday` 0 = Sunday, `minute` after midnight, `h` a steady random number in [0, 1) for that slot. */ +export type Coverage = (weekday: number, minute: number, h: number) => number; + +export type DemoCampaign = { + title: string; + description: string; + goal: string | null; + targetPerSlot?: number; + /** Days from today (negative: started already), or `lent`: Ash Wednesday to Holy Saturday of the next Easter. */ + start: number | 'lent'; + days: number; +}; + +export type DemoAnnouncement = { + slug: string; + title: string; + body: string; + pinned?: boolean; + audience?: 'everyone' | 'members'; + campus?: string; + /** Published this many days ago (negative: scheduled for later). */ + ago: number; + /** Ends this many days from today. */ + ends?: number; + button?: [label: string, url: string]; +}; + +/** [slug, title, days from today (or `easter`), start time, hours, where, what]. */ +export type DemoEvent = [slug: string, title: string, inDays: number | 'easter', time: string, hours: number, location: string, description: string]; + +export type AppScenario = { + language: 'en' | 'af'; + /** The wall's rules, or null for a church that hasn't set them yet (the setup checklist half done). */ + wall: Partial | null; + coverage: Coverage; + /** Whose devotionals show: Cross Code's (fetched from the Hub) or the church's own (devotionals.ts). */ + devotionals: 'crosscode' | 'church'; + campaign: DemoCampaign | null; + announcements: DemoAnnouncement[]; + events: DemoEvent[]; + /** Shared requests waiting for approval. */ + pendingRequests: number; + anonymousAllowed: boolean; + /** The App shared with the church yet (the checklist's last item). */ + shared: boolean; + /** Members who chose WhatsApp for their reminders (the youth church). */ + whatsappReminders: boolean; +}; + +const hours = (from: number, to: number, minute: number) => minute >= from * 60 && minute < to * 60; + +export const APP_SCENARIOS: Record = { + 'heritage-parish': { + language: 'en', + wall: { slotMinutes: 60, targetPerSlot: 1 }, + // A quiet wall: mornings and early evenings, about 10 of 24 hours. + coverage: (_d, m, h) => (hours(6, 12, m) || hours(17, 21, m) ? (h < 0.85 ? 1 : 0) : 0), + devotionals: 'church', + campaign: { + title: 'Forty days of prayer for Lent', start: 'lent', days: 46, goal: 'Every morning hour covered, 06:00 to 12:00', + description: 'From Ash Wednesday to Easter Eve, join St Columba\'s in prayer: an hour a week, for our parish, our town and those who mourn.', + }, + announcements: [ + { slug: 'flower-rota', title: 'Flower rota for the new year', ago: 3, pinned: true, body: 'The flower rota for the coming months is on the board in the porch. Please add your name, or speak to Gillian in the parish office.' }, + { slug: 'carol-service', title: 'Nine lessons and carols', ago: 6, body: 'Our service of nine lessons and carols is on the Sunday before Christmas at 18:00, with mince pies in the hall afterwards. All are welcome.' }, + { slug: 'pastoral-visits', title: 'Home communion visits', ago: 10, audience: 'members', body: 'If you or someone you love cannot come to church and would like home communion, let the parish office know and the rector will visit.' }, + ], + events: [ + ['parish-lunch', 'Parish lunch', 9, '12:30', 2, 'The church hall', 'A bring-and-share lunch after the Sung Eucharist. Bring a dish if you can, and come either way.'], + ['carol-service', 'Nine lessons and carols', 20, '18:00', 1.5, 'St Columba\'s Church', 'Candlelit carols and readings, followed by mince pies in the hall.'], + ['harvest-festival', 'Harvest festival', 45, '09:00', 2, 'St Columba\'s Church', 'Our harvest Eucharist. Bring tinned food for the Old Town soup kitchen.'], + ], + pendingRequests: 1, anonymousAllowed: false, shared: true, whatsappReminders: false, + }, + 'heritage-city': { + language: 'en', + wall: { slotMinutes: 60, targetPerSlot: 1 }, + // Full in office hours (a lunchtime focus), patchy in the evening, gaps at night. + coverage: (_d, m, h) => (hours(12, 14, m) ? 3 : hours(7, 18, m) ? 2 : hours(18, 22, m) ? (h < 0.6 ? 1 : 0) : (h < 0.15 ? 1 : 0)), + devotionals: 'crosscode', + campaign: { + title: 'Lunchtime prayer for the city', start: -5, days: 30, goal: 'Every lunch hour covered three times over', + description: 'For thirty days, the cathedral prays for Cape Town at lunchtime: for those who work in the city, those who sleep on its streets and those who govern it.', + }, + announcements: [ + { slug: 'evensong-broadcast', title: 'Evensong now streamed live', ago: 2, pinned: true, body: 'Choral evensong is streamed live every Sunday at 18:00. Find the link on our YouTube channel.' }, + { slug: 'nine-thirty-children', title: 'Children\'s church at 09:30', ago: 5, body: 'Children\'s church meets in the chapter house during the Cathedral Eucharist and joins us for communion.' }, + { slug: 'lunchtime-soup', title: 'Soup in the crypt', ago: 8, body: 'After Wednesday lunchtime prayer, soup and bread are served in the crypt. Volunteers welcome: speak to Nomvula in the office.' }, + { slug: 'concert-tickets', title: 'Concert series tickets', ago: -2, body: 'Tickets for the next concert in the series go on sale on Friday.' }, + ], + events: [ + ['organ-recital', 'Lunchtime organ recital', 6, '13:00', 1, 'Grace Cathedral', 'Forty minutes of music on the cathedral organ. Free entry, retiring collection.'], + ['messiah-from-scratch', 'Messiah from scratch', 24, '14:00', 4, 'Grace Cathedral', 'Rehearse in the afternoon and sing Handel\'s Messiah in the evening. Scores provided.'], + ['easter-services', 'Easter Day services', 'easter', '07:30', 12, 'Grace Cathedral', 'Easter Day at 07:30, 09:30 and 18:00. The 09:30 service is ticketed: book through the cathedral office.'], + ], + pendingRequests: 1, anonymousAllowed: true, shared: true, whatsappReminders: false, + }, + 'bold-youth': { + language: 'en', + wall: { slotMinutes: 60, targetPerSlot: 1 }, + coverage: (_d, m, h) => (hours(6, 24, m) ? 1 + (h < 0.4 ? 1 : 0) : (h < 0.55 ? 1 : 0)), + devotionals: 'crosscode', + campaign: { + title: '21 days before Ignite Conference', start: -7, days: 21, targetPerSlot: 2, goal: 'Every hour covered, twice', + description: 'Three weeks of prayer before the conference: for every student who comes, for the speakers and the band, and for what God will do.', + }, + announcements: [ + { slug: 'conference-registration', title: 'Ignite Conference: last week to register', ago: 1, pinned: true, body: 'Registration closes on Friday. Early-bird prices are gone, but group discounts are still open for youth groups of 10 or more.', button: ['Register', 'https://example.com/ignite/conference'] }, + { slug: 'worship-night', title: 'Worship night this Sunday', ago: 3, body: 'Ignite Night at 17:30 is a worship night: no sermon, just songs, prayer and space.' }, + { slug: 'band-auditions', title: 'Band auditions', ago: 9, audience: 'members', body: 'Play an instrument or sing? Auditions for the worship team are on Thursday evenings this month. Message Jade.' }, + ], + events: [ + ['worship-night', 'Worship night', 4, '17:30', 2, 'Ignite Church, Factory Road', 'An evening of worship and prayer for students and young adults.'], + ['ignite-conference', 'Ignite Conference', 14, '09:00', 9, 'Ignite Church, Factory Road', 'A day of worship, teaching and workshops for students in grades 8 to 12.'], + ], + pendingRequests: 2, anonymousAllowed: true, shared: true, whatsappReminders: true, + }, + 'bold-plant': { + language: 'en', + // The wall's rules not set yet: the admin's setup checklist is half done. + wall: null, + coverage: (_d, m, h) => (hours(5, 8, m) ? (h < 0.6 ? 1 : 0) : hours(20, 22, m) ? (h < 0.5 ? 1 : 0) : (h < 0.05 ? 1 : 0)), + devotionals: 'church', + campaign: { + title: 'Praying for our second year', start: -60, days: 21, goal: 'Twenty hours a week', + description: 'Three weeks of prayer as Harbour City turned two: for our neighbours in Humewood, our school and the people God is bringing.', + }, + announcements: [ + { slug: 'set-up-team', title: 'Join the set-up team', ago: 2, pinned: true, body: 'Every Sunday starts at 07:30 with chairs, sound and coffee in the school hall. Many hands make it quick: message Megan to join a team.' }, + ], + events: [ + ['newcomers-lunch', 'Newcomers\' lunch', 9, '12:00', 2, 'Seaview Primary School hall', 'New to Harbour City? Join the pastors for lunch after the service and hear the story so far.'], + ['launch-sunday', 'Anniversary Sunday', 30, '09:30', 2, 'Seaview Primary School hall', 'Celebrating two years of Harbour City, with a braai on the field afterwards.'], + ], + pendingRequests: 0, anonymousAllowed: false, shared: false, whatsappReminders: false, + }, + 'community-family': { + language: 'en', + wall: { slotMinutes: 60, targetPerSlot: 1 }, + // Full with a few gaps in the small hours (as in the mockup). + coverage: (_d, m, h) => (hours(1, 5, m) && h < 0.25 ? 0 : 1 + (h > 0.8 ? 1 : 0)), + devotionals: 'crosscode', + campaign: { + title: '21 days of prayer', start: -9, days: 21, goal: 'Every hour covered', + description: 'Three weeks of praying around the clock for Acacia Hill, our families and our city. Pick an hour, or two, and pray with us.', + }, + announcements: [ + { slug: 'family-camp', title: 'Family camp: book by the end of the month', ago: 2, pinned: true, body: 'Family camp is a weekend away for every age, with kids\' programmes, campfires and time to rest. Book through Cross Events before the end of the month.' }, + { slug: 'alpha', title: 'Alpha starts soon', ago: 4, body: 'Eleven Wednesday evenings of food, a short talk and honest conversation about life and faith. Invite a friend.' }, + { slug: 'kids-club-volunteers', title: 'Kids\' club needs helpers', ago: 7, audience: 'members', body: 'We need three more helpers for kids\' club on Friday afternoons. Speak to Naledi.' }, + { slug: 'prayer-evening', title: 'Prayer evening on Wednesday', ago: 1, body: 'Our prayer evening is at 18:30 in the hall, for the 21 days of prayer and for each other.' }, + ], + events: [ + ['kids-club', 'Kids\' club', 3, '15:00', 2, 'Acacia Hill hall', 'Games, stories and snacks for ages 6 to 12.'], + ['alpha', 'Alpha: first evening', 8, '18:30', 2.5, 'Acacia Hill hall', 'Dinner, a short talk and conversation. No question is off limits.'], + ['family-camp', 'Family camp', 40, '16:00', 48, 'Hennops River camp', 'A weekend away for every family in the church.'], + ], + pendingRequests: 3, anonymousAllowed: false, shared: true, whatsappReminders: false, + }, + 'community-town': { + language: 'af', + wall: { slotMinutes: 30, targetPerSlot: 1 }, + coverage: (_d, m, h) => (hours(5, 21, m) ? (h < 0.7 ? 1 : 0) : 0), + devotionals: 'church', + campaign: { + title: 'Bid vir ons dorp', start: -3, days: 21, goal: 'Elke halfuur van 05:00 tot 21:00', + description: 'Drie weke van gebed vir Graaff-Reinet: vir reën, vir ons skole, vir die boere en vir almal wat swaarkry.', + }, + announcements: [ + { slug: 'kerkbasaar', title: 'Kerkbasaar: pannekoek en koeksisters', ago: 3, pinned: true, body: 'Die basaar is op Saterdag op die kerkgronde. Bring jou koeksisters, melktert en handwerk na die saal op Vrydagmiddag.' }, + { slug: 'gebedsontbyt', title: 'Gebedsontbyt vir mans', ago: 6, body: 'Die mans se gebedsontbyt is Saterdag om 07:00 in die saal. Bring \'n vriend.' }, + { slug: 'aanddiens', title: 'English evening service', ago: 9, body: 'Our Sunday evening service at 18:00 is in English. Everyone is welcome.' }, + ], + events: [ + ['gebedsontbyt', 'Gebedsontbyt', 5, '07:00', 2, 'Die kerksaal', 'Ontbyt, getuienis en gebed vir die dorp.'], + ['kerkbasaar', 'Kerkbasaar', 12, '08:00', 6, 'Karoo Gemeenskapskerk, Kerkstraat', 'Pannekoek, koeksisters, tweedehandse boeke en \'n springkasteel vir die kinders.'], + ], + pendingRequests: 1, anonymousAllowed: false, shared: true, whatsappReminders: false, + }, + 'clean-modern': { + language: 'en', + wall: { slotMinutes: 60, targetPerSlot: 2 }, + coverage: (_d, _m, h) => 2 + (h > 0.85 ? 1 : 0), + devotionals: 'crosscode', + campaign: { + title: 'Groups launch: pray for forty new groups', start: -2, days: 14, goal: 'Every hour covered twice', + description: 'Two weeks of prayer as we launch forty new small groups across Durban North. Pray for the leaders, the hosts and everyone looking for a place to belong.', + }, + announcements: [ + { slug: 'groups-launch', title: 'Groups launch Sunday', ago: 1, pinned: true, body: 'Find a group on Sunday: the groups team will be in the foyer after every service.', button: ['See the groups', 'https://example.com/northpoint/groups'] }, + { slug: 'serve-teams', title: 'Serve teams training', ago: 4, audience: 'members', body: 'New to a serve team? Training is on Saturday at 09:00 in the auditorium.' }, + { slug: 'starting-point', title: 'Starting Point course', ago: 8, body: 'Starting Point is a six-week course for anyone exploring faith or new to church.' }, + { slug: 'baptisms', title: 'Baptism Sunday', ago: -3, body: 'Want to be baptised? Sign up at the info desk by the end of the month.' }, + ], + events: [ + ['serve-training', 'Serve teams training', 6, '09:00', 3, 'Northpoint auditorium', 'Training for everyone on a serve team.'], + ['groups-launch', 'Groups launch Sunday', 12, '08:30', 12, 'Northpoint Church', 'Meet the group leaders after every service.'], + ['starting-point', 'Starting Point', 15, '19:00', 2, 'Northpoint café', 'Week one of a six-week course for anyone exploring faith.'], + ], + pendingRequests: 2, anonymousAllowed: true, shared: true, whatsappReminders: false, + }, + 'clean-campus': { + language: 'en', + wall: { slotMinutes: 60, targetPerSlot: 1 }, + // One wall for three campuses, full around the clock; students on the 02:00 slots. + coverage: (_d, m, h) => (m === 120 ? 3 : 1 + (h < 0.5 ? 1 : 0)), + devotionals: 'crosscode', + campaign: { + title: 'Welcome week: pray for new students', start: 5, days: 8, goal: 'Every hour covered', + description: 'A week of prayer for every student arriving in Stellenbosch: for friendships, for faith and for the people who will welcome them.', + }, + announcements: [ + { slug: 'one-church', title: 'One church, three campuses', ago: 2, pinned: true, body: 'Wherever you meet on Sunday, the prayer wall is one wall: Stellenbosch, Paarl and Somerset West praying together.' }, + { slug: 'welcome-week', title: 'Welcome week volunteers', ago: 3, campus: 'stellenbosch', body: 'Help us welcome new students: carry boxes, hand out coffee, invite people to supper. Sign up with Josh.' }, + { slug: 'paarl-kids', title: 'Kids\' church in Paarl', ago: 5, campus: 'paarl', body: 'Kids\' church in Paarl now has a toddler room. Parents, come and see it after the service.' }, + { slug: 'somerset-west-picnic', title: 'Somerset West picnic', ago: 6, campus: 'somerset-west', body: 'Bring a blanket to the picnic after the service on the last Sunday of the month.' }, + { slug: 'combined-worship', title: 'Combined worship night', ago: 1, body: 'All three campuses together for a night of worship in Stellenbosch.' }, + ], + events: [ + ['welcome-week', 'Student welcome week', 5, '10:00', 8, 'Riverside Stellenbosch', 'A week of welcome for new students: suppers, tours and a braai on the river.'], + ['combined-worship', 'Combined worship night', 16, '19:00', 2.5, 'Riverside Stellenbosch', 'Stellenbosch, Paarl and Somerset West together.'], + ], + pendingRequests: 2, anonymousAllowed: true, shared: true, whatsappReminders: false, + }, +}; + +type Request = { text: string; visibility: 'team' | 'members'; showName?: boolean; ago: number; answered?: string; reply?: string; closed?: boolean }; + +/** Prayer requests by language: fictional and gentle (no health details or names of others). */ +export const DEMO_REQUESTS: Record<'en' | 'af', Request[]> = { + en: [ + { text: 'Please pray for my job interview on Thursday. I have been looking for work for six months.', visibility: 'members', showName: true, ago: 4, answered: 'I got the job! Thank you all for praying.' }, + { text: 'Pray for our family as we move house this month, and for the children settling into a new school.', visibility: 'members', showName: true, ago: 6 }, + { text: 'For wisdom as I care for my elderly mother, and for patience on the hard days.', visibility: 'members', ago: 2 }, + { text: 'Please pray for my studies: exams start in two weeks.', visibility: 'members', showName: true, ago: 1 }, + { text: 'I would like prayer for a difficult conversation with a friend. I want to handle it with grace.', visibility: 'team', ago: 3, reply: 'We are praying for you this week. If you would like to talk it through, the prayer team is here.' }, + { text: 'Thank God with me: our son came home safely from his trip.', visibility: 'members', showName: true, ago: 40, closed: true }, + { text: 'Please pray for rain for the farms around us.', visibility: 'members', ago: 5 }, + ], + af: [ + { text: 'Bid asseblief vir reën vir ons plaas. Die damme is amper leeg.', visibility: 'members', showName: true, ago: 4 }, + { text: 'Bid vir my seun wat volgende week matriek eksamen skryf.', visibility: 'members', showName: true, ago: 2, answered: 'Hy het goed gedoen! Baie dankie vir julle gebede.' }, + { text: 'Bid vir wysheid vir ons gesin met \'n moeilike besluit.', visibility: 'team', ago: 3, reply: 'Ons bid saam met julle hierdie week.' }, + { text: 'Bid asseblief vir my werk: die winkel sukkel hierdie jaar.', visibility: 'members', ago: 1 }, + { text: 'Dank die Here saam met my: ons kleinkind is gebore.', visibility: 'members', showName: true, ago: 35, closed: true }, + { text: 'Bid vir die ouetehuis se personeel en inwoners.', visibility: 'members', ago: 5 }, + ], +}; + +/** Testimonies by language: what God has done, the first name or "Anonymous". */ +export const DEMO_TESTIMONIES: Record<'en' | 'af', { text: string; showName: boolean; pending?: boolean }[]> = { + en: [ + { text: 'I signed up for the 03:00 slot not knowing if I could do it. It has become the quietest, best hour of my week.', showName: true }, + { text: 'We prayed for our neighbour for months. Last Sunday she came to church with us.', showName: false }, + { text: 'Praying with others at the same hour, even from home, made me feel part of something bigger.', showName: true }, + { text: 'After weeks of praying for work, I start a new job on Monday.', showName: true, pending: true }, + ], + af: [ + { text: 'Ek het die 05:00 halfuur gevat. Dit het my dag verander.', showName: true }, + { text: 'Ons het vir reën gebid, en verlede week het dit gereën op ons plaas.', showName: false }, + { text: 'Om saam met die gemeente te bid, al is ek by die huis, laat my nie alleen voel nie.', showName: true, pending: true }, + ], +}; + +/** Easter Sunday (Gregorian), as YYYY-MM-DD: the Lent campaign and the cathedral's Easter services. */ +export function easterSunday(year: number): string { + const a = year % 19, b = Math.floor(year / 100), c = year % 100, d = Math.floor(b / 4), e = b % 4; + const f = Math.floor((b + 8) / 25), g = Math.floor((b - f + 1) / 3), h = (19 * a + b - d - g + 15) % 30; + const i = Math.floor(c / 4), k = c % 4, l = (32 + 2 * e + 2 * i - h - k) % 7, m = Math.floor((a + 11 * h + 22 * l) / 451); + const month = Math.floor((h + l - 7 * m + 114) / 31), day = ((h + l - 7 * m + 114) % 31) + 1; + return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`; +} diff --git a/apps/app/backend/src/messaging/send.ts b/apps/app/backend/src/messaging/send.ts index 9c787dd..1348de2 100644 --- a/apps/app/backend/src/messaging/send.ts +++ b/apps/app/backend/src/messaging/send.ts @@ -16,8 +16,10 @@ * - **`devotional-sends`** (every 5 minutes): today's devotional from the chosen source, at each * member's time (06:00 by default), once a day; up to 3 hours late, else skipped for the day. * - * Every message sent is counted per day and channel (MessageCount) for the heartbeat. + * Every message sent is counted per day and channel (MessageCount) for the heartbeat. Nothing ever + * goes to a demo person (an address at contracts DEMO_EMAIL_DOMAIN, the demo scenarios' people, §12). */ +import { DEMO_EMAIL_DOMAIN } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import type { Member, OutboxMessage } from '../generated/prisma/client.js'; import { churchTimezone } from '../church/profile.js'; @@ -82,8 +84,12 @@ async function build(ctx: Ctx, brand: Awaited>, m: Ou } } +/** A demo scenario's person (all at example.com, reserved: no one real has an address there). */ +export const isDemoPerson = (member: Pick) => member.email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`); + /** The channels this message goes on now: the queued one, or the member's choice for request updates. */ async function wanted(ctx: Ctx, m: OutboxMessage, member: Member): Promise<{ email: boolean; whatsapp: boolean; why?: string }> { + if (isDemoPerson(member)) return { email: false, whatsapp: false, why: 'A demo person: nothing is sent to them.' }; let choice: Choice = m.channel; if (m.kind === 'request-update') choice = (await prefsOf(ctx, member.id)).requestUpdates; if (choice === 'off') return { email: false, whatsapp: false, why: 'Turned off by the member.' }; diff --git a/apps/app/backend/tests/demo.test.ts b/apps/app/backend/tests/demo.test.ts new file mode 100644 index 0000000..13ffe5d --- /dev/null +++ b/apps/app/backend/tests/demo.test.ts @@ -0,0 +1,134 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import request from 'supertest'; +import { agent, FREE_BIBLE_TRANSLATION_IDS, parseBibleReference } from '@crosscode/contracts'; +import { demoChurch, demoParts, demoPeople } from '@crosscode/demo'; +import { activeMembers } from '../src/members/activity.js'; +import { fetchMessaging } from '../src/messaging/settings.js'; +import { queueDevotionals, sendOutbox } from '../src/messaging/send.js'; +import { sendReminders } from '../src/prayer/jobs.js'; +import { coverageView } from '../src/prayer/service.js'; +import { churchProfile } from '../src/church/profile.js'; +import { DEMO_DEVOTIONALS } from '../src/demo/devotionals.js'; +import { loadDemo } from '../src/demo/load.js'; +import { DEMO_PASSAGES } from '../src/demo/passages.js'; +import { APP_SCENARIOS } from '../src/demo/scenarios.js'; +import { harness, type Harness } from './support/harness.js'; + +const TODAY = '2026-12-01'; + +describe('the demo (§12)', () => { + it('loads Acacia Hill: the church, its people with their roles and band, a full wall with a few gaps, and no names', async () => { + const h = await harness({ linked: false }) as Harness; + const r = await loadDemo(h.ctx, 'community-family'); + const people = demoPeople('community-family'); + assert.equal(r.church, 'Acacia Hill Church'); + assert.equal((await churchProfile(h.ctx))?.name, 'Acacia Hill Church'); + assert.equal(r.members, people.length); + assert.equal(await h.db.member.count(), people.length); + assert.equal((await activeMembers(h.ctx)).band, agent.demoScenario('community-family').appActiveMembers); + + // The leads have their parts' roles; members have none. + const parts = demoParts('community-family'); + const pastor = people.find((p) => parts.get(p.email)?.includes('pastor'))!; + const coordinator = people.find((p) => parts.get(p.email)?.includes('prayer-coordinator'))!; + assert.deepEqual((await h.db.member.findUnique({ where: { id: pastor.id } }))!.roles, ['owner', 'pastoral_care']); + assert.deepEqual((await h.db.member.findUnique({ where: { id: coordinator.id } }))!.roles, ['prayer_coordinator']); + assert.equal(await h.db.member.count({ where: { roles: { has: 'owner' } } }), 1); + + // Nearly every hour covered, with a gap or two in the week ahead; counts only. + const days = await Promise.all([0, 1, 2, 3, 4, 5, 6].map((n) => coverageView(h.ctx, `2026-12-0${1 + n}`, null))); + const covered = days.reduce((t, d) => t + d.covered, 0); + const total = days.reduce((t, d) => t + d.total, 0); + assert.ok(covered / total > 0.85 && covered < total, `${covered} of ${total} hours covered`); + assert.ok(!JSON.stringify(days).includes(pastor.name.split(' ')[1]!)); + assert.ok(await h.db.prayedMark.count() > 100); + + // The running campaign, the requests waiting for approval, the announcements and events. + const campaign = (await h.ctx.db.prayerCampaign.findMany())[0]!; + assert.ok(campaign.startDate <= TODAY && campaign.endDate >= TODAY); + assert.equal(await h.db.prayerRequest.count({ where: { moderation: 'pending' } }), 3); + assert.equal(await h.db.announcement.count({ where: { pinned: true } }), 1); + assert.equal(r.events.from, 'app'); + assert.equal(await h.db.simpleEvent.count({ where: { publishedAt: { not: null } } }), 3); + // Cross Code's devotionals come from the Hub, which this App isn't registered with. + assert.equal(r.devotionals.source, 'crosscode'); + assert.match(r.devotionals.error ?? '', /registered/); + + // Through the API too: Home's public parts answer. + assert.equal((await request(h.app).get('/api/v1/announcements')).status, 200); + }); + + it('loads every scenario, each in its own App band, with its own wall rules and devotionals', async () => { + for (const key of agent.DEMO_SCENARIO_KEYS) { + const h = await harness({ linked: false }) as Harness; + const r = await loadDemo(h.ctx, key); + const s = APP_SCENARIOS[key]; + assert.equal(r.church, demoChurch(key).profile.name, key); + assert.equal((await activeMembers(h.ctx)).band, agent.demoScenario(key).appActiveMembers, key); + const wall = await h.ctx.settings.json<{ slotMinutes?: number } | null>('prayer_wall', null); + assert.equal(wall?.slotMinutes ?? null, s.wall?.slotMinutes ?? null, key); + assert.equal(await h.ctx.settings.get('devotionals_source'), s.devotionals, key); + const own = await h.db.devotional.findMany({ where: { source: 'church' }, orderBy: { date: 'asc' } }); + assert.equal(own.length, DEMO_DEVOTIONALS[key]?.days.length ?? 0, key); + if (own.length) { + assert.equal(own[5]!.date, TODAY, `${key}: today is the sixth`); + for (const d of own) assert.ok(FREE_BIBLE_TRANSLATION_IDS.includes(d.translation as never), key); + } + assert.ok(r.commitments > 10, key); + } + }); + + it('quotes every passage word for word from the generated file (never written by hand)', () => { + for (const [key, set] of Object.entries(DEMO_DEVOTIONALS)) { + for (const d of set!.days) { + assert.ok(parseBibleReference(d.reference).ok, `${key}: ${d.reference}`); + assert.ok(DEMO_PASSAGES[`${set!.translation} ${d.reference}`], `${key}: ${d.reference} isn't in passages.ts (run scripts/demo-passages.ts)`); + } + } + assert.equal(Object.keys(DEMO_PASSAGES).length, new Set(Object.values(DEMO_DEVOTIONALS).flatMap((s) => s!.days.map((d) => `${s!.translation} ${d.reference}`))).size); + }); + + it('replaces the scenario before: its demo members and content go, real members stay', async () => { + const h = await harness({ linked: false }) as Harness; + await h.db.member.create({ data: { id: 'real-1', name: 'Real Owner', email: 'owner@church.test', roles: ['owner'] } }); + await loadDemo(h.ctx, 'bold-youth'); + const before = (await h.db.simpleEvent.findMany()).map((e) => e.id); + await loadDemo(h.ctx, 'heritage-parish'); + const members = await h.ctx.db.member.findMany(); + assert.equal(members.length, demoPeople('heritage-parish').length + 1); + assert.ok(members.every((m) => m.id === 'real-1' || m.email.includes('stcolumbas'))); + assert.deepEqual(members.find((m) => m.id === 'real-1')!.roles, ['owner']); + assert.equal(await h.db.member.count({ where: { roles: { has: 'owner' } } }), 2); + // Ignite's events are listed as removed in the feed, so linked products drop their copies. + assert.equal(await h.db.feedRemoval.count({ where: { eventId: { in: before } } }), before.length); + assert.equal(await h.db.prayerCampaign.count(), 1); + assert.equal((await h.db.prayerCampaign.findMany())[0]!.title, 'Forty days of prayer for Lent'); + }); + + it('shows Cross Events\' events through the feed when the church has it, and makes none of its own', async () => { + const h = await harness({ linked: false }) as Harness; + await h.db.productLink.create({ data: { installId: 'ev-1', product: 'events', url: 'https://events.hope.test', publicKey: 'x', secret: h.ctx.secrets.encrypt('s'), connectedAt: new Date(), showEvents: false } }); + const r = await loadDemo(h.ctx, 'community-family'); + assert.equal(r.events.from, 'events'); + assert.equal(r.events.made, 0); + assert.equal(await h.db.simpleEvent.count(), 0); + assert.equal((await h.db.productLink.findUnique({ where: { installId: 'ev-1' } }))!.showEvents, true); + }); + + it('never sends a demo person anything: reminders, devotionals and renewals stop at the sender', async () => { + const h = await harness() as Harness; + await fetchMessaging(h.ctx); + await loadDemo(h.ctx, 'bold-plant'); + for (let i = 0; i < 24 * 4; i++) { + await sendReminders(h.ctx); + await queueDevotionals(h.ctx); + await sendOutbox(h.ctx, { pauseMs: 0 }); + h.clock.add(15 * 60e3); + } + assert.ok(await h.db.outboxMessage.count() > 0, 'something was queued'); + assert.equal(h.transport.emails.length, 0); + assert.equal(h.transport.whatsapps.length, 0); + assert.equal(await h.db.outboxMessage.count({ where: { sentAt: null } }), 0); + }); +}); diff --git a/apps/app/backend/tests/support/memoryDb.ts b/apps/app/backend/tests/support/memoryDb.ts index e3b9468..5467ada 100644 --- a/apps/app/backend/tests/support/memoryDb.ts +++ b/apps/app/backend/tests/support/memoryDb.ts @@ -1,7 +1,7 @@ /** * An in-memory stand-in for the Prisma client (from the Website's tests/support/memoryDb.ts): every * model the App uses, with the schema's defaults and unique fields, generic `where` matching - * (equality, in / notIn, gt / gte / lt / lte, not, contains, has, AND / OR), `include` of the + * (equality, in / notIn, gt / gte / lt / lte, not, contains, endsWith, has, AND / OR), `include` of the * relations below and `aggregate` sums. Enough to run the whole app in tests. Each module adds its * models' defaults here as it arrives. */ @@ -61,6 +61,7 @@ function matchValue(actual: unknown, cond: unknown): boolean { case 'not': return x === null ? actual != null : !matchValue(actual, x); case 'isEmpty': return Array.isArray(actual) && (actual.length === 0) === x; case 'has': return Array.isArray(actual) && actual.map(v).includes(v(x)); + case 'endsWith': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().endsWith(String(x).toLowerCase()) : actual.endsWith(String(x))); case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x))); default: throw new Error(`memoryDb: no operator ${op}`); } @@ -149,6 +150,10 @@ function model(name: string, tables: Map>) { table().set(row[key], row); return clone(row); }, + createMany: async ({ data }: { data: Row[] }) => { + for (const d of data) await api.create({ data: d }); + return { count: data.length }; + }, update: async ({ where, data }: { where: Row; data: Row }) => { const r = findWhere(where); if (!r) throw prismaError('P2025', `Record to update not found (${name})`); diff --git a/package-lock.json b/package-lock.json index 8bc9180..2af646d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -145,6 +145,7 @@ "dependencies": { "@crosscode/auth-client": "*", "@crosscode/contracts": "*", + "@crosscode/demo": "*", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "cron-parser": "^5.10.2",