/** * 1.9.0 (docs/APP-1.0-PLAN.md ยง8, decision 4): one set of email and WhatsApp settings per church, * kept here (or copied in from Cross Events). Products that asked for them (`messaging.get`, the * Church App) are sent `messaging.changed` when they change, so they fetch them again. */ import { IDENTITY_REQUEST_SCHEMA, type MessagingChanged } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import { queueCall } from './deliveries.js'; /** The settings that make up the church's email and WhatsApp. */ const EMAIL_KEYS = new Set(['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure']); const WHATSAPP_KEYS = new Set(['wawp_access_token', 'wawp_instance_id']); /** Which parts the changed setting keys touch. */ export function messagingParts(keys: string[]): { email: boolean; whatsapp: boolean } { return { email: keys.some((k) => EMAIL_KEYS.has(k)), whatsapp: keys.some((k) => WHATSAPP_KEYS.has(k)) }; } /** * Records the change and tells every product that asked for the settings, except the one that * made the change (`exceptLinkId`, e.g. Events saving its own into Accounts). */ export async function messagingChanged(ctx: Ctx, parts: { email: boolean; whatsapp: boolean }, exceptLinkId?: string) { if (!parts.email && !parts.whatsapp) return; const at = ctx.now().toISOString(); await ctx.settings.set('messaging_updated_at', at); const wanted = await ctx.db.productLink.findMany({ where: { messagingWantedAt: { not: null } } }); const linkIds = wanted.map((l) => l.installId).filter((id) => id !== exceptLinkId); if (!linkIds.length) return; await queueCall(ctx, 'messaging.changed', (): MessagingChanged => ({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: at, ...parts }), { linkIds }); }