app: prayer requests' backend (APP-1.0-PLAN §4)

Private by default (the prayer team only) or shared with members after a
coordinator approves it, with the first name or "Anonymous"; fully anonymous
requests when the church allows them (off by default). Coordinators approve,
redact (the sender told what changed) or remove (with a reason); anyone on the
team can escalate to Pastoral care (email and WhatsApp at once, an Owner or
Church admin when nobody has the role): it leaves the shared list and the sender
sees nothing different. "I prayed" counts without who, "Answered!" updates,
private replies from the team, closing after 30 days (7-90) and deletion 12
months later (prayer-requests-tidy). Every list with a sender is access-logged;
messages never carry a request's text; nothing in the heartbeat. Export and
delete for a member's requests. Shared helpers: parse (http.ts), accessLog
(lib/accessLog.ts). Migration 20261203000000_prayer_requests (checked on
PostgreSQL 18: applies, no diff). 78 backend tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 10:56:53 +02:00
co-authored by Claude Opus 5.5
parent 1dd3aadb60
commit 6425a6a30d
16 changed files with 893 additions and 22 deletions
+5
View File
@@ -14,6 +14,8 @@
* testimonies, the renew and "I prayed" links (prayer/routes.ts)
* /api/v1/me/prayer/… a member's commitments and testimonies
* /api/v1/admin/prayer/… the prayer wall's rules, bookings with names, campaigns, moderation
* /api/v1/requests, /api/v1/me/requests, /api/v1/admin/requests
* prayer requests: shared, a member's own, the prayer team's (requests/)
*
* To come with the modules (§1): the rest of the public content and member API, and the event feed.
*/
@@ -28,6 +30,7 @@ import { linksRouter } from './links/routes.js';
import { appInfo } from './public/app.js';
import { prayerAdminRouter } from './prayer/admin.js';
import { prayerRouter } from './prayer/routes.js';
import { requestsAdminRouter, requestsRouter } from './requests/routes.js';
export function createApp(ctx: Ctx) {
const app = express();
@@ -56,7 +59,9 @@ export function createApp(ctx: Ctx) {
app.use('/api', authRouter(ctx));
app.use('/api', linksRouter(ctx));
app.use('/api', prayerRouter(ctx));
app.use('/api', requestsRouter(ctx));
app.use('/api/v1/admin/prayer', prayerAdminRouter(ctx));
app.use('/api/v1/admin/requests', requestsAdminRouter(ctx));
app.use('/api/v1/admin', adminRouter(ctx));
app.use('/api', (_req, res) => {
+3 -1
View File
@@ -19,6 +19,7 @@
*/
import express, { type Request, type Response } from 'express';
import { deletePrayer, exportPrayer } from '../prayer/members.js';
import { deleteRequests, exportRequests } from '../requests/members.js';
import { ACCOUNTS_CALL_PATH, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS, safeReturnPath, type AccountsCall, type IdentityClaims, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import type { AppRole } from '../generated/prisma/client.js';
@@ -203,13 +204,14 @@ export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Req
key: 'app_member',
title: 'You in the church\'s App',
records: [{ name: member.name, email: member.email, roles: member.roles, since: member.createdAt.toISOString(), lastSignIn: member.lastSignInAt?.toISOString() ?? null, lastUsed: member.lastActiveAt?.toISOString() ?? null }],
}, ...(await exportPrayer(ctx, member.id))] : [],
}, ...(await exportPrayer(ctx, member.id)), ...(await exportRequests(ctx, member.id))] : [],
};
return reply;
}
case 'user.deleted': {
if (member) {
await deletePrayer(ctx, member.id);
await deleteRequests(ctx, member.id);
await ctx.db.session.deleteMany({ where: { memberId: member.id } });
await ctx.db.member.delete({ where: { id: member.id } });
await audit(ctx, { actorId: null, actorRole: 'accounts', action: 'member_deleted', targetType: 'member', targetId: member.id, metadata: { roles: member.roles }, ip: clientIp(req) });
+11
View File
@@ -3,6 +3,7 @@
* Events' /api/v2), async handlers, and a same-origin check on everything that changes something.
*/
import type { Request, RequestHandler, Response } from 'express';
import type { z } from 'zod';
export class ApiError extends Error {
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
@@ -10,6 +11,16 @@ export class ApiError extends Error {
}
}
/** Parses a body or parameter with `schema`; a 400 VALIDATION with each field's message otherwise. */
export function parse<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) {
const fields = Object.fromEntries(r.error.issues.map((i) => [i.path.join('.') || '_', i.message]));
throw new ApiError(400, 'VALIDATION', 'Please check the highlighted fields.', fields);
}
return r.data;
}
/** Known errors carry a status and code; anything else is a 500. */
export function sendError(res: Response, e: unknown) {
if (e instanceof ApiError) {
+3
View File
@@ -17,12 +17,15 @@ import PgBoss from 'pg-boss';
import type { Ctx } from './context.js';
import { heartbeat } from './hub/client.js';
import { sendReminders, sendRenewalNotices } from './prayer/jobs.js';
import { tidyRequests } from './requests/service.js';
import { DELETE_AFTER_CLOSED_DAYS } from './requests/settings.js';
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
export const JOBS: Job[] = [
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
{ name: 'prayer-reminders', label: 'House of Prayer: slot reminders', cron: '* * * * *', env: 'PRAYER_REMINDERS_ENABLED', run: (ctx) => sendReminders(ctx) },
{ name: 'prayer-requests-tidy', label: 'Prayer requests: close after their days, delete 12 months after closing', cron: '30 3 * * *', env: null, run: (ctx) => tidyRequests(ctx, DELETE_AFTER_CLOSED_DAYS) },
{ name: 'prayer-renewals', label: 'House of Prayer: renewal notices (14 and 3 days before the end)', cron: '0 9 * * *', env: 'PRAYER_RENEWALS_ENABLED', run: (ctx) => sendRenewalNotices(ctx) },
];
+12
View File
@@ -0,0 +1,12 @@
/**
* The access log (APP-1.0-PLAN §3, §4, §10): every view of names on the prayer wall and of prayer
* requests, with who, when and from where. Unlike the audit log, a failure here stops the answer:
* names are never shown unrecorded.
*/
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import { clientIp } from './audit.js';
export async function accessLog(ctx: Ctx, req: Request, entry: { action: string; targetType: string; targetId?: string | null; metadata?: object }) {
await ctx.db.accessLog.create({ data: { actorId: req.signed!.member.id, action: entry.action, targetType: entry.targetType, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: clientIp(req) } });
}
+1 -1
View File
@@ -8,7 +8,7 @@
*/
import type { Ctx } from '../context.js';
export type OutboxKind = 'prayer-reminder' | 'prayer-renewal' | 'testimony-removed';
export type OutboxKind = 'prayer-reminder' | 'prayer-renewal' | 'testimony-removed' | 'request-new' | 'request-update' | 'request-escalated';
export type Channel = 'email' | 'whatsapp' | 'both';
/** Queues a message; false when one with the same key was already queued (never sent twice). */
+3 -7
View File
@@ -20,7 +20,8 @@ import express from 'express';
import { z, ZodError } from 'zod';
import type { Ctx } from '../context.js';
import type { Request } from 'express';
import { ApiError, handle, sameOrigin } from '../http.js';
import { ApiError, handle, parse, sameOrigin } from '../http.js';
import { accessLog } from '../lib/accessLog.js';
import { audit, clientIp } from '../lib/audit.js';
import { enqueue } from '../lib/outbox.js';
import { requireRole } from '../auth/sessions.js';
@@ -28,7 +29,7 @@ import { churchTimezone } from '../church/profile.js';
import { addDays, isDate, localDate } from '../lib/zoned.js';
import { occurrencesBetween, daySlots } from './rules.js';
import { prayerChanged } from './live.js';
import { bookingBody, parse, requirePrayerModule } from './routes.js';
import { bookingBody, requirePrayerModule } from './routes.js';
import { book, cancel, rulesBetween, wallDay } from './service.js';
import { setWallSettings, wallSettings } from './wall.js';
@@ -36,11 +37,6 @@ const COORDINATORS = ['prayer_coordinator'] as const;
const actor = (req: Request) => ({ actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), ip: clientIp(req) });
/** Every view of names goes here (§3: "every view of them goes in the access log"). */
export async function accessLog(ctx: Ctx, req: Request, entry: { action: string; targetType: string; targetId?: string | null; metadata?: object }) {
await ctx.db.accessLog.create({ data: { actorId: req.signed!.member.id, action: entry.action, targetType: entry.targetType, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: clientIp(req) } });
}
const date = z.string().refine(isDate, 'A date as YYYY-MM-DD.');
const campaignBody = z.object({
title: z.string().trim().min(3).max(120),
+1 -10
View File
@@ -27,7 +27,7 @@
import express, { type RequestHandler } from 'express';
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError, handle, sameOrigin } from '../http.js';
import { ApiError, handle, parse, sameOrigin } from '../http.js';
import { currentSession, requireMember } from '../auth/sessions.js';
import { churchTimezone } from '../church/profile.js';
import { isDate, localDate } from '../lib/zoned.js';
@@ -64,15 +64,6 @@ export const bookingBody = z.object({
const changeBody = bookingBody.partial().strict();
export function parse<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) {
const fields = Object.fromEntries(r.error.issues.map((i) => [i.path.join('.') || '_', i.message]));
throw new ApiError(400, 'VALIDATION', 'Please check the highlighted fields.', fields);
}
return r.data;
}
const idParam = (v: unknown) => {
if (typeof v !== 'string' || !/^[0-9a-f-]{36}$/.test(v)) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such prayer slot.');
return v;
+33
View File
@@ -0,0 +1,33 @@
/**
* A member's prayer requests in "Download my data" and "Delete my account" (APP-1.0-PLAN §11):
* the export has their requests with every update and the team's replies (never who escalated, nor
* the team's notes); the delete removes them with their updates and "I prayed" marks.
*/
import type { UserExportReply } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { submitterStatus } from './service.js';
export async function exportRequests(ctx: Ctx, memberId: string): Promise<UserExportReply['sections']> {
const rows = await ctx.db.prayerRequest.findMany({ where: { memberId }, include: { updates: true }, orderBy: { createdAt: 'asc' } });
const prayed = await ctx.db.requestPrayer.count({ where: { memberId } });
const sections: UserExportReply['sections'] = [];
if (rows.length) {
sections.push({
key: 'app_prayer_requests',
title: 'Your prayer requests',
records: rows.map((r) => ({
text: r.text, whoSees: r.visibility === 'team' ? 'The prayer team' : 'Members of the church', showName: r.showName, anonymous: r.anonymous,
state: submitterStatus(r), sent: r.createdAt.toISOString(), closed: r.closedAt?.toISOString() ?? null,
updates: (r as typeof r & { updates: { author: string; text: string; createdAt: Date }[] }).updates.map((u) => ({ from: u.author === 'team' ? 'The prayer team' : 'You', text: u.text, at: u.createdAt.toISOString() })),
})),
});
}
if (prayed) sections.push({ key: 'app_requests_prayed', title: 'Requests you prayed for', records: [{ count: prayed }] });
return sections;
}
export async function deleteRequests(ctx: Ctx, memberId: string): Promise<void> {
const rows = await ctx.db.prayerRequest.findMany({ where: { memberId }, select: { id: true } });
for (const { id } of rows) await ctx.db.prayerRequest.delete({ where: { id } });
await ctx.db.requestPrayer.deleteMany({ where: { memberId } });
}
+203
View File
@@ -0,0 +1,203 @@
/**
* Prayer requests' API (APP-1.0-PLAN §4). Everything answers 404 `MODULE_OFF` while the module is off,
* and nothing is ever public but the form's facts.
*
* GET /api/v1/requests/form what the form says: anonymous allowed, emergency numbers, closing days
* GET /api/v1/requests shared requests (signed-in members), "I prayed" counts
* POST /api/v1/requests/:id/prayed "I prayed"
*
* GET /api/v1/me/requests mine, with replies from the team
* POST /api/v1/me/requests { text, visibility, showName?, anonymous? }
* POST /api/v1/me/requests/:id/updates { text } ("Answered!")
* POST /api/v1/me/requests/:id/close
* DELETE /api/v1/me/requests/:id
*
* The prayer team (/api/v1/admin/requests; Prayer coordinator, Pastoral care, with 2FA): every list
* that shows a sender is access-logged.
*
* GET /?view=queue|open|escalated|closed (Pastoral care: open and escalated)
* POST /:id/approve | /:id/redact { text, note } | /:id/remove { reason } (coordinators)
* POST /:id/escalate { note } | /:id/reply { text }
* GET /settings, PUT /settings (coordinators)
*/
import express, { type RequestHandler } from 'express';
import { z, ZodError } from 'zod';
import type { Ctx } from '../context.js';
import type { Request } from 'express';
import type { Prisma } from '../generated/prisma/client.js';
import { ApiError, handle, parse, sameOrigin } from '../http.js';
import { accessLog } from '../lib/accessLog.js';
import { audit, clientIp } from '../lib/audit.js';
import { hasRole, requireMember, requireRole } from '../auth/sessions.js';
import { enabledModules } from '../modules.js';
import {
addUpdate, anyRequest, approve, close, deleteOwn, escalate, forTeam, mine, prayFor, redact, remove, reply, REQUEST_MAX,
shared, SHARED_WHERE, submit, UPDATE_MAX,
} from './service.js';
import { requestSettings, setRequestSettings } from './settings.js';
const MODULE = 'prayer-requests';
function requireRequestsModule(ctx: Ctx): RequestHandler {
return (_req, _res, next) => {
enabledModules(ctx).then((on) => next(on.includes(MODULE) ? undefined : new ApiError(404, 'MODULE_OFF', 'Prayer requests are switched off.'))).catch(next);
};
}
const noStore: RequestHandler = (_req, res, next) => {
res.set('Cache-Control', 'no-store');
next();
};
const id = (v: unknown) => {
if (typeof v !== 'string' || !/^[0-9a-f-]{36}$/.test(v)) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such prayer request.');
return v;
};
const newBody = z.object({
text: z.string().trim().min(5, 'A few words at least.').max(REQUEST_MAX),
visibility: z.enum(['team', 'members']).default('team'),
showName: z.boolean().optional(),
anonymous: z.boolean().optional(),
}).strict();
const textBody = (max: number) => z.object({ text: z.string().trim().min(2).max(max) }).strict();
const COORD = ['prayer_coordinator'] as const;
const TEAM = ['prayer_coordinator', 'pastoral_care'] as const;
const actor = (req: Request) => ({ actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), ip: clientIp(req) });
export function requestsRouter(ctx: Ctx) {
const r = express.Router();
const common = [requireRequestsModule(ctx), sameOrigin(ctx.config.publicUrl, ctx.config.production), express.json({ limit: '16kb' }), noStore];
r.use('/v1/requests', ...common);
r.use('/v1/me/requests', ...common, requireMember(ctx));
r.get('/v1/requests/form', handle(async () => {
const s = await requestSettings(ctx);
return { anonymousAllowed: s.anonymousAllowed, emergencyNumbers: s.emergencyNumbers, closeAfterDays: s.closeAfterDays };
}));
r.get('/v1/requests', requireMember(ctx), handle(async (req) => {
const rows = await ctx.db.prayerRequest.findMany({ where: SHARED_WHERE, include: { updates: true, prayers: true }, orderBy: { createdAt: 'desc' }, take: 100 });
const names = await ctx.db.member.findMany({ where: { id: { in: rows.filter((x) => x.showName).map((x) => x.memberId) } }, select: { id: true, name: true } });
const byId = new Map(names.map((m) => [m.id, m.name]));
return { requests: rows.map((x) => shared(x, byId.get(x.memberId), req.signed!.member.id)) };
}));
r.post('/v1/requests/:id/prayed', requireMember(ctx), handle(async (req) => prayFor(ctx, req.signed!.member.id, id(req.params.id))));
r.get('/v1/me/requests', handle(async (req) => {
const rows = await ctx.db.prayerRequest.findMany({ where: { memberId: req.signed!.member.id }, include: { updates: true, prayers: true }, orderBy: { createdAt: 'desc' } });
return { requests: rows.map(mine) };
}));
r.post('/v1/me/requests', handle(async (req, res) => {
const body = parse(newBody, req.body);
const created = await submit(ctx, req.signed!.member.id, body);
res.status(201);
return { id: created.id, status: created.visibility === 'team' ? 'with_team' : 'waiting' };
}));
r.post('/v1/me/requests/:id/updates', handle(async (req, res) => {
await addUpdate(ctx, req.signed!.member.id, id(req.params.id), parse(textBody(UPDATE_MAX), req.body).text);
res.status(201);
return { ok: true };
}));
r.post('/v1/me/requests/:id/close', handle(async (req) => {
await close(ctx, req.signed!.member.id, id(req.params.id));
return { closed: true };
}));
r.delete('/v1/me/requests/:id', handle(async (req) => {
await deleteOwn(ctx, req.signed!.member.id, id(req.params.id));
return { deleted: true };
}));
return r;
}
export function requestsAdminRouter(ctx: Ctx) {
const r = express.Router();
r.use(requireRequestsModule(ctx), sameOrigin(ctx.config.publicUrl, ctx.config.production), express.json({ limit: '16kb' }), requireRole(ctx, TEAM), noStore);
const coordOnly = (req: Request) => {
if (!hasRole(req.signed!.activeRoles, COORD)) throw new ApiError(403, 'FORBIDDEN', 'Only a prayer coordinator can do that.');
};
r.get('/settings', handle(async () => ({ settings: await requestSettings(ctx) })));
r.put('/settings', handle(async (req) => {
coordOnly(req);
try {
const settings = await setRequestSettings(ctx, req.body);
await audit(ctx, { ...actor(req), action: 'request_settings_changed', targetType: 'settings', targetId: 'prayer_requests', metadata: req.body });
return { settings };
} catch (e) {
if (e instanceof ZodError) throw new ApiError(400, 'VALIDATION', 'Please check the highlighted fields.', Object.fromEntries(e.issues.map((i) => [i.path.join('.') || '_', i.message])));
throw e;
}
}));
r.get('/', handle(async (req) => {
const view = z.enum(['queue', 'open', 'escalated', 'closed']).catch('queue').parse(req.query.view);
const coordinator = hasRole(req.signed!.activeRoles, COORD);
if (!coordinator && (view === 'queue' || view === 'closed')) throw new ApiError(403, 'FORBIDDEN', 'Pastoral care sees open and escalated requests.');
const where: Prisma.PrayerRequestWhereInput = {
queue: { visibility: 'members' as const, moderation: 'pending' as const, closedAt: null, escalatedAt: null },
open: { closedAt: null, escalatedAt: null, ...(coordinator ? {} : { visibility: 'team' as const }) },
escalated: { escalatedAt: { not: null } },
closed: { closedAt: { not: null } },
}[view];
const rows = await ctx.db.prayerRequest.findMany({ where, include: { updates: true, prayers: true }, orderBy: { createdAt: view === 'queue' ? 'asc' : 'desc' }, take: 200 });
const people = await ctx.db.member.findMany({ where: { id: { in: [...new Set(rows.filter((x) => !x.anonymous).map((x) => x.memberId))] } }, select: { id: true, name: true, email: true, phone: true } });
const byId = new Map(people.map((p) => [p.id, { name: p.name, email: p.email, phone: p.phone }]));
if (rows.length) await accessLog(ctx, req, { action: 'prayer_requests_viewed', targetType: 'prayer_request', metadata: { view, count: rows.length } });
return { view, requests: rows.map((x) => forTeam(x, byId.get(x.memberId))) };
}));
r.post('/:id/approve', handle(async (req) => {
coordOnly(req);
const rid = id(req.params.id);
await approve(ctx, req.signed!.member.id, rid);
await audit(ctx, { ...actor(req), action: 'prayer_request_approved', targetType: 'prayer_request', targetId: rid });
return { moderation: 'approved' };
}));
r.post('/:id/redact', handle(async (req) => {
coordOnly(req);
const rid = id(req.params.id);
const { text, note } = parse(z.object({ text: z.string().trim().min(5).max(REQUEST_MAX), note: z.string().trim().min(3, 'Tell the sender what changed.').max(300) }).strict(), req.body);
await redact(ctx, req.signed!.member.id, rid, text, note);
await audit(ctx, { ...actor(req), action: 'prayer_request_redacted', targetType: 'prayer_request', targetId: rid });
return { redacted: true };
}));
r.post('/:id/remove', handle(async (req) => {
coordOnly(req);
const rid = id(req.params.id);
const { reason } = parse(z.object({ reason: z.string().trim().min(3, 'Say why, for the sender.').max(500) }).strict(), req.body);
await remove(ctx, req.signed!.member.id, rid, reason);
await audit(ctx, { ...actor(req), action: 'prayer_request_removed', targetType: 'prayer_request', targetId: rid });
return { moderation: 'removed' };
}));
r.post('/:id/escalate', handle(async (req) => {
const rid = id(req.params.id);
const { note } = parse(z.object({ note: z.string().trim().max(500).default('') }).strict(), req.body ?? {});
const out = await escalate(ctx, req.signed!.member.id, rid, note);
await audit(ctx, { ...actor(req), action: 'prayer_request_escalated', targetType: 'prayer_request', targetId: rid, metadata: out });
return { escalated: true, ...out };
}));
r.post('/:id/reply', handle(async (req, res) => {
const rid = id(req.params.id);
// A fully anonymous sender still reads replies under My requests; the team never learns who.
await reply(ctx, req.signed!.member.id, rid, parse(textBody(UPDATE_MAX), req.body).text);
await audit(ctx, { ...actor(req), action: 'prayer_request_replied', targetType: 'prayer_request', targetId: rid });
res.status(201);
return { ok: true };
}));
return r;
}
+208
View File
@@ -0,0 +1,208 @@
/**
* Prayer requests (APP-1.0-PLAN §4). Private by default:
*
* | Visibility | Who sees it |
* |---|---|
* | `team` (default) | Prayer coordinators, and Pastoral care |
* | `members` | Signed-in members, once a coordinator approves it (first name or "Anonymous") |
*
* Never public, never in stats, the heartbeat, AI or an email's text: messages say only that there's
* something to look at, with a link. The prayer team sees who sent a request unless it's fully
* anonymous (P9, when the church allows it). An escalated request goes to Pastoral care at once and
* leaves the shared list; its submitter sees nothing different.
*
* Three views of a request, and nothing else leaves this file: the submitter's own (`mine`), what
* members see (`shared`), and the team's (`forTeam`, with the sender: access-logged by the caller).
*/
import type { Ctx } from '../context.js';
import type { AppRole, PrayerRequest, PrayerRequestUpdate } from '../generated/prisma/client.js';
import { ApiError } from '../http.js';
import { enqueue } from '../lib/outbox.js';
import { FULL_ROLES } from '../auth/sessions.js';
import { requestSettings } from './settings.js';
const DAY = 86400e3;
export const REQUEST_MAX = 2000;
export const UPDATE_MAX = 1000;
type Row = PrayerRequest & { updates?: PrayerRequestUpdate[]; prayers?: { memberId: string }[] };
const firstName = (name: string | undefined) => name?.trim().split(/\s+/)[0] || 'Anonymous';
/** What the submitter sees of the state (an escalation never shows, §4). */
export function submitterStatus(r: PrayerRequest): 'closed' | 'with_team' | 'waiting' | 'shared' | 'not_shared' {
if (r.closedAt) return 'closed';
if (r.visibility === 'team') return 'with_team';
return r.moderation === 'approved' ? 'shared' : r.moderation === 'removed' ? 'not_shared' : 'waiting';
}
const updatesOf = (r: Row, who: 'all' | 'submitter') =>
(r.updates ?? []).filter((u) => who === 'all' || u.author === 'submitter').sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
.map((u) => ({ id: u.id, author: u.author as 'submitter' | 'team', text: u.text, createdAt: u.createdAt.toISOString() }));
export function mine(r: Row) {
return {
id: r.id, text: r.text, visibility: r.visibility, showName: r.showName, anonymous: r.anonymous,
status: submitterStatus(r), redactionNote: r.redactedAt ? r.redactionNote : null, removedReason: r.moderation === 'removed' ? r.removedReason : null,
prayedCount: r.prayers?.length ?? 0, updates: updatesOf(r, 'all'),
closesAt: r.closesAt.toISOString(), closedAt: r.closedAt?.toISOString() ?? null, createdAt: r.createdAt.toISOString(),
};
}
export function shared(r: Row, submitterName: string | undefined, memberId: string) {
return {
id: r.id, text: r.text, by: r.showName ? firstName(submitterName) : 'Anonymous',
prayedCount: r.prayers?.length ?? 0, iPrayed: (r.prayers ?? []).some((p) => p.memberId === memberId),
updates: updatesOf(r, 'submitter'), createdAt: r.createdAt.toISOString(), mine: r.memberId === memberId,
};
}
export function forTeam(r: Row, submitter: { name: string; email: string; phone: string | null } | undefined) {
return {
...mine(r),
moderation: r.moderation,
submitter: r.anonymous ? null : submitter ?? null,
escalated: r.escalatedAt ? { at: r.escalatedAt.toISOString(), note: r.escalationNote } : null,
redacted: !!r.redactedAt,
};
}
/** Where the shared list's filter lives, so no other query can show members something it shouldn't. */
export const SHARED_WHERE = { visibility: 'members', moderation: 'approved', closedAt: null, escalatedAt: null } as const;
/** People with any of `roles` (or a full role), for the team's messages. */
async function membersWith(ctx: Ctx, roles: readonly AppRole[]) {
const all = await ctx.db.member.findMany({ where: { roles: { isEmpty: false } }, select: { id: true, roles: true } });
return all.filter((m) => m.roles.some((r) => roles.includes(r)));
}
/** "You have a new prayer request" to the prayer coordinators (no text, §4). */
async function tellCoordinators(ctx: Ctx, r: PrayerRequest) {
let people = await membersWith(ctx, ['prayer_coordinator']);
if (!people.length) people = await membersWith(ctx, FULL_ROLES);
for (const p of people) {
if (p.id === r.memberId) continue;
await enqueue(ctx, { memberId: p.id, kind: 'request-new', channel: 'email', dedupeKey: `request-new:${r.id}:${p.id}`, payload: { requestId: r.id, needsApproval: r.moderation === 'pending', path: '/admin/requests' } });
}
}
/** Tells the submitter something changed (approved, redacted, removed, a reply, prayed): never the text. */
async function tellSubmitter(ctx: Ctx, r: PrayerRequest, what: 'approved' | 'redacted' | 'removed' | 'reply' | 'prayed', extra: object = {}) {
const key = what === 'prayed' ? `request-prayed:${r.id}:${ctx.now().toISOString().slice(0, 10)}` : `request-${what}:${r.id}:${ctx.now().getTime()}`;
await enqueue(ctx, { memberId: r.memberId, kind: 'request-update', channel: 'email', dedupeKey: key, payload: { requestId: r.id, what, path: '/me/requests', ...extra } });
}
export type NewRequest = { text: string; visibility: 'team' | 'members'; showName?: boolean; anonymous?: boolean };
export async function submit(ctx: Ctx, memberId: string, input: NewRequest) {
const settings = await requestSettings(ctx);
if (input.anonymous && !settings.anonymousAllowed) throw new ApiError(400, 'ANONYMOUS_OFF', 'The church doesn\'t take fully anonymous requests: the prayer team sees who sent it, so they can follow up.');
const r = await ctx.db.prayerRequest.create({
data: {
memberId, text: input.text.trim(), visibility: input.visibility,
showName: input.visibility === 'members' ? !!input.showName : false,
anonymous: !!input.anonymous,
moderation: input.visibility === 'members' ? 'pending' : 'none',
closesAt: new Date(ctx.now().getTime() + settings.closeAfterDays * DAY),
},
});
await tellCoordinators(ctx, r);
return r;
}
export async function own(ctx: Ctx, memberId: string, id: string): Promise<Row> {
const r = await ctx.db.prayerRequest.findUnique({ where: { id }, include: { updates: true, prayers: true } }) as Row | null;
if (!r || r.memberId !== memberId) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such prayer request.');
return r;
}
export async function anyRequest(ctx: Ctx, id: string): Promise<Row> {
const r = await ctx.db.prayerRequest.findUnique({ where: { id }, include: { updates: true, prayers: true } }) as Row | null;
if (!r) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such prayer request.');
return r;
}
/** "Answered!" or any update from the submitter, shown with the request. */
export async function addUpdate(ctx: Ctx, memberId: string, id: string, text: string) {
const r = await own(ctx, memberId, id);
if (r.closedAt) throw new ApiError(409, 'CLOSED', 'This request is closed.');
await ctx.db.prayerRequestUpdate.create({ data: { requestId: id, author: 'submitter', authorId: memberId, text: text.trim() } });
}
export async function close(ctx: Ctx, memberId: string, id: string) {
const r = await own(ctx, memberId, id);
if (!r.closedAt) await ctx.db.prayerRequest.update({ where: { id }, data: { closedAt: ctx.now() } });
}
export async function deleteOwn(ctx: Ctx, memberId: string, id: string) {
await own(ctx, memberId, id);
await ctx.db.prayerRequest.delete({ where: { id } });
}
/** "I prayed" on a shared request (once per member); the submitter hears at most once a day. */
export async function prayFor(ctx: Ctx, memberId: string, id: string) {
const r = await ctx.db.prayerRequest.findFirst({ where: { id, ...SHARED_WHERE } });
if (!r) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such prayer request.');
const before = await ctx.db.requestPrayer.findFirst({ where: { requestId: id, memberId } });
if (!before) {
await ctx.db.requestPrayer.create({ data: { requestId: id, memberId } });
if (r.memberId !== memberId) await tellSubmitter(ctx, r, 'prayed');
}
return { prayedCount: await ctx.db.requestPrayer.count({ where: { requestId: id } }), iPrayed: true };
}
// ── The prayer team ──
export async function approve(ctx: Ctx, byId: string, id: string) {
const r = await anyRequest(ctx, id);
if (r.visibility !== 'members') throw new ApiError(400, 'TEAM_ONLY', 'This request is for the prayer team only: there\'s nothing to approve.');
await ctx.db.prayerRequest.update({ where: { id }, data: { moderation: 'approved', removedReason: null, moderatedById: byId, moderatedAt: ctx.now() } });
await tellSubmitter(ctx, r, 'approved');
}
/** Edits out names or details (§4); the submitter is told what changed (`note`). */
export async function redact(ctx: Ctx, byId: string, id: string, text: string, note: string) {
const r = await anyRequest(ctx, id);
await ctx.db.prayerRequest.update({ where: { id }, data: { text: text.trim(), redactedAt: ctx.now(), redactionNote: note.trim(), moderatedById: byId, moderatedAt: ctx.now() } });
await tellSubmitter(ctx, r, 'redacted');
}
export async function remove(ctx: Ctx, byId: string, id: string, reason: string) {
const r = await anyRequest(ctx, id);
if (r.visibility !== 'members') throw new ApiError(400, 'TEAM_ONLY', 'This request is for the prayer team only: it isn\'t shown to members.');
await ctx.db.prayerRequest.update({ where: { id }, data: { moderation: 'removed', removedReason: reason.trim(), moderatedById: byId, moderatedAt: ctx.now() } });
await tellSubmitter(ctx, r, 'removed');
}
/** A private reply from the prayer team, to the submitter alone. */
export async function reply(ctx: Ctx, byId: string, id: string, text: string) {
const r = await anyRequest(ctx, id);
await ctx.db.prayerRequestUpdate.create({ data: { requestId: id, author: 'team', authorId: byId, text: text.trim() } });
await tellSubmitter(ctx, r, 'reply');
}
/**
* Safeguarding (§4): danger, abuse, self-harm. At once, by email and WhatsApp, to everyone with the
* Pastoral care role (an Owner or Church admin when there's none); the request leaves the shared
* list. Answers how many were told.
*/
export async function escalate(ctx: Ctx, byId: string, id: string, note: string): Promise<{ notified: number; fallback: boolean }> {
const r = await anyRequest(ctx, id);
if (!r.escalatedAt) await ctx.db.prayerRequest.update({ where: { id }, data: { escalatedAt: ctx.now(), escalatedById: byId, escalationNote: note.trim() || null } });
let people = await membersWith(ctx, ['pastoral_care']);
const fallback = !people.some((p) => p.roles.includes('pastoral_care'));
if (fallback) people = await membersWith(ctx, FULL_ROLES);
for (const p of people) {
await enqueue(ctx, { memberId: p.id, kind: 'request-escalated', channel: 'both', dedupeKey: `request-escalated:${id}:${p.id}`, payload: { requestId: id, path: '/admin/requests?view=escalated' } });
}
return { notified: people.length, fallback };
}
/** Closes requests past their date and deletes those closed for 12 months (P10). */
export async function tidyRequests(ctx: Ctx, deleteAfterDays: number) {
const now = ctx.now();
const closed = await ctx.db.prayerRequest.updateMany({ where: { closedAt: null, closesAt: { lte: now } }, data: { closedAt: now } });
const old = await ctx.db.prayerRequest.findMany({ where: { closedAt: { lt: new Date(now.getTime() - deleteAfterDays * DAY) } }, select: { id: true } });
for (const { id } of old) await ctx.db.prayerRequest.delete({ where: { id } });
return { closed: closed.count, deleted: old.length };
}
+46
View File
@@ -0,0 +1,46 @@
/**
* Prayer request rules (Settings → Prayer requests, APP-1.0-PLAN §4), in AppSetting
* `prayer_requests`: when requests close themselves (30 days; 7–90, P10), whether fully anonymous
* requests are allowed (P9, off), and the emergency numbers on the request form (South African by
* default, P19). The safeguarding contacts are the people with the Pastoral care role.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
const KEY = 'prayer_requests';
export const EMERGENCY_DEFAULTS = [
{ label: 'Lifeline', number: '0861 322 322' },
{ label: 'SADAG (depression and anxiety)', number: '0800 567 567' },
{ label: 'Childline', number: '116' },
];
export const requestSettingsSchema = z.object({
closeAfterDays: z.number().int().min(7).max(90),
anonymousAllowed: z.boolean(),
emergencyNumbers: z.array(z.object({ label: z.string().trim().min(1).max(80), number: z.string().trim().min(1).max(40) })).max(8),
});
export type RequestSettings = z.infer<typeof requestSettingsSchema>;
export const DEFAULT_REQUEST_SETTINGS: RequestSettings = { closeAfterDays: 30, anonymousAllowed: false, emergencyNumbers: EMERGENCY_DEFAULTS };
/** Deleted this long after closing (P10). */
export const DELETE_AFTER_CLOSED_DAYS = 365;
export async function requestSettings(ctx: Ctx): Promise<RequestSettings> {
const saved = await ctx.settings.json<Record<string, unknown>>(KEY, {});
const out = { ...DEFAULT_REQUEST_SETTINGS };
for (const k of Object.keys(requestSettingsSchema.shape) as (keyof RequestSettings)[]) {
const parsed = requestSettingsSchema.shape[k].safeParse(saved?.[k]);
if (parsed.success) (out as Record<string, unknown>)[k] = parsed.data;
}
return out;
}
export async function setRequestSettings(ctx: Ctx, change: unknown): Promise<RequestSettings> {
const parsed = requestSettingsSchema.partial().strict().parse(change);
const next = { ...(await requestSettings(ctx)), ...parsed };
await ctx.settings.set(KEY, JSON.stringify(next));
return next;
}