Files
crosscode-platform/apps/app/backend/tests/prayer.test.ts
T
joshuaandClaude Opus 5.5 5213bb36c0 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>
2026-12-01 10:29:39 +02:00

323 lines
21 KiB
TypeScript

import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import type { AddressInfo } from 'node:net';
import request from 'supertest';
import { stats } from '../src/hub/client.js';
import { sendReminders, sendRenewalNotices } from '../src/prayer/jobs.js';
import { prayerToken } from '../src/prayer/tokens.js';
import { cookieHeader, harness, MEMBER, signInAs, type Harness } from './support/harness.js';
const OTHER = '44444444-4444-4444-8444-444444444444';
const COORD = '55555555-5555-4555-8555-555555555555';
const DAY = 24 * 3600e3;
// The clock starts on Tuesday 1 December 2026 at 08:00 in Johannesburg (06:00 UTC).
const slot = (over: object = {}) => ({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 60, recurrence: 'once', ...over });
async function setup() {
const h = await harness() as Harness;
const member = await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test' });
const other = await signInAs(h, { sub: OTHER, name: 'Pieter Botha', email: 'pieter@hope.test' });
const as = (cookies: Record<string, string>) => ({
get: (path: string) => request(h.app).get(path).set('Cookie', cookieHeader(cookies)),
post: (path: string, body: object = {}) => request(h.app).post(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body),
patch: (path: string, body: object) => request(h.app).patch(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body),
put: (path: string, body: object) => request(h.app).put(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body),
del: (path: string) => request(h.app).delete(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test'),
});
return { h, thandi: as(member), pieter: as(other), visitor: as({}), as };
}
describe('the prayer wall', () => {
it('shows the day as counts only: no name, email or id of anyone, and "mine" only to the member', async () => {
const { thandi, pieter, visitor } = await setup();
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', slot())).status, 201);
assert.equal((await pieter.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily' }))).status, 201);
const pub = await visitor.get('/api/v1/prayer/day?date=2026-12-02');
assert.equal(pub.status, 200);
assert.match(pub.headers['cache-control']!, /public/);
const two = pub.body.slots.find((s: { minute: number }) => s.minute === 120);
assert.deepEqual({ count: two.count, covered: two.covered, mine: two.mine }, { count: 2, covered: true, mine: false });
assert.equal(pub.body.covered, 1);
assert.equal(pub.body.total, 24);
assert.equal(pub.body.target, 1);
const own = await thandi.get('/api/v1/prayer/day?date=2026-12-02');
assert.match(own.headers['cache-control']!, /private/);
assert.equal(own.body.slots.find((s: { minute: number }) => s.minute === 120).mine, true);
assert.equal(own.body.slots.filter((s: { mine: boolean }) => s.mine).length, 1);
for (const res of [pub, own, await visitor.get('/api/v1/prayer/day'), await visitor.get('/api/v1/prayer/campaign'), await visitor.get('/api/v1/prayer/testimonies')]) {
const text = JSON.stringify(res.body);
for (const secret of ['Thandi', 'Pieter', 'thandi@', 'pieter@', MEMBER, OTHER]) assert.ok(!text.includes(secret), `${secret} in an answer`);
}
});
it('refuses everything while the House of Prayer is switched off', async () => {
const { h, visitor, thandi } = await setup();
await h.ctx.settings.set('modules', JSON.stringify({ 'house-of-prayer': false }));
assert.equal((await visitor.get('/api/v1/prayer/day')).body.error.code, 'MODULE_OFF');
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', slot())).status, 404);
});
it('needs a sign-in to book, and checks the wall\'s rules', async () => {
const { visitor, thandi } = await setup();
assert.equal((await visitor.post('/api/v1/me/prayer/commitments', slot())).status, 401);
const bad = await thandi.post('/api/v1/me/prayer/commitments', slot({ startMinute: 90 }));
assert.equal(bad.status, 400);
assert.equal(bad.body.error.code, 'NOT_A_SLOT');
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 420 }))).body.error.code, 'IN_THE_PAST');
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily', endDate: '2027-12-05' }))).body.error.code, 'TOO_LONG');
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', { ...slot(), name: 'x' })).body.error.code, 'VALIDATION');
});
it('refuses a change from another site', async () => {
const { h } = await setup();
const res = await request(h.app).post('/api/v1/me/prayer/commitments').set('Origin', 'https://evil.test').send(slot());
assert.equal(res.status, 403);
});
});
describe('a member\'s commitments', () => {
it('books every week, skips a date outside the 8 hours, and not one inside them', async () => {
const { h, thandi } = await setup();
const { body } = await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 15 * 60, recurrence: 'weekly', endDate: '2027-03-01' }));
// Today at 15:00 is 7 hours away: locked.
const locked = await thandi.post(`/api/v1/me/prayer/commitments/${body.id}/skip`, { date: '2026-12-01' });
assert.equal(locked.status, 409);
assert.equal(locked.body.error.code, 'LOCKED');
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${body.id}/skip`, { date: '2026-12-08' })).status, 200);
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${body.id}/skip`, { date: '2026-12-09' })).body.error.code, 'NO_OCCURRENCE');
const day = await thandi.get('/api/v1/prayer/day?date=2026-12-08');
assert.equal(day.body.covered, 0);
assert.equal((await thandi.del(`/api/v1/me/prayer/commitments/${body.id}/skip/2026-12-08`)).status, 200);
assert.equal((await thandi.get('/api/v1/prayer/day?date=2026-12-08')).body.covered, 1);
const mine = await thandi.get('/api/v1/me/prayer');
assert.equal(mine.status, 200);
const c = mine.body.commitments[0];
assert.equal(c.upcoming[0].date, '2026-12-01');
assert.equal(c.upcoming[0].locked, true);
assert.equal(c.upcoming[1].locked, false);
assert.equal(mine.body.rules.cancelHours, 8);
assert.ok(h.db.tables.get('prayerSkip')!.size === 0);
});
it('says who to contact inside the window, as Settings says', async () => {
const { h, thandi } = await setup();
await h.ctx.settings.set('prayer_wall', JSON.stringify({ coordinator: { name: 'Lerato', contact: '082 555 0101' } }));
const { body } = await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 12 * 60 }));
const res = await thandi.del(`/api/v1/me/prayer/commitments/${body.id}`);
assert.equal(res.status, 409);
assert.match(res.body.error.message, /Lerato \(082 555 0101\)/);
});
it('cancels: a booking with nothing done goes; a running one ends after its last locked date', async () => {
const { h, thandi } = await setup();
const once = (await thandi.post('/api/v1/me/prayer/commitments', slot())).body;
assert.deepEqual((await thandi.del(`/api/v1/me/prayer/commitments/${once.id}`)).body, { removed: true, endDate: null });
const daily = (await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 12 * 60, recurrence: 'daily' }))).body;
h.clock.add(2 * DAY); // 3 December, 08:00: today's 12:00 is locked.
const res = await thandi.del(`/api/v1/me/prayer/commitments/${daily.id}`);
assert.deepEqual(res.body, { removed: false, endDate: '2026-12-03' });
assert.equal((await thandi.get('/api/v1/prayer/day?date=2026-12-04')).body.covered, 0);
assert.equal((await thandi.get('/api/v1/prayer/day?date=2026-12-02')).body.covered, 1);
});
it('changes the reminder in place, the end date within the limits, and a new time as a new rule', async () => {
const { h, thandi } = await setup();
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 12 * 60, recurrence: 'daily', endDate: '2027-01-31' }))).body;
assert.equal((await thandi.patch(`/api/v1/me/prayer/commitments/${id}`, { reminder: 'evening', channel: 'whatsapp' })).body.id, id);
assert.equal((await thandi.patch(`/api/v1/me/prayer/commitments/${id}`, { endDate: '2027-06-30' })).body.endDate, '2027-06-30');
assert.equal((await thandi.patch(`/api/v1/me/prayer/commitments/${id}`, { endDate: '2027-12-31' })).body.error.code, 'TOO_LONG');
const moved = await thandi.patch(`/api/v1/me/prayer/commitments/${id}`, { startDate: '2026-12-05', startMinute: 3 * 60 });
assert.notEqual(moved.body.id, id);
const old = await h.db.prayerCommitment.findUnique({ where: { id } });
assert.equal(old!.endDate, '2026-12-01');
const fresh = await h.db.prayerCommitment.findUnique({ where: { id: moved.body.id } });
assert.equal(fresh!.reminder, 'evening');
assert.equal(fresh!.endDate, '2027-06-30');
});
it('marks "I prayed" once the slot has ended, in the App or from the reminder\'s link', async () => {
const { h, thandi, visitor } = await setup();
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily', endDate: '2026-12-10' }))).body;
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${id}/prayed`, { date: '2026-12-02' })).body.error.code, 'NOT_YET');
h.clock.add(DAY); // 2 December, 08:00
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${id}/prayed`, { date: '2026-12-02' })).body.prayed, true);
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${id}/prayed`, { date: '2026-12-02' })).body.prayed, true);
h.clock.add(DAY);
const token = prayerToken(h.ctx, 'prayed', id, '2026-12-03');
assert.equal((await visitor.post('/api/v1/prayer/prayed', { token })).body.prayed, true);
assert.equal((await visitor.post('/api/v1/prayer/prayed', { token: token.replace(/.$/, token.endsWith('A') ? 'B' : 'A') })).status, 410);
assert.equal(await h.db.prayedMark.count({ where: { commitmentId: id } }), 2);
assert.equal((await thandi.get('/api/v1/me/prayer')).body.prayedTotal, 2);
});
it('renews for another year from the notice\'s link, once', async () => {
const { h, thandi, visitor } = await setup();
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'weekly', endDate: '2026-12-20' }))).body;
const token = prayerToken(h.ctx, 'renew', id, '2026-12-20');
const res = await visitor.post('/api/v1/prayer/renew', { token });
assert.deepEqual(res.body, { renewed: true, endDate: '2027-12-20' });
assert.equal((await visitor.post('/api/v1/prayer/renew', { token })).body.error.code, 'LINK_USED');
});
it('keeps someone else\'s commitments out of reach', async () => {
const { thandi, pieter } = await setup();
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot())).body;
assert.equal((await pieter.del(`/api/v1/me/prayer/commitments/${id}`)).status, 404);
assert.equal((await pieter.get('/api/v1/me/prayer')).body.commitments.length, 0);
});
});
describe('reminders and renewal notices', () => {
it('queues a reminder once when it\'s due, on the member\'s channel, and none for a skipped date', async () => {
const { h, thandi } = await setup();
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily', endDate: '2026-12-10', channel: 'whatsapp' }))).body;
await thandi.post(`/api/v1/me/prayer/commitments/${id}/skip`, { date: '2026-12-03' });
assert.deepEqual(await sendReminders(h.ctx), { queued: 0 });
h.clock.set('2026-12-01T23:00:00Z'); // 01:00 on 2 December, an hour before.
assert.deepEqual(await sendReminders(h.ctx), { queued: 1 });
assert.deepEqual(await sendReminders(h.ctx), { queued: 0 });
const [m] = [...h.db.tables.get('outboxMessage')!.values()] as { kind: string; channel: string; payload: { date: string; prayedPath: string } }[];
assert.equal(m!.kind, 'prayer-reminder');
assert.equal(m!.channel, 'whatsapp');
assert.equal(m!.payload.date, '2026-12-02');
assert.match(m!.payload.prayedPath, /^\/prayer\/prayed\?token=/);
h.clock.set('2026-12-02T23:10:00Z');
assert.deepEqual(await sendReminders(h.ctx), { queued: 0 });
});
it('sends the renewal notice 14 days before the end and again 3 days before', async () => {
const { h, thandi } = await setup();
await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'weekly', endDate: '2026-12-31' }));
assert.deepEqual(await sendRenewalNotices(h.ctx), { queued: 0 });
h.clock.set('2026-12-17T07:00:00Z');
assert.deepEqual(await sendRenewalNotices(h.ctx), { queued: 1 });
assert.deepEqual(await sendRenewalNotices(h.ctx), { queued: 0 });
h.clock.set('2026-12-28T07:00:00Z');
assert.deepEqual(await sendRenewalNotices(h.ctx), { queued: 1 });
const kinds = [...h.db.tables.get('outboxMessage')!.values()].map((m) => (m as { payload: { renewPath: string } }).payload.renewPath);
assert.equal(kinds.length, 2);
assert.match(kinds[0]!, /^\/prayer\/renew\?token=/);
});
});
describe('live coverage', () => {
it('streams which dates changed, unbuffered', async () => {
const { h, thandi } = await setup();
const server = h.app.listen(0);
try {
const port = (server.address() as AddressInfo).port;
const ac = new AbortController();
const res = await fetch(`http://127.0.0.1:${port}/api/v1/prayer/stream`, { signal: ac.signal });
assert.equal(res.headers.get('content-type'), 'text/event-stream; charset=utf-8');
assert.equal(res.headers.get('x-accel-buffering'), 'no');
const reader = res.body!.getReader();
let text = '';
await thandi.post('/api/v1/me/prayer/commitments', slot());
while (!text.includes('event: changed')) text += new TextDecoder().decode((await reader.read()).value);
assert.match(text, /data: \{"dates":\["2026-12-02"\]\}/);
ac.abort();
} finally {
server.close();
}
});
});
describe('the admin', () => {
it('shows names only to a prayer coordinator with 2FA, and logs every view', async () => {
const { h, thandi, pieter, as } = await setup();
await thandi.post('/api/v1/me/prayer/commitments', slot());
assert.equal((await pieter.get('/api/v1/admin/prayer/bookings?date=2026-12-02')).status, 403);
const coord = as(await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true));
const res = await coord.get('/api/v1/admin/prayer/bookings?date=2026-12-02');
assert.equal(res.status, 200);
assert.equal(res.body.people[0].member.name, 'Thandi Mokoena');
const log = [...h.db.tables.get('accessLog')!.values()] as { actorId: string; action: string; targetId: string }[];
assert.deepEqual(log.map((l) => [l.actorId, l.action, l.targetId]), [[COORD, 'prayer_bookings_viewed', '2026-12-02']]);
const week = await coord.get('/api/v1/admin/prayer/week?from=2026-12-01');
assert.equal(week.body.days[1].covered, 1);
assert.ok(!JSON.stringify(week.body).includes('Thandi'));
});
it('books on a member\'s behalf, changes the rules and runs a campaign', async () => {
const { h, visitor, as } = await setup();
const coord = as(await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true));
const booked = await coord.post('/api/v1/admin/prayer/commitments', { ...slot({ recurrence: 'daily' }), memberId: MEMBER });
assert.equal(booked.status, 201);
assert.equal((await h.db.prayerCommitment.findUnique({ where: { id: booked.body.id } }))!.bookedById, COORD);
assert.equal((await coord.put('/api/v1/admin/prayer/wall', { cancelHours: 49 })).status, 400);
assert.equal((await coord.put('/api/v1/admin/prayer/wall', { slotMinutes: 30, targetPerSlot: 2 })).body.wall.slotMinutes, 30);
assert.equal((await visitor.get('/api/v1/prayer/day?date=2026-12-02')).body.total, 48);
const c = await coord.post('/api/v1/admin/prayer/campaigns', { title: '21 days of prayer', description: 'Before the conference', startDate: '2026-11-28', endDate: '2026-12-18', targetPerSlot: 3 });
assert.equal(c.status, 201);
const summary = (await visitor.get('/api/v1/prayer/campaign')).body.campaign;
assert.equal(summary.title, '21 days of prayer');
assert.equal(summary.daysLeft, 18);
assert.equal(summary.hoursPrayed, 0);
assert.equal((await visitor.get('/api/v1/prayer/day?date=2026-12-02')).body.target, 3);
});
it('moderates testimonies before anyone sees them, with the first name or "Anonymous"', async () => {
const { h, thandi, pieter, visitor, as } = await setup();
const a = (await thandi.post('/api/v1/me/prayer/testimonies', { text: 'My mother is home from hospital.', showName: true })).body;
const b = (await pieter.post('/api/v1/me/prayer/testimonies', { text: 'Work came through after months.' })).body;
assert.equal(a.status, 'pending');
assert.deepEqual((await visitor.get('/api/v1/prayer/testimonies')).body.testimonies, []);
const coord = as(await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true));
assert.equal((await coord.get('/api/v1/admin/prayer/testimonies')).body.testimonies.length, 2);
await coord.post(`/api/v1/admin/prayer/testimonies/${a.id}/approve`);
await coord.post(`/api/v1/admin/prayer/testimonies/${b.id}/approve`);
const shown = (await visitor.get('/api/v1/prayer/testimonies')).body.testimonies.map((t: { by: string }) => t.by).sort();
assert.deepEqual(shown, ['Anonymous', 'Thandi']);
assert.equal((await coord.post(`/api/v1/admin/prayer/testimonies/${b.id}/remove`, {})).status, 400);
await coord.post(`/api/v1/admin/prayer/testimonies/${b.id}/remove`, { reason: 'It names a colleague.' });
assert.equal((await pieter.get('/api/v1/me/prayer/testimonies')).body.testimonies[0].removedReason, 'It names a colleague.');
assert.equal([...h.db.tables.get('outboxMessage')!.values()].length, 1);
assert.equal((await thandi.del(`/api/v1/me/prayer/testimonies/${a.id}`)).status, 200);
assert.deepEqual((await visitor.get('/api/v1/prayer/testimonies')).body.testimonies, []);
});
});
describe('the heartbeat, export and delete', () => {
it('reports last week\'s coverage and active commitments, as counts', async () => {
const { h, thandi } = await setup();
await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 12 * 60, durationMinutes: 12 * 60, recurrence: 'daily' }));
h.clock.add(8 * DAY);
const s = await stats(h.ctx);
// 1 December is half covered from 12:00, and the 6 days after it are too.
assert.deepEqual(s.prayer, { coverageLast7dPercent: 50, activeCommitments: 1 });
});
it('exports a member\'s prayer and, when they delete their account, opens their future slots', async () => {
const { h, thandi } = await setup();
const daily = (await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily' }))).body;
const later = (await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-20' }))).body;
await thandi.post('/api/v1/me/prayer/testimonies', { text: 'Thank you for praying with us.' });
h.clock.add(3 * DAY);
await thandi.post(`/api/v1/me/prayer/commitments/${daily.id}/prayed`, { date: '2026-12-03' });
const call = (type: string, extra: object = {}) => request(h.app).post('/api/accounts/v1/events').set('x-test-signed', 'yes').set('Content-Type', 'application/json')
.send(JSON.stringify({ schema: 'crosscode.identity/1', callId: '66666666-6666-4666-8666-666666666666', occurredAt: '2026-12-04T06:00:00.000Z', sub: MEMBER, type, ...extra }));
const exp = await call('user.export', { exportId: '77777777-7777-4777-8777-777777777777' });
assert.deepEqual(exp.body.sections.map((s: { key: string }) => s.key), ['app_member', 'app_prayer_commitments', 'app_prayed', 'app_testimonies']);
assert.equal(exp.body.sections[1].records[0].time, '02:00');
await call('user.deleted');
assert.equal(await h.db.prayerCommitment.findUnique({ where: { id: later.id } }), null);
const kept = await h.db.prayerCommitment.findUnique({ where: { id: daily.id } });
assert.deepEqual([kept!.memberId, kept!.endDate], [null, '2026-12-03']);
assert.equal(await h.db.testimony.count(), 0);
assert.equal((await h.db.prayedMark.findFirst({}))!.memberId, null);
const past = await request(h.app).get('/api/v1/prayer/day?date=2026-12-03');
assert.equal(past.body.covered, 1);
assert.equal((await request(h.app).get('/api/v1/prayer/day?date=2026-12-05')).body.covered, 0);
});
});