/** * Accounts' part of a demo scenario (1.9.0, docs/APP-1.0-PLAN.md ยง12, "Demo scenarios"): the * scenario's church becomes the church profile (its own name, logo, icon, colours, campuses, * service times and contact details), and its people get accounts. Loaded first, so Cross Events, * the Website and the App then build their demo data around the same church and people. * * Only for demo sites (`crosscode demo accounts --profile `, which takes a backup * first). People keep the same account id on every load (`demoId`), so products' copies still match. * Demo people from before who aren't in this scenario are anonymised; real people (any address not at * example.com) and Accounts admins are never touched. */ import { agent, DEMO_EMAIL_DOMAIN } from '@crosscode/contracts'; import { DEMO_PASSWORD, demoChurch, demoIconSvg, demoLogoSvg, demoPeople } from '@crosscode/demo'; import type { Ctx } from '../context.js'; import { audit } from '../lib/audit.js'; import { hashPassword } from '../lib/passwords.js'; import { updateProfile } from '../church/profile.js'; import { currentNoticeVersion } from '../privacy/notice.js'; import { anonymise } from '../privacy/deletion.js'; /** Where Accounts serves the scenario's logo and icon (`/api/demo-assets//logo.svg`). */ export const DEMO_ASSETS_PATH = '/api/demo-assets'; const DEMO_ASSET_FILES = { 'logo.svg': demoLogoSvg, 'icon.svg': demoIconSvg } as const; /** The SVG for a demo asset, or null for anything else. */ export function demoAsset(scenario: string, file: string): string | null { const key = agent.demoScenarioSchema.safeParse(scenario); const draw = (DEMO_ASSET_FILES as Record string>)[file]; return key.success && draw ? draw(key.data) : null; } export interface ScenarioResult { scenario: agent.DemoScenarioKey; church: string; people: number; created: number; updated: number; removed: number } const isDemo = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`); const CHUNK = 500; export async function loadScenario(ctx: Ctx, scenario: agent.DemoScenarioKey): Promise { const { profile } = demoChurch(scenario); const assets = `${ctx.config.publicUrl.replace(/\/$/, '')}${DEMO_ASSETS_PATH}/${scenario}`; // The church: every shared field replaced, so nothing from the church before is left (tells the products: church.changed). await updateProfile(ctx, { name: profile.name, shortName: profile.shortName, timezone: profile.timezone, locale: profile.locale, branding: { logoUrl: `${assets}/logo.svg`, iconUrl: `${assets}/icon.svg`, colours: profile.colours, style: profile.style }, campuses: profile.campuses, serviceTimes: profile.serviceTimes, contact: { ...profile.contact, phone: null, whatsapp: null }, social: profile.social, }); // The people. const people = demoPeople(scenario); const wanted = new Set(people.map((p) => p.id)); const existing = new Map((await ctx.db.account.findMany({ where: { id: { in: [...wanted] } } })).map((a) => [a.id, a])); let removed = 0; for (const a of await ctx.db.account.findMany({ where: { email: { contains: `@${DEMO_EMAIL_DOMAIN}` }, status: { not: 'deleted' } } })) { if (wanted.has(a.id) || !isDemo(a.email) || a.role === 'admin') continue; await ctx.db.oidcPayload.deleteMany({ where: { accountId: a.id } }); await anonymise(ctx, a.id); await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } }); removed++; } const passwordHash = await hashPassword(DEMO_PASSWORD); const notice = await currentNoticeVersion(ctx); const now = ctx.now(); const fields = (p: (typeof people)[number]) => ({ name: p.name, givenName: p.givenName, familyName: p.familyName, email: p.email, emailVerified: true, phone: null, phoneVerified: false, passwordHash, role: 'member' as const, status: 'active' as const, twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: now, noticeVersionAccepted: notice, failedSignIns: 0, lockedUntil: null, deactivatedAt: null, anonymisedAt: null, whatsappOptedOut: false, whatsappOptedOutAt: null, }); let updated = 0; // Already here (this scenario loaded before, or anonymised when another was): brought back as they were. for (const p of people) { const a = existing.get(p.id); if (!a) continue; // Never take over a real person's account, nor an admin's. if (a.role === 'admin' || (a.status !== 'deleted' && !isDemo(a.email))) continue; const other = await ctx.db.account.findUnique({ where: { email: p.email } }); if (other && other.id !== p.id) continue; await ctx.db.account.update({ where: { id: p.id }, data: fields(p) }); updated++; } // New: in chunks, as the larger scenarios have a couple of thousand people. const taken = new Set((await ctx.db.account.findMany({ where: { email: { in: people.map((p) => p.email) } }, select: { email: true } })).map((a) => a.email)); const fresh = people.filter((p) => !existing.has(p.id) && !taken.has(p.email)); for (let i = 0; i < fresh.length; i += CHUNK) { await ctx.db.account.createMany({ data: fresh.slice(i, i + CHUNK).map((p) => ({ id: p.id, ...fields(p), createdAt: now })) }); } await audit(ctx, { actorId: null, actorRole: 'system', action: 'demo_scenario_loaded', targetType: 'setting', targetId: 'church_profile', metadata: { scenario, people: people.length, created: fresh.length, updated, removed } }); await ctx.settings.set('demo_scenario', JSON.stringify({ scenario, loadedAt: now.toISOString() })); return { scenario, church: profile.name, people: people.length, created: fresh.length, updated, removed }; }