app: email and WhatsApp's backend (APP-1.0-PLAN §8)
The church's one set of settings from Accounts (messaging.get; the SMTP password and WAWP token sealed with the link's secret, kept encrypted in AppSetting messaging_settings), fetched when the App links to Accounts, on Accounts' signed messaging.changed, once a day and on the admin's Fetch again. messages-send (every minute): the outbox by email (nodemailer) and WhatsApp (WAWP), STOP checked before every WhatsApp (the member and anyone with the same number), email instead for what a member asked for (never announcements), retries after 2, 4, 8 and 16 minutes, a reminder never after its slot started, nothing more than 3 days late. announcement-sends and devotional-sends queue "Also send it" at the publish time and today's devotional at each member's time. Members' choices (NotificationSettings), news consent kept from Accounts, MessageCount for the heartbeat's messages, the admin's Email and WhatsApp API with Send a test. Migration messaging (checked on PostgreSQL 18). 110 backend tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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));
|
||||
|
||||
@@ -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<object> {
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<AuthClientModule>;
|
||||
/** 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<AuthClientModule> } = {}): Ctx {
|
||||
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule>; 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;
|
||||
}
|
||||
|
||||
@@ -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<z.infer<typeof hub.appStatsSchema>> {
|
||||
const [{ band }, modules] = await Promise.all([activeMembers(ctx), enabledModules(ctx)]);
|
||||
@@ -86,7 +88,7 @@ export async function stats(ctx: Ctx): Promise<z.infer<typeof hub.appStatsSchema
|
||||
modules,
|
||||
prayer: modules.includes('house-of-prayer') ? await prayerStats(ctx) : { coverageLast7dPercent: 0, activeCommitments: 0 },
|
||||
announcements: { last30d: modules.includes('announcements') ? await announcementsLast30d(ctx) : 0 },
|
||||
messages: { email30d: 0, whatsapp30d: 0 },
|
||||
messages: await messagesLast30d(ctx),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
* however many processes run, and timers in this process if the queue can't start.
|
||||
* JOBS_ENABLED=false turns them all off.
|
||||
*
|
||||
* The Hub heartbeat and the House of Prayer's reminders and renewal notices (prayer/jobs.ts). The
|
||||
* modules add theirs (APP-1.0-PLAN §1): the event feed, Cross Code's devotionals (the next 2 weeks, today included, once a night, §6),
|
||||
* announcement and devotional sends, and the nightly backup.
|
||||
* The Hub heartbeat, the event feed, Cross Code's devotionals (the next 2 weeks, today included, once
|
||||
* a night, §6), the House of Prayer's reminders and renewal notices (prayer/jobs.ts), tidying prayer
|
||||
* requests, and email and WhatsApp (§8, messaging/send.ts): sending what's queued, and queuing
|
||||
* announcements and the day's devotional. The nightly backup comes with the admin (§10).
|
||||
*
|
||||
* Settings → Background jobs (§10) shows each job's schedule and last runs, runs one now, and
|
||||
* switches one on or off or changes its schedule. That choice is kept in the database
|
||||
@@ -21,6 +22,7 @@ import { tidyRequests } from './requests/service.js';
|
||||
import { nightlySync } from './content/devotionals.js';
|
||||
import { syncAll } from './events/feed.js';
|
||||
import { DELETE_AFTER_CLOSED_DAYS } from './requests/settings.js';
|
||||
import { queueAnnouncements, queueDevotionals, sendOutbox } from './messaging/send.js';
|
||||
|
||||
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
||||
|
||||
@@ -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) },
|
||||
];
|
||||
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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<boolean> {
|
||||
|
||||
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) =>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<NotificationSettings, 'requestUpdates' | 'announcements' | 'devotional' | 'devotionalTime' | 'devotionalOfferedAt' | 'lastDevotionalDate'>;
|
||||
|
||||
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<Prefs> {
|
||||
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<typeof prefsBody>;
|
||||
|
||||
type MemberRow = Pick<Member, 'id' | 'phone' | 'whatsappOptedOut' | 'newsEmail' | 'newsWhatsApp'>;
|
||||
|
||||
/** 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<Prefs>) {
|
||||
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<Prefs> = { ...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() }],
|
||||
}] : [];
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<ReturnType<typeof T.brand>>, m: OutboxMessage, member: Member): Promise<Built | null> {
|
||||
const p = (m.payload ?? {}) as Record<string, unknown>;
|
||||
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<ReturnType<typeof T.brand>>, tz: string, pauseMs: number): Promise<Outcome> {
|
||||
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 };
|
||||
}
|
||||
@@ -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<Ctx, Promise<MessagingSettings>>();
|
||||
|
||||
/** What was last fetched from Accounts, or null. */
|
||||
export async function savedMessaging(ctx: Ctx): Promise<MessagingSettings | null> {
|
||||
const s = await ctx.settings.json<MessagingSettings | null>(MESSAGING_KEY, null);
|
||||
return s && typeof s === 'object' && 'fetchedAt' in s ? s : null;
|
||||
}
|
||||
|
||||
export async function messagingStatus(ctx: Ctx): Promise<Status | null> {
|
||||
return ctx.settings.json<Status | null>(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<MessagingSettings> {
|
||||
// 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<MessagingSettings> {
|
||||
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<MessagingSettings | null> {
|
||||
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));
|
||||
});
|
||||
}
|
||||
@@ -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<WhatsAppReach> {
|
||||
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 };
|
||||
}
|
||||
@@ -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, '"').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
|
||||
? `<img src="${esc(b.logoUrl)}" alt="${esc(b.name)}" height="56" style="display:block;margin:0 auto;max-height:56px;max-width:240px;border:0">`
|
||||
: `<h1 style="color:#ffffff;font-size:26px;font-weight:800;margin:0;letter-spacing:-0.5px;font-family:${FONT}">${esc(b.name)}</h1>`;
|
||||
const contact = [esc(b.name), b.email ? `<a href="mailto:${esc(b.email)}" style="color:#94a3b8;text-decoration:underline">${esc(b.email)}</a>` : '', b.phone ? esc(b.phone) : '']
|
||||
.filter(Boolean).join(' • ');
|
||||
const settings = `${b.url}/me/notifications`;
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
|
||||
<title>${esc(b.name)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background-color:#f1f5f9;-webkit-text-size-adjust:100%">
|
||||
<div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">${esc(preheader)}‌ ‌ </div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f1f5f9">
|
||||
<tr><td align="center" style="padding:40px 16px">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px">
|
||||
<tr><td style="background:${b.colour};background:linear-gradient(135deg,${b.colour} 0%,${darker(b.colour)} 100%);border-radius:12px 12px 0 0;padding:32px 40px;text-align:center">
|
||||
${header}
|
||||
<p style="color:#ffffff;font-size:13px;font-weight:500;margin:10px 0 0 0;font-family:${FONT};opacity:0.9">The ${esc(b.name)} App</p>
|
||||
</td></tr>
|
||||
<tr><td style="background:#ffffff;border-left:1px solid #e2e8f0;border-right:1px solid #e2e8f0;padding:40px 40px 32px 40px">
|
||||
<div style="font-family:${FONT};color:#1e293b;font-size:15px;line-height:1.75">
|
||||
${body}
|
||||
</div>
|
||||
</td></tr>
|
||||
<tr><td style="background:#f8fafc;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 12px 12px;padding:22px 40px;text-align:center">
|
||||
<p style="color:#94a3b8;font-size:12px;margin:0 0 4px 0;font-family:${FONT}">${contact}</p>
|
||||
<p style="color:#94a3b8;font-size:11px;margin:6px 0 0 0;font-family:${FONT}">${esc(why)} <a href="${esc(settings)}" style="color:#94a3b8;text-decoration:underline">Choose what the App sends you</a>.</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
const title = (t: string, sub?: string) =>
|
||||
`<p style="font-size:22px;font-weight:800;color:#0f172a;margin:0 0 8px 0;letter-spacing:-0.3px">${esc(t)}</p>`
|
||||
+ (sub ? `<p style="color:#64748b;font-size:14px;margin:0 0 24px 0">${esc(sub)}</p>` : '');
|
||||
const hello = (name?: string | null) => `<p style="margin:0 0 8px 0;color:#374151">Hello <strong>${esc(firstName(name))}</strong>,</p>`;
|
||||
const para = (html: string) => `<p style="margin:0 0 18px 0;color:#374151">${html}</p>`;
|
||||
const small = (html: string) => `<p style="margin:18px 0 0 0;font-size:13px;color:#94a3b8">${html}</p>`;
|
||||
const quote = (html: string) => `<blockquote style="margin:0 0 18px 0;padding:12px 18px;border-left:4px solid #cbd5e1;background:#f8fafc;color:#334155;font-style:italic">${html}</blockquote>`;
|
||||
|
||||
function button(b: Brand, label: string, url: string): string {
|
||||
const href = esc(safeUrl(url));
|
||||
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:24px auto 8px auto">
|
||||
<tr><td align="center" style="border-radius:8px;background-color:${b.colour}">
|
||||
<a href="${href}" target="_blank" style="display:inline-block;padding:13px 32px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:8px;font-family:${FONT}">${esc(label)}</a>
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="text-align:center;margin:4px 0 0 0;font-size:12px;color:#94a3b8;word-break:break-all">Or copy this link: <a href="${href}" style="color:${b.colour}">${esc(url)}</a></p>`;
|
||||
}
|
||||
|
||||
const firstName = (name?: string | null) => String(name ?? '').trim().split(/\s+/)[0] || 'there';
|
||||
const lines = (s: string) => esc(s).replace(/\n/g, '<br>');
|
||||
/** 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<string, unknown>;
|
||||
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: <strong>${esc(day)}, ${esc(time)}</strong>.`)
|
||||
+ 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 <a href="${esc(mine)}" style="color:${b.colour}">My prayer</a> 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 <strong>${esc(end)}</strong>.`)
|
||||
+ 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 <a href="mailto:${esc(b.email)}" style="color:${b.colour}">${esc(b.email)}</a>` : ''}.`);
|
||||
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<string, { subject: string; says: string }> = {
|
||||
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)}<br><span style="font-style:normal;font-weight:600;color:#475569">${esc(d.reference)} (${esc(t.id)})</span>`)
|
||||
+ 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<Brand> {
|
||||
return brandOf(ctx, await churchProfile(ctx).catch(() => null));
|
||||
}
|
||||
|
||||
@@ -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<void>;
|
||||
whatsapp(settings: Wawp, msg: WhatsApp): Promise<void>;
|
||||
}
|
||||
|
||||
/** 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" <app@acaciahill.co.za>`: 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<void> {
|
||||
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<void> {
|
||||
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}).`);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user