app: the church export's app part (APP-1.0-PLAN §11)

crosscode.church-export/1 with its app part, in plain terms with refs made
for the export: members as people with every role, the wall's rules,
commitments as rules (with skips), "I prayed" marks, campaigns, testimonies,
prayer requests with their updates and moderation (who and why; the whole
export is encrypted by the agent), the emergency numbers, announcements,
the church's own devotionals (not Cross Code's) and simple events; uploaded
images listed under uploads/. scripts/export-church.ts writes export.json
for the crosscode script (app.sh comes with slice 7). A test checks the
schema and that no internal id is in it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 14:53:27 +02:00
co-authored by Claude Opus 5.5
parent 62cfb18c0b
commit d8a101567b
4 changed files with 251 additions and 1 deletions
+30
View File
@@ -0,0 +1,30 @@
/**
* The App's part of a church's export (`crosscode export` / uninstall, APP-1.0-PLAN §11):
* `export.json` in --out-dir (src/export/churchExport.ts). The crosscode script adds the uploaded
* images next to it (backend/uploads → uploads/), and the server agent encrypts the whole export.
*
* npx tsx scripts/export-church.ts --out-dir <dir>
*/
import 'dotenv/config';
import fs from 'node:fs';
import path from 'node:path';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { createCtx } from '../src/context.js';
import { buildExport } from '../src/export/churchExport.js';
import { loadConfig } from '../src/lib/config.js';
const i = process.argv.indexOf('--out-dir');
const out = i > 0 ? process.argv[i + 1] : null;
if (!out) {
console.error('Usage: export-church.ts --out-dir <dir>');
process.exit(2);
}
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
const data = await buildExport(createCtx(loadConfig(), db));
fs.mkdirSync(out, { recursive: true });
fs.writeFileSync(path.join(out, 'export.json'), JSON.stringify(data, null, 2), { mode: 0o600 });
const a = data.app!;
console.log(` export.json: ${data.people.length} people, ${a.commitments.length} commitments, ${a.prayerRequests.length} prayer requests, ${a.announcements.length} announcements, ${data.files.length} files`);
await db.$disconnect();
+155
View File
@@ -0,0 +1,155 @@
/**
* The App's part of a church's export when it leaves (`crosscode export` / uninstall,
* APP-1.0-PLAN §11): `crosscode.church-export/1` with its `app` part, in plain terms and our own
* field names (no table names or internal ids; records refer to each other by refs made for the
* export). The whole export is encrypted by the server agent (AGENT-1.0-PLAN §9, decision 31): it
* holds the prayer requests. The uploaded images are copied next to it by the crosscode script
* (`uploads/`, listed in `files`).
*
* Members are `people`, each with their roles. Commitments are the rules they are, not every
* occurrence. Cross Code's devotionals aren't exported (they're Cross Code's); the church's own are.
* An image from elsewhere (an address, not an upload) isn't in the ZIP, so it's left out.
*/
import { churchExportSchema, type ChurchExport, type ExportApp, type PassageLocation, type BibleTranslationId } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import type { AppRole, PrayerRequest } from '../generated/prisma/client.js';
import { churchProfile, churchTimezone } from '../church/profile.js';
import { devotionalSource } from '../content/devotionals.js';
import { zonedTime } from '../lib/zoned.js';
import { uploadedFilename } from '../media/media.js';
import { enabledModules } from '../modules.js';
import { wallSettings } from '../prayer/wall.js';
import { requestSettings } from '../requests/settings.js';
import { appVersion } from '../lib/version.js';
const iso = (d: Date | null | undefined) => (d ? d.toISOString() : null);
const ROLE_NAMES: Record<AppRole, string> = {
owner: 'app owner', church_admin: 'church admin', content_admin: 'content admin', devotional_writer: 'devotional writer', prayer_coordinator: 'prayer coordinator', pastoral_care: 'pastoral care',
};
const ORDER: AppRole[] = ['owner', 'church_admin', 'content_admin', 'devotional_writer', 'prayer_coordinator', 'pastoral_care'];
const REMINDER = { none: 'none', min15: '15m', hour1: '1h', evening: 'evening' } as const;
function requestStatus(r: PrayerRequest): ExportApp['prayerRequests'][number]['status'] {
if (r.closedAt) return 'closed';
if (r.escalatedAt) return 'escalated';
if (r.moderation === 'pending') return 'waiting';
if (r.moderation === 'approved') return 'shared';
if (r.moderation === 'removed') return 'removed';
return 'team';
}
export async function buildExport(ctx: Ctx): Promise<ChurchExport> {
const db = ctx.db;
const [members, commitments, marks, campaigns, testimonies, requests, announcements, devotionals, events, media, modules, wall, reqSettings, source, tz, profile] = await Promise.all([
db.member.findMany({ orderBy: [{ createdAt: 'asc' }, { name: 'asc' }] }),
db.prayerCommitment.findMany({ orderBy: { createdAt: 'asc' }, include: { skips: true } }),
db.prayedMark.findMany({ orderBy: { createdAt: 'asc' } }),
db.prayerCampaign.findMany({ orderBy: { startDate: 'asc' } }),
db.testimony.findMany({ orderBy: { createdAt: 'asc' } }),
db.prayerRequest.findMany({ orderBy: { createdAt: 'asc' }, include: { updates: { orderBy: { createdAt: 'asc' } }, prayers: true } }),
db.announcement.findMany({ orderBy: { createdAt: 'asc' } }),
db.devotional.findMany({ where: { source: 'church' }, orderBy: { date: 'asc' } }),
db.simpleEvent.findMany({ orderBy: { startsAt: 'asc' } }),
db.mediaAsset.findMany({ orderBy: { createdAt: 'asc' } }),
enabledModules(ctx), wallSettings(ctx), requestSettings(ctx), devotionalSource(ctx), churchTimezone(ctx), churchProfile(ctx),
]);
const person = new Map(members.map((m, n) => [m.id, `p${n + 1}`]));
const pRef = (id: string | null | undefined) => (id ? person.get(id) ?? null : null);
const nameOf = new Map(members.map((m) => [m.id, m.name]));
const by = (id: string | null | undefined) => (id ? nameOf.get(id) ?? null : null);
const files = new Set(media.map((m) => m.filename));
const image = (url: string | null) => {
const f = uploadedFilename(ctx, url);
return f && files.has(f) ? `uploads/${f}` : null;
};
const commitmentById = new Map(commitments.map((c) => [c.id, c]));
const campaignRef = new Map(campaigns.map((c, n) => [c.id, `k${n + 1}`]));
const app: ExportApp = {
modules,
prayerWall: {
slotMinutes: wall.slotMinutes, slotTarget: wall.targetPerSlot, bookAheadMonths: wall.bookAheadMonths, recurringMaxMonths: wall.recurringMaxMonths, cancelHours: wall.cancelHours,
contact: [wall.coordinator.name, wall.coordinator.contact].filter(Boolean).join(', ') || null,
},
commitments: commitments.map((c, n) => ({
ref: `c${n + 1}`,
personRef: pRef(c.memberId),
startsAt: iso(zonedTime(c.startDate, c.startMinute, tz)),
minutes: c.durationMinutes,
repeats: c.recurrence,
until: c.recurrence === 'once' ? null : c.endDate,
skipped: c.skips.map((s) => s.date).sort(),
reminder: REMINDER[c.reminder],
channel: c.channel,
note: c.note,
createdAt: iso(c.createdAt),
stoppedAt: null,
})),
prayed: marks.map((m) => {
const c = commitmentById.get(m.commitmentId);
return { personRef: pRef(m.memberId), slotStartsAt: c ? iso(zonedTime(m.date, c.startMinute, tz)) : null, at: iso(m.createdAt) };
}),
campaigns: campaigns.map((c) => ({
ref: campaignRef.get(c.id)!, title: c.title, description: c.description || null, image: image(c.imageUrl), startsOn: c.startDate, endsOn: c.endDate,
goal: c.goal, slotTarget: c.targetPerSlot ?? wall.targetPerSlot,
})),
testimonies: testimonies.map((t) => ({
personRef: pRef(t.memberId), campaignRef: t.campaignId ? campaignRef.get(t.campaignId) ?? null : null, text: t.text, showName: t.showName,
status: t.status === 'pending' ? 'waiting' as const : t.status === 'approved' ? 'shown' as const : 'removed' as const, createdAt: iso(t.createdAt),
})),
prayerRequests: requests.map((r, n) => {
const moderation: ExportApp['prayerRequests'][number]['moderation'] = [];
if (r.moderation === 'approved' && r.moderatedAt) moderation.push({ action: 'approved', by: by(r.moderatedById), reason: null, at: iso(r.moderatedAt) });
if (r.redactedAt) moderation.push({ action: 'redacted', by: by(r.moderatedById), reason: r.redactionNote, at: iso(r.redactedAt) });
if (r.moderation === 'removed' && r.moderatedAt) moderation.push({ action: 'removed', by: by(r.moderatedById), reason: r.removedReason, at: iso(r.moderatedAt) });
if (r.escalatedAt) moderation.push({ action: 'escalated', by: by(r.escalatedById), reason: r.escalationNote, at: iso(r.escalatedAt) });
if (r.closedAt) moderation.push({ action: 'closed', by: null, reason: null, at: iso(r.closedAt) });
return {
ref: `q${n + 1}`,
personRef: r.anonymous ? null : pRef(r.memberId),
visibility: r.visibility, showName: r.showName, text: r.text, status: requestStatus(r),
prayedCount: r.prayers.length, createdAt: iso(r.createdAt), closedAt: iso(r.closedAt),
updates: r.updates.map((u) => ({ text: u.author === 'team' ? `Prayer team: ${u.text}` : u.text, at: iso(u.createdAt) })),
moderation: moderation.sort((a, b) => String(a.at).localeCompare(String(b.at))),
};
}),
safeguarding: { emergencyNumbers: reqSettings.emergencyNumbers.map((e) => ({ name: e.label, number: e.number })) },
announcements: announcements.map((a) => ({
title: a.title, body: a.body, image: image(a.imageUrl),
button: a.buttonLabel && a.buttonUrl ? { label: a.buttonLabel, url: a.buttonUrl } : null,
campus: a.campus, audience: a.audience, pinned: a.pinned, publishAt: iso(a.publishAt), endsAt: iso(a.endsAt),
sent: { email: !!a.sentAt && a.sendEmail, whatsapp: !!a.sentAt && a.sendWhatsApp },
})),
devotionalSource: source,
devotionals: devotionals.map((d) => ({
date: d.date, title: d.title,
passage: { reference: d.reference, location: d.location as PassageLocation, translation: d.translation as BibleTranslationId, text: d.passageText },
body: d.body, prayer: d.prayer, author: d.author, membersOnly: d.membersOnly,
})),
events: events.map((e, n) => ({
ref: `w${n + 1}`, title: e.title, description: e.description, startsAt: iso(e.startsAt), endsAt: iso(e.endsAt), location: e.location,
link: e.link, image: image(e.imageUrl), published: e.publishedAt !== null && !e.cancelled,
})),
};
return churchExportSchema.parse({
schema: 'crosscode.church-export/1',
exportedAt: ctx.now().toISOString(),
product: 'app',
productVersion: appVersion(),
church: { name: profile?.name ?? 'Church App', timezone: tz },
people: members.map((m) => {
const roles = ORDER.filter((r) => m.roles.includes(r));
return {
ref: person.get(m.id)!, name: m.name, email: m.email, phone: m.phone, role: roles[0] ? ROLE_NAMES[roles[0]] : 'member',
roles: roles.length ? roles.map((r) => ROLE_NAMES[r]) : ['member'], createdAt: iso(m.createdAt),
consent: { email: m.newsEmail, whatsapp: m.whatsappOptedOut ? false : m.newsWhatsApp, privacyNoticeAcceptedAt: null },
};
}),
events: [], registrations: [], payments: [], checkIns: [], rosters: [],
settings: { address: ctx.config.publicUrl },
files: media.map((m) => ({ path: `uploads/${m.filename}`, bytes: m.bytes })),
app,
});
}
+65
View File
@@ -0,0 +1,65 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import sharp from 'sharp';
import { churchExportSchema, INTERNAL_ID_KEYS } from '@crosscode/contracts';
import { buildExport } from '../src/export/churchExport.js';
import { cookieHeader, harness, MEMBER, PASTOR, signInAs, type Harness } from './support/harness.js';
const COORD = '55555555-5555-4555-8555-555555555555';
const ORIGIN = 'https://app.hope.test';
/** Every key in the export, at any depth. */
function keys(v: unknown, out: string[] = []): string[] {
if (Array.isArray(v)) v.forEach((x) => keys(x, out));
else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) { out.push(k); keys(x, out); }
return out;
}
describe('the church export (§11)', () => {
it('has the App\'s part in plain terms: members with roles, the wall, requests, content and uploads, no internal ids', async () => {
const h = await harness({ env: { UPLOAD_DIR: fs.mkdtempSync(path.join(os.tmpdir(), 'cca-uploads-')) } }) as Harness;
const as = (c: Record<string, string>) => ({ post: (p: string, body: object) => request(h.app).post(p).set('Cookie', cookieHeader(c)).set('Origin', ORIGIN).send(body) });
const thandi = as(await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test' }));
const owner = await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', roles: ['owner', 'prayer_coordinator'] }, true);
await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true);
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', { startDate: '2026-12-02', startMinute: 120, durationMinutes: 60, recurrence: 'weekly', reminder: 'evening', channel: 'email', note: 'At home' })).status, 201);
const req = await thandi.post('/api/v1/me/requests', { text: 'Please pray for my mother', visibility: 'members', showName: true });
await as(owner).post(`/api/v1/admin/requests/${req.body.id}/approve`, {});
const photo = await sharp({ create: { width: 40, height: 30, channels: 3, background: '#36c' } }).jpeg().toBuffer();
const img = await request(h.app).post('/api/v1/admin/media').set('Cookie', cookieHeader(owner)).set('Origin', ORIGIN).set('Content-Type', 'image/jpeg').send(photo);
await h.db.announcement.create({ data: { slug: 'carols', title: 'Carols', body: 'Sunday at 19:00', imageUrl: img.body.url, publishAt: h.clock.now() } });
await h.db.announcement.create({ data: { slug: 'elsewhere', title: 'Elsewhere', body: 'x', imageUrl: 'https://cdn.example.com/a.jpg', publishAt: h.clock.now() } });
await h.db.devotional.create({ data: { source: 'church', date: '2026-12-01', title: 'Ours', reference: 'John 1:5', location: { book: 'JHN', chapter: 1, verse: 5, endChapter: 1, endVerse: 5 }, translation: 'KJV', passageText: 'And the light shineth in darkness', body: 'Text' } });
await h.db.devotional.create({ data: { source: 'crosscode', date: '2026-12-01', title: 'Cross Code\'s', reference: 'John 1:5', location: { book: 'JHN', chapter: 1, verse: 5, endChapter: 1, endVerse: 5 }, translation: 'KJV', passageText: 'x', body: 'x' } });
const x = await buildExport(h.ctx);
assert.ok(churchExportSchema.safeParse(x).success);
assert.equal(x.product, 'app');
const thandiP = x.people.find((p) => p.name === 'Thandi Mokoena')!;
assert.deepEqual(x.people.find((p) => p.name === 'Pastor Sam')!.roles, ['app owner', 'prayer coordinator']);
assert.deepEqual(thandiP.roles, ['member']);
const app = x.app!;
assert.equal(app.commitments.length, 1);
assert.equal(app.commitments[0]!.personRef, thandiP.ref);
assert.equal(app.commitments[0]!.startsAt, '2026-12-02T00:00:00.000Z', '02:00 in Johannesburg');
assert.equal(app.commitments[0]!.reminder, 'evening');
assert.equal(app.prayerRequests[0]!.status, 'shared');
assert.equal(app.prayerRequests[0]!.text, 'Please pray for my mother');
assert.equal(app.prayerRequests[0]!.moderation[0]!.action, 'approved');
assert.equal(app.prayerRequests[0]!.moderation[0]!.by, 'Pastor Sam');
assert.deepEqual(app.devotionals.map((d) => d.title), ['Ours'], 'Cross Code\'s aren\'t the church\'s');
const [carols, elsewhere] = app.announcements;
assert.match(String(carols!.image), /^uploads\/2026\/12\/[0-9a-f-]+\.jpg$/);
assert.equal(elsewhere!.image, null);
assert.deepEqual(x.files.map((f) => f.path), [carols!.image]);
assert.equal(app.safeguarding.emergencyNumbers.length, 3);
// No internal ids anywhere: not as keys, not as values.
assert.deepEqual(keys(x).filter((k) => INTERNAL_ID_KEYS.test(k)), []);
const text = JSON.stringify(x);
for (const id of [MEMBER, PASTOR, COORD, req.body.id, img.body.id]) assert.ok(!text.includes(id), `no ${id}`);
});
});
+1 -1
View File
@@ -211,7 +211,7 @@ describe('announcements and devotionals (§5, §6)', () => {
assert.equal((await thandi.post('/api/v1/me/notifications/devotional-offer', { choice: 'both' })).status, 200);
await thandi.put('/api/v1/me/notifications', { devotionalTime: '09:00' });
assert.equal((await thandi.get('/api/v1/me/notifications')).body.offerDevotional, false);
await h.db.devotional.create({ data: { source: 'crosscode', date: '2026-12-01', title: 'Light in the dark', reference: 'John 1:5', location: { book: 'JHN', chapter: 1, verses: [5, 5] }, translation: 'BSB', passageText: 'The Light shines in the darkness, and the darkness has not overcome it.', body: 'Text' } });
await h.db.devotional.create({ data: { source: 'crosscode', date: '2026-12-01', title: 'Light in the dark', reference: 'John 1:5', location: { book: 'JHN', chapter: 1, verse: 5, endChapter: 1, endVerse: 5 }, translation: 'BSB', passageText: 'The Light shines in the darkness, and the darkness has not overcome it.', body: 'Text' } });
// 08:00 in Johannesburg: not yet.
assert.equal((await queueDevotionals(h.ctx) as { queued: number }).queued, 0);
h.clock.set('2026-12-01T07:05:00Z');