diff --git a/apps/app/backend/prisma/migrations/20261203000000_prayer_requests/migration.sql b/apps/app/backend/prisma/migrations/20261203000000_prayer_requests/migration.sql new file mode 100644 index 0000000..34803ba --- /dev/null +++ b/apps/app/backend/prisma/migrations/20261203000000_prayer_requests/migration.sql @@ -0,0 +1,82 @@ +-- Church App 1.0.0: prayer requests (docs/APP-1.0-PLAN.md §4): requests with their moderation and +-- escalation, updates and replies, and "I prayed" counts. +-- CreateEnum +CREATE TYPE "RequestVisibility" AS ENUM ('team', 'members'); + +-- CreateEnum +CREATE TYPE "RequestModeration" AS ENUM ('none', 'pending', 'approved', 'removed'); + +-- CreateTable +CREATE TABLE "PrayerRequest" ( + "id" TEXT NOT NULL, + "memberId" TEXT NOT NULL, + "text" TEXT NOT NULL, + "visibility" "RequestVisibility" NOT NULL DEFAULT 'team', + "showName" BOOLEAN NOT NULL DEFAULT false, + "anonymous" BOOLEAN NOT NULL DEFAULT false, + "moderation" "RequestModeration" NOT NULL DEFAULT 'none', + "redactedAt" TIMESTAMP(3), + "redactionNote" TEXT, + "removedReason" TEXT, + "moderatedById" TEXT, + "moderatedAt" TIMESTAMP(3), + "escalatedAt" TIMESTAMP(3), + "escalatedById" TEXT, + "escalationNote" TEXT, + "closesAt" TIMESTAMP(3) NOT NULL, + "closedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "PrayerRequest_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "PrayerRequestUpdate" ( + "id" TEXT NOT NULL, + "requestId" TEXT NOT NULL, + "author" TEXT NOT NULL, + "authorId" TEXT, + "text" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "PrayerRequestUpdate_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "RequestPrayer" ( + "id" TEXT NOT NULL, + "requestId" TEXT NOT NULL, + "memberId" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "RequestPrayer_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "PrayerRequest_moderation_createdAt_idx" ON "PrayerRequest"("moderation", "createdAt"); + +-- CreateIndex +CREATE INDEX "PrayerRequest_memberId_idx" ON "PrayerRequest"("memberId"); + +-- CreateIndex +CREATE INDEX "PrayerRequest_closedAt_idx" ON "PrayerRequest"("closedAt"); + +-- CreateIndex +CREATE INDEX "PrayerRequest_closesAt_idx" ON "PrayerRequest"("closesAt"); + +-- CreateIndex +CREATE INDEX "PrayerRequestUpdate_requestId_createdAt_idx" ON "PrayerRequestUpdate"("requestId", "createdAt"); + +-- CreateIndex +CREATE UNIQUE INDEX "RequestPrayer_requestId_memberId_key" ON "RequestPrayer"("requestId", "memberId"); + +-- AddForeignKey +ALTER TABLE "PrayerRequest" ADD CONSTRAINT "PrayerRequest_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "Member"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "PrayerRequestUpdate" ADD CONSTRAINT "PrayerRequestUpdate_requestId_fkey" FOREIGN KEY ("requestId") REFERENCES "PrayerRequest"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "RequestPrayer" ADD CONSTRAINT "RequestPrayer_requestId_fkey" FOREIGN KEY ("requestId") REFERENCES "PrayerRequest"("id") ON DELETE CASCADE ON UPDATE CASCADE; + diff --git a/apps/app/backend/prisma/schema.prisma b/apps/app/backend/prisma/schema.prisma index f0f9d45..9a24d24 100644 --- a/apps/app/backend/prisma/schema.prisma +++ b/apps/app/backend/prisma/schema.prisma @@ -49,6 +49,7 @@ model Member { prayerCommitments PrayerCommitment[] testimonies Testimony[] outboxMessages OutboxMessage[] + prayerRequests PrayerRequest[] @@index([lastActiveAt]) } @@ -284,3 +285,84 @@ model OutboxMessage { @@index([sentAt, sendAfter]) } + +// ── Prayer requests (§4) ───────────────────────────────────────────────────────────────────── +// Special personal information (POPIA s26): never in stats, the heartbeat, AI or an email's text. +// The rules (closing after 30 days, fully anonymous requests, emergency numbers) are in AppSetting +// `prayer_requests`. Every view of a request with its sender goes in the access log. + +/// Who sees a request (P8): the prayer team only (the default), or members after approval. +enum RequestVisibility { + team + members +} + +/// A shared request's moderation: waiting, approved (shown to members) or removed (with a reason). +/// Team-only requests are never moderated (`none`). +enum RequestModeration { + none + pending + approved + removed +} + +model PrayerRequest { + id String @id @default(uuid()) + memberId String + member Member @relation(fields: [memberId], references: [id], onDelete: Cascade) + text String + visibility RequestVisibility @default(team) + /// For members: show the submitter's first name (else "Anonymous"). + showName Boolean @default(false) + /// Fully anonymous (P9, when the church allows it): the prayer team doesn't see who sent it either. + anonymous Boolean @default(false) + moderation RequestModeration @default(none) + /// A coordinator edited out names or details; the submitter is told what changed. + redactedAt DateTime? + redactionNote String? + removedReason String? + moderatedById String? + moderatedAt DateTime? + /// Safeguarding (§4): sent to Pastoral care at once; it leaves the shared list; the submitter sees nothing different. + escalatedAt DateTime? + escalatedById String? + escalationNote String? + /// Closes itself then (30 days by default), unless closed before. + closesAt DateTime + closedAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + updates PrayerRequestUpdate[] + prayers RequestPrayer[] + + @@index([moderation, createdAt]) + @@index([memberId]) + @@index([closedAt]) + @@index([closesAt]) +} + +/// "Answered!" from the submitter (shown with the request), or a private reply from the prayer team +/// (to the submitter alone). +model PrayerRequestUpdate { + id String @id @default(uuid()) + requestId String + request PrayerRequest @relation(fields: [requestId], references: [id], onDelete: Cascade) + /// `submitter` or `team`. + author String + authorId String? + text String + createdAt DateTime @default(now()) + + @@index([requestId, createdAt]) +} + +/// "I prayed" on a shared request: the submitter sees how many, never who. +model RequestPrayer { + id String @id @default(uuid()) + requestId String + request PrayerRequest @relation(fields: [requestId], references: [id], onDelete: Cascade) + memberId String + createdAt DateTime @default(now()) + + @@unique([requestId, memberId]) +} diff --git a/apps/app/backend/src/app.ts b/apps/app/backend/src/app.ts index f0434d0..54ac601 100644 --- a/apps/app/backend/src/app.ts +++ b/apps/app/backend/src/app.ts @@ -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) => { diff --git a/apps/app/backend/src/auth/routes.ts b/apps/app/backend/src/auth/routes.ts index 3f48e7d..d540f3d 100644 --- a/apps/app/backend/src/auth/routes.ts +++ b/apps/app/backend/src/auth/routes.ts @@ -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) }); diff --git a/apps/app/backend/src/http.ts b/apps/app/backend/src/http.ts index d8521e0..ee11d99 100644 --- a/apps/app/backend/src/http.ts +++ b/apps/app/backend/src/http.ts @@ -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) { @@ -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(schema: z.ZodType, 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) { diff --git a/apps/app/backend/src/jobs.ts b/apps/app/backend/src/jobs.ts index 616d437..4a0b2df 100644 --- a/apps/app/backend/src/jobs.ts +++ b/apps/app/backend/src/jobs.ts @@ -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 }; 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) }, ]; diff --git a/apps/app/backend/src/lib/accessLog.ts b/apps/app/backend/src/lib/accessLog.ts new file mode 100644 index 0000000..1077f9f --- /dev/null +++ b/apps/app/backend/src/lib/accessLog.ts @@ -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) } }); +} diff --git a/apps/app/backend/src/lib/outbox.ts b/apps/app/backend/src/lib/outbox.ts index 1afb980..e23fb87 100644 --- a/apps/app/backend/src/lib/outbox.ts +++ b/apps/app/backend/src/lib/outbox.ts @@ -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). */ diff --git a/apps/app/backend/src/prayer/admin.ts b/apps/app/backend/src/prayer/admin.ts index 98f6104..bb19749 100644 --- a/apps/app/backend/src/prayer/admin.ts +++ b/apps/app/backend/src/prayer/admin.ts @@ -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), diff --git a/apps/app/backend/src/prayer/routes.ts b/apps/app/backend/src/prayer/routes.ts index 2ed3054..37a00ea 100644 --- a/apps/app/backend/src/prayer/routes.ts +++ b/apps/app/backend/src/prayer/routes.ts @@ -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(schema: z.ZodType, 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; diff --git a/apps/app/backend/src/requests/members.ts b/apps/app/backend/src/requests/members.ts new file mode 100644 index 0000000..7a8e02e --- /dev/null +++ b/apps/app/backend/src/requests/members.ts @@ -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 { + 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 { + 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 } }); +} diff --git a/apps/app/backend/src/requests/routes.ts b/apps/app/backend/src/requests/routes.ts new file mode 100644 index 0000000..a775f8b --- /dev/null +++ b/apps/app/backend/src/requests/routes.ts @@ -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; +} diff --git a/apps/app/backend/src/requests/service.ts b/apps/app/backend/src/requests/service.ts new file mode 100644 index 0000000..e3374e9 --- /dev/null +++ b/apps/app/backend/src/requests/service.ts @@ -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 { + 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 { + 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 }; +} diff --git a/apps/app/backend/src/requests/settings.ts b/apps/app/backend/src/requests/settings.ts new file mode 100644 index 0000000..75a4d04 --- /dev/null +++ b/apps/app/backend/src/requests/settings.ts @@ -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; + +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 { + const saved = await ctx.settings.json>(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)[k] = parsed.data; + } + return out; +} + +export async function setRequestSettings(ctx: Ctx, change: unknown): Promise { + const parsed = requestSettingsSchema.partial().strict().parse(change); + const next = { ...(await requestSettings(ctx)), ...parsed }; + await ctx.settings.set(KEY, JSON.stringify(next)); + return next; +} diff --git a/apps/app/backend/tests/requests.test.ts b/apps/app/backend/tests/requests.test.ts new file mode 100644 index 0000000..c2a1448 --- /dev/null +++ b/apps/app/backend/tests/requests.test.ts @@ -0,0 +1,192 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import request from 'supertest'; +import { tidyRequests } from '../src/requests/service.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 CARE = '66666666-6666-4666-8666-666666666666'; +const DAY = 24 * 3600e3; +const SECRET = 'My brother Themba is in hospital after the accident'; + +async function setup() { + const h = await harness() as Harness; + const as = (cookies: Record) => ({ + 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), + 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'), + }); + const thandi = as(await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test' })); + const pieter = as(await signInAs(h, { sub: OTHER, name: 'Pieter Botha', email: 'pieter@hope.test' })); + const coord = as(await signInAs(h, { sub: COORD, name: 'Lerato Dlamini', roles: ['prayer_coordinator'] }, true)); + const care = as(await signInAs(h, { sub: CARE, name: 'Pastor Sam', roles: ['pastoral_care'] }, true)); + return { h, thandi, pieter, coord, care, visitor: as({}) }; +} + +const outbox = (h: Harness) => [...(h.db.tables.get('outboxMessage')?.values() ?? [])] as { memberId: string; kind: string; channel: string; payload: Record }[]; + +describe('asking for prayer', () => { + it('is private by default: the prayer team sees it with the sender, members and visitors never do', async () => { + const { h, thandi, pieter, coord, visitor } = await setup(); + const res = await thandi.post('/api/v1/me/requests', { text: SECRET }); + assert.equal(res.status, 201); + assert.equal(res.body.status, 'with_team'); + assert.equal((await visitor.get('/api/v1/requests')).status, 401); + assert.deepEqual((await pieter.get('/api/v1/requests')).body.requests, []); + const team = await coord.get('/api/v1/admin/requests?view=open'); + assert.equal(team.body.requests[0].text, SECRET); + assert.equal(team.body.requests[0].submitter.name, 'Thandi Mokoena'); + const log = [...h.db.tables.get('accessLog')!.values()] as { actorId: string; action: string }[]; + assert.deepEqual(log.map((l) => [l.actorId, l.action]), [[COORD, 'prayer_requests_viewed']]); + // The coordinator is told there's a request, never what it says. + const [m] = outbox(h); + assert.equal(m!.memberId, COORD); + assert.equal(m!.kind, 'request-new'); + assert.ok(!JSON.stringify(m).includes('Themba')); + }); + + it('shows the form\'s facts publicly: emergency numbers and the closing days, nothing else', async () => { + const { visitor } = await setup(); + const form = await visitor.get('/api/v1/requests/form'); + assert.equal(form.status, 200); + assert.equal(form.body.anonymousAllowed, false); + assert.deepEqual(form.body.emergencyNumbers.map((n: { number: string }) => n.number), ['0861 322 322', '0800 567 567', '116']); + assert.equal(form.body.closeAfterDays, 30); + }); + + it('refuses a fully anonymous request unless the church allows them; then hides the sender from the team too', async () => { + const { thandi, coord } = await setup(); + assert.equal((await thandi.post('/api/v1/me/requests', { text: SECRET, anonymous: true })).body.error.code, 'ANONYMOUS_OFF'); + assert.equal((await coord.put('/api/v1/admin/requests/settings', { anonymousAllowed: true })).status, 200); + assert.equal((await thandi.post('/api/v1/me/requests', { text: SECRET, anonymous: true })).status, 201); + const team = await coord.get('/api/v1/admin/requests?view=open'); + assert.equal(team.body.requests[0].submitter, null); + assert.ok(!JSON.stringify(team.body).includes('Thandi')); + assert.ok(!JSON.stringify(team.body).includes(MEMBER)); + }); + + it('a shared request waits for approval, then members see it with the first name or "Anonymous"', async () => { + const { h, thandi, pieter, coord } = await setup(); + const { id } = (await thandi.post('/api/v1/me/requests', { text: 'Pray for our exams next week', visibility: 'members', showName: true })).body; + assert.deepEqual((await pieter.get('/api/v1/requests')).body.requests, []); + assert.equal((await coord.get('/api/v1/admin/requests?view=queue')).body.requests.length, 1); + assert.equal((await pieter.post(`/api/v1/admin/requests/${id}/approve`)).status, 403); + assert.equal((await coord.post(`/api/v1/admin/requests/${id}/approve`)).status, 200); + const list = (await pieter.get('/api/v1/requests')).body.requests; + assert.equal(list[0].by, 'Thandi'); + assert.equal(list[0].text, 'Pray for our exams next week'); + assert.deepEqual(Object.keys(list[0]).sort(), ['by', 'createdAt', 'iPrayed', 'id', 'mine', 'prayedCount', 'text', 'updates']); + assert.equal((await thandi.get('/api/v1/me/requests')).body.requests[0].status, 'shared'); + assert.ok(outbox(h).some((m) => m.memberId === MEMBER && m.payload.what === 'approved')); + }); + + it('counts "I prayed" once per member and shows the sender how many, not who', async () => { + const { thandi, pieter, coord } = await setup(); + const { id } = (await thandi.post('/api/v1/me/requests', { text: 'Pray for rain on the farm', visibility: 'members' })).body; + assert.equal((await pieter.post(`/api/v1/requests/${id}/prayed`)).status, 404); + await coord.post(`/api/v1/admin/requests/${id}/approve`); + await pieter.post(`/api/v1/requests/${id}/prayed`); + const again = await pieter.post(`/api/v1/requests/${id}/prayed`); + assert.deepEqual(again.body, { prayedCount: 1, iPrayed: true }); + const mine = (await thandi.get('/api/v1/me/requests')).body.requests[0]; + assert.equal(mine.prayedCount, 1); + assert.ok(!JSON.stringify(mine).includes('Pieter')); + assert.ok(!JSON.stringify(mine).includes(OTHER)); + }); + + it('redacts with a note to the sender, or removes with a reason', async () => { + const { thandi, coord, pieter } = await setup(); + const a = (await thandi.post('/api/v1/me/requests', { text: SECRET, visibility: 'members' })).body; + assert.equal((await coord.post(`/api/v1/admin/requests/${a.id}/redact`, { text: 'Pray for my brother in hospital', note: '' })).status, 400); + await coord.post(`/api/v1/admin/requests/${a.id}/redact`, { text: 'Pray for my brother in hospital', note: 'We took out his name.' }); + await coord.post(`/api/v1/admin/requests/${a.id}/approve`); + assert.equal((await pieter.get('/api/v1/requests')).body.requests[0].text, 'Pray for my brother in hospital'); + const b = (await thandi.post('/api/v1/me/requests', { text: 'Something about a colleague', visibility: 'members' })).body; + await coord.post(`/api/v1/admin/requests/${b.id}/remove`, { reason: 'It names someone at work.' }); + const mine = (await thandi.get('/api/v1/me/requests')).body.requests; + const byId = Object.fromEntries(mine.map((r: { id: string }) => [r.id, r])); + assert.equal(byId[a.id].redactionNote, 'We took out his name.'); + assert.equal(byId[b.id].status, 'not_shared'); + assert.equal(byId[b.id].removedReason, 'It names someone at work.'); + }); + + it('escalates to Pastoral care by email and WhatsApp at once; it leaves the shared list; the sender sees nothing different', async () => { + const { h, thandi, pieter, coord, care } = await setup(); + const { id } = (await thandi.post('/api/v1/me/requests', { text: 'I don\'t feel safe at home', visibility: 'members' })).body; + await coord.post(`/api/v1/admin/requests/${id}/approve`); + const before = (await thandi.get('/api/v1/me/requests')).body.requests[0]; + const res = await coord.post(`/api/v1/admin/requests/${id}/escalate`, { note: 'Danger at home' }); + assert.deepEqual([res.body.notified, res.body.fallback], [1, false]); + const sent = outbox(h).find((m) => m.kind === 'request-escalated')!; + assert.deepEqual([sent.memberId, sent.channel], [CARE, 'both']); + assert.ok(!JSON.stringify(sent).includes('safe')); + assert.deepEqual((await pieter.get('/api/v1/requests')).body.requests, []); + assert.deepEqual((await thandi.get('/api/v1/me/requests')).body.requests[0], before); + const esc = await care.get('/api/v1/admin/requests?view=escalated'); + assert.equal(esc.body.requests[0].escalated.note, 'Danger at home'); + assert.equal((await care.get('/api/v1/admin/requests?view=queue')).status, 403); + }); + + it('tells an Owner or Church admin when nobody has the Pastoral care role', async () => { + const h = await harness() as Harness; + const thandi = await signInAs(h, { sub: MEMBER, name: 'Thandi' }); + const coord = await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true); + await h.db.member.create({ data: { id: 'owner-1', name: 'Pastor Sam', email: 'p@hope.test', roles: ['owner'] } }); + const { id } = (await request(h.app).post('/api/v1/me/requests').set('Cookie', cookieHeader(thandi)).set('Origin', 'https://app.hope.test').send({ text: 'Please help me, urgently' })).body; + const res = await request(h.app).post(`/api/v1/admin/requests/${id}/escalate`).set('Cookie', cookieHeader(coord)).set('Origin', 'https://app.hope.test').send({}); + assert.deepEqual([res.body.notified, res.body.fallback], [1, true]); + }); + + it('lets the sender add "Answered!", read the team\'s private reply, close it and delete it', async () => { + const { thandi, pieter, coord } = await setup(); + const { id } = (await thandi.post('/api/v1/me/requests', { text: 'Pray for my job interview', visibility: 'members' })).body; + await coord.post(`/api/v1/admin/requests/${id}/approve`); + await coord.post(`/api/v1/admin/requests/${id}/reply`, { text: 'We are praying. Let us know how it goes.' }); + await thandi.post(`/api/v1/me/requests/${id}/updates`, { text: 'Answered! I got the job.' }); + const shared = (await pieter.get('/api/v1/requests')).body.requests[0]; + assert.deepEqual(shared.updates.map((u: { text: string }) => u.text), ['Answered! I got the job.']); + const mine = (await thandi.get('/api/v1/me/requests')).body.requests[0]; + assert.deepEqual(mine.updates.map((u: { author: string }) => u.author), ['team', 'submitter']); + await thandi.post(`/api/v1/me/requests/${id}/close`); + assert.deepEqual((await pieter.get('/api/v1/requests')).body.requests, []); + assert.equal((await pieter.del(`/api/v1/me/requests/${id}`)).status, 404); + assert.equal((await thandi.del(`/api/v1/me/requests/${id}`)).status, 200); + }); + + it('closes requests after 30 days and deletes them 12 months after closing', async () => { + const { h, thandi } = await setup(); + await thandi.post('/api/v1/me/requests', { text: 'Pray for my family' }); + h.clock.add(29 * DAY); + assert.deepEqual(await tidyRequests(h.ctx, 365), { closed: 0, deleted: 0 }); + h.clock.add(2 * DAY); + assert.deepEqual(await tidyRequests(h.ctx, 365), { closed: 1, deleted: 0 }); + h.clock.add(366 * DAY); + assert.deepEqual(await tidyRequests(h.ctx, 365), { closed: 0, deleted: 1 }); + }); + + it('is switched off with its module', async () => { + const { h, thandi } = await setup(); + await h.ctx.settings.set('modules', JSON.stringify({ 'prayer-requests': false })); + assert.equal((await thandi.post('/api/v1/me/requests', { text: SECRET })).body.error.code, 'MODULE_OFF'); + }); + + it('never puts a request in the heartbeat; exports and deletes a member\'s requests', async () => { + const { h, thandi, pieter, coord } = await setup(); + const { id } = (await thandi.post('/api/v1/me/requests', { text: SECRET, visibility: 'members' })).body; + await coord.post(`/api/v1/admin/requests/${id}/approve`); + await pieter.post(`/api/v1/requests/${id}/prayed`); + const { stats } = await import('../src/hub/client.js'); + assert.ok(!JSON.stringify(await stats(h.ctx)).includes('Themba')); + 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: '77777777-7777-4777-8777-777777777777', occurredAt: '2026-12-01T06:00:00.000Z', sub: MEMBER, type, ...extra })); + const exp = await call('user.export', { exportId: '88888888-8888-4888-8888-888888888888' }); + const section = exp.body.sections.find((s: { key: string }) => s.key === 'app_prayer_requests'); + assert.equal(section.records[0].text, SECRET); + assert.equal(section.records[0].whoSees, 'Members of the church'); + await call('user.deleted'); + assert.equal(await h.db.prayerRequest.count(), 0); + assert.equal(await h.db.requestPrayer.count(), 0); + }); +}); diff --git a/apps/app/backend/tests/support/memoryDb.ts b/apps/app/backend/tests/support/memoryDb.ts index 80eabc0..02363e6 100644 --- a/apps/app/backend/tests/support/memoryDb.ts +++ b/apps/app/backend/tests/support/memoryDb.ts @@ -20,14 +20,17 @@ const DEFAULTS: Record Row> = { 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 }), + prayerRequest: () => ({ visibility: 'team', showName: false, anonymous: false, moderation: 'none', redactedAt: null, redactionNote: null, removedReason: null, moderatedById: null, moderatedAt: null, escalatedAt: null, escalatedById: null, escalationNote: null, closedAt: null }), + prayerRequestUpdate: () => ({ authorId: null }), }; const KEYS: Record = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' }; /** Unique fields: one field, or several together (`@@unique([a, b])`). */ -const UNIQUE: Record = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']] }; -const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign']); +const UNIQUE: Record = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']] }; +const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest']); /** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */ const RELATIONS: Record> = { member: { sessions: { model: 'session', many: true, key: 'memberId' } }, + prayerRequest: { updates: { model: 'prayerRequestUpdate', many: true, key: 'requestId' }, prayers: { model: 'requestPrayer', many: true, key: 'requestId' } }, prayerCommitment: { skips: { model: 'prayerSkip', many: true, key: 'commitmentId' }, marks: { model: 'prayedMark', many: true, key: 'commitmentId' } }, }; @@ -48,6 +51,7 @@ function matchValue(actual: unknown, cond: unknown): boolean { case 'lt': return actual != null && (v(actual) as number) < (v(x) as number); case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number); case 'not': return x === null ? actual != null : !matchValue(actual, x); + case 'isEmpty': return Array.isArray(actual) && (actual.length === 0) === x; case 'has': return Array.isArray(actual) && actual.map(v).includes(v(x)); case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x))); default: throw new Error(`memoryDb: no operator ${op}`); @@ -159,9 +163,10 @@ function model(name: string, tables: Map>) { const cascade = (from: string, id: unknown) => { 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 === 'member') { drop('session', 'memberId'); drop('testimony', 'memberId'); drop('outboxMessage', 'memberId'); drop('prayerRequest', 'memberId'); unset('prayerCommitment', 'memberId'); } if (from === 'prayerCommitment') { drop('prayerSkip', 'commitmentId'); drop('prayedMark', 'commitmentId'); } if (from === 'prayerCampaign') unset('testimony', 'campaignId'); + if (from === 'prayerRequest') { drop('prayerRequestUpdate', 'requestId'); drop('requestPrayer', 'requestId'); } }; const withIncludes = (row: Row, include?: Row) => { for (const [rel, on] of Object.entries(include ?? {})) {