diff --git a/apps/app/backend/package.json b/apps/app/backend/package.json index caa146d..70a2c5b 100644 --- a/apps/app/backend/package.json +++ b/apps/app/backend/package.json @@ -24,12 +24,14 @@ "cron-parser": "^5.10.2", "dotenv": "^16.3.1", "express": "^5.3.0", + "nodemailer": "^10.3.0", "pg-boss": "^11.1.2", "zod": "^4.6.7" }, "devDependencies": { "@types/express": "^5.0.6", "@types/node": "^20.19.43", + "@types/nodemailer": "^6.4.17", "@types/supertest": "^7.2.1", "prisma": "^7.10.1", "supertest": "^7.3.1", diff --git a/apps/app/backend/prisma/migrations/20261205000000_messaging/migration.sql b/apps/app/backend/prisma/migrations/20261205000000_messaging/migration.sql new file mode 100644 index 0000000..1286b24 --- /dev/null +++ b/apps/app/backend/prisma/migrations/20261205000000_messaging/migration.sql @@ -0,0 +1,45 @@ +-- Church App 1.0.0: email and WhatsApp (docs/APP-1.0-PLAN.md §8): members' news consent from Accounts, +-- what each member chose the App sends them, what each outbox message went by, and the counts per day. +-- CreateEnum +CREATE TYPE "NotifyChoice" AS ENUM ('off', 'email', 'whatsapp', 'both'); + +-- AlterTable +ALTER TABLE "Member" ADD COLUMN "newsEmail" BOOLEAN NOT NULL DEFAULT false, +ADD COLUMN "newsWhatsApp" BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable +ALTER TABLE "OutboxMessage" ADD COLUMN "sentVia" TEXT; + +-- CreateTable +CREATE TABLE "NotificationSettings" ( + "memberId" TEXT NOT NULL, + "requestUpdates" "NotifyChoice" NOT NULL DEFAULT 'email', + "announcements" "NotifyChoice" NOT NULL DEFAULT 'off', + "devotional" "NotifyChoice" NOT NULL DEFAULT 'off', + "devotionalTime" TEXT NOT NULL DEFAULT '06:00', + "devotionalOfferedAt" TIMESTAMP(3), + "lastDevotionalDate" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "NotificationSettings_pkey" PRIMARY KEY ("memberId") +); + +-- CreateTable +CREATE TABLE "MessageCount" ( + "key" TEXT NOT NULL, + "day" TEXT NOT NULL, + "channel" TEXT NOT NULL, + "count" INTEGER NOT NULL DEFAULT 0, + + CONSTRAINT "MessageCount_pkey" PRIMARY KEY ("key") +); + +-- CreateIndex +CREATE INDEX "NotificationSettings_devotional_idx" ON "NotificationSettings"("devotional"); + +-- CreateIndex +CREATE INDEX "MessageCount_day_idx" ON "MessageCount"("day"); + +-- AddForeignKey +ALTER TABLE "NotificationSettings" ADD CONSTRAINT "NotificationSettings_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "Member"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/app/backend/prisma/schema.prisma b/apps/app/backend/prisma/schema.prisma index 9650e16..bae39f5 100644 --- a/apps/app/backend/prisma/schema.prisma +++ b/apps/app/backend/prisma/schema.prisma @@ -39,6 +39,9 @@ model Member { phone String? /// The person replied STOP to the church's WhatsApp number (decision 11): no WhatsApp of any kind. whatsappOptedOut Boolean @default(false) + /// News consent from Accounts (`news_consent`): announcements the church sends go only on these (§8). + newsEmail Boolean @default(false) + newsWhatsApp Boolean @default(false) roles AppRole[] @default([]) /// The last day they used the App signed in (written at most once a day): active members (§10). lastActiveAt DateTime? @@ -50,6 +53,7 @@ model Member { testimonies Testimony[] outboxMessages OutboxMessage[] prayerRequests PrayerRequest[] + notifications NotificationSettings? @@index([lastActiveAt]) } @@ -267,8 +271,11 @@ model AccessLog { @@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. +/// Email and WhatsApp to send (§8): reminders, renewal notices, the prayer team's and submitters' +/// notices, announcements and devotionals. Written once (`dedupeKey`), sent by the `messages-send` +/// job with the church's settings from Accounts; what's in `payload` is the message's facts only +/// (never a prayer request's text). `sentVia` says what went (`email`, `whatsapp`, `email,whatsapp`, +/// or `none` when there was nothing to send it on); `error` why a channel didn't. model OutboxMessage { id String @id @default(uuid()) memberId String @@ -279,6 +286,7 @@ model OutboxMessage { dedupeKey String @unique sendAfter DateTime sentAt DateTime? + sentVia String? failedAt DateTime? error String? attempts Int @default(0) @@ -287,6 +295,52 @@ model OutboxMessage { @@index([sentAt, sendAfter]) } +// ── Email and WhatsApp (§8) ────────────────────────────────────────────────────────────────── +// The church's one set of settings comes from Accounts (`messaging.get`) and is kept encrypted in +// AppSetting `messaging_settings`; the App never asks for its own (decision 4). + +/// How a member wants one kind of message: email, WhatsApp, both or not at all (§8). +enum NotifyChoice { + off + email + whatsapp + both +} + +/// What a member chose the App sends them (§8). Prayer reminders and renewals follow each +/// commitment's own channel; these are the rest. No row: the defaults. +model NotificationSettings { + memberId String @id + member Member @relation(fields: [memberId], references: [id], onDelete: Cascade) + /// Approved, someone prayed, a reply (email by default). + requestUpdates NotifyChoice @default(email) + /// The announcements the church sends (off until the member turns them on, P13). + announcements NotifyChoice @default(off) + /// Today's devotional (offered at the first sign-in, §6). + devotional NotifyChoice @default(off) + /// When (HH:MM in the church's timezone), 06:00 by default. + devotionalTime String @default("06:00") + /// When the first-sign-in offer was answered or dismissed. + devotionalOfferedAt DateTime? + /// The last local day a devotional was queued for them (once a day). + lastDevotionalDate String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([devotional]) +} + +/// Messages sent per local day and channel, for the heartbeat (`messages.email30d`, `whatsapp30d`). +/// Counts only: kept when a member or their messages are deleted. `key` is `:`. +model MessageCount { + key String @id + day String + channel String + count Int @default(0) + + @@index([day]) +} + // ── Prayer requests (§4) ───────────────────────────────────────────────────────────────────── // Special personal information (POPIA s26): never in stats, the heartbeat, AI or an email's text. // The rules (closing after 30 days, fully anonymous requests, emergency numbers) are in AppSetting diff --git a/apps/app/backend/src/app.ts b/apps/app/backend/src/app.ts index f8cd08b..ed07038 100644 --- a/apps/app/backend/src/app.ts +++ b/apps/app/backend/src/app.ts @@ -19,6 +19,9 @@ * * /api/v1/announcements, /devotionals, /events and their admin content (content/routes.ts) * /api/feed/v1/… the event feed, both ways (events/feed.ts) + * /api/v1/me/notifications what the App sends a member (email, WhatsApp, both or off) + * /api/v1/admin/messaging Settings → Email and WhatsApp: the church's settings from Accounts, Send a test + * /api/accounts/v1/messaging-changed Accounts: the email or WhatsApp settings changed (links/routes.ts) */ import express from 'express'; import type { Ctx } from './context.js'; @@ -33,6 +36,7 @@ import { prayerAdminRouter } from './prayer/admin.js'; import { prayerRouter } from './prayer/routes.js'; import { requestsAdminRouter, requestsRouter } from './requests/routes.js'; import { contentAdminRouter, contentRouter } from './content/routes.js'; +import { messagingAdminRouter, notificationsRouter } from './messaging/routes.js'; export function createApp(ctx: Ctx) { const app = express(); @@ -63,6 +67,8 @@ export function createApp(ctx: Ctx) { app.use('/api', prayerRouter(ctx)); app.use('/api', requestsRouter(ctx)); app.use('/api', contentRouter(ctx)); + app.use('/api/v1/me/notifications', notificationsRouter(ctx)); + app.use('/api/v1/admin/messaging', messagingAdminRouter(ctx)); app.use('/api/v1/admin/prayer', prayerAdminRouter(ctx)); app.use('/api/v1/admin/requests', requestsAdminRouter(ctx)); app.use('/api/v1/admin', contentAdminRouter(ctx)); diff --git a/apps/app/backend/src/auth/routes.ts b/apps/app/backend/src/auth/routes.ts index d540f3d..4e62314 100644 --- a/apps/app/backend/src/auth/routes.ts +++ b/apps/app/backend/src/auth/routes.ts @@ -20,6 +20,7 @@ import express, { type Request, type Response } from 'express'; import { deletePrayer, exportPrayer } from '../prayer/members.js'; import { deleteRequests, exportRequests } from '../requests/members.js'; +import { exportNotifications } from '../messaging/preferences.js'; import { ACCOUNTS_CALL_PATH, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS, safeReturnPath, type AccountsCall, type IdentityClaims, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import type { AppRole } from '../generated/prisma/client.js'; @@ -48,11 +49,14 @@ const isAdminPath = (path: string) => path === '/admin' || path.startsWith('/adm type MemberRow = { id: string; name: string; email: string; roles: AppRole[] }; /** The profile fields the App keeps a copy of. */ -const profileData = (p: { name: string; email: string; phone_number: string | null; phone_number_verified: boolean; whatsapp_opted_out?: boolean }) => ({ +const profileData = (p: { name: string; email: string; phone_number: string | null; phone_number_verified: boolean; whatsapp_opted_out?: boolean; news_consent: { email: boolean; whatsapp: boolean } }) => ({ name: p.name, email: p.email.toLowerCase(), phone: p.phone_number_verified ? p.phone_number : null, whatsappOptedOut: p.whatsapp_opted_out ?? false, + // Announcements go only on the channels the person allowed news on (§8). + newsEmail: p.news_consent.email, + newsWhatsApp: p.news_consent.whatsapp, }); /** @@ -187,7 +191,7 @@ export function authRouter(ctx: Ctx) { /** * Accounts' signed calls (§11): a member's profile copy, roles and sign-ins, and the House of * Prayer's commitments, "I prayed" marks and testimonies (prayer/members.ts). Each later module - * adds its own records to the export and the delete (requests, notification settings). Someone the App doesn't know is + * adds its own records to the export and the delete (requests; notification settings go with the member). Someone the App doesn't know is * answered as done. */ export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Request): Promise { @@ -204,7 +208,7 @@ export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Req key: 'app_member', title: 'You in the church\'s App', records: [{ name: member.name, email: member.email, roles: member.roles, since: member.createdAt.toISOString(), lastSignIn: member.lastSignInAt?.toISOString() ?? null, lastUsed: member.lastActiveAt?.toISOString() ?? null }], - }, ...(await exportPrayer(ctx, member.id)), ...(await exportRequests(ctx, member.id))] : [], + }, ...(await exportPrayer(ctx, member.id)), ...(await exportRequests(ctx, member.id)), ...(await exportNotifications(ctx, member.id))] : [], }; return reply; } diff --git a/apps/app/backend/src/context.ts b/apps/app/backend/src/context.ts index c1e60f5..afeb4ab 100644 --- a/apps/app/backend/src/context.ts +++ b/apps/app/backend/src/context.ts @@ -7,6 +7,7 @@ import type { Config } from './lib/config.js'; import { Secrets } from './lib/crypto.js'; import { Settings } from './lib/settings.js'; import { loadAuthClient, type AuthClientModule } from './auth/accounts.js'; +import { LiveTransport, type Transport } from './messaging/transport.js'; export type Db = PrismaClient; @@ -17,14 +18,17 @@ export type Ctx = { settings: Settings; /** `@crosscode/auth-client` (tests give a stand-in). */ authClient: () => Promise; + /** Sends email and WhatsApp (tests give a stand-in that keeps them). */ + transport: Transport; now: () => Date; }; -export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise } = {}): Ctx { +export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise; transport?: Transport } = {}): Ctx { const secrets = new Secrets(config.secret); const partial = { config, db, secrets } as Ctx; partial.settings = new Settings(partial); partial.authClient = opts.authClient ?? loadAuthClient; + partial.transport = opts.transport ?? new LiveTransport(); partial.now = opts.now ?? (() => new Date()); return partial; } diff --git a/apps/app/backend/src/hub/client.ts b/apps/app/backend/src/hub/client.ts index de6eaeb..9612e77 100644 --- a/apps/app/backend/src/hub/client.ts +++ b/apps/app/backend/src/hub/client.ts @@ -21,6 +21,7 @@ import { enabledModules } from '../modules.js'; import { hubPublicKey, verifyToken } from './licence.js'; import { prayerStats } from '../prayer/service.js'; import { announcementsLast30d } from '../content/announcements.js'; +import { messagesLast30d } from '../messaging/send.js'; import { jobsHealth } from '../jobs.js'; export const PROTOCOL_VERSION = 2; @@ -77,7 +78,8 @@ export async function health(ctx: Ctx) { /** * Aggregate counts only (hub.appStatsSchema): prayer coverage of the last 7 days and active - * commitments (no names, no times), announcements published in 30 days. Messages are 0 until §8. + * commitments (no names, no times), announcements published in 30 days, emails and WhatsApp + * messages sent in 30 days (§8). */ export async function stats(ctx: Ctx): Promise> { const [{ band }, modules] = await Promise.all([activeMembers(ctx), enabledModules(ctx)]); @@ -86,7 +88,7 @@ export async function stats(ctx: Ctx): Promise Promise }; @@ -30,6 +32,9 @@ export const JOBS: Job[] = [ { name: 'crosscode-devotionals', label: 'Cross Code\'s devotionals from the Hub (the next 2 weeks)', cron: '15 1 * * *', env: null, run: (ctx) => nightlySync(ctx) }, { name: 'prayer-reminders', label: 'House of Prayer: slot reminders', cron: '* * * * *', env: 'PRAYER_REMINDERS_ENABLED', run: (ctx) => sendReminders(ctx) }, { name: 'prayer-requests-tidy', label: 'Prayer requests: close after their days, delete 12 months after closing', cron: '30 3 * * *', env: null, run: (ctx) => tidyRequests(ctx, DELETE_AFTER_CLOSED_DAYS) }, + { name: 'messages-send', label: 'Email and WhatsApp: send what\'s queued (reminders, notices, announcements, devotionals)', cron: '* * * * *', env: 'MESSAGES_ENABLED', run: (ctx) => sendOutbox(ctx) }, + { name: 'announcement-sends', label: 'Announcements: queue "Also send it" at the publish time', cron: '* * * * *', env: null, run: (ctx) => queueAnnouncements(ctx) }, + { name: 'devotional-sends', label: 'Today\'s devotional: queue it at each member\'s time', cron: '*/5 * * * *', env: null, run: (ctx) => queueDevotionals(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) }, ]; diff --git a/apps/app/backend/src/lib/outbox.ts b/apps/app/backend/src/lib/outbox.ts index e23fb87..2f83a39 100644 --- a/apps/app/backend/src/lib/outbox.ts +++ b/apps/app/backend/src/lib/outbox.ts @@ -1,14 +1,15 @@ /** * 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, + * due: prayer reminders and renewal notices (prayer/jobs.ts), the prayer team's and submitters' + * notices (requests/service.ts), announcements and devotionals (messaging/send.ts). The + * `messages-send` 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' | 'request-new' | 'request-update' | 'request-escalated'; +export type OutboxKind = 'prayer-reminder' | 'prayer-renewal' | 'testimony-removed' | 'request-new' | 'request-update' | 'request-escalated' | 'announcement' | 'devotional'; export type Channel = 'email' | 'whatsapp' | 'both'; /** Queues a message; false when one with the same key was already queued (never sent twice). */ diff --git a/apps/app/backend/src/lib/settings.ts b/apps/app/backend/src/lib/settings.ts index eff46bc..7d87d57 100644 --- a/apps/app/backend/src/lib/settings.ts +++ b/apps/app/backend/src/lib/settings.ts @@ -5,7 +5,8 @@ */ import type { Ctx } from '../context.js'; -export const SECRET_SETTINGS = new Set(['hub_install_secret', 'hub_private_key']); +/** `messaging_settings`: the church's SMTP password and WAWP token from Accounts (§8). */ +export const SECRET_SETTINGS = new Set(['hub_install_secret', 'hub_private_key', 'messaging_settings']); const TTL_MS = 30_000; diff --git a/apps/app/backend/src/links/connect.ts b/apps/app/backend/src/links/connect.ts index 6759167..299aa66 100644 --- a/apps/app/backend/src/links/connect.ts +++ b/apps/app/backend/src/links/connect.ts @@ -1,8 +1,8 @@ /** * Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4, Accounts and the Website). The * App links to the church's **Accounts** (signing in: the link's secret is where the client secret - * comes from, and Accounts registers the App as an OIDC client when it accepts; later also the - * shared email and WhatsApp settings, APP-1.0-PLAN §8) and, for the event feed (§7), to **Events** + * comes from, and Accounts registers the App as an OIDC client when it accepts; and the + * church's email and WhatsApp settings, fetched as soon as the link is made, APP-1.0-PLAN §8) and, for the event feed (§7), to **Events** * and the **Website**. * * Trust comes from the Hub's list on both sides: a message is accepted only from an install in this @@ -85,7 +85,11 @@ async function firstUse(ctx: Ctx, nonce: string): Promise { async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) { const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById, lastSyncError: null }; - return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data }); + const link = await ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data }); + // A new link to Accounts: the church's email and WhatsApp settings (§8). Imported here, as the + // Hub client above: messaging/settings.ts reaches this file through auth/accounts.ts. + if (link.product === 'accounts') import('../messaging/settings.js').then((m) => m.fetchMessagingSoon(ctx)).catch(() => {}); + return link; } const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: Actor | null, req: Request | undefined, by: string) => diff --git a/apps/app/backend/src/links/routes.ts b/apps/app/backend/src/links/routes.ts index 653c1e1..ce00b7a 100644 --- a/apps/app/backend/src/links/routes.ts +++ b/apps/app/backend/src/links/routes.ts @@ -8,16 +8,18 @@ * GET /feed/v1/events?updatedSince= the App's events (crosscode.event-feed/1), public * POST /feed/v1/changed a sibling's events changed: fetch them now (signed) * - * To come: Accounts' "the messaging settings changed" (§8). + * POST /accounts/v1/messaging-changed Accounts: the church's email or WhatsApp settings changed: + * fetch them again (signed, APP-1.0-PLAN §8) */ import express from 'express'; -import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS } from '@crosscode/contracts'; +import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, IDENTITY_REQUEST_SCHEMA, LINK_PATHS, MESSAGING_CHANGED_PATH, messagingChangedSchema } from '@crosscode/contracts'; import { LINK_HEADERS, verify } from '@crosscode/contracts/signing'; import type { Ctx } from '../context.js'; import { churchChanged } from '../church/profile.js'; import { acceptConnect, acceptDisconnect, LinkError } from './connect.js'; import { buildFeed, publishOn, syncLink } from '../events/feed.js'; import { enabledModules } from '../modules.js'; +import { fetchMessagingSoon } from '../messaging/settings.js'; export function linksRouter(ctx: Ctx) { const r = express.Router(); @@ -108,5 +110,18 @@ export function linksRouter(ctx: Ctx) { return fail(res, e); } }); + + r.post(MESSAGING_CHANGED_PATH.replace(/^\/api/, ''), raw, async (req, res) => { + try { + const got = await signedBy(req, res, true); + if (!got) return undefined; + if (!messagingChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t a messaging.changed message.'); + // Fetched after answering: Accounts doesn't wait for it (the send job tries again if it fails). + fetchMessagingSoon(ctx); + return res.json({ schema: IDENTITY_REQUEST_SCHEMA, ok: true }); + } catch (e) { + return fail(res, e); + } + }); return r; } diff --git a/apps/app/backend/src/messaging/preferences.ts b/apps/app/backend/src/messaging/preferences.ts new file mode 100644 index 0000000..a36f64a --- /dev/null +++ b/apps/app/backend/src/messaging/preferences.ts @@ -0,0 +1,106 @@ +/** + * What a member chose the App sends them (APP-1.0-PLAN §8): per kind, email, WhatsApp, both or + * off. Prayer reminders and renewals follow each commitment's channel (chosen when booking); the + * rest are here, with the defaults when there's no row: + * + * | Kind | Default | + * |---|---| + * | Prayer request updates (approved, someone prayed, a reply) | email | + * | Announcements the church sends | off until the member turns them on (P13) | + * | Today's devotional | off; offered at the first sign-in, at 06:00 by default (§6) | + * + * Announcements also need the member's news consent in Accounts for that channel. + */ +import { z } from 'zod'; +import type { Ctx } from '../context.js'; +import type { Member, NotificationSettings } from '../generated/prisma/client.js'; +import { ApiError } from '../http.js'; +import { enabledModules } from '../modules.js'; +import { messagingSettings } from './settings.js'; +import { whatsappReach } from './stop.js'; + +export const CHOICES = ['off', 'email', 'whatsapp', 'both'] as const; +export type Choice = (typeof CHOICES)[number]; + +export type Prefs = Pick; + +export const DEFAULT_PREFS: Prefs = { requestUpdates: 'email', announcements: 'off', devotional: 'off', devotionalTime: '06:00', devotionalOfferedAt: null, lastDevotionalDate: null }; + +/** HH:MM on a quarter hour (the devotional job runs every 5 minutes). */ +const TIME = /^([01]\d|2[0-3]):(00|15|30|45)$/; + +export async function prefsOf(ctx: Ctx, memberId: string): Promise { + return (await ctx.db.notificationSettings.findUnique({ where: { memberId } })) ?? DEFAULT_PREFS; +} + +/** Whether a choice includes email / WhatsApp. */ +export const wantsEmail = (c: Choice) => c === 'email' || c === 'both'; +export const wantsWhatsApp = (c: Choice) => c === 'whatsapp' || c === 'both'; + +export const prefsBody = z.object({ + requestUpdates: z.enum(CHOICES).optional(), + announcements: z.enum(CHOICES).optional(), + devotional: z.enum(CHOICES).optional(), + devotionalTime: z.string().regex(TIME, 'A time on the quarter hour, e.g. 06:00 or 06:30.').optional(), +}).strict(); +export type PrefsInput = z.infer; + +type MemberRow = Pick; + +/** What the Me → Notifications page shows. */ +export async function myNotifications(ctx: Ctx, member: MemberRow) { + const [prefs, settings, modules, reach] = await Promise.all([prefsOf(ctx, member.id), messagingSettings(ctx), enabledModules(ctx), whatsappReach(ctx, member)]); + return { + requestUpdates: prefs.requestUpdates, + announcements: prefs.announcements, + devotional: prefs.devotional, + devotionalTime: prefs.devotionalTime, + /** The first-sign-in offer of today's devotional (§6), until it's answered. */ + offerDevotional: !prefs.devotionalOfferedAt && prefs.devotional === 'off' && modules.includes('devotionals'), + channels: { + email: { ready: !!settings?.email }, + whatsapp: { ready: !!settings?.whatsapp, reach: reach.ok ? 'ok' : reach.reason }, + }, + news: { email: member.newsEmail, whatsapp: member.newsWhatsApp }, + modules: modules.filter((m) => m === 'prayer-requests' || m === 'announcements' || m === 'devotionals' || m === 'house-of-prayer'), + }; +} + +async function save(ctx: Ctx, memberId: string, data: Partial) { + return ctx.db.notificationSettings.upsert({ where: { memberId }, create: { memberId, ...data }, update: data }); +} + +/** Saves the member's choices. WhatsApp only to a verified number that hasn't replied STOP. */ +export async function setMyNotifications(ctx: Ctx, member: MemberRow, input: PrefsInput) { + const asksWhatsApp = [input.requestUpdates, input.announcements, input.devotional].some((c) => c && wantsWhatsApp(c)); + if (asksWhatsApp) { + const reach = await whatsappReach(ctx, member); + if (!reach.ok) { + throw new ApiError(400, reach.reason === 'opted_out' ? 'WHATSAPP_STOPPED' : 'NO_PHONE', reach.reason === 'opted_out' + ? 'You replied STOP to the church\'s WhatsApp number, so nothing is sent to you on WhatsApp. Turn WhatsApp back on in your church account first.' + : 'WhatsApp needs a verified mobile number. Add one in your church account first.'); + } + } + const data: Partial = { ...input }; + // Choosing anything about the devotional answers the first-sign-in offer too. + if (input.devotional !== undefined || input.devotionalTime !== undefined) data.devotionalOfferedAt = ctx.now(); + await save(ctx, member.id, data); + return myNotifications(ctx, member); +} + +/** The first-sign-in offer (§6): a channel to start getting today's devotional, or "Not now". */ +export async function answerDevotionalOffer(ctx: Ctx, member: MemberRow, choice: Choice | null) { + if (choice && choice !== 'off') return setMyNotifications(ctx, member, { devotional: choice }); + await save(ctx, member.id, { devotionalOfferedAt: ctx.now() }); + return myNotifications(ctx, member); +} + +/** The member's part of "Download my data" (§11). */ +export async function exportNotifications(ctx: Ctx, memberId: string) { + const p = await ctx.db.notificationSettings.findUnique({ where: { memberId } }); + return p ? [{ + key: 'app_notifications', + title: 'What the App sends you', + records: [{ requestUpdates: p.requestUpdates, announcements: p.announcements, devotional: p.devotional, devotionalTime: p.devotionalTime, changed: p.updatedAt.toISOString() }], + }] : []; +} diff --git a/apps/app/backend/src/messaging/routes.ts b/apps/app/backend/src/messaging/routes.ts new file mode 100644 index 0000000..5ef280e --- /dev/null +++ b/apps/app/backend/src/messaging/routes.ts @@ -0,0 +1,104 @@ +/** + * Email and WhatsApp (APP-1.0-PLAN §8). + * + * A member (signed in): + * GET /api/v1/me/notifications what the App sends them, and whether WhatsApp reaches them + * PUT /api/v1/me/notifications { requestUpdates?, announcements?, devotional?, devotionalTime? } + * POST /api/v1/me/notifications/devotional-offer { choice: 'email' | 'whatsapp' | 'both' | null } (null: "Not now") + * + * The admin, Settings → Email and WhatsApp (Owner, Church admin; with 2FA): + * GET /api/v1/admin/messaging which address and number the App sends from (no secrets), where + * they're kept, the last fetch, what's waiting or failed, the counts + * POST /api/v1/admin/messaging/fetch fetch them from Accounts again now + * POST /api/v1/admin/messaging/test { channel: 'email' | 'whatsapp' }: a test to the admin themself + * + * Changing the settings is done where they're kept (Cross Events or Accounts), never here (decision 4). + */ +import express from 'express'; +import { z } from 'zod'; +import type { Ctx } from '../context.js'; +import { ApiError, handle, parse, sameOrigin } from '../http.js'; +import { audit, clientIp } from '../lib/audit.js'; +import { requireMember, requireRole } from '../auth/sessions.js'; +import { CHOICES, answerDevotionalOffer, myNotifications, prefsBody, setMyNotifications } from './preferences.js'; +import { outboxSummary, sendTest } from './send.js'; +import { fetchMessaging, messagingStatus, savedMessaging } from './settings.js'; + +const noStore: express.RequestHandler = (_req, res, next) => { + res.set('Cache-Control', 'no-store'); + next(); +}; + +async function memberRow(ctx: Ctx, id: string) { + const m = await ctx.db.member.findUnique({ where: { id } }); + if (!m) throw new ApiError(401, 'SIGNED_OUT', 'Please sign in.'); + return m; +} + +export function notificationsRouter(ctx: Ctx) { + const r = express.Router(); + r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production)); + r.use(express.json({ limit: '16kb' })); + r.use(noStore); + + r.get('/', requireMember(ctx), handle(async (req) => myNotifications(ctx, await memberRow(ctx, req.signed!.member.id)))); + + r.put('/', requireMember(ctx), handle(async (req) => setMyNotifications(ctx, await memberRow(ctx, req.signed!.member.id), parse(prefsBody, req.body)))); + + const offerBody = z.object({ choice: z.enum(CHOICES).nullable() }).strict(); + r.post('/devotional-offer', requireMember(ctx), handle(async (req) => answerDevotionalOffer(ctx, await memberRow(ctx, req.signed!.member.id), parse(offerBody, req.body).choice))); + return r; +} + +/** Who keeps the settings: Cross Events when the church has it (it copies them into Accounts), else Accounts. */ +async function keptIn(ctx: Ctx) { + const links = await ctx.db.productLink.findMany({ where: { product: { in: ['accounts', 'events'] } } }); + const events = links.find((l) => l.product === 'events'); + const accounts = links.find((l) => l.product === 'accounts'); + return events ? { product: 'events', url: events.url } : accounts ? { product: 'accounts', url: accounts.url } : null; +} + +export function messagingAdminRouter(ctx: Ctx) { + const r = express.Router(); + r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production)); + r.use(express.json({ limit: '16kb' })); + r.use(noStore); + const admins = requireRole(ctx, ['owner', 'church_admin']); + + r.get('/', admins, handle(async () => { + const [saved, status, kept, outbox] = await Promise.all([savedMessaging(ctx), messagingStatus(ctx), keptIn(ctx), outboxSummary(ctx)]); + return { + email: saved?.email ? { ready: true, from: saved.email.from, host: saved.email.host } : { ready: false, from: null, host: null }, + whatsapp: saved?.whatsapp ? { ready: true, instanceId: saved.whatsapp.instanceId } : { ready: false, instanceId: null }, + fetchedAt: saved?.fetchedAt ?? null, + changedAt: saved?.updatedAt ?? null, + lastTry: status, + keptIn: kept, + outbox, + }; + })); + + r.post('/fetch', admins, handle(async (req) => { + try { + const s = await fetchMessaging(ctx); + await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'messaging_fetched', targetType: 'settings', targetId: 'messaging', metadata: { email: !!s.email, whatsapp: !!s.whatsapp }, ip: clientIp(req) }); + return { email: !!s.email, whatsapp: !!s.whatsapp, fetchedAt: s.fetchedAt }; + } catch (e) { + throw new ApiError(502, 'NOT_FETCHED', `The settings couldn't be fetched from Accounts: ${(e as Error).message}`); + } + })); + + const testBody = z.object({ channel: z.enum(['email', 'whatsapp']) }).strict(); + r.post('/test', admins, handle(async (req) => { + const { channel } = parse(testBody, req.body); + const member = await memberRow(ctx, req.signed!.member.id); + try { + const out = await sendTest(ctx, member, channel); + await audit(ctx, { actorId: member.id, actorRole: member.roles.join(','), action: 'messaging_test_sent', targetType: 'settings', targetId: 'messaging', metadata: { channel }, ip: clientIp(req) }); + return { sent: true, ...out }; + } catch (e) { + throw new ApiError(502, 'NOT_SENT', (e as Error).message); + } + })); + return r; +} diff --git a/apps/app/backend/src/messaging/send.ts b/apps/app/backend/src/messaging/send.ts new file mode 100644 index 0000000..9c787dd --- /dev/null +++ b/apps/app/backend/src/messaging/send.ts @@ -0,0 +1,302 @@ +/** + * Sending what's queued (APP-1.0-PLAN §8), and queuing the church's announcements and the day's + * devotional for the members who asked for them. + * + * - **`messages-send`** (every minute): the outbox (lib/outbox.ts), oldest first, at most 100 a + * run, with the church's settings from Accounts (messaging/settings.ts). Every WhatsApp is + * checked against STOP first (messaging/stop.ts). Something the member asked for (a reminder, a + * renewal, a notice, the devotional) goes by email instead when WhatsApp can't reach them; + * announcements never do (they need the news consent for the channel). A failed send is tried + * again after 2, 4, 8 and 16 minutes, then given up. A reminder is never sent once its slot has + * started, and nothing is sent more than 3 days late. While the church has neither email nor + * WhatsApp set up, messages wait. + * - **`announcement-sends`** (every minute): an announcement with "Also send it" is queued once, at + * its publish time, for members who turned announcements on (P13), on the channels the admin + * chose and the member allows (their choice and their news consent in Accounts). + * - **`devotional-sends`** (every 5 minutes): today's devotional from the chosen source, at each + * member's time (06:00 by default), once a day; up to 3 hours late, else skipped for the day. + * + * Every message sent is counted per day and channel (MessageCount) for the heartbeat. + */ +import type { Ctx } from '../context.js'; +import type { Member, OutboxMessage } from '../generated/prisma/client.js'; +import { churchTimezone } from '../church/profile.js'; +import { devotionalSource } from '../content/devotionals.js'; +import { enqueue, type Channel } from '../lib/outbox.js'; +import { addDays, localDate, localParts } from '../lib/zoned.js'; +import { enabledModules } from '../modules.js'; +import { prefsOf, wantsEmail, wantsWhatsApp, type Choice } from './preferences.js'; +import { messagingSettings, type MessagingSettings } from './settings.js'; +import { whatsappReach } from './stop.js'; +import * as T from './templates.js'; + +const BATCH = 100; +const MAX_ATTEMPTS = 5; +const LATE_MS = 3 * 864e5; +/** A devotional is sent up to this many minutes after the member's time, else skipped that day. */ +const DEVOTIONAL_LATE_MINUTES = 180; + +/** Kinds that go by email when WhatsApp can't reach the member: things they asked for. */ +const EMAIL_INSTEAD = new Set(['prayer-reminder', 'prayer-renewal', 'testimony-removed', 'request-new', 'request-update', 'request-escalated', 'devotional']); + +type Built = T.Built; +type Outcome = { done: true; via: string; error: string | null } | { done: false; error: string; wait?: boolean }; + +/** Adds one to today's count for a channel (the heartbeat's `messages`). */ +export async function countSent(ctx: Ctx, channel: 'email' | 'whatsapp', tz: string) { + const day = localDate(ctx.now(), tz); + const key = `${day}:${channel}`; + await ctx.db.messageCount.upsert({ where: { key }, create: { key, day, channel, count: 1 }, update: { count: { increment: 1 } } }); +} + +/** Messages sent in the last 30 days, per channel (hub.appStatsSchema `messages`). */ +export async function messagesLast30d(ctx: Ctx): Promise<{ email30d: number; whatsapp30d: number }> { + const tz = await churchTimezone(ctx); + const since = addDays(localDate(ctx.now(), tz), -29); + const rows = await ctx.db.messageCount.findMany({ where: { day: { gte: since } } }); + const sum = (c: string) => rows.filter((r) => r.channel === c).reduce((t, r) => t + r.count, 0); + return { email30d: sum('email'), whatsapp30d: sum('whatsapp') }; +} + +/** What the message says, from its payload (and for announcements and devotionals, the record now). */ +async function build(ctx: Ctx, brand: Awaited>, m: OutboxMessage, member: Member): Promise { + const p = (m.payload ?? {}) as Record; + switch (m.kind) { + case 'prayer-reminder': return T.prayerReminder(brand, member, p); + case 'prayer-renewal': return T.prayerRenewal(brand, member, p); + case 'testimony-removed': return T.testimonyRemoved(brand, member, p); + case 'request-new': return T.requestNew(brand, member, p); + case 'request-update': return T.requestUpdate(brand, member, p); + case 'request-escalated': return T.requestEscalated(brand, member, p); + case 'announcement': { + const a = await ctx.db.announcement.findUnique({ where: { id: String(p.announcementId) } }); + const now = ctx.now(); + if (!a || !a.publishAt || a.publishAt > now || (a.endsAt && a.endsAt <= now)) return null; + return T.announcementMessage(brand, member, a); + } + case 'devotional': { + const d = await ctx.db.devotional.findUnique({ where: { id: String(p.devotionalId) } }); + return d ? T.devotionalMessage(brand, member, d) : null; + } + default: return null; + } +} + +/** The channels this message goes on now: the queued one, or the member's choice for request updates. */ +async function wanted(ctx: Ctx, m: OutboxMessage, member: Member): Promise<{ email: boolean; whatsapp: boolean; why?: string }> { + let choice: Choice = m.channel; + if (m.kind === 'request-update') choice = (await prefsOf(ctx, member.id)).requestUpdates; + if (choice === 'off') return { email: false, whatsapp: false, why: 'Turned off by the member.' }; + const want = { email: wantsEmail(choice), whatsapp: wantsWhatsApp(choice) }; + // Announcements: the news consent may have been withdrawn in Accounts since it was queued. + if (m.kind === 'announcement') { + want.email &&= member.newsEmail; + want.whatsapp &&= member.newsWhatsApp; + if (!want.email && !want.whatsapp) return { ...want, why: 'No news consent for that channel.' }; + } + return want; +} + +async function deliver(ctx: Ctx, settings: MessagingSettings, m: OutboxMessage & { member: Member }, brand: Awaited>, tz: string, pauseMs: number): Promise { + const msg = await build(ctx, brand, m, m.member); + if (!msg) return { done: true, via: 'none', error: 'What it was about is gone.' }; + const want = await wanted(ctx, m, m.member); + if (!want.email && !want.whatsapp) return { done: true, via: 'none', error: want.why ?? null }; + const notes: string[] = []; + let to: string | null = null; + if (want.whatsapp) { + const reach = await whatsappReach(ctx, m.member); + const problem = !reach.ok ? (reach.reason === 'opted_out' ? 'They replied STOP to WhatsApp.' : 'They have no verified mobile number.') : !settings.whatsapp ? 'The church\'s WhatsApp isn\'t set up.' : null; + if (problem) { + want.whatsapp = false; + notes.push(problem); + if (!want.email && EMAIL_INSTEAD.has(m.kind)) { + want.email = true; + notes.push('Sent by email instead.'); + } + } else if (reach.ok) { + to = reach.to; + } + } + if (want.email && !settings.email) { + want.email = false; + notes.push('The church\'s email isn\'t set up.'); + } + if (!want.email && !want.whatsapp) { + // Nothing the church has set up reaches them: wait while that's the church's settings, else done. + const churchSide = notes.some((n) => n.startsWith('The church')); + return churchSide ? { done: false, error: notes.join(' '), wait: true } : { done: true, via: 'none', error: notes.join(' ') || null }; + } + const via: string[] = []; + if (want.email) { + try { + await ctx.transport.email(settings.email!, { to: m.member.email, subject: msg.subject, text: msg.text, html: msg.html, fromName: brand.name }); + via.push('email'); + await countSent(ctx, 'email', tz); + } catch (e) { + notes.push(`Email: ${(e as Error).message}`); + } + } + if (want.whatsapp && to) { + try { + if (pauseMs) await new Promise((r) => setTimeout(r, pauseMs)); + await ctx.transport.whatsapp(settings.whatsapp!, { to, text: msg.whatsapp }); + via.push('whatsapp'); + await countSent(ctx, 'whatsapp', tz); + } catch (e) { + notes.push(`WhatsApp: ${(e as Error).message}`); + } + } + const error = notes.length ? notes.join(' ').slice(0, 500) : null; + return via.length ? { done: true, via: via.join(','), error } : { done: false, error: error ?? 'Not sent.' }; +} + +/** Old messages give up: a reminder once its slot started, anything after 3 days. */ +async function expire(ctx: Ctx) { + const now = ctx.now(); + const old = await ctx.db.outboxMessage.updateMany({ where: { sentAt: null, failedAt: null, sendAfter: { lt: new Date(now.getTime() - LATE_MS) } }, data: { failedAt: now, error: 'Not sent within 3 days.' } }); + const reminders = await ctx.db.outboxMessage.findMany({ where: { sentAt: null, failedAt: null, kind: 'prayer-reminder' }, select: { id: true, payload: true } }); + let late = 0; + for (const r of reminders) { + const start = new Date(String((r.payload as { start?: string } | null)?.start ?? '')); + if (Number.isFinite(start.getTime()) && start <= now) { + await ctx.db.outboxMessage.update({ where: { id: r.id }, data: { failedAt: now, error: 'Too late: the slot had started.' } }); + late++; + } + } + return old.count + late; +} + +export async function sendOutbox(ctx: Ctx, opts: { pauseMs?: number } = {}) { + const expired = await expire(ctx); + const settings = await messagingSettings(ctx); + if (!settings?.email && !settings?.whatsapp) { + const waiting = await ctx.db.outboxMessage.count({ where: { sentAt: null, failedAt: null } }); + return { skipped: 'The church\'s email and WhatsApp aren\'t set up in Accounts (or not fetched yet).', waiting, expired }; + } + const now = ctx.now(); + const due = await ctx.db.outboxMessage.findMany({ + where: { sentAt: null, failedAt: null, sendAfter: { lte: now } }, + orderBy: { sendAfter: 'asc' }, + take: BATCH, + include: { member: true }, + }) as (OutboxMessage & { member: Member })[]; + if (!due.length) return { sent: 0, expired }; + const [brand, tz] = await Promise.all([T.brand(ctx), churchTimezone(ctx)]); + let sent = 0; + let failed = 0; + let waiting = 0; + for (const m of due) { + let out: Outcome; + try { + out = await deliver(ctx, settings, m, brand, tz, opts.pauseMs ?? 300); + } catch (e) { + out = { done: false, error: (e as Error).message.slice(0, 500) }; + } + if (out.done) { + await ctx.db.outboxMessage.update({ where: { id: m.id }, data: { sentAt: ctx.now(), sentVia: out.via, error: out.error } }); + if (out.via !== 'none') sent++; + } else if (out.wait) { + waiting++; + await ctx.db.outboxMessage.update({ where: { id: m.id }, data: { error: out.error, sendAfter: new Date(ctx.now().getTime() + 15 * 60e3) } }); + } else { + const attempts = m.attempts + 1; + failed++; + await ctx.db.outboxMessage.update({ + where: { id: m.id }, + data: attempts >= MAX_ATTEMPTS + ? { attempts, error: out.error, failedAt: ctx.now() } + : { attempts, error: out.error, sendAfter: new Date(ctx.now().getTime() + 2 ** attempts * 60e3) }, + }); + } + } + return { sent, failed, waiting, expired }; +} + +/** "Also send it": each announcement once, at its publish time (§5). */ +export async function queueAnnouncements(ctx: Ctx) { + if (!(await enabledModules(ctx)).includes('announcements')) return { skipped: 'Announcements are switched off.' }; + const now = ctx.now(); + const rows = await ctx.db.announcement.findMany({ where: { sentAt: null, publishAt: { not: null, lte: now }, OR: [{ sendEmail: true }, { sendWhatsApp: true }] } }); + let queued = 0; + for (const a of rows) { + // Claimed first, so two runs never both queue it. + const claim = await ctx.db.announcement.updateMany({ where: { id: a.id, sentAt: null }, data: { sentAt: now } }); + if (claim.count !== 1) continue; + // Published long ago (saved with "send" after the event) or ended: not sent. + if (a.publishAt!.getTime() < now.getTime() - 864e5 || (a.endsAt && a.endsAt <= now)) continue; + const wanting = await ctx.db.notificationSettings.findMany({ where: { announcements: { not: 'off' } }, select: { memberId: true, announcements: true } }); + const members = new Map((await ctx.db.member.findMany({ where: { id: { in: wanting.map((w) => w.memberId) } }, select: { id: true, newsEmail: true, newsWhatsApp: true } })).map((m) => [m.id, m])); + for (const w of wanting) { + const m = members.get(w.memberId); + if (!m) continue; + const email = a.sendEmail && wantsEmail(w.announcements) && m.newsEmail; + const whatsapp = a.sendWhatsApp && wantsWhatsApp(w.announcements) && m.newsWhatsApp; + if (!email && !whatsapp) continue; + const channel: Channel = email && whatsapp ? 'both' : email ? 'email' : 'whatsapp'; + if (await enqueue(ctx, { memberId: m.id, kind: 'announcement', channel, dedupeKey: `announcement:${a.id}:${m.id}`, payload: { announcementId: a.id } })) queued++; + } + } + return { announcements: rows.length, queued }; +} + +const toMinutes = (hhmm: string) => { + const [h, m] = hhmm.split(':').map(Number); + return (h ?? 0) * 60 + (m ?? 0); +}; + +/** Today's devotional at each member's time, once a day (§6, decision 5). */ +export async function queueDevotionals(ctx: Ctx) { + if (!(await enabledModules(ctx)).includes('devotionals')) return { skipped: 'Devotionals are switched off.' }; + const tz = await churchTimezone(ctx); + const { date: today, minute } = localParts(ctx.now(), tz); + const source = await devotionalSource(ctx); + const d = await ctx.db.devotional.findUnique({ where: { source_date: { source, date: today } } }); + if (!d) return { skipped: `There's no devotional for ${today}${source === 'crosscode' ? ' from Cross Code yet' : ''}.` }; + const rows = await ctx.db.notificationSettings.findMany({ + where: { devotional: { not: 'off' }, OR: [{ lastDevotionalDate: null }, { lastDevotionalDate: { not: today } }] }, + select: { memberId: true, devotional: true, devotionalTime: true }, + }); + let queued = 0; + let missed = 0; + for (const r of rows) { + const at = toMinutes(r.devotionalTime); + if (at > minute) continue; + if (minute - at <= DEVOTIONAL_LATE_MINUTES) { + if (await enqueue(ctx, { memberId: r.memberId, kind: 'devotional', channel: r.devotional as Channel, dedupeKey: `devotional:${today}:${r.memberId}`, payload: { devotionalId: d.id, date: today } })) queued++; + } else { + missed++; + } + await ctx.db.notificationSettings.update({ where: { memberId: r.memberId }, data: { lastDevotionalDate: today } }); + } + return { date: today, queued, missed }; +} + +/** Settings → Email and WhatsApp → Send a test, to the admin themself. Throws why it couldn't. */ +export async function sendTest(ctx: Ctx, member: Member, channel: 'email' | 'whatsapp') { + const settings = await messagingSettings(ctx); + const brand = await T.brand(ctx); + const msg = T.testMessage(brand, member); + if (channel === 'email') { + if (!settings?.email) throw new Error('The church\'s email isn\'t set up in Accounts (or Cross Events).'); + await ctx.transport.email(settings.email, { to: member.email, subject: msg.subject, text: msg.text, html: msg.html, fromName: brand.name }); + return { sentTo: member.email }; + } + if (!settings?.whatsapp) throw new Error('The church\'s WhatsApp isn\'t set up in Accounts (or Cross Events).'); + const reach = await whatsappReach(ctx, member); + if (!reach.ok) throw new Error(reach.reason === 'opted_out' ? 'You replied STOP to the church\'s WhatsApp number, so the App sends you none. Turn WhatsApp back on in your church account.' : 'Your church account has no verified mobile number to send the test to.'); + await ctx.transport.whatsapp(settings.whatsapp, { to: reach.to, text: msg.whatsapp }); + return { sentTo: reach.to }; +} + +/** For the admin: what's waiting, what failed in the last 7 days, what was sent. */ +export async function outboxSummary(ctx: Ctx) { + const since = new Date(ctx.now().getTime() - 7 * 864e5); + const [waiting, failed, recentFailures, counts] = await Promise.all([ + ctx.db.outboxMessage.count({ where: { sentAt: null, failedAt: null } }), + ctx.db.outboxMessage.count({ where: { failedAt: { gte: since } } }), + ctx.db.outboxMessage.findMany({ where: { failedAt: { gte: since } }, orderBy: { failedAt: 'desc' }, take: 10, select: { kind: true, failedAt: true, error: true } }), + messagesLast30d(ctx), + ]); + return { waiting, failedLast7d: failed, recentFailures: recentFailures.map((f) => ({ kind: f.kind, at: f.failedAt!.toISOString(), error: f.error })), sentLast30d: counts }; +} diff --git a/apps/app/backend/src/messaging/settings.ts b/apps/app/backend/src/messaging/settings.ts new file mode 100644 index 0000000..80563c7 --- /dev/null +++ b/apps/app/backend/src/messaging/settings.ts @@ -0,0 +1,106 @@ +/** + * The church's email and WhatsApp settings (APP-1.0-PLAN §8, decision 4): one set per church, kept + * in Events or Accounts. The App never asks for its own: it takes them from Accounts over the + * signed link (`messaging.get`, the SMTP password and WAWP token sealed with the link's secret) and + * keeps them encrypted in AppSetting `messaging_settings`. + * + * They're fetched when the App links to Accounts, when Accounts says they changed + * (`messaging.changed`), once a day by the send job (a missed hint), on the admin's **Fetch + * again**, and whenever there's nothing saved yet (at most every 10 minutes). While Accounts + * can't be reached the last copy keeps working. + */ +import { messagingGetReplySchema, type MessagingGetReply } from '@crosscode/contracts'; +import { openLinkValue } from '@crosscode/contracts/signing'; +import type { Ctx } from '../context.js'; +import { accounts, accountsLink } from '../auth/accounts.js'; +import type { Smtp, Wawp } from './transport.js'; + +export const MESSAGING_KEY = 'messaging_settings'; +const STATUS_KEY = 'messaging_status'; +const RETRY_MS = 10 * 60e3; +/** Fetched again after this, in case a `messaging.changed` was missed. */ +export const REFRESH_AFTER_MS = 24 * 3600e3; + +export type MessagingSettings = { email: Smtp | null; whatsapp: Wawp | null; updatedAt: string | null; fetchedAt: string }; +/** The last try: when, and what went wrong (no secrets). */ +type Status = { triedAt: string; error: string | null }; + +const pending = new WeakMap>(); + +/** What was last fetched from Accounts, or null. */ +export async function savedMessaging(ctx: Ctx): Promise { + const s = await ctx.settings.json(MESSAGING_KEY, null); + return s && typeof s === 'object' && 'fetchedAt' in s ? s : null; +} + +export async function messagingStatus(ctx: Ctx): Promise { + return ctx.settings.json(STATUS_KEY, null); +} + +function open(secret: string, reply: MessagingGetReply, now: Date): MessagingSettings { + const e = reply.email; + const w = reply.whatsapp; + return { + email: e ? { host: e.host, port: e.port, secure: e.secure, user: e.user, pass: e.pass ? openLinkValue(secret, e.pass) : null, from: e.from } : null, + whatsapp: w ? { accessToken: openLinkValue(secret, w.accessToken), instanceId: w.instanceId } : null, + updatedAt: reply.updatedAt, + fetchedAt: now.toISOString(), + }; +} + +/** Asks Accounts for the settings now and saves them. Throws why it couldn't (the last copy stays). */ +export function fetchMessaging(ctx: Ctx): Promise { + // One at a time: a hint and the job can both ask. + let run = pending.get(ctx); + if (!run) { + run = fetchOnce(ctx).finally(() => pending.delete(ctx)); + pending.set(ctx, run); + } + return run; +} + +async function fetchOnce(ctx: Ctx): Promise { + const triedAt = ctx.now().toISOString(); + try { + const link = await accountsLink(ctx); + if (!link) throw new Error('The App isn\'t linked to the church\'s Accounts yet.'); + const client = await accounts(ctx); + const reply = messagingGetReplySchema.safeParse(await client.request({ type: 'messaging.get', actor: null })); + if (!reply.success) throw new Error('Accounts answered in a way the App doesn\'t understand.'); + const settings = open(ctx.secrets.decrypt(link.secret), reply.data, ctx.now()); + await ctx.settings.set(MESSAGING_KEY, JSON.stringify(settings)); + await ctx.settings.set(STATUS_KEY, JSON.stringify({ triedAt, error: null } satisfies Status)); + return settings; + } catch (e) { + const error = (e as Error).message.slice(0, 300); + await ctx.settings.set(STATUS_KEY, JSON.stringify({ triedAt, error } satisfies Status)).catch(() => {}); + throw e; + } +} + +/** + * The settings to send with: the saved copy, fetched first when there's none (at most every + * 10 minutes) or it's a day old. Never throws: null while nothing could be fetched. + */ +export async function messagingSettings(ctx: Ctx): Promise { + const saved = await savedMessaging(ctx); + const now = ctx.now().getTime(); + const status = await messagingStatus(ctx); + const triedRecently = !!status && now - new Date(status.triedAt).getTime() < RETRY_MS; + const stale = !saved || now - new Date(saved.fetchedAt).getTime() > REFRESH_AFTER_MS; + if (stale && !triedRecently) { + try { + return await fetchMessaging(ctx); + } catch (e) { + console.warn('[messaging] The settings weren\'t fetched from Accounts:', (e as Error).message); + } + } + return saved; +} + +/** Fetched in the background (after linking to Accounts, or Accounts' `messaging.changed`). */ +export function fetchMessagingSoon(ctx: Ctx): void { + setImmediate(() => { + fetchMessaging(ctx).catch((e) => console.warn('[messaging] The settings weren\'t fetched from Accounts:', (e as Error).message)); + }); +} diff --git a/apps/app/backend/src/messaging/stop.ts b/apps/app/backend/src/messaging/stop.ts new file mode 100644 index 0000000..d92a7ea --- /dev/null +++ b/apps/app/backend/src/messaging/stop.ts @@ -0,0 +1,27 @@ +/** + * Whether the App may send someone WhatsApp (APP-1.0-PLAN §8, decision 11). STOP means no WhatsApp + * from any of the church's products, of any kind, reminders included. Accounts keeps the opt-out + * and tells the App with `user.updated` (`whatsapp_opted_out`, kept as `Member.whatsappOptedOut`). + * Checked before every WhatsApp message, by number too: anyone in the App with the same number + * who is opted out stops it (as Cross Events' `isWhatsAppStopped`). + * + * The App has no WhatsApp webhook of its own: the church's number sends replies to Events or + * Accounts, which keep the STOP and pass it on, so the App never receives one to pass on itself. + */ +import type { Ctx } from '../context.js'; +import { waNumber } from './transport.js'; + +export type WhatsAppReach = { ok: true; to: string } | { ok: false; reason: 'no_phone' | 'opted_out' }; + +/** The forms a number may be stored in: +27821234567, 27821234567, 0821234567. */ +function storedForms(n: string): string[] { + return [`+${n}`, n, ...(n.startsWith('27') ? [`0${n.slice(2)}`] : [])]; +} + +export async function whatsappReach(ctx: Ctx, member: { phone: string | null; whatsappOptedOut: boolean }): Promise { + if (member.whatsappOptedOut) return { ok: false, reason: 'opted_out' }; + const n = waNumber(member.phone); + if (!member.phone || !n) return { ok: false, reason: 'no_phone' }; + const stopped = await ctx.db.member.findFirst({ where: { whatsappOptedOut: true, phone: { in: storedForms(n) } }, select: { id: true } }); + return stopped ? { ok: false, reason: 'opted_out' } : { ok: true, to: member.phone }; +} diff --git a/apps/app/backend/src/messaging/templates.ts b/apps/app/backend/src/messaging/templates.ts new file mode 100644 index 0000000..9c0b195 --- /dev/null +++ b/apps/app/backend/src/messaging/templates.ts @@ -0,0 +1,278 @@ +/** + * What each message says (APP-1.0-PLAN §8), by email and by WhatsApp. Emails are laid out as + * Accounts' and Cross Events' (a header in the church's colour with its logo or name, a white card, + * one button with the link written out under it, the church's contact in the footer) and always + * carry a plain-text version too. Everything put into the HTML is escaped. + * + * Never a prayer request's text (§4): only that something happened, and a link. A devotional's + * passage always goes with its translation's copyright line (§6, contracts 1.22.0). + */ +import { bibleTranslation, type BibleTranslationId, type Church } from '@crosscode/contracts'; +import type { Ctx } from '../context.js'; +import type { Announcement, Devotional } from '../generated/prisma/client.js'; +import { churchProfile } from '../church/profile.js'; + +export type Built = { subject: string; text: string; html: string; whatsapp: string }; + +type Brand = { name: string; colour: string; logoUrl: string | null; email: string | null; phone: string | null; url: string }; + +const FONT = `-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif`; +const HEX = /^#[0-9a-fA-F]{6}$/; + +export const esc = (s: unknown) => String(s ?? '') + .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); + +/** Only http(s) links go in an href. */ +const safeUrl = (u: string) => (/^https?:\/\//i.test(u) ? u : '#'); + +function darker(hex: string, by = 0.25): string { + const n = parseInt(hex.slice(1), 16); + const ch = (shift: number) => Math.max(0, Math.round(((n >> shift) & 255) * (1 - by))); + return `#${[ch(16), ch(8), ch(0)].map((c) => c.toString(16).padStart(2, '0')).join('')}`; +} + +export function brandOf(ctx: Ctx, c: Church | null): Brand { + const base = ctx.config.publicUrl.replace(/\/+$/, ''); + if (!c) return { name: 'Your church', colour: '#1f4e79', logoUrl: null, email: null, phone: null, url: base }; + const logo = c.branding.logoUrl; + return { + name: c.name || 'Your church', + colour: HEX.test(c.branding.colours.primary) ? c.branding.colours.primary : '#1f4e79', + logoUrl: logo && /^https:\/\//i.test(logo) ? logo : null, + email: c.contact.email ?? null, + phone: c.contact.phone ?? null, + url: base, + }; +} + +function layout(b: Brand, body: string, preheader: string, why: string): string { + const header = b.logoUrl + ? `${esc(b.name)}` + : `

${esc(b.name)}

`; + const contact = [esc(b.name), b.email ? `${esc(b.email)}` : '', b.phone ? esc(b.phone) : ''] + .filter(Boolean).join(' • '); + const settings = `${b.url}/me/notifications`; + return ` + + + + +${esc(b.name)} + + +
${esc(preheader)}‌ ‌ 
+ + +
+ + + + +
+ ${header} +

The ${esc(b.name)} App

+
+
+ ${body} +
+
+

${contact}

+

${esc(why)} Choose what the App sends you.

+
+
+ +`; +} + +const title = (t: string, sub?: string) => + `

${esc(t)}

` + + (sub ? `

${esc(sub)}

` : ''); +const hello = (name?: string | null) => `

Hello ${esc(firstName(name))},

`; +const para = (html: string) => `

${html}

`; +const small = (html: string) => `

${html}

`; +const quote = (html: string) => `
${html}
`; + +function button(b: Brand, label: string, url: string): string { + const href = esc(safeUrl(url)); + return ` + +
+ ${esc(label)} +
+

Or copy this link: ${esc(url)}

`; +} + +const firstName = (name?: string | null) => String(name ?? '').trim().split(/\s+/)[0] || 'there'; +const lines = (s: string) => esc(s).replace(/\n/g, '
'); +/** Markdown to plain text for a message (links, emphasis and headings' marks dropped). */ +export function plain(md: string): string { + return md + .replace(/!\[[^\]]*\]\([^)]*\)/g, '') + .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1 ($2)') + .replace(/^#{1,6}\s+/gm, '') + .replace(/(\*\*|__|\*|_|`)/g, '') + .replace(/\n{3,}/g, '\n\n') + .trim(); +} +const cut = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s); + +function when(iso: string, tz: string, opts: Intl.DateTimeFormatOptions) { + return new Intl.DateTimeFormat('en-ZA', { timeZone: tz, ...opts }).format(new Date(iso)); +} +const dayLong = (iso: string, tz: string) => when(iso, tz, { weekday: 'long', day: 'numeric', month: 'long' }); +const hm = (iso: string, tz: string) => when(iso, tz, { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); +const dateLong = (date: string) => new Intl.DateTimeFormat('en-ZA', { timeZone: 'UTC', weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' }).format(new Date(`${date}T12:00:00Z`)); +const minuteHm = (m: number) => `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`; + +type Who = { name: string }; + +const P = (payload: unknown) => (payload ?? {}) as Record; +const str = (v: unknown) => (typeof v === 'string' ? v : ''); + +// ─── The messages ─────────────────────────────────────────────────────────────────────────── + +export function prayerReminder(b: Brand, who: Who, payload: unknown): Built { + const p = P(payload); + const tz = str(p.timezone) || 'Africa/Johannesburg'; + const time = `${hm(str(p.start), tz)}–${hm(str(p.end), tz)}`; + const day = dayLong(str(p.start), tz); + const prayed = `${b.url}${str(p.prayedPath)}`; + const mine = `${b.url}/me/prayer`; + const body = title('Your time to pray', `${day}, ${time}`) + + hello(who.name) + + para(`This is a reminder of your time on ${esc(b.name)}'s prayer wall: ${esc(day)}, ${esc(time)}.`) + + para('Afterwards, you can mark it as prayed (it only counts towards the church\'s total, never a ranking).') + + button(b, 'I prayed', prayed) + + small(`To skip it or change your times, open My prayer in the App.`); + const text = `Hello ${firstName(who.name)},\n\nA reminder of your time on ${b.name}'s prayer wall: ${day}, ${time}.\n\nAfterwards, mark it as prayed: ${prayed}\n\nSkip it or change your times in the App: ${mine}`; + const whatsapp = `🙏 *${b.name}*: your time to pray is ${day}, ${time}.\n\nAfterwards, tap to mark it as prayed: ${prayed}`; + return { subject: `Your time to pray: ${day}, ${time}`, text, whatsapp, html: layout(b, body, `Your time on the prayer wall: ${day}, ${time}.`, 'You\'re getting this because you asked for a reminder of your prayer slot.') }; +} + +export function prayerRenewal(b: Brand, who: Who, payload: unknown): Built { + const p = P(payload); + const end = dateLong(str(p.endDate)); + const start = Number(p.startMinute) || 0; + const slot = `${minuteHm(start)}–${minuteHm(start + (Number(p.durationMinutes) || 60))}`; + const how = p.recurrence === 'daily' ? `every day, ${slot}` : `every week, ${slot}`; + const renew = `${b.url}${str(p.renewPath)}`; + const body = title('Keep praying with us?', `Your commitment ends on ${end}`) + + hello(who.name) + + para(`Thank you for praying ${esc(how)}. Your commitment ends on ${esc(end)}.`) + + para('To keep your time for another year, tap the button. You don\'t need to sign in.') + + button(b, 'Renew for another year', renew) + + small('If you don\'t renew it, your time opens up for someone else after that day.'); + const text = `Hello ${firstName(who.name)},\n\nThank you for praying ${how}. Your commitment ends on ${end}.\n\nRenew it for another year (no sign-in needed): ${renew}`; + const whatsapp = `🙏 *${b.name}*: thank you for praying ${how}. Your commitment ends on ${end}.\n\nRenew it for another year: ${renew}`; + return { subject: `Your prayer commitment ends on ${end}`, text, whatsapp, html: layout(b, body, `Renew your prayer time for another year.`, 'You\'re getting this because you committed to pray on the church\'s prayer wall.') }; +} + +export function testimonyRemoved(b: Brand, who: Who, payload: unknown): Built { + const reason = str(P(payload).reason); + const body = title('Your testimony wasn\'t shared') + + hello(who.name) + + para('Thank you for sharing what God has done. The prayer team didn\'t share this testimony with the church.') + + (reason ? quote(lines(reason)) : '') + + small(`Questions? Contact the church${b.email ? ` at ${esc(b.email)}` : ''}.`); + const text = `Hello ${firstName(who.name)},\n\nThank you for sharing what God has done. The prayer team didn't share this testimony with the church.${reason ? `\n\nThe reason they gave: ${reason}` : ''}`; + return { subject: 'Your testimony wasn\'t shared', text, whatsapp: `*${b.name}*: the prayer team didn't share your testimony.${reason ? ` The reason they gave: ${reason}` : ''}`, html: layout(b, body, 'About the testimony you shared.', 'You\'re getting this because you shared a testimony in the App.') }; +} + +/** To the prayer team: no text, no name (§4). */ +export function requestNew(b: Brand, who: Who, payload: unknown): Built { + const p = P(payload); + const url = `${b.url}${str(p.path) || '/admin/requests'}`; + const needs = p.needsApproval === true; + const body = title('You have a new prayer request', needs ? 'It waits for approval before members see it' : 'For the prayer team') + + hello(who.name) + + para(needs ? 'Someone asked the church to pray, and wants it shared with members. It waits for a coordinator to approve it.' : 'Someone asked the prayer team to pray.') + + button(b, 'Open the prayer requests', url) + + small('The request itself is only in the App, never in an email or a message.'); + const text = `Hello ${firstName(who.name)},\n\nYou have a new prayer request${needs ? ' waiting for approval' : ''}. Open it in the App: ${url}`; + return { subject: needs ? 'A prayer request waits for approval' : 'You have a new prayer request', text, whatsapp: `🙏 *${b.name}*: you have a new prayer request${needs ? ' waiting for approval' : ''}. ${url}`, html: layout(b, body, 'Open it in the App.', 'You\'re getting this because you\'re on the church\'s prayer team.') }; +} + +/** To Pastoral care, by email and WhatsApp at once (§4). */ +export function requestEscalated(b: Brand, who: Who, payload: unknown): Built { + const url = `${b.url}${str(P(payload).path) || '/admin/requests?view=escalated'}`; + const body = title('A prayer request needs pastoral care', 'Escalated by the prayer team') + + hello(who.name) + + para('A prayer coordinator escalated a request to the church\'s safeguarding contacts. Please look at it as soon as you can.') + + button(b, 'Open the escalated requests', url) + + small('The request itself is only in the App, never in an email or a message.'); + const text = `Hello ${firstName(who.name)},\n\nA prayer coordinator escalated a request to the church's safeguarding contacts. Please look at it as soon as you can: ${url}`; + return { subject: 'A prayer request needs pastoral care', text, whatsapp: `⚠️ *${b.name}*: a prayer request was escalated to pastoral care. Please look at it as soon as you can: ${url}`, html: layout(b, body, 'Please look at it as soon as you can.', 'You\'re getting this because you\'re one of the church\'s safeguarding contacts.') }; +} + +const UPDATE: Record = { + approved: { subject: 'Your prayer request is shared', says: 'Your prayer request was approved, and members of the church can now pray for it.' }, + redacted: { subject: 'Your prayer request was edited', says: 'The prayer team edited out some names or details before sharing your request. You can see what changed in the App.' }, + removed: { subject: 'Your prayer request wasn\'t shared', says: 'The prayer team didn\'t share your request with members. The prayer team still has it. You can see why in the App.' }, + reply: { subject: 'The prayer team replied', says: 'The prayer team sent you a reply about your prayer request. It\'s for you alone.' }, + prayed: { subject: 'Someone prayed for your request', says: 'Members of the church prayed for your request today.' }, +}; + +export function requestUpdate(b: Brand, who: Who, payload: unknown): Built { + const p = P(payload); + const u = UPDATE[str(p.what)] ?? UPDATE.reply!; + const url = `${b.url}${str(p.path) || '/me/requests'}`; + const body = title(u.subject) + + hello(who.name) + + para(esc(u.says)) + + button(b, 'Open my prayer requests', url); + const text = `Hello ${firstName(who.name)},\n\n${u.says}\n\n${url}`; + return { subject: u.subject, text, whatsapp: `🙏 *${b.name}*: ${u.says} ${url}`, html: layout(b, body, u.says, 'You\'re getting this because you asked for prayer in the App.') }; +} + +export function announcementMessage(b: Brand, who: Who, a: Announcement): Built { + const url = `${b.url}/announcements/${encodeURIComponent(a.slug)}`; + const text = plain(a.body); + const short = cut(text, 600); + const body = title(a.title) + + hello(who.name) + + para(lines(short)) + + button(b, 'Read it in the App', url); + return { + subject: a.title, + text: `Hello ${firstName(who.name)},\n\n${a.title}\n\n${short}\n\nRead it in the App: ${url}`, + whatsapp: `📣 *${b.name}*: *${a.title}*\n\n${cut(text, 500)}\n\n${url}`, + html: layout(b, body, cut(text, 120), 'You\'re getting this because you asked for the church\'s announcements.'), + }; +} + +/** The title, the verse (reference and text, with its translation's notice) and a link (decision 5). */ +export function devotionalMessage(b: Brand, who: Who, d: Devotional): Built { + const t = bibleTranslation(d.translation as BibleTranslationId); + const url = `${b.url}/devotional/${d.date}`; + const notice = [t.copyright, t.disclaimer].filter(Boolean).join(' '); + const passage = cut(d.passageText.trim(), 1200); + const body = title(d.title, dateLong(d.date)) + + hello(who.name) + + quote(`${lines(passage)}
${esc(d.reference)} (${esc(t.id)})`) + + button(b, 'Read today\'s devotional', url) + + small(esc(notice)); + return { + subject: `Today's devotional: ${d.title}`, + text: `Hello ${firstName(who.name)},\n\n${d.title}\n\n"${passage}"\n${d.reference} (${t.id})\n\nRead today's devotional: ${url}\n\n${notice}`, + whatsapp: `📖 *${d.title}*\n\n_"${passage}"_\n*${d.reference}* (${t.id})\n\nRead today's devotional: ${url}\n\n${notice}`, + html: layout(b, body, `${d.reference}: ${cut(passage, 100)}`, 'You\'re getting this because you asked for the day\'s devotional.'), + }; +} + +/** Settings → Email and WhatsApp → Send a test. */ +export function testMessage(b: Brand, who: Who): Built { + const body = title('A test from the App', 'Email from the church\'s App works') + + hello(who.name) + + para(`This test shows that the ${esc(b.name)} App can send email with the church's settings. Members get their prayer reminders, notices and devotionals the same way.`); + return { + subject: `A test from the ${b.name} App`, + text: `Hello ${firstName(who.name)},\n\nThis test shows that the ${b.name} App can send email with the church's settings.`, + whatsapp: `✅ A test from the ${b.name} App: WhatsApp works.`, + html: layout(b, body, 'Email from the App works.', 'You\'re getting this because you sent a test from the App\'s admin.'), + }; +} + +export async function brand(ctx: Ctx): Promise { + return brandOf(ctx, await churchProfile(ctx).catch(() => null)); +} + diff --git a/apps/app/backend/src/messaging/transport.ts b/apps/app/backend/src/messaging/transport.ts new file mode 100644 index 0000000..47f127e --- /dev/null +++ b/apps/app/backend/src/messaging/transport.ts @@ -0,0 +1,52 @@ +/** + * Sending one email (SMTP) or WhatsApp message (WAWP), with the church's settings from Accounts + * (messaging/settings.ts), as Accounts' and Cross Events' messengers do. Tests give a stand-in + * that keeps what would have been sent (tests/support/harness.ts). + */ +import nodemailer from 'nodemailer'; + +export type Smtp = { host: string; port: number; secure: boolean; user: string; pass: string | null; from: string }; +export type Wawp = { accessToken: string; instanceId: string }; + +export type Email = { to: string; subject: string; text: string; html?: string; fromName?: string | null }; +export type WhatsApp = { to: string; text: string }; + +export interface Transport { + email(settings: Smtp, msg: Email): Promise; + whatsapp(settings: Wawp, msg: WhatsApp): Promise; +} + +/** 0821234567 / +27 82 123 4567 → 27821234567 (South African mobiles; others as given, digits only). */ +export function waNumber(raw: string | null | undefined): string | null { + let d = String(raw || '').replace(/\D/g, ''); + if (d.startsWith('0') && d.length === 10) d = `27${d.slice(1)}`; + return d.length >= 10 && d.length <= 15 ? d : null; +} + +/** `"Acacia Hill" `: the church's name on the address it sends from. */ +export function fromHeader(from: string, name?: string | null): string { + const clean = String(name ?? '').replace(/["<>\r\n]/g, '').trim(); + return clean && !from.includes('<') ? `"${clean}" <${from}>` : from; +} + +export class LiveTransport implements Transport { + async email(s: Smtp, msg: Email): Promise { + const transport = nodemailer.createTransport({ + host: s.host, port: s.port, secure: s.secure, auth: s.user ? { user: s.user, pass: s.pass ?? '' } : undefined, + connectionTimeout: 15000, greetingTimeout: 15000, socketTimeout: 20000, + }); + await transport.sendMail({ from: fromHeader(s.from, msg.fromName), to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) }); + } + + async whatsapp(s: Wawp, msg: WhatsApp): Promise { + const number = waNumber(msg.to); + if (!number) throw new Error('That isn\'t a WhatsApp number.'); + const res = await fetch('https://api.wawp.net/v2/send/text', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ access_token: s.accessToken, instance_id: s.instanceId, chatId: `${number}@c.us`, message: msg.text }), + signal: AbortSignal.timeout(15000), + }); + if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`); + } +} diff --git a/apps/app/backend/tests/messaging.test.ts b/apps/app/backend/tests/messaging.test.ts new file mode 100644 index 0000000..a00dbb0 --- /dev/null +++ b/apps/app/backend/tests/messaging.test.ts @@ -0,0 +1,295 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import request from 'supertest'; +import { bibleTranslation, IDENTITY_REQUEST_SCHEMA, MESSAGING_CHANGED_PATH } from '@crosscode/contracts'; +import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing'; +import { stats } from '../src/hub/client.js'; +import { enqueue } from '../src/lib/outbox.js'; +import { queueAnnouncements, queueDevotionals, sendOutbox } from '../src/messaging/send.js'; +import { fetchMessaging, MESSAGING_KEY, savedMessaging } from '../src/messaging/settings.js'; +import { sendReminders } from '../src/prayer/jobs.js'; +import { + ACCOUNTS_INSTALL_ID, CHURCH_SMTP, CHURCH_WAWP, cookieHeader, harness, LINK_SECRET, MEMBER, PASTOR, signInAs, type Harness, +} from './support/harness.js'; + +const OTHER = '44444444-4444-4444-8444-444444444444'; +const COORD = '55555555-5555-4555-8555-555555555555'; +const ORIGIN = 'https://app.hope.test'; +const SECRET = 'My brother Themba is in hospital after the accident'; + +async function setup() { + const h = await harness() as Harness; + const as = (cookies: Record) => ({ + get: (path: string) => request(h.app).get(path).set('Cookie', cookieHeader(cookies)), + post: (path: string, body: object = {}) => request(h.app).post(path).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body), + put: (path: string, body: object) => request(h.app).put(path).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body), + }); + const thandi = as(await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test' })); + const pieter = as(await signInAs(h, { sub: OTHER, name: 'Pieter Botha', email: 'pieter@hope.test' })); + const admin = as(await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['owner'] }, true)); + // Each their own number (the stand-in Accounts gives everyone the same one). + await h.db.member.update({ where: { id: MEMBER }, data: { phone: '+27821110001' } }); + await h.db.member.update({ where: { id: OTHER }, data: { phone: '+27821110002' } }); + await h.db.member.update({ where: { id: PASTOR }, data: { phone: '+27821110003' } }); + return { h, thandi, pieter, admin, visitor: as({}) }; +} + +const send = (h: Harness) => sendOutbox(h.ctx, { pauseMs: 0 }); +const rows = (h: Harness, table: string) => [...(h.db.tables.get(table)?.values() ?? [])] as Record[]; +const inAnHour = (h: Harness) => new Date(h.clock.now().getTime() + 3600e3).toISOString(); + +async function reminder(h: Harness, memberId: string, channel: 'email' | 'whatsapp' | 'both', key = 'r1') { + const start = inAnHour(h); + await enqueue(h.ctx, { + memberId, kind: 'prayer-reminder', channel, dedupeKey: key, + payload: { commitmentId: 'c1', date: '2026-12-01', start, end: new Date(Date.parse(start) + 3600e3).toISOString(), timezone: 'Africa/Johannesburg', prayedPath: '/prayer/prayed?token=abc' }, + }); +} + +describe('the church\'s email and WhatsApp settings (decision 4)', () => { + it('takes them from Accounts with messaging.get, opens the sealed secrets, and keeps them encrypted', async () => { + const { h } = await setup(); + const s = await fetchMessaging(h.ctx); + assert.deepEqual(h.fake.requests.at(-1), { type: 'messaging.get', actor: null }); + assert.deepEqual(s.email, CHURCH_SMTP); + assert.deepEqual(s.whatsapp, CHURCH_WAWP); + const stored = String(rows(h, 'appSetting').find((r) => r.key === MESSAGING_KEY)!.value); + assert.ok(!stored.includes('smtp-pass') && !stored.includes('wawp-token')); + }); + + it('fetches them again when Accounts says they changed, and refuses an unsigned hint', async () => { + const { h } = await setup(); + await fetchMessaging(h.ctx); + h.fake.messaging = { email: { ...CHURCH_SMTP, from: 'office@hope.test' }, whatsapp: null }; + const body = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: h.clock.now().toISOString(), email: true, whatsapp: true }); + const unsigned = await request(h.app).post(MESSAGING_CHANGED_PATH).set('Content-Type', 'application/json').send(body); + assert.equal(unsigned.status, 404); + const headers = signedHeaders(LINK_HEADERS, { senderId: ACCOUNTS_INSTALL_ID, secret: LINK_SECRET, rawBody: body, now: h.clock.now() }); + const res = await request(h.app).post(MESSAGING_CHANGED_PATH).set(headers).set('Content-Type', 'application/json').send(body); + assert.equal(res.status, 200); + assert.deepEqual(res.body, { schema: IDENTITY_REQUEST_SCHEMA, ok: true }); + await new Promise((r) => setTimeout(r, 20)); + const saved = await savedMessaging(h.ctx); + assert.equal(saved!.email!.from, 'office@hope.test'); + assert.equal(saved!.whatsapp, null); + }); + + it('keeps messages waiting while the church has neither set up, and keeps the last copy when Accounts is down', async () => { + const { h } = await setup(); + h.fake.messaging = { email: null, whatsapp: null }; + await reminder(h, MEMBER, 'email'); + const out = await send(h); + assert.match(String((out as { skipped: string }).skipped), /aren't set up/); + assert.equal(h.transport.emails.length, 0); + h.fake.messaging = { email: CHURCH_SMTP, whatsapp: CHURCH_WAWP }; + await fetchMessaging(h.ctx); + h.fake.messaging = new Error('Accounts could not be reached'); + await assert.rejects(fetchMessaging(h.ctx)); + assert.equal((await send(h) as { sent: number }).sent, 1); + assert.equal(h.transport.emails[0]!.to, 'thandi@hope.test'); + }); +}); + +describe('sending (§8)', () => { + it('sends a prayer reminder on the commitment\'s channel, with the "I prayed" link and the church\'s settings', async () => { + const { h, thandi } = await setup(); + // 10:00 tomorrow, reminded an hour before. + assert.equal((await thandi.post('/api/v1/me/prayer/commitments', { startDate: '2026-12-02', startMinute: 600, durationMinutes: 60, recurrence: 'once', reminder: 'hour1', channel: 'both' })).status, 201); + h.clock.set('2026-12-02T07:00:00Z'); + assert.equal((await sendReminders(h.ctx) as { queued: number }).queued, 1); + await send(h); + const [mail] = h.transport.emails; + const [wa] = h.transport.whatsapps; + assert.equal(mail!.to, 'thandi@hope.test'); + assert.deepEqual(mail!.settings, CHURCH_SMTP); + assert.match(mail!.subject, /10:00–11:00/); + assert.match(mail!.text, /https:\/\/app\.hope\.test\/prayer\/prayed\?token=/); + assert.equal(wa!.to, '+27821110001'); + assert.match(wa!.text, /10:00–11:00/); + assert.equal(rows(h, 'outboxMessage')[0]!.sentVia, 'email,whatsapp'); + }); + + it('checks STOP before every WhatsApp: a reminder goes by email instead, never to WhatsApp', async () => { + const { h } = await setup(); + await h.db.member.update({ where: { id: MEMBER }, data: { whatsappOptedOut: true } }); + await reminder(h, MEMBER, 'whatsapp'); + await send(h); + assert.equal(h.transport.whatsapps.length, 0); + assert.equal(h.transport.emails.length, 1); + const m = rows(h, 'outboxMessage')[0]!; + assert.equal(m.sentVia, 'email'); + assert.match(String(m.error), /STOP/); + }); + + it('stops WhatsApp to a number anyone in the App opted out with', async () => { + const { h } = await setup(); + await h.db.member.update({ where: { id: OTHER }, data: { phone: '0821110001', whatsappOptedOut: true } }); + await reminder(h, MEMBER, 'whatsapp'); + await send(h); + assert.equal(h.transport.whatsapps.length, 0); + assert.equal(h.transport.emails.length, 1); + }); + + it('tries a failed send again later, then gives up after five tries', async () => { + const { h } = await setup(); + await enqueue(h.ctx, { memberId: MEMBER, kind: 'request-update', channel: 'email', dedupeKey: 'u1', payload: { requestId: 'x', what: 'approved', path: '/me/requests' } }); + h.transport.fail.email = 'connect ECONNREFUSED'; + await send(h); + let m = rows(h, 'outboxMessage')[0]!; + assert.equal(m.attempts, 1); + assert.equal(m.sentAt, null); + assert.equal((await send(h) as { sent: number }).sent, 0, 'not again before its time'); + for (let i = 0; i < 4; i++) { + h.clock.add(40 * 60e3); + await send(h); + } + m = rows(h, 'outboxMessage')[0]!; + assert.equal(m.attempts, 5); + assert.ok(m.failedAt); + assert.match(String(m.error), /ECONNREFUSED/); + }); + + it('never sends a reminder once its slot has started', async () => { + const { h } = await setup(); + await reminder(h, MEMBER, 'email'); + h.clock.add(2 * 3600e3); + await send(h); + assert.equal(h.transport.emails.length, 0); + assert.match(String(rows(h, 'outboxMessage')[0]!.error), /Too late/); + }); + + it('sends request updates on the member\'s choice (or not at all), and never a prayer request\'s text', async () => { + const { h, thandi } = await setup(); + const coord = await signInAs(h, { sub: COORD, name: 'Lerato Dlamini', roles: ['prayer_coordinator'] }, true); + await h.db.member.update({ where: { id: COORD }, data: { phone: '+27821110004' } }); + assert.equal((await thandi.put('/api/v1/me/notifications', { requestUpdates: 'whatsapp' })).status, 200); + const r = await thandi.post('/api/v1/me/requests', { text: SECRET, visibility: 'members' }); + assert.equal(r.status, 201); + await request(h.app).post(`/api/v1/admin/requests/${r.body.id}/approve`).set('Cookie', cookieHeader(coord)).set('Origin', ORIGIN).send({}); + await send(h); + const toThandi = h.transport.whatsapps.filter((w) => w.to === '+27821110001'); + assert.equal(toThandi.length, 1); + assert.match(toThandi[0]!.text, /approved/); + const coordEmail = (await h.db.member.findUnique({ where: { id: COORD } }))!.email; + assert.deepEqual(h.transport.emails.filter((e) => e.to === coordEmail).map((e) => e.subject), ['A prayer request waits for approval']); + const everything = JSON.stringify([h.transport.emails, h.transport.whatsapps]); + assert.ok(!everything.includes('Themba')); + // Turned off: nothing more. + await thandi.put('/api/v1/me/notifications', { requestUpdates: 'off' }); + await request(h.app).post(`/api/v1/admin/requests/${r.body.id}/reply`).set('Cookie', cookieHeader(coord)).set('Origin', ORIGIN).send({ text: 'We are praying with you.' }); + const before = h.transport.whatsapps.length + h.transport.emails.length; + await send(h); + assert.equal(h.transport.whatsapps.length + h.transport.emails.length, before); + }); +}); + +describe('announcements and devotionals (§5, §6)', () => { + it('sends an announcement once, at its publish time, to members who turned announcements on and gave news consent', async () => { + const { h, thandi, pieter } = await setup(); + await thandi.put('/api/v1/me/notifications', { announcements: 'both' }); + await pieter.put('/api/v1/me/notifications', { announcements: 'email' }); + await h.db.member.update({ where: { id: MEMBER }, data: { newsEmail: true, newsWhatsApp: false } }); + // Pieter has no news consent: nothing for him. + const publishAt = new Date(h.clock.now().getTime() + 3600e3); + await h.db.announcement.create({ data: { slug: 'carols', title: 'Carols by candlelight', body: 'Join us on **Sunday** at 19:00.', publishAt, sendEmail: true, sendWhatsApp: true } }); + assert.equal((await queueAnnouncements(h.ctx) as { queued: number }).queued, 0, 'not before its publish time'); + h.clock.add(3600e3); + assert.equal((await queueAnnouncements(h.ctx) as { queued: number }).queued, 1); + assert.equal((await queueAnnouncements(h.ctx) as { queued: number }).queued, 0, 'once'); + await send(h); + assert.equal(h.transport.emails.length, 1); + assert.equal(h.transport.emails[0]!.to, 'thandi@hope.test'); + assert.match(h.transport.emails[0]!.text, /Join us on Sunday at 19:00/); + assert.match(h.transport.emails[0]!.text, /\/announcements\/carols/); + assert.equal(h.transport.whatsapps.length, 0, 'no news consent on WhatsApp, and never by email instead'); + }); + + it('sends today\'s devotional at the member\'s time, once a day, with the translation\'s notice', async () => { + const { h, thandi } = await setup(); + const offer = await thandi.get('/api/v1/me/notifications'); + assert.equal(offer.body.offerDevotional, true); + assert.equal((await thandi.post('/api/v1/me/notifications/devotional-offer', { choice: 'both' })).status, 200); + await thandi.put('/api/v1/me/notifications', { devotionalTime: '09:00' }); + assert.equal((await thandi.get('/api/v1/me/notifications')).body.offerDevotional, false); + await h.db.devotional.create({ data: { source: 'crosscode', date: '2026-12-01', title: 'Light in the dark', reference: 'John 1:5', location: { book: 'JHN', chapter: 1, verses: [5, 5] }, translation: 'BSB', passageText: 'The Light shines in the darkness, and the darkness has not overcome it.', body: 'Text' } }); + // 08:00 in Johannesburg: not yet. + assert.equal((await queueDevotionals(h.ctx) as { queued: number }).queued, 0); + h.clock.set('2026-12-01T07:05:00Z'); + assert.equal((await queueDevotionals(h.ctx) as { queued: number }).queued, 1); + assert.equal((await queueDevotionals(h.ctx) as { queued: number }).queued, 0, 'once a day'); + await send(h); + const notice = bibleTranslation('BSB').copyright; + assert.match(h.transport.emails[0]!.text, /The Light shines in the darkness/); + assert.ok(h.transport.emails[0]!.text.includes(notice)); + assert.ok(h.transport.emails[0]!.html!.includes('John 1:5')); + assert.ok(h.transport.whatsapps[0]!.text.includes(notice)); + assert.match(h.transport.whatsapps[0]!.text, /\/devotional\/2026-12-01/); + }); +}); + +describe('what the App sends me', () => { + it('starts with the defaults, and refuses WhatsApp without a verified number or after STOP', async () => { + const { h, thandi } = await setup(); + const me = await thandi.get('/api/v1/me/notifications'); + assert.equal(me.status, 200); + assert.equal(me.body.requestUpdates, 'email'); + assert.equal(me.body.announcements, 'off'); + assert.equal(me.body.devotional, 'off'); + assert.equal(me.body.devotionalTime, '06:00'); + assert.equal(me.body.channels.whatsapp.reach, 'ok'); + await h.db.member.update({ where: { id: MEMBER }, data: { whatsappOptedOut: true } }); + assert.equal((await thandi.put('/api/v1/me/notifications', { announcements: 'whatsapp' })).body.error.code, 'WHATSAPP_STOPPED'); + await h.db.member.update({ where: { id: MEMBER }, data: { whatsappOptedOut: false, phone: null } }); + assert.equal((await thandi.put('/api/v1/me/notifications', { devotional: 'both' })).body.error.code, 'NO_PHONE'); + assert.equal((await thandi.put('/api/v1/me/notifications', { devotionalTime: '06:10' })).status, 400); + assert.equal((await thandi.put('/api/v1/me/notifications', { devotional: 'email', devotionalTime: '05:30' })).body.devotionalTime, '05:30'); + }); + + it('needs a sign-in', async () => { + const { visitor } = await setup(); + assert.equal((await visitor.get('/api/v1/me/notifications')).status, 401); + }); + + it('keeps the news consent from Accounts, exports the choices and deletes them with the account', async () => { + const { h, thandi } = await setup(); + await thandi.put('/api/v1/me/notifications', { announcements: 'email' }); + const call = (body: object) => request(h.app).post('/api/accounts/v1/events').set('x-test-signed', 'yes').set('Content-Type', 'application/json').send(JSON.stringify(body)); + await call({ schema: 'crosscode.identity/1', type: 'user.updated', sub: MEMBER, occurredAt: h.clock.now().toISOString(), profile: { name: 'Thandi Mokoena', given_name: 'Thandi', family_name: 'Mokoena', email: 'thandi@hope.test', email_verified: true, phone_number: '+27821110001', phone_number_verified: true, news_consent: { email: true, whatsapp: false } } }); + assert.equal((await h.db.member.findUnique({ where: { id: MEMBER } }))!.newsEmail, true); + const exp = await call({ schema: 'crosscode.identity/1', type: 'user.export', sub: MEMBER, exportId: '77777777-7777-4777-8777-777777777777', occurredAt: h.clock.now().toISOString() }); + assert.ok(exp.body.sections.some((s: { key: string }) => s.key === 'app_notifications')); + await call({ schema: 'crosscode.identity/1', type: 'user.deleted', sub: MEMBER, occurredAt: h.clock.now().toISOString() }); + assert.equal(rows(h, 'notificationSettings').length, 0); + }); +}); + +describe('Settings → Email and WhatsApp', () => { + it('shows what the App sends from (never the secrets), and sends the admin a test', async () => { + const { h, admin, thandi } = await setup(); + assert.equal((await thandi.get('/api/v1/admin/messaging')).status, 403); + assert.equal((await admin.post('/api/v1/admin/messaging/fetch')).status, 200); + const s = await admin.get('/api/v1/admin/messaging'); + assert.equal(s.status, 200); + assert.equal(s.body.email.from, 'app@hope.test'); + assert.equal(s.body.whatsapp.instanceId, 'HOPE1'); + assert.equal(s.body.keptIn.product, 'accounts'); + assert.ok(!JSON.stringify(s.body).includes('smtp-pass') && !JSON.stringify(s.body).includes('wawp-token')); + const email = await admin.post('/api/v1/admin/messaging/test', { channel: 'email' }); + assert.equal(email.body.sentTo, 'pastor@hope.test'); + const wa = await admin.post('/api/v1/admin/messaging/test', { channel: 'whatsapp' }); + assert.equal(wa.body.sentTo, '+27821110003'); + await h.db.member.update({ where: { id: PASTOR }, data: { whatsappOptedOut: true } }); + const stopped = await admin.post('/api/v1/admin/messaging/test', { channel: 'whatsapp' }); + assert.equal(stopped.status, 502); + assert.match(stopped.body.error.message, /STOP/); + }); + + it('counts what was sent for the Hub\'s heartbeat', async () => { + const { h } = await setup(); + await reminder(h, MEMBER, 'both'); + await reminder(h, OTHER, 'email', 'r2'); + await send(h); + const s = await stats(h.ctx); + assert.deepEqual(s.messages, { email30d: 2, whatsapp30d: 1 }); + }); +}); diff --git a/apps/app/backend/tests/support/harness.ts b/apps/app/backend/tests/support/harness.ts index 2fc7909..a60c21d 100644 --- a/apps/app/backend/tests/support/harness.ts +++ b/apps/app/backend/tests/support/harness.ts @@ -3,11 +3,13 @@ * tested against Accounts' provider in apps/accounts/backend/tests/authClient.test.ts), linked to a * church's Accounts and registered with the Hub, and a clock the tests can move. */ -import type { IdentityClaims } from '@crosscode/contracts'; +import { IDENTITY_REQUEST_SCHEMA, type IdentityClaims } from '@crosscode/contracts'; +import { sealLinkValue } from '@crosscode/contracts/signing'; import type { AuthClientModule } from '../../src/auth/accounts.js'; import { createApp } from '../../src/app.js'; import { createCtx, type Ctx, type Db } from '../../src/context.js'; import { loadConfig } from '../../src/lib/config.js'; +import type { Email, Smtp, Transport, Wawp, WhatsApp } from '../../src/messaging/transport.js'; import { memoryDb, type MemoryDb } from './memoryDb.js'; export const SITE = 'https://app.hope.test'; @@ -22,8 +24,33 @@ export const MEMBER = '33333333-3333-4333-8333-333333333333'; export type FakeAccounts = { next: Partial & { sub: string }; started: { returnTo: string; requireTwoFactor: boolean }[]; + /** Requests the App sent Accounts (`crosscode.identity-request/1`). */ + requests: Record[]; + /** What `messaging.get` answers: the church's settings in the clear (sealed on the way), or an error. */ + messaging: { email: (Omit & { pass: string | null }) | null; whatsapp: Wawp | null } | Error; }; +/** The link secret the tests' Accounts link has. */ +export const LINK_SECRET = 'link-secret'; + +export const CHURCH_SMTP = { host: 'smtp.hope.test', port: 587, secure: false, user: 'app@hope.test', pass: 'smtp-pass', from: 'app@hope.test' }; +export const CHURCH_WAWP = { accessToken: 'wawp-token', instanceId: 'HOPE1' }; + +/** Keeps what would have been sent; `fail` makes a channel throw. */ +export class MemoryTransport implements Transport { + emails: (Email & { settings: Smtp })[] = []; + whatsapps: (WhatsApp & { settings: Wawp })[] = []; + fail: { email?: string; whatsapp?: string } = {}; + async email(settings: Smtp, msg: Email) { + if (this.fail.email) throw new Error(this.fail.email); + this.emails.push({ ...msg, settings }); + } + async whatsapp(settings: Wawp, msg: WhatsApp) { + if (this.fail.whatsapp) throw new Error(this.fail.whatsapp); + this.whatsapps.push({ ...msg, settings }); + } +} + export function claims(over: Partial & { sub: string }): IdentityClaims { return { schema: 'crosscode.identity/1', @@ -68,6 +95,20 @@ function fakeAuthClient(fake: FakeAccounts): AuthClientModule { throw new SignInError('bad', 'BAD_TOKEN'); } }, + request: async (input: Record) => { + fake.requests.push(input); + if (input.type === 'messaging.get') { + if (fake.messaging instanceof Error) throw fake.messaging; + const { email, whatsapp } = fake.messaging; + return { + schema: IDENTITY_REQUEST_SCHEMA, + email: email ? { ...email, pass: email.pass ? sealLinkValue(LINK_SECRET, email.pass) : null } : null, + whatsapp: whatsapp ? { instanceId: whatsapp.instanceId, accessToken: sealLinkValue(LINK_SECRET, whatsapp.accessToken) } : null, + updatedAt: '2026-11-30T10:00:00.000Z', + }; + } + return { schema: IDENTITY_REQUEST_SCHEMA, ok: true }; + }, verifyAccountsCall: (raw: Buffer, headers: Record) => { if (headers['x-test-signed'] !== 'yes') throw new SignInError('That call isn\'t signed by Accounts.', 'BAD_SIGNATURE'); return JSON.parse(raw.toString('utf8')); @@ -85,14 +126,15 @@ export function testClock(start = '2026-12-01T06:00:00Z') { export async function harness(opts: { linked?: boolean; env?: Record } = {}) { const db = memoryDb(); const clock = testClock(); - const fake: FakeAccounts = { next: { sub: PASTOR }, started: [] }; + const fake: FakeAccounts = { next: { sub: PASTOR }, started: [], requests: [], messaging: { email: CHURCH_SMTP, whatsapp: CHURCH_WAWP } }; + const transport = new MemoryTransport(); const config = loadConfig({ APP_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env }); - const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake), now: clock.now }); + const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake), now: clock.now, transport }); await ctx.settings.set('hub_install_id', INSTALL_ID); if (opts.linked !== false) { - await db.productLink.create({ data: { installId: ACCOUNTS_INSTALL_ID, product: 'accounts', url: ACCOUNTS, publicKey: 'unused', secret: ctx.secrets.encrypt('link-secret'), connectedAt: new Date() } }); + await db.productLink.create({ data: { installId: ACCOUNTS_INSTALL_ID, product: 'accounts', url: ACCOUNTS, publicKey: 'unused', secret: ctx.secrets.encrypt(LINK_SECRET), connectedAt: new Date() } }); } - return { db, ctx, fake, clock, app: createApp(ctx) }; + return { db, ctx, fake, clock, transport, app: createApp(ctx) }; } export type Harness = Awaited> & { db: MemoryDb; ctx: Ctx }; diff --git a/apps/app/backend/tests/support/memoryDb.ts b/apps/app/backend/tests/support/memoryDb.ts index 3db731b..11f021b 100644 --- a/apps/app/backend/tests/support/memoryDb.ts +++ b/apps/app/backend/tests/support/memoryDb.ts @@ -10,7 +10,7 @@ import crypto from 'node:crypto'; type Row = Record; const DEFAULTS: Record Row> = { - member: () => ({ phone: null, whatsappOptedOut: false, roles: [], lastActiveAt: null, lastSignInAt: null }), + member: () => ({ phone: null, whatsappOptedOut: false, newsEmail: false, newsWhatsApp: false, roles: [], lastActiveAt: null, lastSignInAt: null }), session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }), productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }), auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }), @@ -19,7 +19,9 @@ const DEFAULTS: Record Row> = { 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 }), + outboxMessage: () => ({ sentAt: null, sentVia: null, failedAt: null, error: null, attempts: 0 }), + notificationSettings: () => ({ requestUpdates: 'email', announcements: 'off', devotional: 'off', devotionalTime: '06:00', devotionalOfferedAt: null, lastDevotionalDate: null }), + messageCount: () => ({ count: 0 }), prayerRequest: () => ({ visibility: 'team', showName: false, anonymous: false, moderation: 'none', redactedAt: null, redactionNote: null, removedReason: null, moderatedById: null, moderatedAt: null, escalatedAt: null, escalatedById: null, escalationNote: null, closedAt: null }), prayerRequestUpdate: () => ({ authorId: null }), announcement: () => ({ imageUrl: null, buttonLabel: null, buttonUrl: null, campus: null, audience: 'everyone', pinned: false, publishAt: null, endsAt: null, sendEmail: false, sendWhatsApp: false, sentAt: null, createdById: null }), @@ -27,13 +29,14 @@ const DEFAULTS: Record Row> = { simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageUrl: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }), importedEvent: () => ({ syncedAt: new Date() }), }; -const KEYS: Record = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' }; +const KEYS: Record = { appSetting: 'key', notificationSettings: 'memberId', messageCount: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' }; /** Unique fields: one field, or several together (`@@unique([a, b])`). */ const UNIQUE: Record = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] }; -const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest', 'announcement', 'devotional', 'simpleEvent']); +const HAS_UPDATED_AT = new Set(['notificationSettings', 'member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest', 'announcement', 'devotional', 'simpleEvent']); /** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */ const RELATIONS: Record> = { member: { sessions: { model: 'session', many: true, key: 'memberId' } }, + outboxMessage: { member: { model: 'member', many: false, key: 'memberId' } }, prayerRequest: { updates: { model: 'prayerRequestUpdate', many: true, key: 'requestId' }, prayers: { model: 'requestPrayer', many: true, key: 'requestId' } }, prayerCommitment: { skips: { model: 'prayerSkip', many: true, key: 'commitmentId' }, marks: { model: 'prayedMark', many: true, key: 'commitmentId' } }, }; @@ -97,6 +100,15 @@ function prismaError(code: string, message: string) { return Object.assign(new Error(message), { code }); } +/** `data` for an update, with `{ increment: n }` worked out against the row. */ +function applied(row: Row, data: Row): Row { + const out = clone(data); + for (const [k, x] of Object.entries(out)) { + if (x && typeof x === 'object' && !(x instanceof Date) && !Array.isArray(x) && 'increment' in (x as Row)) out[k] = Number(row[k] ?? 0) + Number((x as Row).increment); + } + return out; +} + function model(name: string, tables: Map>) { const key = KEYS[name] ?? 'id'; const table = () => { @@ -139,14 +151,14 @@ function model(name: string, tables: Map>) { update: async ({ where, data }: { where: Row; data: Row }) => { const r = findWhere(where); if (!r) throw prismaError('P2025', `Record to update not found (${name})`); - const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) }; + const next = { ...r, ...applied(r, data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) }; checkUnique(next, r[key]); table().set(r[key], next); return clone(next); }, updateMany: async ({ where, data }: { where?: Row; data: Row }) => { let count = 0; - for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; } + for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...applied(r, data) }); count++; } return { count }; }, upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => { @@ -169,7 +181,7 @@ function model(name: string, tables: Map>) { const cascade = (from: string, id: unknown) => { const drop = (model: string, field: string) => { for (const [k, r] of tables.get(model) ?? []) if (r[field] === id) tables.get(model)!.delete(k); }; const unset = (model: string, field: string) => { for (const r of tables.get(model)?.values() ?? []) if (r[field] === id) r[field] = null; }; - if (from === 'member') { drop('session', 'memberId'); drop('testimony', 'memberId'); drop('outboxMessage', 'memberId'); drop('prayerRequest', 'memberId'); unset('prayerCommitment', 'memberId'); } + if (from === 'member') { drop('session', 'memberId'); drop('testimony', 'memberId'); drop('outboxMessage', 'memberId'); drop('prayerRequest', 'memberId'); drop('notificationSettings', 'memberId'); unset('prayerCommitment', 'memberId'); } if (from === 'prayerCommitment') { drop('prayerSkip', 'commitmentId'); drop('prayedMark', 'commitmentId'); } if (from === 'prayerCampaign') unset('testimony', 'campaignId'); if (from === 'productLink') drop('importedEvent', 'linkId'); diff --git a/package-lock.json b/package-lock.json index 0691150..9486306 100644 --- a/package-lock.json +++ b/package-lock.json @@ -150,12 +150,14 @@ "cron-parser": "^5.10.2", "dotenv": "^16.3.1", "express": "^5.3.0", + "nodemailer": "^10.3.0", "pg-boss": "^11.1.2", "zod": "^4.6.7" }, "devDependencies": { "@types/express": "^5.0.6", "@types/node": "^20.19.43", + "@types/nodemailer": "^6.4.17", "@types/supertest": "^7.2.1", "prisma": "^7.10.1", "supertest": "^7.3.1", @@ -423,7 +425,7 @@ }, "apps/website/backend": { "name": "@crosscode/website-backend", - "version": "1.12.0", + "version": "1.12.1", "hasInstallScript": true, "dependencies": { "@crosscode/auth-client": "*", @@ -453,7 +455,7 @@ }, "apps/website/frontend": { "name": "@crosscode/website-frontend", - "version": "1.12.0", + "version": "1.12.1", "dependencies": { "@crosscode/contracts": "*", "@crosscode/seo": "*",