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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 10:29:39 +02:00
co-authored by Claude Opus 5.5
parent 6726518175
commit 5213bb36c0
23 changed files with 2376 additions and 30 deletions
+9 -2
View File
@@ -10,9 +10,12 @@
* /api/links/v1/… Connect and Disconnect with the church's other products
* /api/church/v1/changed Accounts: the church profile changed
* /api/v1/admin/… the admin (a role above Member, with 2FA)
* /api/v1/prayer/… the House of Prayer: the day's clock, live coverage (SSE), campaign,
* 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
*
* To come with the modules (§1): the public content API, the member API (/api/v1/me/…), live
* coverage (/api/v1/prayer/stream) and the event feed.
* To come with the modules (§1): the rest of the public content and member API, and the event feed.
*/
import express from 'express';
import type { Ctx } from './context.js';
@@ -23,6 +26,8 @@ import { ApiError, handle, sendError } from './http.js';
import { appVersion } from './lib/version.js';
import { linksRouter } from './links/routes.js';
import { appInfo } from './public/app.js';
import { prayerAdminRouter } from './prayer/admin.js';
import { prayerRouter } from './prayer/routes.js';
export function createApp(ctx: Ctx) {
const app = express();
@@ -50,6 +55,8 @@ export function createApp(ctx: Ctx) {
app.use('/api', authRouter(ctx));
app.use('/api', linksRouter(ctx));
app.use('/api', prayerRouter(ctx));
app.use('/api/v1/admin/prayer', prayerAdminRouter(ctx));
app.use('/api/v1/admin', adminRouter(ctx));
app.use('/api', (_req, res) => {
+6 -4
View File
@@ -18,6 +18,7 @@
* exact page it started from (ROADMAP-v3 §3).
*/
import express, { type Request, type Response } from 'express';
import { deletePrayer, exportPrayer } from '../prayer/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';
@@ -183,9 +184,9 @@ export function authRouter(ctx: Ctx) {
}
/**
* Accounts' signed calls (§11). So far the App keeps a member's profile copy, roles and sign-ins;
* each module adds its own records to the export and the delete as it arrives (commitments, "I
* prayed" marks, requests, testimonies, notification settings). Someone the App doesn't know is
* Accounts' signed calls (§11): a member's profile copy, roles and sign-ins, and the House of
* Prayer's commitments, "I prayed" marks and testimonies (prayer/members.ts). Each later module
* adds its own records to the export and the delete (requests, notification settings). Someone the App doesn't know is
* answered as done.
*/
export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Request): Promise<object> {
@@ -202,12 +203,13 @@ 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))] : [],
};
return reply;
}
case 'user.deleted': {
if (member) {
await deletePrayer(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) });
+5
View File
@@ -69,3 +69,8 @@ export function churchChanged(ctx: Ctx): void {
const state = caches.get(ctx);
if (state?.cached) state.cached = { ...state.cached, at: 0 };
}
/** The church's timezone: the profile's, else APP_TIMEZONE (§1). Days and prayer slots are in it. */
export async function churchTimezone(ctx: Ctx): Promise<string> {
return (await churchProfile(ctx))?.timezone ?? ctx.config.timezone;
}
+4 -3
View File
@@ -19,6 +19,7 @@ import { keyPair, saveLinkedProducts } from '../links/store.js';
import { activeMembers } from '../members/activity.js';
import { enabledModules } from '../modules.js';
import { hubPublicKey, verifyToken } from './licence.js';
import { prayerStats } from '../prayer/service.js';
import { jobsHealth } from '../jobs.js';
export const PROTOCOL_VERSION = 2;
@@ -74,15 +75,15 @@ export async function health(ctx: Ctx) {
}
/**
* Aggregate counts only (hub.appStatsSchema). Prayer coverage, commitments, announcements and
* messages are 0 until their modules arrive.
* Aggregate counts only (hub.appStatsSchema): prayer coverage of the last 7 days and active
* commitments (no names, no times). Announcements and messages are 0 until their modules arrive.
*/
export async function stats(ctx: Ctx): Promise<z.infer<typeof hub.appStatsSchema>> {
const [{ band }, modules] = await Promise.all([activeMembers(ctx), enabledModules(ctx)]);
return {
activeMembers90d: band,
modules,
prayer: { coverageLast7dPercent: 0, activeCommitments: 0 },
prayer: modules.includes('house-of-prayer') ? await prayerStats(ctx) : { coverageLast7dPercent: 0, activeCommitments: 0 },
announcements: { last30d: 0 },
messages: { email30d: 0, whatsapp30d: 0 },
};
+5 -2
View File
@@ -3,8 +3,8 @@
* however many processes run, and timers in this process if the queue can't start.
* JOBS_ENABLED=false turns them all off.
*
* So far only the Hub heartbeat. The modules add theirs (APP-1.0-PLAN §1): reminders, renewals,
* the event feed, Cross Code's devotionals (the next 2 weeks, today included, once a night, §6),
* The Hub heartbeat and the House of Prayer's reminders and renewal notices (prayer/jobs.ts). The
* modules add theirs (APP-1.0-PLAN §1): the event feed, Cross Code's devotionals (the next 2 weeks, today included, once a night, §6),
* announcement and devotional sends, and the nightly backup.
*
* Settings → Background jobs (§10) shows each job's schedule and last runs, runs one now, and
@@ -16,11 +16,14 @@ import { CronExpressionParser } from 'cron-parser';
import PgBoss from 'pg-boss';
import type { Ctx } from './context.js';
import { heartbeat } from './hub/client.js';
import { sendReminders, sendRenewalNotices } from './prayer/jobs.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-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) },
];
const SCHEMA = 'pgboss_app';
+23
View File
@@ -0,0 +1,23 @@
/**
* Messages to send (APP-1.0-PLAN §8), written once each (`dedupeKey`) by whatever decides one is
* due: prayer reminders and renewal notices (prayer/jobs.ts), and the later modules' sends. The
* messaging job sends them by email and/or WhatsApp with the church's settings from Accounts,
* checking the WhatsApp STOP first (§8, decision 11).
*
* `payload` holds the facts the message is built from (times, links), never a prayer request's text.
*/
import type { Ctx } from '../context.js';
export type OutboxKind = 'prayer-reminder' | 'prayer-renewal' | 'testimony-removed';
export type Channel = 'email' | 'whatsapp' | 'both';
/** Queues a message; false when one with the same key was already queued (never sent twice). */
export async function enqueue(ctx: Ctx, m: { memberId: string; kind: OutboxKind; channel: Channel; dedupeKey: string; payload: object; sendAfter?: Date }): Promise<boolean> {
try {
await ctx.db.outboxMessage.create({ data: { memberId: m.memberId, kind: m.kind, channel: m.channel, dedupeKey: m.dedupeKey, payload: m.payload as never, sendAfter: m.sendAfter ?? ctx.now() } });
return true;
} catch (e) {
if ((e as { code?: string }).code === 'P2002') return false;
throw e;
}
}
+119
View File
@@ -0,0 +1,119 @@
/**
* Local dates and times in the church's timezone (APP-1.0-PLAN §1), with `Intl` only. A local day
* is a `YYYY-MM-DD` string and a time in it is minutes after midnight; instants are UTC `Date`s.
*
* Daylight saving: a local time that doesn't exist (the hour the clocks jump forward) has no
* instant (`zonedTime` answers null); a local time that happens twice (the hour the clocks go
* back) means its first instant. South Africa has neither, but a church elsewhere may.
*/
const formatters = new Map<string, Intl.DateTimeFormat>();
function formatter(tz: string): Intl.DateTimeFormat {
let f = formatters.get(tz);
if (!f) {
f = new Intl.DateTimeFormat('en-CA', { timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });
formatters.set(tz, f);
}
return f;
}
function parts(at: Date, tz: string) {
const out: Record<string, number> = {};
for (const p of formatter(tz).formatToParts(at)) if (p.type !== 'literal') out[p.type] = Number(p.value);
return out as { year: number; month: number; day: number; hour: number; minute: number; second: number };
}
const pad = (n: number, w = 2) => String(n).padStart(w, '0');
/** Whether `tz` is a timezone `Intl` knows. */
export function isTimezone(tz: string): boolean {
try {
formatter(tz);
return true;
} catch {
return false;
}
}
/** The local date, minute of the day and weekday (0 = Sunday) of an instant in `tz`. */
export function localParts(at: Date, tz: string): { date: string; minute: number; weekday: number } {
const p = parts(at, tz);
const date = `${pad(p.year, 4)}-${pad(p.month)}-${pad(p.day)}`;
return { date, minute: p.hour * 60 + p.minute, weekday: weekday(date) };
}
/** The local date of an instant in `tz`. */
export const localDate = (at: Date, tz: string) => localParts(at, tz).date;
/** The offset of `tz` from UTC at an instant, in milliseconds (SAST: +2 hours). */
function offsetAt(t: number, tz: string): number {
const p = parts(new Date(t), tz);
return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - Math.floor(t / 1000) * 1000;
}
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
/** Whether `s` is a real `YYYY-MM-DD` date. */
export function isDate(s: unknown): s is string {
if (typeof s !== 'string') return false;
const m = DATE.exec(s);
if (!m) return false;
const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
return d.getUTCFullYear() === Number(m[1]) && d.getUTCMonth() === Number(m[2]) - 1 && d.getUTCDate() === Number(m[3]);
}
const utcDay = (date: string) => {
const m = DATE.exec(date);
if (!m) throw new Error(`Not a date: ${date}`);
return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
};
const fromUtcDay = (t: number) => {
const d = new Date(t);
return `${pad(d.getUTCFullYear(), 4)}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
};
/** `date` plus `n` days. */
export const addDays = (date: string, n: number) => fromUtcDay(utcDay(date) + n * 86400e3);
/** `date` plus `n` months, kept inside the month (31 January + 1 month = 28 or 29 February). */
export function addMonths(date: string, n: number): string {
const d = new Date(utcDay(date));
const target = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + n, 1));
const last = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();
target.setUTCDate(Math.min(d.getUTCDate(), last));
return fromUtcDay(target.getTime());
}
/** Days from `a` to `b` (negative when `b` is earlier). */
export const daysBetween = (a: string, b: string) => Math.round((utcDay(b) - utcDay(a)) / 86400e3);
/** 0 = Sunday … 6 = Saturday. */
export const weekday = (date: string) => new Date(utcDay(date)).getUTCDay();
/**
* The instant of `minute` minutes after local midnight on `date` in `tz` (minute may be 1440 or
* more: the next day). Null when that local time doesn't exist (clocks jumping forward).
*/
export function zonedTime(date: string, minute: number, tz: string): Date | null {
const day = addDays(date, Math.floor(minute / 1440));
const min = ((minute % 1440) + 1440) % 1440;
const guess = utcDay(day) + min * 60e3;
// Two passes find the offset in force at that local time; the earlier of two (clocks going back).
const first = guess - offsetAt(guess, tz);
const candidates = [first, guess - offsetAt(first, tz), guess - offsetAt(first - 3600e3, tz), guess - offsetAt(first + 3600e3, tz)];
const ok = [...new Set(candidates)].filter((t) => {
const p = localParts(new Date(t), tz);
return p.date === day && p.minute === min;
});
return ok.length ? new Date(Math.min(...ok)) : null;
}
/** The instant local midnight starts `date` (the first instant of the day, whatever DST does). */
export function startOfDay(date: string, tz: string): Date {
for (let m = 0; m < 180; m += 15) {
const t = zonedTime(date, m, tz);
if (t) return t;
}
throw new Error(`No start of ${date} in ${tz}`);
}
+199
View File
@@ -0,0 +1,199 @@
/**
* The House of Prayer in the admin (APP-1.0-PLAN §3, §10), under /api/v1/admin/prayer: Prayer
* coordinators (and Owner / Church admin), with 2FA. Every answer that has names is written to
* the access log first.
*
* GET /wall the rules (slot length, target, limits, cancel window, contact)
* PUT /wall change them
* GET /week?from=YYYY-MM-DD 7 days of coverage (counts) and the gaps
* GET /bookings?date=YYYY-MM-DD who prays when that day (names: access-logged)
* POST /commitments book on a member's behalf { memberId, …booking }
* DELETE /commitments/:id cancel one (the cancel window doesn't apply)
* GET /members?q= members to book for (name and email)
* GET /campaigns all, newest first
* POST /campaigns, PUT /campaigns/:id, DELETE /campaigns/:id
* GET /testimonies?status=pending the queue (and approved / removed)
* POST /testimonies/:id/approve
* POST /testimonies/:id/remove { reason } (sent to the author)
*/
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 { audit, clientIp } from '../lib/audit.js';
import { enqueue } from '../lib/outbox.js';
import { requireRole } from '../auth/sessions.js';
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 { book, cancel, rulesBetween, wallDay } from './service.js';
import { setWallSettings, wallSettings } from './wall.js';
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),
description: z.string().trim().max(4000).default(''),
imageUrl: z.string().trim().url().max(500).nullable().optional(),
startDate: date,
endDate: date,
goal: z.string().trim().max(200).nullable().optional(),
targetPerSlot: z.number().int().min(1).max(50).nullable().optional(),
}).strict().refine((c) => c.endDate >= c.startDate, { path: ['endDate'], message: 'The end is before the start.' });
export function prayerAdminRouter(ctx: Ctx) {
const r = express.Router();
r.use(requirePrayerModule(ctx), sameOrigin(ctx.config.publicUrl, ctx.config.production), express.json({ limit: '32kb' }), requireRole(ctx, COORDINATORS), (_req, res, next) => {
res.set('Cache-Control', 'no-store');
next();
});
r.get('/wall', handle(async () => ({ wall: await wallSettings(ctx) })));
r.put('/wall', handle(async (req) => {
try {
const wall = await setWallSettings(ctx, req.body);
await audit(ctx, { ...actor(req), action: 'prayer_wall_changed', targetType: 'settings', targetId: 'prayer_wall', metadata: req.body });
prayerChanged(ctx, { all: true });
return { wall };
} 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('/week', handle(async (req) => {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const from = req.query.from === undefined ? localDate(ctx.now(), tz) : String(req.query.from);
if (!isDate(from)) throw new ApiError(400, 'VALIDATION', 'Give the date as YYYY-MM-DD.');
const days = [];
for (let i = 0; i < 7; i++) {
const d = await wallDay(ctx, addDays(from, i), wall, tz);
days.push({ date: d.date, covered: d.covered, total: d.total, gaps: d.slots.filter((s) => !s.covered).map((s) => s.minute), slots: d.slots.map((s) => s.count) });
}
return { timezone: tz, slotMinutes: wall.slotMinutes, target: wall.targetPerSlot, days };
}));
r.get('/bookings', handle(async (req) => {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const d = String(req.query.date ?? localDate(ctx.now(), tz));
if (!isDate(d)) throw new ApiError(400, 'VALIDATION', 'Give the date as YYYY-MM-DD.');
const slots = daySlots(d, wall.slotMinutes, tz);
if (!slots.length) return { date: d, people: [] };
const rules = (await rulesBetween(ctx, d, d)).filter((x) => x.memberId);
const from = slots[0]!.start;
const to = slots[slots.length - 1]!.end;
const occurrences = rules.flatMap((rule) => occurrencesBetween(rule, from, to, tz).map((o) => ({ rule, o })));
const members = await ctx.db.member.findMany({ where: { id: { in: [...new Set(occurrences.map((x) => x.rule.memberId!))] } }, select: { id: true, name: true, email: true, phone: true } });
const byId = new Map(members.map((m) => [m.id, m]));
await accessLog(ctx, req, { action: 'prayer_bookings_viewed', targetType: 'prayer_day', targetId: d, metadata: { people: members.length } });
return {
date: d,
timezone: tz,
people: occurrences.map(({ rule, o }) => ({
commitmentId: rule.id, start: o.start.toISOString(), end: o.end.toISOString(), recurrence: rule.recurrence,
member: byId.get(rule.memberId!) ?? null,
})).sort((a, b) => a.start.localeCompare(b.start)),
};
}));
r.get('/members', handle(async (req) => {
const q = String(req.query.q ?? '').trim().slice(0, 80);
if (q.length < 2) return { members: [] };
const members = await ctx.db.member.findMany({ where: { OR: [{ name: { contains: q, mode: 'insensitive' } }, { email: { contains: q, mode: 'insensitive' } }] }, select: { id: true, name: true, email: true }, take: 20, orderBy: { name: 'asc' } });
await accessLog(ctx, req, { action: 'members_searched', targetType: 'member', metadata: { results: members.length } });
return { members };
}));
r.post('/commitments', handle(async (req, res) => {
const { memberId, ...booking } = parse(bookingBody.extend({ memberId: z.string().min(1).max(100) }), req.body);
if (!(await ctx.db.member.findUnique({ where: { id: memberId } }))) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such member.');
const row = await book(ctx, memberId, booking, { bookedById: req.signed!.member.id });
await audit(ctx, { ...actor(req), action: 'prayer_booked_for_member', targetType: 'prayer_commitment', targetId: row.id, metadata: { memberId } });
res.status(201);
return { id: row.id, endDate: row.endDate };
}));
r.delete('/commitments/:id', handle(async (req) => {
const out = await cancel(ctx, null, String(req.params.id), { force: true });
await audit(ctx, { ...actor(req), action: 'prayer_commitment_cancelled', targetType: 'prayer_commitment', targetId: String(req.params.id), metadata: out });
return out;
}));
// ── Campaigns ──
r.get('/campaigns', handle(async () => ({ campaigns: await ctx.db.prayerCampaign.findMany({ orderBy: { startDate: 'desc' } }) })));
r.post('/campaigns', handle(async (req, res) => {
const data = parse(campaignBody, req.body);
const c = await ctx.db.prayerCampaign.create({ data: { ...data, imageUrl: data.imageUrl ?? null, goal: data.goal ?? null, targetPerSlot: data.targetPerSlot ?? null, createdById: req.signed!.member.id } });
await audit(ctx, { ...actor(req), action: 'prayer_campaign_created', targetType: 'prayer_campaign', targetId: c.id });
prayerChanged(ctx, { all: true });
res.status(201);
return { campaign: c };
}));
r.put('/campaigns/:id', handle(async (req) => {
const data = parse(campaignBody, req.body);
const id = String(req.params.id);
if (!(await ctx.db.prayerCampaign.findUnique({ where: { id } }))) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such campaign.');
const c = await ctx.db.prayerCampaign.update({ where: { id }, data: { ...data, imageUrl: data.imageUrl ?? null, goal: data.goal ?? null, targetPerSlot: data.targetPerSlot ?? null } });
await audit(ctx, { ...actor(req), action: 'prayer_campaign_changed', targetType: 'prayer_campaign', targetId: id });
prayerChanged(ctx, { all: true });
return { campaign: c };
}));
r.delete('/campaigns/:id', handle(async (req) => {
const id = String(req.params.id);
const { count } = await ctx.db.prayerCampaign.deleteMany({ where: { id } });
if (!count) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such campaign.');
await ctx.db.testimony.updateMany({ where: { campaignId: id }, data: { campaignId: null } });
await audit(ctx, { ...actor(req), action: 'prayer_campaign_deleted', targetType: 'prayer_campaign', targetId: id });
prayerChanged(ctx, { all: true });
return { deleted: true };
}));
// ── Testimonies ──
r.get('/testimonies', handle(async (req) => {
const status = z.enum(['pending', 'approved', 'removed']).catch('pending').parse(req.query.status);
const rows = await ctx.db.testimony.findMany({ where: { status }, orderBy: { createdAt: status === 'pending' ? 'asc' : 'desc' }, take: 100 });
const members = await ctx.db.member.findMany({ where: { id: { in: [...new Set(rows.map((t) => t.memberId))] } }, select: { id: true, name: true } });
const names = new Map(members.map((m) => [m.id, m.name]));
if (rows.length) await accessLog(ctx, req, { action: 'testimonies_viewed', targetType: 'testimony', metadata: { status, count: rows.length } });
return { testimonies: rows.map((t) => ({ id: t.id, text: t.text, showName: t.showName, campaignId: t.campaignId, status: t.status, removedReason: t.removedReason, createdAt: t.createdAt.toISOString(), author: names.get(t.memberId) ?? null })) };
}));
r.post('/testimonies/:id/approve', handle(async (req) => {
const id = String(req.params.id);
const { count } = await ctx.db.testimony.updateMany({ where: { id }, data: { status: 'approved', removedReason: null, moderatedById: req.signed!.member.id, moderatedAt: ctx.now() } });
if (!count) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such testimony.');
await audit(ctx, { ...actor(req), action: 'testimony_approved', targetType: 'testimony', targetId: id });
return { status: 'approved' };
}));
r.post('/testimonies/:id/remove', handle(async (req) => {
const id = String(req.params.id);
const { reason } = parse(z.object({ reason: z.string().trim().min(3, 'Say why, for its author.').max(500) }).strict(), req.body);
const t = await ctx.db.testimony.findUnique({ where: { id } });
if (!t) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such testimony.');
await ctx.db.testimony.update({ where: { id }, data: { status: 'removed', removedReason: reason, moderatedById: req.signed!.member.id, moderatedAt: ctx.now() } });
// The author is told why (§3), by email; their own words aren't in the message.
await enqueue(ctx, { memberId: t.memberId, kind: 'testimony-removed', channel: 'email', dedupeKey: `testimony-removed:${id}:${ctx.now().getTime()}`, payload: { testimonyId: id, reason } });
await audit(ctx, { ...actor(req), action: 'testimony_removed', targetType: 'testimony', targetId: id });
return { status: 'removed' };
}));
return r;
}
+83
View File
@@ -0,0 +1,83 @@
/**
* The House of Prayer's background jobs (APP-1.0-PLAN §3):
*
* - **Reminders** (`prayer-reminders`, every minute): each occurrence whose reminder time has come
* and which hasn't started yet gets one message, on the commitment's channel, with an "I prayed"
* link for afterwards. Night-time slots too: that's where reminders matter. A missed run catches
* up as long as the slot hasn't started.
* - **Renewal notices** (`prayer-renewals`, daily 09:00): a recurring commitment ending in 14 days
* gets "Renew for another year" (a signed, single-use link); a second notice 3 days before.
*
* Both only queue messages (lib/outbox.ts); the messaging job sends them.
*/
import type { Ctx } from '../context.js';
import { churchTimezone } from '../church/profile.js';
import { enqueue } from '../lib/outbox.js';
import { addDays, daysBetween, localDate } from '../lib/zoned.js';
import { enabledModules } from '../modules.js';
import { occurrencesBetween, reminderAt, type Reminder } from './rules.js';
import { toRule } from './service.js';
import { prayerToken } from './tokens.js';
/** The longest a reminder comes before its slot: 20:00 the evening before a slot at 23:45. */
const LOOKAHEAD_MS = 28 * 3600e3;
const on = async (ctx: Ctx) => (await enabledModules(ctx)).includes('house-of-prayer');
export async function sendReminders(ctx: Ctx): Promise<{ queued: number } | { skipped: string }> {
if (!(await on(ctx))) return { skipped: 'The House of Prayer is switched off.' };
const tz = await churchTimezone(ctx);
const now = ctx.now();
const until = new Date(now.getTime() + LOOKAHEAD_MS);
const today = localDate(now, tz);
const rows = await ctx.db.prayerCommitment.findMany({
where: { memberId: { not: null }, reminder: { not: 'none' }, startDate: { lte: addDays(today, 2) }, endDate: { gte: today } },
include: { skips: true },
});
let queued = 0;
for (const row of rows) {
for (const o of occurrencesBetween(toRule(row), now, until, tz)) {
if (o.start <= now) continue;
const at = reminderAt(row.reminder as Reminder, o, tz);
if (!at || at > now) continue;
const added = await enqueue(ctx, {
memberId: row.memberId!, kind: 'prayer-reminder', channel: row.channel, dedupeKey: `prayer-reminder:${row.id}:${o.date}`,
payload: {
commitmentId: row.id, date: o.date, start: o.start.toISOString(), end: o.end.toISOString(), timezone: tz,
prayedPath: `/prayer/prayed?token=${encodeURIComponent(prayerToken(ctx, 'prayed', row.id, o.date))}`,
},
});
if (added) queued++;
}
}
return { queued };
}
/** Days before the end that each notice goes (§3): the first at 14, the second at 3. */
export const RENEWAL_NOTICES = [14, 3] as const;
export async function sendRenewalNotices(ctx: Ctx): Promise<{ queued: number } | { skipped: string }> {
if (!(await on(ctx))) return { skipped: 'The House of Prayer is switched off.' };
const tz = await churchTimezone(ctx);
const today = localDate(ctx.now(), tz);
const rows = await ctx.db.prayerCommitment.findMany({
where: { memberId: { not: null }, recurrence: { not: 'once' }, endDate: { gte: today, lte: addDays(today, RENEWAL_NOTICES[0]) }, renewalNoticesSent: { lt: RENEWAL_NOTICES.length } },
});
let queued = 0;
for (const row of rows) {
const left = daysBetween(today, row.endDate);
// Which notice is due now: the second once 3 days are left, else the first.
const due = left <= RENEWAL_NOTICES[1] ? 2 : 1;
if (row.renewalNoticesSent >= due) continue;
await enqueue(ctx, {
memberId: row.memberId!, kind: 'prayer-renewal', channel: row.channel, dedupeKey: `prayer-renewal:${row.id}:${row.endDate}:${due}`,
payload: {
commitmentId: row.id, endDate: row.endDate, daysLeft: left, startMinute: row.startMinute, durationMinutes: row.durationMinutes, recurrence: row.recurrence, timezone: tz,
renewPath: `/prayer/renew?token=${encodeURIComponent(prayerToken(ctx, 'renew', row.id, row.endDate))}`,
},
});
await ctx.db.prayerCommitment.update({ where: { id: row.id }, data: { renewalNoticesSent: due } });
queued++;
}
return { queued };
}
+74
View File
@@ -0,0 +1,74 @@
/**
* Live coverage (APP-1.0-PLAN §3): `/api/v1/prayer/stream` sends server-sent events when anyone
* books, changes or cancels, and the clock fetches its day again. The stream carries no
* coverage and no names, only which dates changed (`all` for a recurring rule).
*
* Through FastPanel's nginx and frp without a config change: `X-Accel-Buffering: no` and a comment
* every 25 seconds, so nothing buffers it or closes it as idle. The clock polls every 30 seconds
* if the stream drops.
*
* In-process: the App runs as one PM2 process per church. The day cache is kept here too, so a
* change empties it at once.
*/
import { EventEmitter } from 'node:events';
import type { Request, Response } from 'express';
import type { Ctx } from '../context.js';
export const KEEPALIVE_MS = 25_000;
/** More streams than this (per process) are refused; the clock falls back to polling. */
export const MAX_STREAMS = 1000;
export type Change = { dates: string[] } | { all: true };
type Live = { emitter: EventEmitter; version: number; streams: number };
const lives = new WeakMap<Ctx, Live>();
function live(ctx: Ctx): Live {
let l = lives.get(ctx);
if (!l) {
l = { emitter: new EventEmitter(), version: 0, streams: 0 };
l.emitter.setMaxListeners(0);
lives.set(ctx, l);
}
return l;
}
/** A booking changed: caches are dropped and every open clock hears of it. */
export function prayerChanged(ctx: Ctx, change: Change): void {
const l = live(ctx);
l.version++;
l.emitter.emit('change', change);
}
/** Changes with each booking change: the day cache's key (service.ts). */
export const coverageVersion = (ctx: Ctx) => live(ctx).version;
export function openStream(ctx: Ctx, req: Request, res: Response): void {
const l = live(ctx);
if (l.streams >= MAX_STREAMS) {
res.status(503).set('Retry-After', '30').json({ error: { code: 'BUSY', message: 'Too many open clocks; this one will update every 30 seconds.' } });
return;
}
l.streams++;
res.status(200).set({
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-store, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.flushHeaders?.();
res.write('retry: 5000\n\n');
const onChange = (change: Change) => res.write(`event: changed\ndata: ${JSON.stringify(change)}\n\n`);
const keepAlive = setInterval(() => res.write(': keep-alive\n\n'), KEEPALIVE_MS);
l.emitter.on('change', onChange);
let closed = false;
const close = () => {
if (closed) return;
closed = true;
clearInterval(keepAlive);
l.emitter.off('change', onChange);
l.streams--;
};
req.on('close', close);
res.on('close', close);
}
+58
View File
@@ -0,0 +1,58 @@
/**
* A member's House of Prayer records in "Download my data" and "Delete my account" (APP-1.0-PLAN
* §11):
*
* - **Export:** their commitments (with skipped dates), "I prayed" marks and testimonies.
* - **Delete:** future occurrences go (the slots open up); what already happened stays only as a
* count in coverage history (the rule kept without the member, its note cleared); "I prayed"
* marks lose the member; testimonies and queued messages are deleted.
*/
import type { UserExportReply } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { churchTimezone } from '../church/profile.js';
import { addDays, localDate } from '../lib/zoned.js';
import { prayerChanged } from './live.js';
export async function exportPrayer(ctx: Ctx, memberId: string): Promise<UserExportReply['sections']> {
const [commitments, marks, testimonies] = await Promise.all([
ctx.db.prayerCommitment.findMany({ where: { memberId }, include: { skips: true }, orderBy: { createdAt: 'asc' } }),
ctx.db.prayedMark.findMany({ where: { memberId }, orderBy: { date: 'asc' } }),
ctx.db.testimony.findMany({ where: { memberId }, orderBy: { createdAt: 'asc' } }),
]);
const hhmm = (m: number) => `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
const sections: UserExportReply['sections'] = [];
if (commitments.length) {
sections.push({
key: 'app_prayer_commitments',
title: 'Your prayer slots',
records: commitments.map((c) => ({
from: c.startDate, until: c.endDate, time: hhmm(c.startMinute), minutes: c.durationMinutes, repeats: c.recurrence,
reminder: c.reminder, channel: c.channel, note: c.note, skipped: (c as typeof c & { skips: { date: string }[] }).skips.map((s) => s.date), booked: c.createdAt.toISOString(),
})),
});
}
if (marks.length) sections.push({ key: 'app_prayed', title: '"I prayed" (self-reported)', records: marks.map((m) => ({ date: m.date, marked: m.createdAt.toISOString() })) });
if (testimonies.length) {
sections.push({ key: 'app_testimonies', title: 'Your testimonies', records: testimonies.map((t) => ({ text: t.text, showName: t.showName, status: t.status, removedReason: t.removedReason, shared: t.createdAt.toISOString() })) });
}
return sections;
}
export async function deletePrayer(ctx: Ctx, memberId: string): Promise<void> {
const today = localDate(ctx.now(), await churchTimezone(ctx));
const yesterday = addDays(today, -1);
const rows = await ctx.db.prayerCommitment.findMany({ where: { memberId } });
for (const row of rows) {
if (row.startDate > yesterday) {
await ctx.db.prayerSkip.deleteMany({ where: { commitmentId: row.id } });
await ctx.db.prayedMark.deleteMany({ where: { commitmentId: row.id } });
await ctx.db.prayerCommitment.delete({ where: { id: row.id } });
} else {
await ctx.db.prayerCommitment.update({ where: { id: row.id }, data: { memberId: null, note: null, endDate: row.endDate < yesterday ? row.endDate : yesterday } });
}
}
await ctx.db.prayedMark.updateMany({ where: { memberId }, data: { memberId: null } });
await ctx.db.testimony.deleteMany({ where: { memberId } });
await ctx.db.outboxMessage.deleteMany({ where: { memberId } });
if (rows.length) prayerChanged(ctx, { all: true });
}
+184
View File
@@ -0,0 +1,184 @@
/**
* The House of Prayer's public and member API (APP-1.0-PLAN §3). Everything answers 404
* `MODULE_OFF` while the church has the module switched off.
*
* Public (/api/v1/prayer), counts only, never a name:
* GET /day?date=YYYY-MM-DD the day's clock (today by default); `mine` for a signed-in member
* GET /stream server-sent events: which dates changed (live.ts)
* GET /campaign the running (or next) campaign: days left, coverage, hours prayed
* GET /testimonies approved testimonies, first name or "Anonymous"
* POST /renew { token } "Renew for another year" from a renewal notice, no sign-in
* POST /prayed { token } "I prayed" from a reminder, no sign-in
*
* Member (/api/v1/me/prayer):
* GET / my commitments, next dates, what can be marked
* POST /commitments book (once, daily, weekly)
* PATCH /commitments/:id change (reminder, channel, note and end date in place;
* a new time or days ends the old rule and starts a new one)
* DELETE /commitments/:id cancel (outside the cancel window)
* POST /commitments/:id/skip { date }
* DELETE /commitments/:id/skip/:date add a skipped date back
* POST /commitments/:id/renew
* POST /commitments/:id/prayed { date }
* GET /testimonies mine, with their state
* POST /testimonies { text, showName, campaignId? } (waits for approval)
* DELETE /testimonies/:id removed by its author at any time
*/
import express, { type RequestHandler } from 'express';
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError, handle, sameOrigin } from '../http.js';
import { currentSession, requireMember } from '../auth/sessions.js';
import { churchTimezone } from '../church/profile.js';
import { isDate, localDate } from '../lib/zoned.js';
import { enabledModules } from '../modules.js';
import { openStream } from './live.js';
import { RECURRENCES, REMINDERS } from './rules.js';
import { book, campaignSummary, cancel, change, coverageView, markPrayed, myPrayer, renew, skip, unskip } from './service.js';
import { approvedTestimonies, deleteOwnTestimony, myTestimonies, submitTestimony } from './testimonies.js';
import { readPrayerToken } from './tokens.js';
const MODULE = 'house-of-prayer';
/** 404 while the church has the House of Prayer switched off (§2). */
export function requirePrayerModule(ctx: Ctx): RequestHandler {
return (_req, _res, next) => {
enabledModules(ctx).then((on) => next(on.includes(MODULE) ? undefined : new ApiError(404, 'MODULE_OFF', 'The House of Prayer is switched off.'))).catch(next);
};
}
const date = z.string().refine(isDate, 'A date as YYYY-MM-DD.');
const channel = z.enum(['email', 'whatsapp', 'both']);
const note = z.string().trim().max(200).nullable();
export const bookingBody = z.object({
startDate: date,
startMinute: z.number().int().min(0).max(1439),
durationMinutes: z.number().int().min(15).max(720),
recurrence: z.enum(RECURRENCES),
endDate: date.nullable().optional(),
reminder: z.enum(REMINDERS).optional(),
channel: channel.optional(),
note: note.optional(),
}).strict();
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;
};
export function prayerRouter(ctx: Ctx) {
const r = express.Router();
const gate = requirePrayerModule(ctx);
r.use('/v1/prayer', gate, sameOrigin(ctx.config.publicUrl, ctx.config.production), express.json({ limit: '16kb' }));
r.use('/v1/me/prayer', gate, sameOrigin(ctx.config.publicUrl, ctx.config.production), express.json({ limit: '16kb' }), requireMember(ctx), (_req, res, next) => {
res.set('Cache-Control', 'no-store');
next();
});
// ── Public ──
r.get('/v1/prayer/day', handle(async (req, res) => {
const tz = await churchTimezone(ctx);
const asked = req.query.date === undefined ? localDate(ctx.now(), tz) : String(req.query.date);
if (!isDate(asked)) throw new ApiError(400, 'VALIDATION', 'Give the date as YYYY-MM-DD.');
const signed = await currentSession(ctx, req);
// Signed in, the answer has the member's own slots, so it's theirs alone.
res.set('Cache-Control', signed ? 'private, no-store' : 'public, max-age=15');
return coverageView(ctx, asked, signed?.member.id ?? null);
}));
r.get('/v1/prayer/stream', (req, res) => openStream(ctx, req, res));
r.get('/v1/prayer/campaign', handle(async (_req, res) => {
res.set('Cache-Control', 'public, max-age=60');
return { campaign: await campaignSummary(ctx) };
}));
r.get('/v1/prayer/testimonies', handle(async (req, res) => {
res.set('Cache-Control', 'public, max-age=60');
const campaignId = typeof req.query.campaign === 'string' ? req.query.campaign : null;
return { testimonies: await approvedTestimonies(ctx, campaignId) };
}));
r.post('/v1/prayer/renew', handle(async (req) => {
const t = readPrayerToken(ctx, 'renew', req.body?.token);
const row = t ? await ctx.db.prayerCommitment.findUnique({ where: { id: t.id } }) : null;
// Signed over the end date: once renewed (or changed), the link is spent.
if (!t || !row || row.endDate !== t.date) throw new ApiError(410, 'LINK_USED', 'This link has been used or has expired. Open the App to renew your prayer slot.');
const renewed = await renew(ctx, null, t.id);
return { renewed: true, endDate: renewed.endDate };
}));
r.post('/v1/prayer/prayed', handle(async (req) => {
const t = readPrayerToken(ctx, 'prayed', req.body?.token);
if (!t) throw new ApiError(410, 'LINK_USED', 'This link isn\'t valid. Open the App to mark it.');
return markPrayed(ctx, null, t.id, t.date);
}));
// ── Member ──
r.get('/v1/me/prayer', handle(async (req) => myPrayer(ctx, req.signed!.member.id)));
r.post('/v1/me/prayer/commitments', handle(async (req, res) => {
const body = parse(bookingBody, req.body);
const row = await book(ctx, req.signed!.member.id, body);
res.status(201);
return { id: row.id, endDate: row.endDate };
}));
r.patch('/v1/me/prayer/commitments/:id', handle(async (req) => {
const row = await change(ctx, req.signed!.member.id, idParam(req.params.id), parse(changeBody, req.body));
return { id: row.id, endDate: row.endDate };
}));
r.delete('/v1/me/prayer/commitments/:id', handle(async (req) => cancel(ctx, req.signed!.member.id, idParam(req.params.id))));
r.post('/v1/me/prayer/commitments/:id/skip', handle(async (req) => {
const { date: d } = parse(z.object({ date }).strict(), req.body);
await skip(ctx, req.signed!.member.id, idParam(req.params.id), d);
return { skipped: d };
}));
r.delete('/v1/me/prayer/commitments/:id/skip/:date', handle(async (req) => {
const d = parse(date, req.params.date);
await unskip(ctx, req.signed!.member.id, idParam(req.params.id), d);
return { skipped: null };
}));
r.post('/v1/me/prayer/commitments/:id/renew', handle(async (req) => {
const row = await renew(ctx, req.signed!.member.id, idParam(req.params.id));
return { renewed: true, endDate: row.endDate };
}));
r.post('/v1/me/prayer/commitments/:id/prayed', handle(async (req) => {
const { date: d } = parse(z.object({ date }).strict(), req.body);
return markPrayed(ctx, req.signed!.member.id, idParam(req.params.id), d);
}));
r.get('/v1/me/prayer/testimonies', handle(async (req) => ({ testimonies: await myTestimonies(ctx, req.signed!.member.id) })));
r.post('/v1/me/prayer/testimonies', handle(async (req, res) => {
const t = await submitTestimony(ctx, req.signed!.member.id, req.body);
res.status(201);
return t;
}));
r.delete('/v1/me/prayer/testimonies/:id', handle(async (req) => {
await deleteOwnTestimony(ctx, req.signed!.member.id, String(req.params.id));
return { deleted: true };
}));
return r;
}
+252
View File
@@ -0,0 +1,252 @@
/**
* The House of Prayer's rules (APP-1.0-PLAN §3), pure: no database, no clock of their own.
*
* - **Slots:** the church's day cut into slots of its slot length (60 minutes by default; 15 or
* 30), in the church's timezone. A slot whose local start doesn't exist (clocks jumping forward)
* isn't on that day.
* - **Commitments are rules, not rows:** a start date and time, a length, `once` / `daily` /
* `weekly` (on the start date's weekday), an end date and the dates skipped. The occurrences in
* any window are worked out from them, so a year of daily slots is one row.
* - **Coverage:** a slot's count is the people whose occurrences overlap it (one person once,
* however many of their commitments do). A slot is covered with at least one; the target (1 by
* default) is what "2 of 3" is measured against.
* - **Never a name:** coverage carries counts and whether a slot is the asker's own, nothing else.
*/
import { addDays, addMonths, daysBetween, localParts, weekday, zonedTime } from '../lib/zoned.js';
export const SLOT_LENGTHS = [15, 30, 60] as const;
export type SlotLength = (typeof SLOT_LENGTHS)[number];
export const RECURRENCES = ['once', 'daily', 'weekly'] as const;
export type Recurrence = (typeof RECURRENCES)[number];
export const REMINDERS = ['none', 'min15', 'hour1', 'evening'] as const;
export type Reminder = (typeof REMINDERS)[number];
/** The church's prayer wall rules (Settings → House of Prayer, decision 12). */
export type WallSettings = {
slotMinutes: SlotLength;
/** How many people make a slot "fully" covered (a slot counts as covered with one, P5). */
targetPerSlot: number;
/** A slot can be booked up to this many months ahead (12 at most). */
bookAheadMonths: number;
/** A recurring commitment lasts up to this many months from the day of booking (12 at most). */
recurringMaxMonths: number;
/** An occurrence can't be skipped or cancelled in the App this close to its start (0–48). */
cancelHours: number;
/** Who to contact inside the cancel window (shown to members). */
coordinator: { name: string | null; contact: string | null };
};
export const DEFAULT_WALL: WallSettings = {
slotMinutes: 60,
targetPerSlot: 1,
bookAheadMonths: 12,
recurringMaxMonths: 12,
cancelHours: 8,
coordinator: { name: null, contact: null },
};
/** The longest single commitment (several slots in a row, e.g. 02:00 for 2 hours). */
export const MAX_DURATION_MINUTES = 12 * 60;
export type Rule = {
id: string;
/** Null once the member deleted their account: the past stays as a count only (§11). */
memberId: string | null;
startDate: string;
startMinute: number;
durationMinutes: number;
recurrence: Recurrence;
/** The last date with an occurrence (a `once` rule ends on its start date). */
endDate: string;
skips: readonly string[];
};
export type Occurrence = { ruleId: string; date: string; start: Date; end: Date };
export type Slot = { minute: number; start: Date; end: Date };
/** Whether the rule has an occurrence on `date` (skips left out). */
export function occursOn(rule: Rule, date: string): boolean {
if (date < rule.startDate || date > rule.endDate) return false;
if (rule.skips.includes(date)) return false;
if (rule.recurrence === 'once') return date === rule.startDate;
if (rule.recurrence === 'weekly') return weekday(date) === weekday(rule.startDate);
return true;
}
/**
* The instant an occurrence on `date` starts. A start inside a jump forward moves to the first
* minute after it (the member still prays that night).
*/
function startOn(date: string, minute: number, tz: string): Date | null {
for (let m = minute; m < minute + 180; m += 15) {
const t = zonedTime(date, m, tz);
if (t) return t;
}
return null;
}
export function occurrenceOn(rule: Rule, date: string, tz: string): Occurrence | null {
if (!occursOn(rule, date)) return null;
const start = startOn(date, rule.startMinute, tz);
if (!start) return null;
return { ruleId: rule.id, date, start, end: new Date(start.getTime() + rule.durationMinutes * 60e3) };
}
/** The rule's occurrences that overlap [from, to), in order. */
export function occurrencesBetween(rule: Rule, from: Date, to: Date, tz: string): Occurrence[] {
// An occurrence can start on the local day before `from` and run past midnight into it.
let date = localParts(from, tz).date;
date = addDays(date, -1) < rule.startDate ? rule.startDate : addDays(date, -1);
const last = localParts(to, tz).date < rule.endDate ? localParts(to, tz).date : rule.endDate;
const out: Occurrence[] = [];
if (rule.recurrence === 'once') {
const o = occurrenceOn(rule, rule.startDate, tz);
return o && o.start < to && o.end > from ? [o] : [];
}
const step = rule.recurrence === 'weekly' ? 7 : 1;
if (step === 7) {
// Move to the first date on the rule's weekday.
const shift = (weekday(rule.startDate) - weekday(date) + 7) % 7;
date = addDays(date, shift);
}
for (; date <= last; date = addDays(date, step)) {
const o = occurrenceOn(rule, date, tz);
if (o && o.start < to && o.end > from) out.push(o);
}
return out;
}
/** The next occurrence starting at or after `at`, or null. */
export function nextOccurrence(rule: Rule, at: Date, tz: string): Occurrence | null {
let date = localParts(at, tz).date;
if (date < rule.startDate) date = rule.startDate;
for (; date <= rule.endDate; date = addDays(date, 1)) {
const o = occurrenceOn(rule, date, tz);
if (o && o.start >= at) return o;
}
return null;
}
/** The day's slots in the church's timezone (24, 48 or 96; fewer or more on a DST change day). */
export function daySlots(date: string, slotMinutes: number, tz: string): Slot[] {
const out: Slot[] = [];
for (let minute = 0; minute < 1440; minute += slotMinutes) {
const start = zonedTime(date, minute, tz);
if (!start) continue;
const next = zonedTime(date, minute + slotMinutes, tz) ?? new Date(start.getTime() + slotMinutes * 60e3);
out.push({ minute, start, end: next });
}
return out;
}
export type SlotCoverage = { minute: number; start: string; end: string; count: number; covered: boolean; mine: boolean };
export type DayCoverage = { date: string; slots: SlotCoverage[]; covered: number; total: number };
/** Who an occurrence counts as: the member, or the rule itself once the member is gone. */
const personOf = (r: Rule) => r.memberId ?? `rule:${r.id}`;
/**
* The day's coverage: for each slot, how many people pray in it, whether it's covered and whether
* it's `memberId`'s own. Counts only, never who (§3, ROADMAP-v3 §7).
*/
export function dayCoverage(date: string, rules: readonly Rule[], wall: Pick<WallSettings, 'slotMinutes'>, tz: string, memberId: string | null = null): DayCoverage {
const slots = daySlots(date, wall.slotMinutes, tz);
if (!slots.length) return { date, slots: [], covered: 0, total: 0 };
const from = slots[0]!.start;
const to = slots[slots.length - 1]!.end;
const occurrences: { person: string; o: Occurrence }[] = [];
for (const r of rules) for (const o of occurrencesBetween(r, from, to, tz)) occurrences.push({ person: personOf(r), o });
const out = slots.map((s) => {
const people = new Set<string>();
let mine = false;
for (const { person, o } of occurrences) {
if (o.start < s.end && o.end > s.start) {
people.add(person);
if (memberId && person === memberId) mine = true;
}
}
return { minute: s.minute, start: s.start.toISOString(), end: s.end.toISOString(), count: people.size, covered: people.size > 0, mine };
});
return { date, slots: out, covered: out.filter((s) => s.covered).length, total: out.length };
}
/** The share of slots covered over several days, 0–100 (the heartbeat's last 7 days, campaigns). */
export function coveragePercent(days: readonly DayCoverage[]): number {
const total = days.reduce((t, d) => t + d.total, 0);
if (!total) return 0;
return Math.round((days.reduce((t, d) => t + d.covered, 0) / total) * 100);
}
/** Whether an occurrence is inside the cancel window (or already started): it can't be changed. */
export const isLocked = (o: Pick<Occurrence, 'start'>, now: Date, cancelHours: number) => o.start.getTime() - now.getTime() < cancelHours * 3600e3;
/**
* Where a cancelled rule ends: the date of its last occurrence that has started or is locked.
* Null when it has none (nothing happened yet: the rule can go altogether).
*/
export function cancelledEndDate(rule: Rule, now: Date, wall: Pick<WallSettings, 'cancelHours'>, tz: string): string | null {
const lockedUntil = new Date(now.getTime() + wall.cancelHours * 3600e3);
const from = zonedTime(rule.startDate, 0, tz) ?? new Date(0);
if (from >= lockedUntil) return null;
// Look back far enough for a once rule or the recent past of a long recurring one.
const windowStart = new Date(Math.max(from.getTime(), now.getTime() - 400 * 86400e3));
const before = occurrencesBetween(rule, windowStart, lockedUntil, tz).filter((o) => o.start < lockedUntil);
if (before.length) return before[before.length - 1]!.date;
// Earlier occurrences may exist before the window (a long rule): keep its end before today.
return from < windowStart ? addDays(localParts(now, tz).date, -1) : null;
}
export type BookingInput = {
startDate: string;
startMinute: number;
durationMinutes: number;
recurrence: Recurrence;
/** For a recurring booking; the longest allowed when left out. */
endDate?: string | null;
};
export type BookingError = { code: string; message: string };
/**
* Checks a new booking against the wall's rules (§3, decision 12) and answers the end date it
* gets, or why it can't be booked. `today` is the local date of `now` in the church's timezone.
*/
export function checkBooking(input: BookingInput, now: Date, wall: WallSettings, tz: string): { endDate: string } | { error: BookingError } {
const today = localParts(now, tz).date;
const err = (code: string, message: string) => ({ error: { code, message } });
if (input.startMinute < 0 || input.startMinute >= 1440 || input.startMinute % wall.slotMinutes !== 0) {
return err('NOT_A_SLOT', `Slots start every ${wall.slotMinutes} minutes.`);
}
if (input.durationMinutes < wall.slotMinutes || input.durationMinutes % wall.slotMinutes !== 0 || input.durationMinutes > MAX_DURATION_MINUTES) {
return err('BAD_LENGTH', `Book one slot or several in a row (${wall.slotMinutes} minutes each, up to ${MAX_DURATION_MINUTES / 60} hours).`);
}
const lastStart = addMonths(today, wall.bookAheadMonths);
if (input.startDate > lastStart) return err('TOO_FAR_AHEAD', `Slots can be booked up to ${wall.bookAheadMonths} months ahead.`);
let endDate = input.startDate;
if (input.recurrence !== 'once') {
const maxEnd = addMonths(today, wall.recurringMaxMonths);
endDate = input.endDate ?? maxEnd;
if (endDate < input.startDate) return err('END_BEFORE_START', 'The end date is before the first slot.');
if (endDate > maxEnd) return err('TOO_LONG', `A recurring slot can last up to ${wall.recurringMaxMonths} months from today.`);
}
const first = startOn(input.startDate, input.startMinute, tz);
if (!first || first <= now) return err('IN_THE_PAST', 'That slot has already started.');
return { endDate };
}
/** When a reminder is due for an occurrence, or null for none (§3, P6). */
export function reminderAt(reminder: Reminder, o: Pick<Occurrence, 'date' | 'start'>, tz: string): Date | null {
switch (reminder) {
case 'none': return null;
case 'min15': return new Date(o.start.getTime() - 15 * 60e3);
case 'hour1': return new Date(o.start.getTime() - 60 * 60e3);
case 'evening': return zonedTime(addDays(o.date, -1), 20 * 60, tz) ?? new Date(o.start.getTime() - 6 * 3600e3);
}
}
/** The new end date of "Renew for another year": the same length again from the current end. */
export const renewedEndDate = (rule: Pick<Rule, 'endDate'>, wall: Pick<WallSettings, 'recurringMaxMonths'>) => addMonths(rule.endDate, wall.recurringMaxMonths);
/** Days until a rule's last date, from the local `today` (renewal notices at 14 and 3, §3). */
export const daysLeft = (rule: Pick<Rule, 'endDate'>, today: string) => daysBetween(today, rule.endDate);
+346
View File
@@ -0,0 +1,346 @@
/**
* The House of Prayer on the database (APP-1.0-PLAN §3): coverage per day (cached until a booking
* changes), and booking, skipping, changing, cancelling, renewing and "I prayed". The rules
* themselves are in rules.ts; every change here calls `prayerChanged` (live.ts).
*
* Nothing here answers a name: the admin's bookings with names are in admin.ts, access-logged.
*/
import type { Ctx } from '../context.js';
import type { PrayerCommitment, PrayerSkip } from '../generated/prisma/client.js';
import { ApiError } from '../http.js';
import { churchTimezone } from '../church/profile.js';
import { addDays, addMonths, daysBetween, localDate } from '../lib/zoned.js';
import { coverageVersion, prayerChanged } from './live.js';
import {
cancelledEndDate, checkBooking, coveragePercent, dayCoverage, isLocked, nextOccurrence, occurrenceOn,
renewedEndDate, type BookingInput, type DayCoverage, type Occurrence, type Reminder, type Rule, type WallSettings,
} from './rules.js';
import { wallSettings } from './wall.js';
type Row = PrayerCommitment & { skips: PrayerSkip[] };
type Channel = 'email' | 'whatsapp' | 'both';
export const toRule = (r: Row): Rule => ({
id: r.id, memberId: r.memberId, startDate: r.startDate, startMinute: r.startMinute, durationMinutes: r.durationMinutes,
recurrence: r.recurrence, endDate: r.endDate, skips: r.skips.map((s) => s.date),
});
/** Rules with an occurrence that can touch [from, to] (a day before, for slots past midnight). */
export async function rulesBetween(ctx: Ctx, from: string, to: string, where: Record<string, unknown> = {}): Promise<Rule[]> {
const rows = await ctx.db.prayerCommitment.findMany({ where: { ...where, startDate: { lte: to }, endDate: { gte: addDays(from, -1) } }, include: { skips: true } });
return (rows as Row[]).map(toRule);
}
// ── Coverage ─────────────────────────────────────────────────────────────────────────────────
const DAY_CACHE_MAX = 400;
const dayCaches = new WeakMap<Ctx, Map<string, { version: number; day: DayCoverage }>>();
/** One day's coverage for everyone (counts only), cached until a booking changes. */
export async function wallDay(ctx: Ctx, date: string, wall: WallSettings, tz: string): Promise<DayCoverage> {
let cache = dayCaches.get(ctx);
if (!cache) dayCaches.set(ctx, (cache = new Map()));
const key = `${date}|${wall.slotMinutes}|${tz}`;
const version = coverageVersion(ctx);
const hit = cache.get(key);
if (hit && hit.version === version) return hit.day;
const day = dayCoverage(date, await rulesBetween(ctx, date, date), wall, tz);
if (cache.size >= DAY_CACHE_MAX) cache.clear();
cache.set(key, { version, day });
return day;
}
export type CoverageView = DayCoverage & {
timezone: string;
slotMinutes: number;
/** People per slot for "2 of 3" (the wall's, or the running campaign's own). */
target: number;
today: string;
now: string;
};
/** The day's clock: counts, covered, the asker's own slots (`mine`), never who. */
export async function coverageView(ctx: Ctx, date: string, memberId: string | null): Promise<CoverageView> {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const day = await wallDay(ctx, date, wall, tz);
let slots = day.slots;
if (memberId) {
const own = dayCoverage(date, await rulesBetween(ctx, date, date, { memberId }), wall, tz, memberId);
const mine = new Set(own.slots.filter((s) => s.mine).map((s) => s.minute));
slots = slots.map((s) => ({ ...s, mine: mine.has(s.minute) }));
}
const campaign = await currentCampaign(ctx, localDate(ctx.now(), tz));
return {
...day, slots, timezone: tz, slotMinutes: wall.slotMinutes,
target: campaign?.targetPerSlot ?? wall.targetPerSlot,
today: localDate(ctx.now(), tz), now: ctx.now().toISOString(),
};
}
/** Coverage of several days as a share (0–100): the heartbeat's last 7 days, a campaign. */
export async function coverageOver(ctx: Ctx, from: string, to: string): Promise<number> {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const days: DayCoverage[] = [];
for (let d = from; d <= to; d = addDays(d, 1)) days.push(await wallDay(ctx, d, wall, tz));
return coveragePercent(days);
}
// ── Campaigns ────────────────────────────────────────────────────────────────────────────────
export async function currentCampaign(ctx: Ctx, today: string) {
return ctx.db.prayerCampaign.findFirst({ where: { startDate: { lte: today }, endDate: { gte: today } }, orderBy: { startDate: 'desc' } });
}
/** Hours marked as prayed (self-reported) on dates in [from, to]. */
export async function hoursPrayed(ctx: Ctx, from: string, to: string): Promise<number> {
const marks = await ctx.db.prayedMark.findMany({ where: { date: { gte: from, lte: to } }, select: { commitmentId: true } });
if (!marks.length) return 0;
const ids = [...new Set(marks.map((m) => m.commitmentId))];
const rows = await ctx.db.prayerCommitment.findMany({ where: { id: { in: ids } }, select: { id: true, durationMinutes: true } });
const minutes = new Map(rows.map((r) => [r.id, r.durationMinutes]));
return Math.round(marks.reduce((t, m) => t + (minutes.get(m.commitmentId) ?? 0), 0) / 60);
}
/**
* What Home and the Prayer tab lead with during a campaign (P7): days left, collective coverage so
* far, hours marked as prayed. No rankings, no one's own total.
*/
export async function campaignSummary(ctx: Ctx) {
const tz = await churchTimezone(ctx);
const today = localDate(ctx.now(), tz);
const c = (await currentCampaign(ctx, today))
?? await ctx.db.prayerCampaign.findFirst({ where: { startDate: { gt: today, lte: addDays(today, 30) } }, orderBy: { startDate: 'asc' } });
if (!c) return null;
const started = c.startDate <= today;
const upTo = today < c.endDate ? today : c.endDate;
return {
id: c.id, title: c.title, description: c.description, imageUrl: c.imageUrl, goal: c.goal, startDate: c.startDate, endDate: c.endDate,
targetPerSlot: c.targetPerSlot,
started,
daysLeft: Math.max(0, daysBetween(today, c.endDate) + 1),
startsInDays: started ? 0 : daysBetween(today, c.startDate),
coveragePercent: started ? await coverageOver(ctx, c.startDate, upTo) : 0,
hoursPrayed: started ? await hoursPrayed(ctx, c.startDate, upTo) : 0,
};
}
// ── A member's commitments ───────────────────────────────────────────────────────────────────
export type NewCommitment = BookingInput & { reminder?: Reminder; channel?: Channel; note?: string | null };
function bookingError(e: { code: string; message: string }): never {
throw new ApiError(400, e.code, e.message);
}
export async function book(ctx: Ctx, memberId: string, input: NewCommitment, opts: { bookedById?: string } = {}) {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const checked = checkBooking(input, ctx.now(), wall, tz);
if ('error' in checked) bookingError(checked.error);
const row = await ctx.db.prayerCommitment.create({
data: {
memberId, startDate: input.startDate, startMinute: input.startMinute, durationMinutes: input.durationMinutes,
recurrence: input.recurrence, endDate: checked.endDate, reminder: input.reminder ?? 'hour1', channel: input.channel ?? 'email',
note: input.note?.trim() || null, bookedById: opts.bookedById ?? null,
},
});
prayerChanged(ctx, input.recurrence === 'once' ? { dates: [input.startDate] } : { all: true });
return row;
}
/** A member's own commitment (404 for anyone else's: never says it exists). */
export async function ownCommitment(ctx: Ctx, memberId: string | null, id: string): Promise<Row> {
const row = await ctx.db.prayerCommitment.findUnique({ where: { id }, include: { skips: true } }) as Row | null;
if (!row || (memberId !== null && row.memberId !== memberId)) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such prayer slot.');
return row;
}
function lockedError(wall: WallSettings): never {
const who = wall.coordinator.name ? `${wall.coordinator.name}${wall.coordinator.contact ? ` (${wall.coordinator.contact})` : ''}` : 'the prayer coordinator';
throw new ApiError(409, 'LOCKED', `This slot is less than ${wall.cancelHours} hours away, so it can't be changed in the App. Please contact ${who}.`);
}
export async function skip(ctx: Ctx, memberId: string, id: string, date: string) {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const row = await ownCommitment(ctx, memberId, id);
const rule = toRule(row);
if (row.recurrence === 'once') throw new ApiError(400, 'ONCE', 'Cancel a one-off slot instead of skipping it.');
const o = occurrenceOn({ ...rule, skips: [] }, date, tz);
if (!o) throw new ApiError(400, 'NO_OCCURRENCE', 'This slot doesn\'t happen on that date.');
if (isLocked(o, ctx.now(), wall.cancelHours)) lockedError(wall);
if (!rule.skips.includes(date)) await ctx.db.prayerSkip.create({ data: { commitmentId: id, date } });
prayerChanged(ctx, { dates: [date] });
}
export async function unskip(ctx: Ctx, memberId: string, id: string, date: string) {
const tz = await churchTimezone(ctx);
const row = await ownCommitment(ctx, memberId, id);
const o = occurrenceOn({ ...toRule(row), skips: [] }, date, tz);
if (!o || o.start <= ctx.now()) throw new ApiError(400, 'NO_OCCURRENCE', 'That date can\'t be added back.');
await ctx.db.prayerSkip.deleteMany({ where: { commitmentId: id, date } });
prayerChanged(ctx, { dates: [date] });
}
/**
* Cancels a commitment: what's left after its last started or locked occurrence goes (the slots
* open up). With nothing done yet it's removed. `force` (a prayer coordinator) ignores the window.
*/
export async function cancel(ctx: Ctx, memberId: string | null, id: string, opts: { force?: boolean } = {}): Promise<{ removed: boolean; endDate: string | null }> {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const row = await ownCommitment(ctx, memberId, id);
const rule = toRule(row);
const end = cancelledEndDate(rule, ctx.now(), { cancelHours: opts.force ? 0 : wall.cancelHours }, tz);
if (end === null) {
// Nothing has happened yet (so nothing was marked as prayed either): it goes altogether.
await ctx.db.prayerSkip.deleteMany({ where: { commitmentId: id } });
await ctx.db.prayerCommitment.delete({ where: { id } });
prayerChanged(ctx, row.recurrence === 'once' ? { dates: [row.startDate] } : { all: true });
return { removed: true, endDate: null };
}
if (end >= row.endDate) {
// What's left has started or is locked: nothing to cancel in the App.
if (nextOccurrence(rule, ctx.now(), tz)) lockedError(wall);
return { removed: false, endDate: row.endDate };
}
await ctx.db.prayerCommitment.update({ where: { id }, data: { endDate: end } });
prayerChanged(ctx, { all: true });
return { removed: false, endDate: end };
}
export type CommitmentChange = Partial<NewCommitment> & { endDate?: string | null };
/**
* Changes a commitment. The end date alone (a recurring one) is changed in place; anything about
* when it happens ends the old rule (as a cancel) and starts a new one, so the past stays as it was.
* Reminder, channel and the note change in place.
*/
export async function change(ctx: Ctx, memberId: string, id: string, c: CommitmentChange) {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const row = await ownCommitment(ctx, memberId, id);
const now = ctx.now();
const today = localDate(now, tz);
const inPlace: Record<string, unknown> = {};
if (c.reminder !== undefined) inPlace.reminder = c.reminder;
if (c.channel !== undefined) inPlace.channel = c.channel;
if (c.note !== undefined) inPlace.note = c.note?.trim() || null;
const when = (['startDate', 'startMinute', 'durationMinutes', 'recurrence'] as const).some((k) => c[k] !== undefined && c[k] !== row[k]);
if (!when) {
if (c.endDate !== undefined && c.endDate !== row.endDate) {
if (row.recurrence === 'once') throw new ApiError(400, 'ONCE', 'A one-off slot has no end date to change.');
const endDate = c.endDate ?? row.endDate;
const lockedEnd = cancelledEndDate(toRule(row), now, wall, tz) ?? addDays(row.startDate, -1);
if (endDate < lockedEnd || endDate < row.startDate) lockedError(wall);
if (endDate > addMonths(today, wall.recurringMaxMonths) && endDate > row.endDate) throw new ApiError(400, 'TOO_LONG', `A recurring slot can last up to ${wall.recurringMaxMonths} months from today.`);
inPlace.endDate = endDate;
inPlace.renewalNoticesSent = 0;
}
if (!Object.keys(inPlace).length) return row;
const updated = await ctx.db.prayerCommitment.update({ where: { id }, data: inPlace });
if ('endDate' in inPlace) prayerChanged(ctx, { all: true });
return updated;
}
const input: NewCommitment = {
startDate: c.startDate ?? row.startDate,
startMinute: c.startMinute ?? row.startMinute,
durationMinutes: c.durationMinutes ?? row.durationMinutes,
recurrence: c.recurrence ?? row.recurrence,
endDate: c.endDate === undefined ? (row.recurrence === 'once' ? null : row.endDate) : c.endDate,
reminder: (c.reminder ?? row.reminder) as Reminder,
channel: c.channel ?? row.channel,
note: c.note === undefined ? row.note : c.note,
};
const checked = checkBooking(input, now, wall, tz);
if ('error' in checked) bookingError(checked.error);
await cancel(ctx, memberId, id);
return book(ctx, memberId, input);
}
export async function renew(ctx: Ctx, memberId: string | null, id: string) {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const row = await ownCommitment(ctx, memberId, id);
const today = localDate(ctx.now(), tz);
if (row.recurrence === 'once') throw new ApiError(400, 'ONCE', 'A one-off slot can\'t be renewed.');
if (row.endDate < today || !row.memberId) throw new ApiError(410, 'ENDED', 'This prayer slot has ended. Book it again in the App.');
const endDate = renewedEndDate(row, wall);
const updated = await ctx.db.prayerCommitment.update({ where: { id }, data: { endDate, renewalNoticesSent: 0, renewedAt: ctx.now() } });
prayerChanged(ctx, { all: true });
return updated;
}
/** How far back "I prayed" can be marked. */
export const PRAYED_DAYS = 14;
/** "I prayed" for one occurrence, once it has ended (self-reported). */
export async function markPrayed(ctx: Ctx, memberId: string | null, id: string, date: string) {
const tz = await churchTimezone(ctx);
const row = await ownCommitment(ctx, memberId, id);
const o = occurrenceOn(toRule(row), date, tz);
if (!o) throw new ApiError(400, 'NO_OCCURRENCE', 'This slot didn\'t happen on that date.');
if (o.end > ctx.now()) throw new ApiError(400, 'NOT_YET', '"I prayed" can be marked once the slot has ended.');
if (daysBetween(date, localDate(ctx.now(), tz)) > PRAYED_DAYS) throw new ApiError(400, 'TOO_OLD', `"I prayed" can be marked for the last ${PRAYED_DAYS} days.`);
const existing = await ctx.db.prayedMark.findFirst({ where: { commitmentId: id, date } });
if (!existing) await ctx.db.prayedMark.create({ data: { commitmentId: id, memberId: row.memberId, date } });
return { date, prayed: true };
}
/** Everything "Me: my prayer" shows (mockup): each commitment, its next dates and what can be done. */
export async function myPrayer(ctx: Ctx, memberId: string) {
const [wall, tz] = await Promise.all([wallSettings(ctx), churchTimezone(ctx)]);
const now = ctx.now();
const today = localDate(now, tz);
const rows = await ctx.db.prayerCommitment.findMany({ where: { memberId, endDate: { gte: addDays(today, -PRAYED_DAYS) } }, include: { skips: true }, orderBy: [{ startMinute: 'asc' }] }) as Row[];
const marks = await ctx.db.prayedMark.findMany({ where: { memberId, date: { gte: addDays(today, -PRAYED_DAYS) } } });
const marked = new Set(marks.map((m) => `${m.commitmentId}|${m.date}`));
const commitments = rows.map((row) => {
const rule = toRule(row);
const upcoming: (Occurrence & { locked: boolean })[] = [];
for (let d = today < row.startDate ? row.startDate : today, n = 0; d <= row.endDate && upcoming.length < 6 && n < 400; d = addDays(d, 1), n++) {
const o = occurrenceOn({ ...rule, skips: [] }, d, tz);
if (o && o.start > now) upcoming.push({ ...o, locked: isLocked(o, now, wall.cancelHours) });
}
// Ended occurrences of the last 14 days that can still be marked.
const toMark: string[] = [];
for (let d = addDays(today, -PRAYED_DAYS); d <= today; d = addDays(d, 1)) {
const o = occurrenceOn(rule, d, tz);
if (o && o.end <= now && !marked.has(`${row.id}|${d}`)) toMark.push(d);
}
const active = row.endDate >= today;
return {
id: row.id, startDate: row.startDate, startMinute: row.startMinute, durationMinutes: row.durationMinutes,
recurrence: row.recurrence, endDate: row.endDate, reminder: row.reminder, channel: row.channel, note: row.note,
active,
daysLeft: daysBetween(today, row.endDate),
canRenew: active && row.recurrence !== 'once' && daysBetween(today, row.endDate) <= 30,
upcoming: upcoming.map((o) => ({ date: o.date, start: o.start.toISOString(), end: o.end.toISOString(), skipped: rule.skips.includes(o.date), locked: o.locked })),
toMark: toMark.reverse(),
};
}).filter((c) => c.active || c.toMark.length);
const prayedTotal = await ctx.db.prayedMark.count({ where: { memberId } });
return {
timezone: tz,
rules: { slotMinutes: wall.slotMinutes, cancelHours: wall.cancelHours, bookAheadMonths: wall.bookAheadMonths, recurringMaxMonths: wall.recurringMaxMonths },
coordinator: wall.coordinator,
commitments,
/** "12 times marked as prayed (self-reported)": the member's own count, shown to them alone. */
prayedTotal,
};
}
/** The heartbeat's counts (hub.appStatsSchema `prayer`): no names, no times. */
export async function prayerStats(ctx: Ctx): Promise<{ coverageLast7dPercent: number; activeCommitments: number }> {
const tz = await churchTimezone(ctx);
const today = localDate(ctx.now(), tz);
const [coverageLast7dPercent, activeCommitments] = await Promise.all([
coverageOver(ctx, addDays(today, -7), addDays(today, -1)),
ctx.db.prayerCommitment.count({ where: { endDate: { gte: today }, memberId: { not: null } } }),
]);
return { coverageLast7dPercent, activeCommitments };
}
/** An occurrence that exists on `date` (skips counted), for the reminder links. */
export async function occurrenceFor(ctx: Ctx, id: string, date: string): Promise<{ row: Row; o: Occurrence } | null> {
const row = await ctx.db.prayerCommitment.findUnique({ where: { id }, include: { skips: true } }) as Row | null;
if (!row) return null;
const o = occurrenceOn(toRule(row), date, await churchTimezone(ctx));
return o ? { row, o } : null;
}
@@ -0,0 +1,46 @@
/**
* Testimonies (APP-1.0-PLAN §3): what God has done, shared by a member, optionally for a campaign.
* **Moderated before anyone sees it**, shown with the first name or "Anonymous" (the author's
* choice), removable by its author at any time. A removed one tells its author why.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
export const TESTIMONY_MAX = 2000;
const submitBody = z.object({
text: z.string().trim().min(10, 'A few words at least.').max(TESTIMONY_MAX),
showName: z.boolean().default(false),
campaignId: z.string().uuid().nullable().optional(),
}).strict();
const firstName = (name: string) => name.trim().split(/\s+/)[0] || 'Anonymous';
export async function submitTestimony(ctx: Ctx, memberId: string, body: unknown) {
const r = submitBody.safeParse(body);
if (!r.success) throw new ApiError(400, 'VALIDATION', 'Please check the highlighted fields.', Object.fromEntries(r.error.issues.map((i) => [i.path.join('.') || '_', i.message])));
if (r.data.campaignId && !(await ctx.db.prayerCampaign.findUnique({ where: { id: r.data.campaignId } }))) {
throw new ApiError(400, 'VALIDATION', 'There\'s no such campaign.', { campaignId: 'There\'s no such campaign.' });
}
const t = await ctx.db.testimony.create({ data: { memberId, text: r.data.text, showName: r.data.showName, campaignId: r.data.campaignId ?? null } });
return { id: t.id, status: t.status };
}
export async function myTestimonies(ctx: Ctx, memberId: string) {
const rows = await ctx.db.testimony.findMany({ where: { memberId }, orderBy: { createdAt: 'desc' } });
return rows.map((t) => ({ id: t.id, text: t.text, showName: t.showName, campaignId: t.campaignId, status: t.status, removedReason: t.removedReason, createdAt: t.createdAt.toISOString() }));
}
export async function deleteOwnTestimony(ctx: Ctx, memberId: string, id: string) {
const { count } = await ctx.db.testimony.deleteMany({ where: { id, memberId } });
if (!count) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such testimony.');
}
/** Approved testimonies for everyone: the text, the first name or "Anonymous", the date. */
export async function approvedTestimonies(ctx: Ctx, campaignId: string | null, take = 30) {
const rows = await ctx.db.testimony.findMany({ where: { status: 'approved', ...(campaignId ? { campaignId } : {}) }, orderBy: { createdAt: 'desc' }, take });
const members = await ctx.db.member.findMany({ where: { id: { in: rows.filter((t) => t.showName).map((t) => t.memberId) } }, select: { id: true, name: true } });
const names = new Map(members.map((m) => [m.id, firstName(m.name)]));
return rows.map((t) => ({ id: t.id, text: t.text, by: (t.showName && names.get(t.memberId)) || 'Anonymous', campaignId: t.campaignId, createdAt: t.createdAt.toISOString() }));
}
+30
View File
@@ -0,0 +1,30 @@
/**
* Signed links in reminders and renewal notices (APP-1.0-PLAN §3), usable without signing in:
*
* - **Renew** (`renew`): signed over the commitment and its current end date, so it works once
* (renewing moves the end date) and expires with the commitment.
* - **I prayed** (`prayed`): signed over the commitment and the occurrence's date; a second use
* changes nothing.
*
* `<commitment id>.<date>.<signature>`, HMAC-SHA256 with APP_SECRET.
*/
import crypto from 'node:crypto';
import type { Ctx } from '../context.js';
export type TokenPurpose = 'renew' | 'prayed';
const sign = (ctx: Ctx, purpose: TokenPurpose, id: string, date: string) =>
crypto.createHmac('sha256', ctx.config.secret).update(`app-prayer|${purpose}|${id}|${date}`).digest('base64url').slice(0, 32);
export const prayerToken = (ctx: Ctx, purpose: TokenPurpose, id: string, date: string) => `${id}.${date}.${sign(ctx, purpose, id, date)}`;
/** The commitment id and date a token is for, or null when it isn't one of ours. */
export function readPrayerToken(ctx: Ctx, purpose: TokenPurpose, token: unknown): { id: string; date: string } | null {
if (typeof token !== 'string' || token.length > 200) return null;
const m = /^([0-9a-f-]{36})\.(\d{4}-\d{2}-\d{2})\.([\w-]{32})$/.exec(token);
if (!m) return null;
const expected = Buffer.from(sign(ctx, purpose, m[1]!, m[2]!));
const given = Buffer.from(m[3]!);
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) return null;
return { id: m[1]!, date: m[2]! };
}
+41
View File
@@ -0,0 +1,41 @@
/**
* The prayer wall's rules (Settings → House of Prayer, APP-1.0-PLAN §3, decision 12), kept in
* AppSetting `prayer_wall`. Anything not saved is the default; a saved value outside the limits
* is ignored (the default wins), so a hand-edited row never breaks the wall.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { DEFAULT_WALL, SLOT_LENGTHS, type WallSettings } from './rules.js';
const KEY = 'prayer_wall';
export const wallSchema = z.object({
slotMinutes: z.union(SLOT_LENGTHS.map((n) => z.literal(n)) as [z.ZodLiteral<15>, z.ZodLiteral<30>, z.ZodLiteral<60>]),
targetPerSlot: z.number().int().min(1).max(50),
bookAheadMonths: z.number().int().min(1).max(12),
recurringMaxMonths: z.number().int().min(1).max(12),
cancelHours: z.number().int().min(0).max(48),
coordinator: z.object({
name: z.string().trim().max(120).nullable(),
contact: z.string().trim().max(200).nullable(),
}),
});
export async function wallSettings(ctx: Ctx): Promise<WallSettings> {
const saved = await ctx.settings.json<Record<string, unknown>>(KEY, {});
const out = { ...DEFAULT_WALL, coordinator: { ...DEFAULT_WALL.coordinator } } as WallSettings;
const shape = wallSchema.shape;
for (const k of Object.keys(shape) as (keyof WallSettings)[]) {
const parsed = shape[k].safeParse(saved?.[k]);
if (parsed.success) (out as Record<string, unknown>)[k] = parsed.data;
}
return out;
}
/** Saves a change (only the fields given); answers the new settings. Throws a ZodError when invalid. */
export async function setWallSettings(ctx: Ctx, change: unknown): Promise<WallSettings> {
const parsed = wallSchema.partial().strict().parse(change);
const next = { ...(await wallSettings(ctx)), ...parsed };
await ctx.settings.set(KEY, JSON.stringify(next));
return next;
}