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:
@@ -0,0 +1,169 @@
|
|||||||
|
-- Church App 1.0.0: the House of Prayer (docs/APP-1.0-PLAN.md §3): commitments as rules with their
|
||||||
|
-- skips, "I prayed" marks, campaigns, testimonies, the access log and the outbox for reminders.
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PrayerRecurrence" AS ENUM ('once', 'daily', 'weekly');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PrayerReminder" AS ENUM ('none', 'min15', 'hour1', 'evening');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "MessageChannel" AS ENUM ('email', 'whatsapp', 'both');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "TestimonyStatus" AS ENUM ('pending', 'approved', 'removed');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "PrayerCommitment" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"memberId" TEXT,
|
||||||
|
"startDate" TEXT NOT NULL,
|
||||||
|
"startMinute" INTEGER NOT NULL,
|
||||||
|
"durationMinutes" INTEGER NOT NULL,
|
||||||
|
"recurrence" "PrayerRecurrence" NOT NULL,
|
||||||
|
"endDate" TEXT NOT NULL,
|
||||||
|
"reminder" "PrayerReminder" NOT NULL DEFAULT 'hour1',
|
||||||
|
"channel" "MessageChannel" NOT NULL DEFAULT 'email',
|
||||||
|
"note" TEXT,
|
||||||
|
"bookedById" TEXT,
|
||||||
|
"renewalNoticesSent" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"renewedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "PrayerCommitment_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "PrayerSkip" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"commitmentId" TEXT NOT NULL,
|
||||||
|
"date" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "PrayerSkip_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "PrayedMark" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"commitmentId" TEXT NOT NULL,
|
||||||
|
"memberId" TEXT,
|
||||||
|
"date" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "PrayedMark_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "PrayerCampaign" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"description" TEXT NOT NULL,
|
||||||
|
"imageUrl" TEXT,
|
||||||
|
"startDate" TEXT NOT NULL,
|
||||||
|
"endDate" TEXT NOT NULL,
|
||||||
|
"goal" TEXT,
|
||||||
|
"targetPerSlot" INTEGER,
|
||||||
|
"createdById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "PrayerCampaign_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Testimony" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"memberId" TEXT NOT NULL,
|
||||||
|
"campaignId" TEXT,
|
||||||
|
"text" TEXT NOT NULL,
|
||||||
|
"showName" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"status" "TestimonyStatus" NOT NULL DEFAULT 'pending',
|
||||||
|
"removedReason" TEXT,
|
||||||
|
"moderatedById" TEXT,
|
||||||
|
"moderatedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "Testimony_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "AccessLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"actorId" TEXT NOT NULL,
|
||||||
|
"action" TEXT NOT NULL,
|
||||||
|
"targetType" TEXT NOT NULL,
|
||||||
|
"targetId" TEXT,
|
||||||
|
"metadata" JSONB,
|
||||||
|
"ip" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "AccessLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "OutboxMessage" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"memberId" TEXT NOT NULL,
|
||||||
|
"kind" TEXT NOT NULL,
|
||||||
|
"channel" "MessageChannel" NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"dedupeKey" TEXT NOT NULL,
|
||||||
|
"sendAfter" TIMESTAMP(3) NOT NULL,
|
||||||
|
"sentAt" TIMESTAMP(3),
|
||||||
|
"failedAt" TIMESTAMP(3),
|
||||||
|
"error" TEXT,
|
||||||
|
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "OutboxMessage_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "PrayerCommitment_endDate_idx" ON "PrayerCommitment"("endDate");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "PrayerCommitment_memberId_idx" ON "PrayerCommitment"("memberId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "PrayerSkip_commitmentId_date_key" ON "PrayerSkip"("commitmentId", "date");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "PrayedMark_date_idx" ON "PrayedMark"("date");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "PrayedMark_commitmentId_date_key" ON "PrayedMark"("commitmentId", "date");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "PrayerCampaign_endDate_idx" ON "PrayerCampaign"("endDate");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Testimony_status_createdAt_idx" ON "Testimony"("status", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AccessLog_createdAt_idx" ON "AccessLog"("createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "OutboxMessage_dedupeKey_key" ON "OutboxMessage"("dedupeKey");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "OutboxMessage_sentAt_sendAfter_idx" ON "OutboxMessage"("sentAt", "sendAfter");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "PrayerCommitment" ADD CONSTRAINT "PrayerCommitment_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "Member"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "PrayerSkip" ADD CONSTRAINT "PrayerSkip_commitmentId_fkey" FOREIGN KEY ("commitmentId") REFERENCES "PrayerCommitment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "PrayedMark" ADD CONSTRAINT "PrayedMark_commitmentId_fkey" FOREIGN KEY ("commitmentId") REFERENCES "PrayerCommitment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Testimony" ADD CONSTRAINT "Testimony_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "Member"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Testimony" ADD CONSTRAINT "Testimony_campaignId_fkey" FOREIGN KEY ("campaignId") REFERENCES "PrayerCampaign"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "OutboxMessage" ADD CONSTRAINT "OutboxMessage_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "Member"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
@@ -32,20 +32,23 @@ enum AppRole {
|
|||||||
/// signed in is a Member; `roles` adds what the admin can do. A copy of the Accounts profile, kept
|
/// signed in is a Member; `roles` adds what the admin can do. A copy of the Accounts profile, kept
|
||||||
/// up to date by `user.updated`.
|
/// up to date by `user.updated`.
|
||||||
model Member {
|
model Member {
|
||||||
id String @id
|
id String @id
|
||||||
name String
|
name String
|
||||||
email String
|
email String
|
||||||
/// The verified number from Accounts (reminders by WhatsApp), or null.
|
/// The verified number from Accounts (reminders by WhatsApp), or null.
|
||||||
phone String?
|
phone String?
|
||||||
/// The person replied STOP to the church's WhatsApp number (decision 11): no WhatsApp of any kind.
|
/// The person replied STOP to the church's WhatsApp number (decision 11): no WhatsApp of any kind.
|
||||||
whatsappOptedOut Boolean @default(false)
|
whatsappOptedOut Boolean @default(false)
|
||||||
roles AppRole[] @default([])
|
roles AppRole[] @default([])
|
||||||
/// The last day they used the App signed in (written at most once a day): active members (§10).
|
/// The last day they used the App signed in (written at most once a day): active members (§10).
|
||||||
lastActiveAt DateTime?
|
lastActiveAt DateTime?
|
||||||
lastSignInAt DateTime?
|
lastSignInAt DateTime?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
sessions Session[]
|
sessions Session[]
|
||||||
|
prayerCommitments PrayerCommitment[]
|
||||||
|
testimonies Testimony[]
|
||||||
|
outboxMessages OutboxMessage[]
|
||||||
|
|
||||||
@@index([lastActiveAt])
|
@@index([lastActiveAt])
|
||||||
}
|
}
|
||||||
@@ -117,3 +120,167 @@ model AppSetting {
|
|||||||
value String
|
value String
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── House of Prayer (§3) ─────────────────────────────────────────────────────────────────────
|
||||||
|
// The wall's rules (slot length, target, booking limits, the cancel window, the coordinator to
|
||||||
|
// contact) are in AppSetting `prayer_wall`. Days are local dates (YYYY-MM-DD) in the church's
|
||||||
|
// timezone; minutes are after local midnight (src/prayer/rules.ts).
|
||||||
|
|
||||||
|
enum PrayerRecurrence {
|
||||||
|
once
|
||||||
|
daily
|
||||||
|
weekly
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When a member is reminded of a slot (P6): none, 15 minutes or an hour before, or 20:00 the evening before.
|
||||||
|
enum PrayerReminder {
|
||||||
|
none
|
||||||
|
min15
|
||||||
|
hour1
|
||||||
|
evening
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a member is reached for one kind of message (§8).
|
||||||
|
enum MessageChannel {
|
||||||
|
email
|
||||||
|
whatsapp
|
||||||
|
both
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A commitment to pray: a rule (start, length, recurrence, end) plus the dates skipped, never a
|
||||||
|
/// row per occurrence (§3). The member's name is never in coverage; only the prayer team sees it.
|
||||||
|
model PrayerCommitment {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
/// Null once the member deleted their account: past occurrences stay as counts only (§11).
|
||||||
|
memberId String?
|
||||||
|
member Member? @relation(fields: [memberId], references: [id], onDelete: SetNull)
|
||||||
|
/// The first local date it happens on (a weekly rule keeps this date's weekday).
|
||||||
|
startDate String
|
||||||
|
/// Minutes after local midnight (02:00 = 120), on a slot boundary when booked.
|
||||||
|
startMinute Int
|
||||||
|
durationMinutes Int
|
||||||
|
recurrence PrayerRecurrence
|
||||||
|
/// The last local date with an occurrence (a once rule: its start date).
|
||||||
|
endDate String
|
||||||
|
reminder PrayerReminder @default(hour1)
|
||||||
|
/// Reminders and renewal notices for this commitment.
|
||||||
|
channel MessageChannel @default(email)
|
||||||
|
/// "Where I'll pray", for the member alone.
|
||||||
|
note String?
|
||||||
|
/// A prayer coordinator who booked it on the member's behalf.
|
||||||
|
bookedById String?
|
||||||
|
/// Renewal notices sent for the current end date: 0, 1 (14 days before) or 2 (3 days before).
|
||||||
|
renewalNoticesSent Int @default(0)
|
||||||
|
renewedAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
skips PrayerSkip[]
|
||||||
|
marks PrayedMark[]
|
||||||
|
|
||||||
|
@@index([endDate])
|
||||||
|
@@index([memberId])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One occurrence skipped ("Skip 14 December").
|
||||||
|
model PrayerSkip {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
commitmentId String
|
||||||
|
commitment PrayerCommitment @relation(fields: [commitmentId], references: [id], onDelete: Cascade)
|
||||||
|
date String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@unique([commitmentId, date])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "I prayed" for one occurrence: self-reported, counted as a number only, never a ranking (§3).
|
||||||
|
model PrayedMark {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
commitmentId String
|
||||||
|
commitment PrayerCommitment @relation(fields: [commitmentId], references: [id], onDelete: Cascade)
|
||||||
|
memberId String?
|
||||||
|
date String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@unique([commitmentId, date])
|
||||||
|
@@index([date])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A time-bound focus ("21 days of prayer", P7): collective coverage and hours prayed only.
|
||||||
|
model PrayerCampaign {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
title String
|
||||||
|
description String
|
||||||
|
imageUrl String?
|
||||||
|
startDate String
|
||||||
|
endDate String
|
||||||
|
/// "Every hour covered", shown as the campaign's aim.
|
||||||
|
goal String?
|
||||||
|
/// The campaign's own people per slot, instead of the wall's target, while it runs.
|
||||||
|
targetPerSlot Int?
|
||||||
|
createdById String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
testimonies Testimony[]
|
||||||
|
|
||||||
|
@@index([endDate])
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TestimonyStatus {
|
||||||
|
pending
|
||||||
|
approved
|
||||||
|
removed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What God has done, shared by a member: moderated before anyone sees it, the first name or
|
||||||
|
/// "Anonymous", removable by its author at any time (§3). Deleted with the account (§11).
|
||||||
|
model Testimony {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
memberId String
|
||||||
|
member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
|
||||||
|
campaignId String?
|
||||||
|
campaign PrayerCampaign? @relation(fields: [campaignId], references: [id], onDelete: SetNull)
|
||||||
|
text String
|
||||||
|
showName Boolean @default(false)
|
||||||
|
status TestimonyStatus @default(pending)
|
||||||
|
/// Why a coordinator removed it (sent to the author).
|
||||||
|
removedReason String?
|
||||||
|
moderatedById String?
|
||||||
|
moderatedAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([status, createdAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who saw names (§3, §10 Access log): every view of bookings with names, and later of prayer requests.
|
||||||
|
model AccessLog {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
actorId String
|
||||||
|
action String
|
||||||
|
targetType String
|
||||||
|
targetId String?
|
||||||
|
metadata Json?
|
||||||
|
ip String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([createdAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Email and WhatsApp to send (§8): reminders, renewal notices and later the modules' sends. Written
|
||||||
|
/// once (`dedupeKey`), sent by the messaging job; what's in `payload` is the message's facts only.
|
||||||
|
model OutboxMessage {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
memberId String
|
||||||
|
member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
|
||||||
|
kind String
|
||||||
|
channel MessageChannel
|
||||||
|
payload Json
|
||||||
|
dedupeKey String @unique
|
||||||
|
sendAfter DateTime
|
||||||
|
sentAt DateTime?
|
||||||
|
failedAt DateTime?
|
||||||
|
error String?
|
||||||
|
attempts Int @default(0)
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([sentAt, sendAfter])
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,9 +10,12 @@
|
|||||||
* /api/links/v1/… Connect and Disconnect with the church's other products
|
* /api/links/v1/… Connect and Disconnect with the church's other products
|
||||||
* /api/church/v1/changed Accounts: the church profile changed
|
* /api/church/v1/changed Accounts: the church profile changed
|
||||||
* /api/v1/admin/… the admin (a role above Member, with 2FA)
|
* /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
|
* To come with the modules (§1): the rest of the public content and member API, and the event feed.
|
||||||
* coverage (/api/v1/prayer/stream) and the event feed.
|
|
||||||
*/
|
*/
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
import type { Ctx } from './context.js';
|
import type { Ctx } from './context.js';
|
||||||
@@ -23,6 +26,8 @@ import { ApiError, handle, sendError } from './http.js';
|
|||||||
import { appVersion } from './lib/version.js';
|
import { appVersion } from './lib/version.js';
|
||||||
import { linksRouter } from './links/routes.js';
|
import { linksRouter } from './links/routes.js';
|
||||||
import { appInfo } from './public/app.js';
|
import { appInfo } from './public/app.js';
|
||||||
|
import { prayerAdminRouter } from './prayer/admin.js';
|
||||||
|
import { prayerRouter } from './prayer/routes.js';
|
||||||
|
|
||||||
export function createApp(ctx: Ctx) {
|
export function createApp(ctx: Ctx) {
|
||||||
const app = express();
|
const app = express();
|
||||||
@@ -50,6 +55,8 @@ export function createApp(ctx: Ctx) {
|
|||||||
|
|
||||||
app.use('/api', authRouter(ctx));
|
app.use('/api', authRouter(ctx));
|
||||||
app.use('/api', linksRouter(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/v1/admin', adminRouter(ctx));
|
||||||
|
|
||||||
app.use('/api', (_req, res) => {
|
app.use('/api', (_req, res) => {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
* exact page it started from (ROADMAP-v3 §3).
|
* exact page it started from (ROADMAP-v3 §3).
|
||||||
*/
|
*/
|
||||||
import express, { type Request, type Response } from 'express';
|
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 { 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 { Ctx } from '../context.js';
|
||||||
import type { AppRole } from '../generated/prisma/client.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;
|
* Accounts' signed calls (§11): a member's profile copy, roles and sign-ins, and the House of
|
||||||
* each module adds its own records to the export and the delete as it arrives (commitments, "I
|
* Prayer's commitments, "I prayed" marks and testimonies (prayer/members.ts). Each later module
|
||||||
* prayed" marks, requests, testimonies, notification settings). Someone the App doesn't know is
|
* adds its own records to the export and the delete (requests, notification settings). Someone the App doesn't know is
|
||||||
* answered as done.
|
* answered as done.
|
||||||
*/
|
*/
|
||||||
export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Request): Promise<object> {
|
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',
|
key: 'app_member',
|
||||||
title: 'You in the church\'s App',
|
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 }],
|
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;
|
return reply;
|
||||||
}
|
}
|
||||||
case 'user.deleted': {
|
case 'user.deleted': {
|
||||||
if (member) {
|
if (member) {
|
||||||
|
await deletePrayer(ctx, member.id);
|
||||||
await ctx.db.session.deleteMany({ where: { memberId: member.id } });
|
await ctx.db.session.deleteMany({ where: { memberId: member.id } });
|
||||||
await ctx.db.member.delete({ where: { id: 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) });
|
await audit(ctx, { actorId: null, actorRole: 'accounts', action: 'member_deleted', targetType: 'member', targetId: member.id, metadata: { roles: member.roles }, ip: clientIp(req) });
|
||||||
|
|||||||
@@ -69,3 +69,8 @@ export function churchChanged(ctx: Ctx): void {
|
|||||||
const state = caches.get(ctx);
|
const state = caches.get(ctx);
|
||||||
if (state?.cached) state.cached = { ...state.cached, at: 0 };
|
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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { keyPair, saveLinkedProducts } from '../links/store.js';
|
|||||||
import { activeMembers } from '../members/activity.js';
|
import { activeMembers } from '../members/activity.js';
|
||||||
import { enabledModules } from '../modules.js';
|
import { enabledModules } from '../modules.js';
|
||||||
import { hubPublicKey, verifyToken } from './licence.js';
|
import { hubPublicKey, verifyToken } from './licence.js';
|
||||||
|
import { prayerStats } from '../prayer/service.js';
|
||||||
import { jobsHealth } from '../jobs.js';
|
import { jobsHealth } from '../jobs.js';
|
||||||
|
|
||||||
export const PROTOCOL_VERSION = 2;
|
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
|
* Aggregate counts only (hub.appStatsSchema): prayer coverage of the last 7 days and active
|
||||||
* messages are 0 until their modules arrive.
|
* 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>> {
|
export async function stats(ctx: Ctx): Promise<z.infer<typeof hub.appStatsSchema>> {
|
||||||
const [{ band }, modules] = await Promise.all([activeMembers(ctx), enabledModules(ctx)]);
|
const [{ band }, modules] = await Promise.all([activeMembers(ctx), enabledModules(ctx)]);
|
||||||
return {
|
return {
|
||||||
activeMembers90d: band,
|
activeMembers90d: band,
|
||||||
modules,
|
modules,
|
||||||
prayer: { coverageLast7dPercent: 0, activeCommitments: 0 },
|
prayer: modules.includes('house-of-prayer') ? await prayerStats(ctx) : { coverageLast7dPercent: 0, activeCommitments: 0 },
|
||||||
announcements: { last30d: 0 },
|
announcements: { last30d: 0 },
|
||||||
messages: { email30d: 0, whatsapp30d: 0 },
|
messages: { email30d: 0, whatsapp30d: 0 },
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
* however many processes run, and timers in this process if the queue can't start.
|
* however many processes run, and timers in this process if the queue can't start.
|
||||||
* JOBS_ENABLED=false turns them all off.
|
* 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 Hub heartbeat and the House of Prayer's reminders and renewal notices (prayer/jobs.ts). The
|
||||||
* the event feed, Cross Code's devotionals (the next 2 weeks, today included, once a night, §6),
|
* 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.
|
* announcement and devotional sends, and the nightly backup.
|
||||||
*
|
*
|
||||||
* Settings → Background jobs (§10) shows each job's schedule and last runs, runs one now, and
|
* 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 PgBoss from 'pg-boss';
|
||||||
import type { Ctx } from './context.js';
|
import type { Ctx } from './context.js';
|
||||||
import { heartbeat } from './hub/client.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 type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
||||||
|
|
||||||
export const JOBS: Job[] = [
|
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: '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';
|
const SCHEMA = 'pgboss_app';
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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}`);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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 };
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
@@ -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() }));
|
||||||
|
}
|
||||||
@@ -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]! };
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import type { AddressInfo } from 'node:net';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { stats } from '../src/hub/client.js';
|
||||||
|
import { sendReminders, sendRenewalNotices } from '../src/prayer/jobs.js';
|
||||||
|
import { prayerToken } from '../src/prayer/tokens.js';
|
||||||
|
import { cookieHeader, harness, MEMBER, signInAs, type Harness } from './support/harness.js';
|
||||||
|
|
||||||
|
const OTHER = '44444444-4444-4444-8444-444444444444';
|
||||||
|
const COORD = '55555555-5555-4555-8555-555555555555';
|
||||||
|
|
||||||
|
const DAY = 24 * 3600e3;
|
||||||
|
|
||||||
|
// The clock starts on Tuesday 1 December 2026 at 08:00 in Johannesburg (06:00 UTC).
|
||||||
|
const slot = (over: object = {}) => ({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 60, recurrence: 'once', ...over });
|
||||||
|
|
||||||
|
async function setup() {
|
||||||
|
const h = await harness() as Harness;
|
||||||
|
const member = await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test' });
|
||||||
|
const other = await signInAs(h, { sub: OTHER, name: 'Pieter Botha', email: 'pieter@hope.test' });
|
||||||
|
const as = (cookies: Record<string, string>) => ({
|
||||||
|
get: (path: string) => request(h.app).get(path).set('Cookie', cookieHeader(cookies)),
|
||||||
|
post: (path: string, body: object = {}) => request(h.app).post(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body),
|
||||||
|
patch: (path: string, body: object) => request(h.app).patch(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body),
|
||||||
|
put: (path: string, body: object) => request(h.app).put(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body),
|
||||||
|
del: (path: string) => request(h.app).delete(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test'),
|
||||||
|
});
|
||||||
|
return { h, thandi: as(member), pieter: as(other), visitor: as({}), as };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('the prayer wall', () => {
|
||||||
|
it('shows the day as counts only: no name, email or id of anyone, and "mine" only to the member', async () => {
|
||||||
|
const { thandi, pieter, visitor } = await setup();
|
||||||
|
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', slot())).status, 201);
|
||||||
|
assert.equal((await pieter.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily' }))).status, 201);
|
||||||
|
|
||||||
|
const pub = await visitor.get('/api/v1/prayer/day?date=2026-12-02');
|
||||||
|
assert.equal(pub.status, 200);
|
||||||
|
assert.match(pub.headers['cache-control']!, /public/);
|
||||||
|
const two = pub.body.slots.find((s: { minute: number }) => s.minute === 120);
|
||||||
|
assert.deepEqual({ count: two.count, covered: two.covered, mine: two.mine }, { count: 2, covered: true, mine: false });
|
||||||
|
assert.equal(pub.body.covered, 1);
|
||||||
|
assert.equal(pub.body.total, 24);
|
||||||
|
assert.equal(pub.body.target, 1);
|
||||||
|
|
||||||
|
const own = await thandi.get('/api/v1/prayer/day?date=2026-12-02');
|
||||||
|
assert.match(own.headers['cache-control']!, /private/);
|
||||||
|
assert.equal(own.body.slots.find((s: { minute: number }) => s.minute === 120).mine, true);
|
||||||
|
assert.equal(own.body.slots.filter((s: { mine: boolean }) => s.mine).length, 1);
|
||||||
|
|
||||||
|
for (const res of [pub, own, await visitor.get('/api/v1/prayer/day'), await visitor.get('/api/v1/prayer/campaign'), await visitor.get('/api/v1/prayer/testimonies')]) {
|
||||||
|
const text = JSON.stringify(res.body);
|
||||||
|
for (const secret of ['Thandi', 'Pieter', 'thandi@', 'pieter@', MEMBER, OTHER]) assert.ok(!text.includes(secret), `${secret} in an answer`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses everything while the House of Prayer is switched off', async () => {
|
||||||
|
const { h, visitor, thandi } = await setup();
|
||||||
|
await h.ctx.settings.set('modules', JSON.stringify({ 'house-of-prayer': false }));
|
||||||
|
assert.equal((await visitor.get('/api/v1/prayer/day')).body.error.code, 'MODULE_OFF');
|
||||||
|
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', slot())).status, 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('needs a sign-in to book, and checks the wall\'s rules', async () => {
|
||||||
|
const { visitor, thandi } = await setup();
|
||||||
|
assert.equal((await visitor.post('/api/v1/me/prayer/commitments', slot())).status, 401);
|
||||||
|
const bad = await thandi.post('/api/v1/me/prayer/commitments', slot({ startMinute: 90 }));
|
||||||
|
assert.equal(bad.status, 400);
|
||||||
|
assert.equal(bad.body.error.code, 'NOT_A_SLOT');
|
||||||
|
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 420 }))).body.error.code, 'IN_THE_PAST');
|
||||||
|
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily', endDate: '2027-12-05' }))).body.error.code, 'TOO_LONG');
|
||||||
|
assert.equal((await thandi.post('/api/v1/me/prayer/commitments', { ...slot(), name: 'x' })).body.error.code, 'VALIDATION');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a change from another site', async () => {
|
||||||
|
const { h } = await setup();
|
||||||
|
const res = await request(h.app).post('/api/v1/me/prayer/commitments').set('Origin', 'https://evil.test').send(slot());
|
||||||
|
assert.equal(res.status, 403);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('a member\'s commitments', () => {
|
||||||
|
it('books every week, skips a date outside the 8 hours, and not one inside them', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
const { body } = await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 15 * 60, recurrence: 'weekly', endDate: '2027-03-01' }));
|
||||||
|
// Today at 15:00 is 7 hours away: locked.
|
||||||
|
const locked = await thandi.post(`/api/v1/me/prayer/commitments/${body.id}/skip`, { date: '2026-12-01' });
|
||||||
|
assert.equal(locked.status, 409);
|
||||||
|
assert.equal(locked.body.error.code, 'LOCKED');
|
||||||
|
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${body.id}/skip`, { date: '2026-12-08' })).status, 200);
|
||||||
|
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${body.id}/skip`, { date: '2026-12-09' })).body.error.code, 'NO_OCCURRENCE');
|
||||||
|
const day = await thandi.get('/api/v1/prayer/day?date=2026-12-08');
|
||||||
|
assert.equal(day.body.covered, 0);
|
||||||
|
assert.equal((await thandi.del(`/api/v1/me/prayer/commitments/${body.id}/skip/2026-12-08`)).status, 200);
|
||||||
|
assert.equal((await thandi.get('/api/v1/prayer/day?date=2026-12-08')).body.covered, 1);
|
||||||
|
|
||||||
|
const mine = await thandi.get('/api/v1/me/prayer');
|
||||||
|
assert.equal(mine.status, 200);
|
||||||
|
const c = mine.body.commitments[0];
|
||||||
|
assert.equal(c.upcoming[0].date, '2026-12-01');
|
||||||
|
assert.equal(c.upcoming[0].locked, true);
|
||||||
|
assert.equal(c.upcoming[1].locked, false);
|
||||||
|
assert.equal(mine.body.rules.cancelHours, 8);
|
||||||
|
assert.ok(h.db.tables.get('prayerSkip')!.size === 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says who to contact inside the window, as Settings says', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
await h.ctx.settings.set('prayer_wall', JSON.stringify({ coordinator: { name: 'Lerato', contact: '082 555 0101' } }));
|
||||||
|
const { body } = await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 12 * 60 }));
|
||||||
|
const res = await thandi.del(`/api/v1/me/prayer/commitments/${body.id}`);
|
||||||
|
assert.equal(res.status, 409);
|
||||||
|
assert.match(res.body.error.message, /Lerato \(082 555 0101\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cancels: a booking with nothing done goes; a running one ends after its last locked date', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
const once = (await thandi.post('/api/v1/me/prayer/commitments', slot())).body;
|
||||||
|
assert.deepEqual((await thandi.del(`/api/v1/me/prayer/commitments/${once.id}`)).body, { removed: true, endDate: null });
|
||||||
|
|
||||||
|
const daily = (await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 12 * 60, recurrence: 'daily' }))).body;
|
||||||
|
h.clock.add(2 * DAY); // 3 December, 08:00: today's 12:00 is locked.
|
||||||
|
const res = await thandi.del(`/api/v1/me/prayer/commitments/${daily.id}`);
|
||||||
|
assert.deepEqual(res.body, { removed: false, endDate: '2026-12-03' });
|
||||||
|
assert.equal((await thandi.get('/api/v1/prayer/day?date=2026-12-04')).body.covered, 0);
|
||||||
|
assert.equal((await thandi.get('/api/v1/prayer/day?date=2026-12-02')).body.covered, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('changes the reminder in place, the end date within the limits, and a new time as a new rule', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 12 * 60, recurrence: 'daily', endDate: '2027-01-31' }))).body;
|
||||||
|
assert.equal((await thandi.patch(`/api/v1/me/prayer/commitments/${id}`, { reminder: 'evening', channel: 'whatsapp' })).body.id, id);
|
||||||
|
assert.equal((await thandi.patch(`/api/v1/me/prayer/commitments/${id}`, { endDate: '2027-06-30' })).body.endDate, '2027-06-30');
|
||||||
|
assert.equal((await thandi.patch(`/api/v1/me/prayer/commitments/${id}`, { endDate: '2027-12-31' })).body.error.code, 'TOO_LONG');
|
||||||
|
const moved = await thandi.patch(`/api/v1/me/prayer/commitments/${id}`, { startDate: '2026-12-05', startMinute: 3 * 60 });
|
||||||
|
assert.notEqual(moved.body.id, id);
|
||||||
|
const old = await h.db.prayerCommitment.findUnique({ where: { id } });
|
||||||
|
assert.equal(old!.endDate, '2026-12-01');
|
||||||
|
const fresh = await h.db.prayerCommitment.findUnique({ where: { id: moved.body.id } });
|
||||||
|
assert.equal(fresh!.reminder, 'evening');
|
||||||
|
assert.equal(fresh!.endDate, '2027-06-30');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks "I prayed" once the slot has ended, in the App or from the reminder\'s link', async () => {
|
||||||
|
const { h, thandi, visitor } = await setup();
|
||||||
|
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily', endDate: '2026-12-10' }))).body;
|
||||||
|
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${id}/prayed`, { date: '2026-12-02' })).body.error.code, 'NOT_YET');
|
||||||
|
h.clock.add(DAY); // 2 December, 08:00
|
||||||
|
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${id}/prayed`, { date: '2026-12-02' })).body.prayed, true);
|
||||||
|
assert.equal((await thandi.post(`/api/v1/me/prayer/commitments/${id}/prayed`, { date: '2026-12-02' })).body.prayed, true);
|
||||||
|
h.clock.add(DAY);
|
||||||
|
const token = prayerToken(h.ctx, 'prayed', id, '2026-12-03');
|
||||||
|
assert.equal((await visitor.post('/api/v1/prayer/prayed', { token })).body.prayed, true);
|
||||||
|
assert.equal((await visitor.post('/api/v1/prayer/prayed', { token: token.replace(/.$/, token.endsWith('A') ? 'B' : 'A') })).status, 410);
|
||||||
|
assert.equal(await h.db.prayedMark.count({ where: { commitmentId: id } }), 2);
|
||||||
|
assert.equal((await thandi.get('/api/v1/me/prayer')).body.prayedTotal, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renews for another year from the notice\'s link, once', async () => {
|
||||||
|
const { h, thandi, visitor } = await setup();
|
||||||
|
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'weekly', endDate: '2026-12-20' }))).body;
|
||||||
|
const token = prayerToken(h.ctx, 'renew', id, '2026-12-20');
|
||||||
|
const res = await visitor.post('/api/v1/prayer/renew', { token });
|
||||||
|
assert.deepEqual(res.body, { renewed: true, endDate: '2027-12-20' });
|
||||||
|
assert.equal((await visitor.post('/api/v1/prayer/renew', { token })).body.error.code, 'LINK_USED');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps someone else\'s commitments out of reach', async () => {
|
||||||
|
const { thandi, pieter } = await setup();
|
||||||
|
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot())).body;
|
||||||
|
assert.equal((await pieter.del(`/api/v1/me/prayer/commitments/${id}`)).status, 404);
|
||||||
|
assert.equal((await pieter.get('/api/v1/me/prayer')).body.commitments.length, 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('reminders and renewal notices', () => {
|
||||||
|
it('queues a reminder once when it\'s due, on the member\'s channel, and none for a skipped date', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
const { id } = (await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily', endDate: '2026-12-10', channel: 'whatsapp' }))).body;
|
||||||
|
await thandi.post(`/api/v1/me/prayer/commitments/${id}/skip`, { date: '2026-12-03' });
|
||||||
|
assert.deepEqual(await sendReminders(h.ctx), { queued: 0 });
|
||||||
|
h.clock.set('2026-12-01T23:00:00Z'); // 01:00 on 2 December, an hour before.
|
||||||
|
assert.deepEqual(await sendReminders(h.ctx), { queued: 1 });
|
||||||
|
assert.deepEqual(await sendReminders(h.ctx), { queued: 0 });
|
||||||
|
const [m] = [...h.db.tables.get('outboxMessage')!.values()] as { kind: string; channel: string; payload: { date: string; prayedPath: string } }[];
|
||||||
|
assert.equal(m!.kind, 'prayer-reminder');
|
||||||
|
assert.equal(m!.channel, 'whatsapp');
|
||||||
|
assert.equal(m!.payload.date, '2026-12-02');
|
||||||
|
assert.match(m!.payload.prayedPath, /^\/prayer\/prayed\?token=/);
|
||||||
|
h.clock.set('2026-12-02T23:10:00Z');
|
||||||
|
assert.deepEqual(await sendReminders(h.ctx), { queued: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends the renewal notice 14 days before the end and again 3 days before', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'weekly', endDate: '2026-12-31' }));
|
||||||
|
assert.deepEqual(await sendRenewalNotices(h.ctx), { queued: 0 });
|
||||||
|
h.clock.set('2026-12-17T07:00:00Z');
|
||||||
|
assert.deepEqual(await sendRenewalNotices(h.ctx), { queued: 1 });
|
||||||
|
assert.deepEqual(await sendRenewalNotices(h.ctx), { queued: 0 });
|
||||||
|
h.clock.set('2026-12-28T07:00:00Z');
|
||||||
|
assert.deepEqual(await sendRenewalNotices(h.ctx), { queued: 1 });
|
||||||
|
const kinds = [...h.db.tables.get('outboxMessage')!.values()].map((m) => (m as { payload: { renewPath: string } }).payload.renewPath);
|
||||||
|
assert.equal(kinds.length, 2);
|
||||||
|
assert.match(kinds[0]!, /^\/prayer\/renew\?token=/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('live coverage', () => {
|
||||||
|
it('streams which dates changed, unbuffered', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
const server = h.app.listen(0);
|
||||||
|
try {
|
||||||
|
const port = (server.address() as AddressInfo).port;
|
||||||
|
const ac = new AbortController();
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/api/v1/prayer/stream`, { signal: ac.signal });
|
||||||
|
assert.equal(res.headers.get('content-type'), 'text/event-stream; charset=utf-8');
|
||||||
|
assert.equal(res.headers.get('x-accel-buffering'), 'no');
|
||||||
|
const reader = res.body!.getReader();
|
||||||
|
let text = '';
|
||||||
|
await thandi.post('/api/v1/me/prayer/commitments', slot());
|
||||||
|
while (!text.includes('event: changed')) text += new TextDecoder().decode((await reader.read()).value);
|
||||||
|
assert.match(text, /data: \{"dates":\["2026-12-02"\]\}/);
|
||||||
|
ac.abort();
|
||||||
|
} finally {
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the admin', () => {
|
||||||
|
it('shows names only to a prayer coordinator with 2FA, and logs every view', async () => {
|
||||||
|
const { h, thandi, pieter, as } = await setup();
|
||||||
|
await thandi.post('/api/v1/me/prayer/commitments', slot());
|
||||||
|
assert.equal((await pieter.get('/api/v1/admin/prayer/bookings?date=2026-12-02')).status, 403);
|
||||||
|
const coord = as(await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true));
|
||||||
|
const res = await coord.get('/api/v1/admin/prayer/bookings?date=2026-12-02');
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
assert.equal(res.body.people[0].member.name, 'Thandi Mokoena');
|
||||||
|
const log = [...h.db.tables.get('accessLog')!.values()] as { actorId: string; action: string; targetId: string }[];
|
||||||
|
assert.deepEqual(log.map((l) => [l.actorId, l.action, l.targetId]), [[COORD, 'prayer_bookings_viewed', '2026-12-02']]);
|
||||||
|
const week = await coord.get('/api/v1/admin/prayer/week?from=2026-12-01');
|
||||||
|
assert.equal(week.body.days[1].covered, 1);
|
||||||
|
assert.ok(!JSON.stringify(week.body).includes('Thandi'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('books on a member\'s behalf, changes the rules and runs a campaign', async () => {
|
||||||
|
const { h, visitor, as } = await setup();
|
||||||
|
const coord = as(await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true));
|
||||||
|
const booked = await coord.post('/api/v1/admin/prayer/commitments', { ...slot({ recurrence: 'daily' }), memberId: MEMBER });
|
||||||
|
assert.equal(booked.status, 201);
|
||||||
|
assert.equal((await h.db.prayerCommitment.findUnique({ where: { id: booked.body.id } }))!.bookedById, COORD);
|
||||||
|
assert.equal((await coord.put('/api/v1/admin/prayer/wall', { cancelHours: 49 })).status, 400);
|
||||||
|
assert.equal((await coord.put('/api/v1/admin/prayer/wall', { slotMinutes: 30, targetPerSlot: 2 })).body.wall.slotMinutes, 30);
|
||||||
|
assert.equal((await visitor.get('/api/v1/prayer/day?date=2026-12-02')).body.total, 48);
|
||||||
|
|
||||||
|
const c = await coord.post('/api/v1/admin/prayer/campaigns', { title: '21 days of prayer', description: 'Before the conference', startDate: '2026-11-28', endDate: '2026-12-18', targetPerSlot: 3 });
|
||||||
|
assert.equal(c.status, 201);
|
||||||
|
const summary = (await visitor.get('/api/v1/prayer/campaign')).body.campaign;
|
||||||
|
assert.equal(summary.title, '21 days of prayer');
|
||||||
|
assert.equal(summary.daysLeft, 18);
|
||||||
|
assert.equal(summary.hoursPrayed, 0);
|
||||||
|
assert.equal((await visitor.get('/api/v1/prayer/day?date=2026-12-02')).body.target, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moderates testimonies before anyone sees them, with the first name or "Anonymous"', async () => {
|
||||||
|
const { h, thandi, pieter, visitor, as } = await setup();
|
||||||
|
const a = (await thandi.post('/api/v1/me/prayer/testimonies', { text: 'My mother is home from hospital.', showName: true })).body;
|
||||||
|
const b = (await pieter.post('/api/v1/me/prayer/testimonies', { text: 'Work came through after months.' })).body;
|
||||||
|
assert.equal(a.status, 'pending');
|
||||||
|
assert.deepEqual((await visitor.get('/api/v1/prayer/testimonies')).body.testimonies, []);
|
||||||
|
const coord = as(await signInAs(h, { sub: COORD, name: 'Lerato', roles: ['prayer_coordinator'] }, true));
|
||||||
|
assert.equal((await coord.get('/api/v1/admin/prayer/testimonies')).body.testimonies.length, 2);
|
||||||
|
await coord.post(`/api/v1/admin/prayer/testimonies/${a.id}/approve`);
|
||||||
|
await coord.post(`/api/v1/admin/prayer/testimonies/${b.id}/approve`);
|
||||||
|
const shown = (await visitor.get('/api/v1/prayer/testimonies')).body.testimonies.map((t: { by: string }) => t.by).sort();
|
||||||
|
assert.deepEqual(shown, ['Anonymous', 'Thandi']);
|
||||||
|
assert.equal((await coord.post(`/api/v1/admin/prayer/testimonies/${b.id}/remove`, {})).status, 400);
|
||||||
|
await coord.post(`/api/v1/admin/prayer/testimonies/${b.id}/remove`, { reason: 'It names a colleague.' });
|
||||||
|
assert.equal((await pieter.get('/api/v1/me/prayer/testimonies')).body.testimonies[0].removedReason, 'It names a colleague.');
|
||||||
|
assert.equal([...h.db.tables.get('outboxMessage')!.values()].length, 1);
|
||||||
|
assert.equal((await thandi.del(`/api/v1/me/prayer/testimonies/${a.id}`)).status, 200);
|
||||||
|
assert.deepEqual((await visitor.get('/api/v1/prayer/testimonies')).body.testimonies, []);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the heartbeat, export and delete', () => {
|
||||||
|
it('reports last week\'s coverage and active commitments, as counts', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-01', startMinute: 12 * 60, durationMinutes: 12 * 60, recurrence: 'daily' }));
|
||||||
|
h.clock.add(8 * DAY);
|
||||||
|
const s = await stats(h.ctx);
|
||||||
|
// 1 December is half covered from 12:00, and the 6 days after it are too.
|
||||||
|
assert.deepEqual(s.prayer, { coverageLast7dPercent: 50, activeCommitments: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('exports a member\'s prayer and, when they delete their account, opens their future slots', async () => {
|
||||||
|
const { h, thandi } = await setup();
|
||||||
|
const daily = (await thandi.post('/api/v1/me/prayer/commitments', slot({ recurrence: 'daily' }))).body;
|
||||||
|
const later = (await thandi.post('/api/v1/me/prayer/commitments', slot({ startDate: '2026-12-20' }))).body;
|
||||||
|
await thandi.post('/api/v1/me/prayer/testimonies', { text: 'Thank you for praying with us.' });
|
||||||
|
h.clock.add(3 * DAY);
|
||||||
|
await thandi.post(`/api/v1/me/prayer/commitments/${daily.id}/prayed`, { date: '2026-12-03' });
|
||||||
|
const call = (type: string, extra: object = {}) => request(h.app).post('/api/accounts/v1/events').set('x-test-signed', 'yes').set('Content-Type', 'application/json')
|
||||||
|
.send(JSON.stringify({ schema: 'crosscode.identity/1', callId: '66666666-6666-4666-8666-666666666666', occurredAt: '2026-12-04T06:00:00.000Z', sub: MEMBER, type, ...extra }));
|
||||||
|
const exp = await call('user.export', { exportId: '77777777-7777-4777-8777-777777777777' });
|
||||||
|
assert.deepEqual(exp.body.sections.map((s: { key: string }) => s.key), ['app_member', 'app_prayer_commitments', 'app_prayed', 'app_testimonies']);
|
||||||
|
assert.equal(exp.body.sections[1].records[0].time, '02:00');
|
||||||
|
|
||||||
|
await call('user.deleted');
|
||||||
|
assert.equal(await h.db.prayerCommitment.findUnique({ where: { id: later.id } }), null);
|
||||||
|
const kept = await h.db.prayerCommitment.findUnique({ where: { id: daily.id } });
|
||||||
|
assert.deepEqual([kept!.memberId, kept!.endDate], [null, '2026-12-03']);
|
||||||
|
assert.equal(await h.db.testimony.count(), 0);
|
||||||
|
assert.equal((await h.db.prayedMark.findFirst({}))!.memberId, null);
|
||||||
|
const past = await request(h.app).get('/api/v1/prayer/day?date=2026-12-03');
|
||||||
|
assert.equal(past.body.covered, 1);
|
||||||
|
assert.equal((await request(h.app).get('/api/v1/prayer/day?date=2026-12-05')).body.covered, 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { addMonths, localParts, zonedTime } from '../src/lib/zoned.js';
|
||||||
|
import {
|
||||||
|
cancelledEndDate, checkBooking, coveragePercent, dayCoverage, daySlots, DEFAULT_WALL, isLocked, nextOccurrence,
|
||||||
|
occurrencesBetween, reminderAt, renewedEndDate, type Rule,
|
||||||
|
} from '../src/prayer/rules.js';
|
||||||
|
|
||||||
|
const SA = 'Africa/Johannesburg';
|
||||||
|
const LONDON = 'Europe/London';
|
||||||
|
|
||||||
|
const rule = (over: Partial<Rule>): Rule => ({
|
||||||
|
id: 'r1', memberId: 'm1', startDate: '2026-12-01', startMinute: 120, durationMinutes: 60, recurrence: 'once', endDate: '2026-12-01', skips: [], ...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('local times in the church\'s timezone', () => {
|
||||||
|
it('turns a local date and minute into an instant and back', () => {
|
||||||
|
const t = zonedTime('2026-12-01', 120, SA)!;
|
||||||
|
assert.equal(t.toISOString(), '2026-12-01T00:00:00.000Z');
|
||||||
|
assert.deepEqual(localParts(t, SA), { date: '2026-12-01', minute: 120, weekday: 2 });
|
||||||
|
assert.equal(zonedTime('2026-12-01', 1440 + 60, SA)!.toISOString(), '2026-12-01T23:00:00.000Z');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('has no instant for a time the clocks jump over, and the first of a time that happens twice', () => {
|
||||||
|
assert.equal(zonedTime('2027-03-28', 60, LONDON), null);
|
||||||
|
assert.equal(zonedTime('2027-03-28', 120, LONDON)!.toISOString(), '2027-03-28T01:00:00.000Z');
|
||||||
|
assert.equal(zonedTime('2026-10-25', 60, LONDON)!.toISOString(), '2026-10-25T00:00:00.000Z');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a month\'s end inside the month', () => {
|
||||||
|
assert.equal(addMonths('2027-01-31', 1), '2027-02-28');
|
||||||
|
assert.equal(addMonths('2026-12-01', 12), '2027-12-01');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('slots', () => {
|
||||||
|
it('cuts the day into 24, 48 or 96 slots', () => {
|
||||||
|
assert.equal(daySlots('2026-12-01', 60, SA).length, 24);
|
||||||
|
assert.equal(daySlots('2026-12-01', 30, SA).length, 48);
|
||||||
|
assert.equal(daySlots('2026-12-01', 15, SA).length, 96);
|
||||||
|
assert.equal(daySlots('2026-12-01', 60, SA)[0]!.start.toISOString(), '2026-11-30T22:00:00.000Z');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives a day with daylight saving whole hours: 23 when the clocks jump forward, 24 when they go back', () => {
|
||||||
|
const spring = daySlots('2027-03-28', 60, LONDON);
|
||||||
|
assert.equal(spring.length, 23);
|
||||||
|
assert.ok(!spring.some((s) => s.minute === 60));
|
||||||
|
for (const s of spring) assert.equal(s.end.getTime() - s.start.getTime(), 3600e3);
|
||||||
|
const autumn = daySlots('2026-10-25', 60, LONDON);
|
||||||
|
assert.equal(autumn.length, 24);
|
||||||
|
// 01:00 happens twice: its slot runs to the (first) 02:00, two hours later.
|
||||||
|
assert.equal(autumn.find((s) => s.minute === 60)!.end.getTime() - autumn.find((s) => s.minute === 60)!.start.getTime(), 2 * 3600e3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('commitments as rules', () => {
|
||||||
|
it('works out daily, weekly and once occurrences, without the skipped dates', () => {
|
||||||
|
const from = zonedTime('2026-12-01', 0, SA)!;
|
||||||
|
const to = zonedTime('2026-12-15', 0, SA)!;
|
||||||
|
const daily = rule({ recurrence: 'daily', endDate: '2027-11-30', skips: ['2026-12-03'] });
|
||||||
|
assert.equal(occurrencesBetween(daily, from, to, SA).length, 13);
|
||||||
|
const weekly = rule({ recurrence: 'weekly', endDate: '2027-11-30' });
|
||||||
|
assert.deepEqual(occurrencesBetween(weekly, from, to, SA).map((o) => o.date), ['2026-12-01', '2026-12-08']);
|
||||||
|
assert.equal(occurrencesBetween(rule({}), from, to, SA).length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a weekly rule on its weekday and stops at its end date', () => {
|
||||||
|
const r = rule({ recurrence: 'weekly', startDate: '2026-12-03', endDate: '2026-12-24' });
|
||||||
|
const all = occurrencesBetween(r, zonedTime('2026-11-01', 0, SA)!, zonedTime('2027-02-01', 0, SA)!, SA);
|
||||||
|
assert.deepEqual(all.map((o) => o.date), ['2026-12-03', '2026-12-10', '2026-12-17', '2026-12-24']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a year of daily slots is one rule', () => {
|
||||||
|
const r = rule({ recurrence: 'daily', endDate: '2027-11-30' });
|
||||||
|
assert.equal(occurrencesBetween(r, zonedTime('2026-12-01', 0, SA)!, zonedTime('2027-12-01', 0, SA)!, SA).length, 365);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('finds the next occurrence', () => {
|
||||||
|
const r = rule({ recurrence: 'daily', endDate: '2026-12-10' });
|
||||||
|
assert.equal(nextOccurrence(r, new Date('2026-12-01T06:00:00Z'), SA)!.date, '2026-12-02');
|
||||||
|
assert.equal(nextOccurrence(r, new Date('2026-12-11T06:00:00Z'), SA), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves a start the clocks jump over to just after the jump', () => {
|
||||||
|
const r = rule({ startDate: '2027-03-28', endDate: '2027-03-28', startMinute: 60 });
|
||||||
|
const [o] = occurrencesBetween(r, zonedTime('2027-03-27', 0, LONDON)!, zonedTime('2027-03-29', 0, LONDON)!, LONDON);
|
||||||
|
assert.equal(o!.start.toISOString(), '2027-03-28T01:00:00.000Z');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('coverage', () => {
|
||||||
|
it('counts people per slot, once each, and marks the asker\'s own; no names', () => {
|
||||||
|
const rules = [
|
||||||
|
rule({ id: 'a', memberId: 'm1', startMinute: 120, durationMinutes: 120 }),
|
||||||
|
rule({ id: 'b', memberId: 'm1', startMinute: 120, durationMinutes: 60 }),
|
||||||
|
rule({ id: 'c', memberId: 'm2', startMinute: 180, durationMinutes: 60, recurrence: 'daily', endDate: '2027-01-01' }),
|
||||||
|
rule({ id: 'd', memberId: null, startMinute: 600, durationMinutes: 60 }),
|
||||||
|
];
|
||||||
|
const day = dayCoverage('2026-12-01', rules, { slotMinutes: 60 }, SA, 'm2');
|
||||||
|
const at = (h: number) => day.slots.find((s) => s.minute === h * 60)!;
|
||||||
|
assert.equal(at(2).count, 1);
|
||||||
|
assert.equal(at(2).mine, false);
|
||||||
|
assert.equal(at(3).count, 2);
|
||||||
|
assert.equal(at(3).mine, true);
|
||||||
|
assert.equal(at(10).count, 1);
|
||||||
|
assert.equal(day.covered, 3);
|
||||||
|
assert.equal(day.total, 24);
|
||||||
|
assert.deepEqual(Object.keys(at(3)).sort(), ['count', 'covered', 'end', 'mine', 'minute', 'start']);
|
||||||
|
assert.ok(!JSON.stringify(day).includes('m1'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts a slot that runs past midnight on the next day too', () => {
|
||||||
|
const r = rule({ startMinute: 23 * 60, durationMinutes: 120 });
|
||||||
|
const next = dayCoverage('2026-12-02', [r], { slotMinutes: 60 }, SA);
|
||||||
|
assert.equal(next.slots[0]!.count, 1);
|
||||||
|
assert.equal(next.covered, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts a 1-hour commitment in both 30-minute slots it covers', () => {
|
||||||
|
const day = dayCoverage('2026-12-01', [rule({ startMinute: 120 })], { slotMinutes: 30 }, SA);
|
||||||
|
assert.equal(day.covered, 2);
|
||||||
|
assert.equal(day.total, 48);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives the share of slots covered', () => {
|
||||||
|
const one = dayCoverage('2026-12-01', [rule({ durationMinutes: 12 * 60, startMinute: 0 })], { slotMinutes: 60 }, SA);
|
||||||
|
assert.equal(coveragePercent([one]), 50);
|
||||||
|
assert.equal(coveragePercent([]), 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('booking rules', () => {
|
||||||
|
const now = new Date('2026-12-01T06:00:00Z'); // 08:00 SAST
|
||||||
|
|
||||||
|
it('books once, every day or every week, up to 12 months', () => {
|
||||||
|
assert.deepEqual(checkBooking({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 60, recurrence: 'once' }, now, DEFAULT_WALL, SA), { endDate: '2026-12-02' });
|
||||||
|
assert.deepEqual(checkBooking({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 120, recurrence: 'daily' }, now, DEFAULT_WALL, SA), { endDate: '2027-12-01' });
|
||||||
|
assert.deepEqual(checkBooking({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 60, recurrence: 'weekly', endDate: '2027-03-01' }, now, DEFAULT_WALL, SA), { endDate: '2027-03-01' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses what the rules don\'t allow', () => {
|
||||||
|
const code = (input: Parameters<typeof checkBooking>[0], wall = DEFAULT_WALL) => {
|
||||||
|
const r = checkBooking(input, now, wall, SA);
|
||||||
|
return 'error' in r ? r.error.code : 'ok';
|
||||||
|
};
|
||||||
|
assert.equal(code({ startDate: '2026-12-02', startMinute: 90, durationMinutes: 60, recurrence: 'once' }), 'NOT_A_SLOT');
|
||||||
|
assert.equal(code({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 45, recurrence: 'once' }), 'BAD_LENGTH');
|
||||||
|
assert.equal(code({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 13 * 60, recurrence: 'once' }), 'BAD_LENGTH');
|
||||||
|
assert.equal(code({ startDate: '2027-12-02', startMinute: 120, durationMinutes: 60, recurrence: 'once' }), 'TOO_FAR_AHEAD');
|
||||||
|
assert.equal(code({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 60, recurrence: 'daily', endDate: '2027-12-02' }), 'TOO_LONG');
|
||||||
|
assert.equal(code({ startDate: '2026-12-02', startMinute: 120, durationMinutes: 60, recurrence: 'daily', endDate: '2026-12-01' }), 'END_BEFORE_START');
|
||||||
|
assert.equal(code({ startDate: '2026-12-01', startMinute: 7 * 60, durationMinutes: 60, recurrence: 'once' }), 'IN_THE_PAST');
|
||||||
|
assert.equal(code({ startDate: '2026-12-01', startMinute: 30, durationMinutes: 30, recurrence: 'once' }, { ...DEFAULT_WALL, slotMinutes: 30 }), 'IN_THE_PAST');
|
||||||
|
assert.equal(code({ startDate: '2026-12-02', startMinute: 30, durationMinutes: 30, recurrence: 'once' }, { ...DEFAULT_WALL, slotMinutes: 30 }), 'ok');
|
||||||
|
assert.equal(code({ startDate: '2027-03-01', startMinute: 0, durationMinutes: 60, recurrence: 'once' }, { ...DEFAULT_WALL, bookAheadMonths: 2 }), 'TOO_FAR_AHEAD');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('locks an occurrence within the cancel window', () => {
|
||||||
|
assert.equal(isLocked({ start: new Date('2026-12-01T13:00:00Z') }, now, 8), true);
|
||||||
|
assert.equal(isLocked({ start: new Date('2026-12-01T14:00:00Z') }, now, 8), false);
|
||||||
|
assert.equal(isLocked({ start: new Date('2026-12-01T07:00:00Z') }, now, 0), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ends a cancelled rule after its last locked occurrence, or removes it when nothing happened yet', () => {
|
||||||
|
// Daily at 02:00 from 25 November: 1 December's has happened, 2 December's is 18 hours away.
|
||||||
|
const daily = rule({ startDate: '2026-11-25', recurrence: 'daily', endDate: '2027-11-24' });
|
||||||
|
assert.equal(cancelledEndDate(daily, now, DEFAULT_WALL, SA), '2026-12-01');
|
||||||
|
// With a 24-hour window, 2 December's 02:00 is locked too.
|
||||||
|
assert.equal(cancelledEndDate(daily, now, { cancelHours: 24 }, SA), '2026-12-02');
|
||||||
|
assert.equal(cancelledEndDate(rule({ startDate: '2026-12-05', endDate: '2026-12-05' }), now, DEFAULT_WALL, SA), null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('reminders and renewals', () => {
|
||||||
|
it('reminds 15 minutes or an hour before, or at 20:00 the evening before', () => {
|
||||||
|
const o = { date: '2026-12-02', start: zonedTime('2026-12-02', 120, SA)! };
|
||||||
|
assert.equal(reminderAt('none', o, SA), null);
|
||||||
|
assert.equal(reminderAt('min15', o, SA)!.toISOString(), '2026-12-01T23:45:00.000Z');
|
||||||
|
assert.equal(reminderAt('hour1', o, SA)!.toISOString(), '2026-12-01T23:00:00.000Z');
|
||||||
|
assert.equal(reminderAt('evening', o, SA)!.toISOString(), '2026-12-01T18:00:00.000Z');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renews for another year from the current end', () => {
|
||||||
|
assert.equal(renewedEndDate({ endDate: '2027-11-30' }, DEFAULT_WALL), '2028-11-30');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -113,3 +113,19 @@ export function cookiesFrom(res: { headers: Record<string, unknown> }, keep: Rec
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const cookieHeader = (c: Record<string, string>) => Object.entries(c).map(([k, v]) => `${k}=${v}`).join('; ');
|
export const cookieHeader = (c: Record<string, string>) => Object.entries(c).map(([k, v]) => `${k}=${v}`).join('; ');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signs `who` in through the stand-in Accounts (with 2FA when `mfa`), creating them as a Member
|
||||||
|
* with `roles` first if given; answers the cookies to send.
|
||||||
|
*/
|
||||||
|
export async function signInAs(h: Harness, who: { sub: string; name?: string; email?: string; roles?: string[] }, mfa = false): Promise<Record<string, string>> {
|
||||||
|
const { default: request } = await import('supertest');
|
||||||
|
if (who.roles?.length) {
|
||||||
|
await h.db.member.upsert({ where: { id: who.sub }, create: { id: who.sub, name: who.name ?? 'Someone', email: who.email ?? `${who.sub}@hope.test`, roles: who.roles }, update: { roles: who.roles } });
|
||||||
|
}
|
||||||
|
h.fake.next = { sub: who.sub, name: who.name ?? 'Someone', email: who.email ?? `${who.sub.slice(0, 8)}@hope.test`, amr: mfa ? ['pwd', 'mfa'] : ['pwd'] };
|
||||||
|
const start = await request(h.app).get(`/api/auth/signin?returnTo=%2F${mfa ? '&mfa=1' : ''}`);
|
||||||
|
const after = cookiesFrom(start);
|
||||||
|
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
|
||||||
|
return cookiesFrom(back, after);
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,13 +14,21 @@ const DEFAULTS: Record<string, () => Row> = {
|
|||||||
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
|
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
|
||||||
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
|
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
|
||||||
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
||||||
|
prayerCommitment: () => ({ reminder: 'hour1', channel: 'email', note: null, bookedById: null, renewalNoticesSent: 0, renewedAt: null }),
|
||||||
|
prayedMark: () => ({ memberId: null }),
|
||||||
|
prayerCampaign: () => ({ imageUrl: null, goal: null, targetPerSlot: null, createdById: null }),
|
||||||
|
testimony: () => ({ campaignId: null, showName: false, status: 'pending', removedReason: null, moderatedById: null, moderatedAt: null }),
|
||||||
|
accessLog: () => ({ targetId: null, metadata: null, ip: null }),
|
||||||
|
outboxMessage: () => ({ sentAt: null, failedAt: null, error: null, attempts: 0 }),
|
||||||
};
|
};
|
||||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
|
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
|
||||||
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'] };
|
/** Unique fields: one field, or several together (`@@unique([a, b])`). */
|
||||||
const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink']);
|
const UNIQUE: Record<string, (string | string[])[]> = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']] };
|
||||||
|
const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign']);
|
||||||
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
|
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
|
||||||
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
||||||
member: { sessions: { model: 'session', many: true, key: 'memberId' } },
|
member: { sessions: { model: 'session', many: true, key: 'memberId' } },
|
||||||
|
prayerCommitment: { skips: { model: 'prayerSkip', many: true, key: 'commitmentId' }, marks: { model: 'prayedMark', many: true, key: 'commitmentId' } },
|
||||||
};
|
};
|
||||||
|
|
||||||
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
|
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
|
||||||
@@ -89,19 +97,20 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
|||||||
};
|
};
|
||||||
const findWhere = (where: Row) => {
|
const findWhere = (where: Row) => {
|
||||||
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
|
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
|
||||||
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
|
for (const u of UNIQUE[name] ?? []) if (typeof u === 'string' && where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
|
||||||
return [...table().values()].find((r) => matches(r, where)) ?? null;
|
return [...table().values()].find((r) => matches(r, where)) ?? null;
|
||||||
};
|
};
|
||||||
const checkUnique = (row: Row, except?: unknown) => {
|
const checkUnique = (row: Row, except?: unknown) => {
|
||||||
for (const u of UNIQUE[name] ?? []) {
|
for (const u of UNIQUE[name] ?? []) {
|
||||||
if (row[u] == null) continue;
|
const fields = typeof u === 'string' ? [u] : u;
|
||||||
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
|
if (fields.some((f) => row[f] == null)) continue;
|
||||||
|
if ([...table().values()].some((r) => r[key] !== except && fields.every((f) => v(r[f]) === v(row[f])))) throw prismaError('P2002', `Unique constraint failed on ${name}.${fields.join('_')}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const api = {
|
const api = {
|
||||||
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
|
findUnique: async ({ where, select, include }: { where: Row; select?: Row; include?: Row }) => { const r = findWhere(where); return r ? withIncludes(pick(clone(r), select), include) : null; },
|
||||||
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
|
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
|
||||||
findFirst: async ({ where, orderBy, select }: { where?: Row; orderBy?: Row | Row[]; select?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? pick(clone(r), select) : null; },
|
findFirst: async ({ where, orderBy, select, include }: { where?: Row; orderBy?: Row | Row[]; select?: Row; include?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? withIncludes(pick(clone(r), select), include) : null; },
|
||||||
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
|
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
|
||||||
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
|
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
|
||||||
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
|
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
|
||||||
@@ -148,7 +157,11 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
const cascade = (from: string, id: unknown) => {
|
const cascade = (from: string, id: unknown) => {
|
||||||
if (from === 'member') for (const [k, r] of tables.get('session') ?? []) if (r.memberId === id) tables.get('session')!.delete(k);
|
const drop = (model: string, field: string) => { for (const [k, r] of tables.get(model) ?? []) if (r[field] === id) tables.get(model)!.delete(k); };
|
||||||
|
const unset = (model: string, field: string) => { for (const r of tables.get(model)?.values() ?? []) if (r[field] === id) r[field] = null; };
|
||||||
|
if (from === 'member') { drop('session', 'memberId'); drop('testimony', 'memberId'); drop('outboxMessage', 'memberId'); unset('prayerCommitment', 'memberId'); }
|
||||||
|
if (from === 'prayerCommitment') { drop('prayerSkip', 'commitmentId'); drop('prayedMark', 'commitmentId'); }
|
||||||
|
if (from === 'prayerCampaign') unset('testimony', 'campaignId');
|
||||||
};
|
};
|
||||||
const withIncludes = (row: Row, include?: Row) => {
|
const withIncludes = (row: Row, include?: Row) => {
|
||||||
for (const [rel, on] of Object.entries(include ?? {})) {
|
for (const [rel, on] of Object.entries(include ?? {})) {
|
||||||
|
|||||||
Reference in New Issue
Block a user