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:
@@ -10,7 +10,7 @@ import crypto from 'node:crypto';
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
const DEFAULTS: Record<string, () => 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<string, () => 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<string, () => 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<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
|
||||
const KEYS: Record<string, string> = { 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<string, (string | string[])[]> = { 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<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
||||
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<string, Map<unknown, Row>>) {
|
||||
const key = KEYS[name] ?? 'id';
|
||||
const table = () => {
|
||||
@@ -139,14 +151,14 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
||||
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<string, Map<unknown, Row>>) {
|
||||
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');
|
||||
|
||||
Reference in New Issue
Block a user