app: the House of Prayer's backend (APP-1.0-PLAN §3)

Commitments stored as rules (start, length, once/daily/weekly, end, skips) in the
church's timezone, daylight saving included; the day's coverage as counts only,
cached until a booking changes, live over server-sent events (X-Accel-Buffering
off, a comment every 25 s). Booking, skipping, changing, cancelling within the
8-hour rule, renewing (a signed single-use link), "I prayed" (self-reported).
Campaigns and moderated testimonies; the admin's bookings with names, always
access-logged; booking on a member's behalf. Reminders (every minute) and
renewal notices (14 and 3 days before) queued in an outbox for the messaging
slice. The heartbeat's prayer counts; export and delete for a member's prayer.
Migration 20261202000000_house_of_prayer (checked on PostgreSQL 18: applies, no
diff). 66 backend tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 10:29:39 +02:00
co-authored by Claude Opus 5.5
parent 6726518175
commit 5213bb36c0
23 changed files with 2376 additions and 30 deletions
+16
View File
@@ -113,3 +113,19 @@ export function cookiesFrom(res: { headers: Record<string, unknown> }, keep: Rec
}
export const cookieHeader = (c: Record<string, string>) => Object.entries(c).map(([k, v]) => `${k}=${v}`).join('; ');
/**
* Signs `who` in through the stand-in Accounts (with 2FA when `mfa`), creating them as a Member
* with `roles` first if given; answers the cookies to send.
*/
export async function signInAs(h: Harness, who: { sub: string; name?: string; email?: string; roles?: string[] }, mfa = false): Promise<Record<string, string>> {
const { default: request } = await import('supertest');
if (who.roles?.length) {
await h.db.member.upsert({ where: { id: who.sub }, create: { id: who.sub, name: who.name ?? 'Someone', email: who.email ?? `${who.sub}@hope.test`, roles: who.roles }, update: { roles: who.roles } });
}
h.fake.next = { sub: who.sub, name: who.name ?? 'Someone', email: who.email ?? `${who.sub.slice(0, 8)}@hope.test`, amr: mfa ? ['pwd', 'mfa'] : ['pwd'] };
const start = await request(h.app).get(`/api/auth/signin?returnTo=%2F${mfa ? '&mfa=1' : ''}`);
const after = cookiesFrom(start);
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
return cookiesFrom(back, after);
}
+21 -8
View File
@@ -14,13 +14,21 @@ const DEFAULTS: Record<string, () => Row> = {
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
prayerCommitment: () => ({ reminder: 'hour1', channel: 'email', note: null, bookedById: null, renewalNoticesSent: 0, renewedAt: null }),
prayedMark: () => ({ memberId: null }),
prayerCampaign: () => ({ imageUrl: null, goal: null, targetPerSlot: null, createdById: null }),
testimony: () => ({ campaignId: null, showName: false, status: 'pending', removedReason: null, moderatedById: null, moderatedAt: null }),
accessLog: () => ({ targetId: null, metadata: null, ip: null }),
outboxMessage: () => ({ sentAt: null, failedAt: null, error: null, attempts: 0 }),
};
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'] };
const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink']);
/** Unique fields: one field, or several together (`@@unique([a, b])`). */
const UNIQUE: Record<string, (string | string[])[]> = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']] };
const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign']);
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
member: { sessions: { model: 'session', many: true, key: 'memberId' } },
prayerCommitment: { skips: { model: 'prayerSkip', many: true, key: 'commitmentId' }, marks: { model: 'prayedMark', many: true, key: 'commitmentId' } },
};
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
@@ -89,19 +97,20 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
};
const findWhere = (where: Row) => {
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
for (const u of UNIQUE[name] ?? []) if (typeof u === 'string' && where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
return [...table().values()].find((r) => matches(r, where)) ?? null;
};
const checkUnique = (row: Row, except?: unknown) => {
for (const u of UNIQUE[name] ?? []) {
if (row[u] == null) continue;
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
const fields = typeof u === 'string' ? [u] : u;
if (fields.some((f) => row[f] == null)) continue;
if ([...table().values()].some((r) => r[key] !== except && fields.every((f) => v(r[f]) === v(row[f])))) throw prismaError('P2002', `Unique constraint failed on ${name}.${fields.join('_')}`);
}
};
const api = {
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
findUnique: async ({ where, select, include }: { where: Row; select?: Row; include?: Row }) => { const r = findWhere(where); return r ? withIncludes(pick(clone(r), select), include) : null; },
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
findFirst: async ({ where, orderBy, select }: { where?: Row; orderBy?: Row | Row[]; select?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? pick(clone(r), select) : null; },
findFirst: async ({ where, orderBy, select, include }: { where?: Row; orderBy?: Row | Row[]; select?: Row; include?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? withIncludes(pick(clone(r), select), include) : null; },
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
@@ -148,7 +157,11 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
},
};
const cascade = (from: string, id: unknown) => {
if (from === 'member') for (const [k, r] of tables.get('session') ?? []) if (r.memberId === id) tables.get('session')!.delete(k);
const drop = (model: string, field: string) => { for (const [k, r] of tables.get(model) ?? []) if (r[field] === id) tables.get(model)!.delete(k); };
const unset = (model: string, field: string) => { for (const r of tables.get(model)?.values() ?? []) if (r[field] === id) r[field] = null; };
if (from === 'member') { drop('session', 'memberId'); drop('testimony', 'memberId'); drop('outboxMessage', 'memberId'); unset('prayerCommitment', 'memberId'); }
if (from === 'prayerCommitment') { drop('prayerSkip', 'commitmentId'); drop('prayedMark', 'commitmentId'); }
if (from === 'prayerCampaign') unset('testimony', 'campaignId');
};
const withIncludes = (row: Row, include?: Row) => {
for (const [rel, on] of Object.entries(include ?? {})) {