/** * 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): a STOP to the church's WhatsApp number means no * WhatsApp from any of the church's products, event updates and codes included, until the person * turns it back on (in the church's Accounts; or, without Accounts, by replying START here). * * Two records, either of which stops a message: * - `WhatsAppStop`, by number: STOPs this site's webhook received (with or without an account). * - `User.whatsappOptedOut`: from Accounts (`user.updated` carries `whatsapp_opted_out`), so a STOP * another product received reaches Events too. * * `sendText` / `sendPdf` (utils/whatsapp.js) check `isWhatsAppStopped` before every message. */ 'use strict'; const prisma = require('../config/db'); function normalise(raw) { return require('./whatsapp').normalizeZAPhone(raw); } /** The ways a number may be stored on an account: 27821234567, +27821234567, 0821234567. */ function storedForms(n) { return [n, `+${n}`, `0${n.slice(2)}`]; } /** Whether nothing may go to this number on WhatsApp. */ async function isWhatsAppStopped(rawPhone) { const n = normalise(rawPhone); if (!n) return false; if (await prisma.whatsAppStop.findUnique({ where: { phone: n } })) return true; const user = await prisma.user.findFirst({ where: { whatsappOptedOut: true, phoneNumber: { in: storedForms(n) } }, select: { id: true } }); return !!user; } /** A STOP from this number: kept, and every account with it opted out. Returns the number (27…) or null. */ async function recordStop(rawPhone, { keyword, source = 'events' }) { const n = normalise(rawPhone); if (!n) return null; const word = String(keyword || 'STOP').trim().toUpperCase().slice(0, 40); await prisma.whatsAppStop.upsert({ where: { phone: n }, update: { keyword: word, source, receivedAt: new Date() }, create: { phone: n, keyword: word, source, receivedAt: new Date() }, }); await prisma.user.updateMany({ where: { phoneNumber: { in: storedForms(n) } }, data: { whatsappOptedOut: true } }); return n; } /** WhatsApp back on for this number (Accounts said so, or a START here without Accounts). */ async function clearStop(rawPhone) { const n = normalise(rawPhone); if (!n) return null; await prisma.whatsAppStop.deleteMany({ where: { phone: n } }); await prisma.user.updateMany({ where: { phoneNumber: { in: storedForms(n) } }, data: { whatsappOptedOut: false } }); return n; } /** "START" (or "BEGIN", Afrikaans "BEGIN"/"AAN"): WhatsApp back on, for a site without Accounts. */ function isStartKeyword(text) { return /^\s*(start|unstop|begin|aan)\s*[.!]?\s*$/i.test(String(text || '')); } module.exports = { isWhatsAppStopped, recordStop, clearStop, isStartKeyword, storedForms };