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
+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,
});
}