Files
crosscode-platform/apps/events/backend/src/services/churchExport.ts
T
joshuaandClaude Opus 5.5 350ab9f4e8 Events: env template, church export, register with HUB_LICENCE_KEY
- apps/events/env.template.json (crosscode.env-template/1): every .env
  variable with its layer (server, defaults, install, generated).
- scripts/export-church.ts writes crosscode.church-export/1 (export-only
  references, no internal ids or secrets) for crosscode export.
- Installs made from the Hub register by themselves on first start when
  HUB_LICENCE_KEY is set (retries while the Hub is unreachable).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:06:01 +02:00

143 lines
6.8 KiB
TypeScript

/**
* The church's data when it leaves: crosscode.church-export/1 (packages/contracts,
* docs/AGENT-1.0-PLAN.md §9). Plain terms and our own field names: no tables, Prisma models or
* internal ids. Records point at each other with references made for the export (p1, e1, t1, r1)
* that mean nothing outside the file. `crosscode export` runs scripts/export-church.ts, which
* writes this as export.json next to the uploads.
*
* Not included: passwords, 2FA secrets, tokens, provider keys, audit and access logs (they're
* about the site's running, not the church's data), and analytics.
*/
import { prisma } from '../v2/legacy';
type Row = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any -- rows from Prisma
const iso = (d: unknown): string | null => (d instanceof Date ? d.toISOString() : d ? new Date(String(d)).toISOString() : null);
const cents = (rand: unknown): number => Math.round(Number(rand || 0) * 100);
/** Hands out p1, p2 … for ids, in the order they're first seen. */
class Refs {
private map = new Map<string, string>();
constructor(private prefix: string) {}
of(id: string | null | undefined): string | null {
if (!id) return null;
let r = this.map.get(id);
if (!r) {
r = `${this.prefix}${this.map.size + 1}`;
this.map.set(id, r);
}
return r;
}
has(id: string | null | undefined): boolean {
return !!id && this.map.has(id);
}
}
/** Settings worth giving back (never secrets: those are stored encrypted under other keys). */
export const EXPORT_SETTING_KEYS = [
'org_name', 'org_tagline', 'org_email', 'org_phone', 'org_address', 'org_website', 'brand_primary_color', 'logo_url', 'favicon_url',
'app_name', 'timezone', 'currency', 'privacy_contact_email',
];
export type ExportInput = {
users: Row[]; events: Row[]; registrations: Row[]; payments: Row[]; usages: Row[]; slots: Row[]; roles: Row[];
settings: Row[]; fields: Row[]; version: string;
};
/** Builds the export from rows (kept separate from the database reads, so it can be tested). */
export function buildExport(input: ExportInput, now = new Date()) {
const people = new Refs('p');
const events = new Refs('e');
const tickets = new Refs('t');
const regs = new Refs('r');
const labels = new Map(input.fields.map(f => [f.id, String(f.label)]));
const settings = Object.fromEntries(input.settings.filter(s => EXPORT_SETTING_KEYS.includes(s.key)).map(s => [s.key, String(s.value)]));
const out = {
schema: 'crosscode.church-export/1' as const,
exportedAt: now.toISOString(),
product: 'events' as const,
productVersion: input.version,
church: { name: settings.org_name || 'Church', timezone: process.env.APP_TIMEZONE || 'Africa/Johannesburg' },
people: input.users.map(u => ({
ref: people.of(u.id)!,
name: String(u.name || ''),
email: u.email || null,
phone: u.phoneNumber || null,
role: String(u.role || 'user'),
createdAt: iso(u.createdAt),
consent: { email: typeof u.newsEmail === 'boolean' ? u.newsEmail : null, whatsapp: typeof u.newsWhatsApp === 'boolean' ? u.newsWhatsApp : null, privacyNoticeAcceptedAt: null },
})),
events: input.events.map(e => ({
ref: events.of(e.id)!,
title: String(e.title || ''),
description: e.description || null,
startsAt: iso(e.startDate),
endsAt: iso(e.endDate),
location: e.location || null,
sessions: (e.sessions || []).map((s: Row) => ({ label: s.label || null, startsAt: iso(s.startsAt), endsAt: iso(s.endsAt) })),
ticketTypes: (e.eventOptions || []).map((o: Row) => ({ ref: tickets.of(o.id)!, name: String(o.name || ''), priceCents: cents(o.price), currency: 'ZAR' })),
capacity: null as number | null,
published: !!e.isActive && !e.isHidden,
})),
registrations: input.registrations.filter(r => events.has(r.eventId)).map(r => ({
ref: regs.of(r.id)!,
eventRef: events.of(r.eventId)!,
personRef: people.has(r.userId) ? people.of(r.userId) : null,
status: String(r.status),
createdAt: iso(r.createdAt),
attendees: (r.attendees || []).map((a: Row) => ({
name: String(a.name || ''),
email: a.email || null,
ticketTypeRef: tickets.has(a.eventOptionId) ? tickets.of(a.eventOptionId) : null,
checkedInAt: iso(a.ticket?.usages?.[0]?.scannedAt),
})),
answers: (r.formResponses || []).flatMap((fr: Row) => (fr.answers || []).map((x: Row) => ({ question: labels.get(x.fieldId) || 'Question', answer: String(x.value ?? '') }))),
})),
payments: input.payments.map(p => ({
registrationRef: regs.has(p.registrationId) ? regs.of(p.registrationId) : null,
amountCents: cents(p.amount),
currency: 'ZAR',
method: String(p.method || 'unknown'),
status: String(p.status || 'completed'),
paidAt: iso(p.createdAt),
reference: p.externalId || null,
})),
checkIns: input.usages.filter(u => events.has(u.ticket?.eventId)).map(u => ({
eventRef: events.of(u.ticket.eventId)!,
personRef: people.has(u.ticket?.holderUserId || u.ticket?.userId) ? people.of(u.ticket.holderUserId || u.ticket.userId) : null,
name: u.ticket?.attendee?.name || null,
at: iso(u.scannedAt),
})),
rosters: input.slots.map(s => {
const role = input.roles.find(r => r.id === s.roleId);
return {
eventRef: role && events.has(role.eventId) ? events.of(role.eventId) : null,
role: String(role?.name || 'Volunteer'),
personRef: people.has(s.userId) ? people.of(s.userId) : null,
startsAt: iso(role?.startsAt),
endsAt: iso(role?.endsAt),
};
}),
settings,
files: [] as { path: string; bytes: number }[],
};
return out;
}
/** Reads everything the export needs. */
export async function readExportInput(version: string): Promise<ExportInput> {
const [users, events, registrations, payments, usages, slots, roles, settings, fields] = await Promise.all([
prisma.user.findMany({ orderBy: { createdAt: 'asc' } }),
prisma.event.findMany({ orderBy: { startDate: 'asc' }, include: { sessions: { orderBy: { order: 'asc' } }, eventOptions: true } }),
prisma.registration.findMany({ orderBy: { createdAt: 'asc' }, include: { attendees: { orderBy: { order: 'asc' }, include: { ticket: { include: { usages: { orderBy: { scannedAt: 'asc' }, take: 1 } } } } }, formResponses: { include: { answers: true } } } }),
prisma.payment.findMany({ orderBy: { createdAt: 'asc' } }),
prisma.ticketUsage.findMany({ orderBy: { scannedAt: 'asc' }, include: { ticket: { include: { attendee: true } } } }),
prisma.volunteerSlot.findMany(),
prisma.servingRole.findMany(),
prisma.appSetting.findMany(),
prisma.eventFormField.findMany(),
]);
return { users, events, registrations, payments, usages, slots, roles, settings, fields, version } as ExportInput;
}