VirtualPR/backend/src/services/whatsappQueue.js

700 lines
24 KiB
JavaScript

import { createHash } from 'node:crypto';
import { Cohort } from '../models/Cohort.js';
import { OnboardedPatient } from '../models/OnboardedPatient.js';
import { User } from '../models/User.js';
import { WhatsAppReminderSend } from '../models/WhatsAppReminderSend.js';
import { WhatsAppTask } from '../models/WhatsAppTask.js';
import { readOnboardedPii } from './cryptoPii.js';
import { groupDescription, groupSubject, inviteMessage, toWhatsappDigits } from './whatsappFormat.js';
import { toYmd } from './schedule.js';
import { getAppSettings, isWhatsappEnabled } from './settings.js';
import { createGroup, fetchInvite, sendCta, sendText, updateGroup, updateParticipants } from './wastra.js';
const LIVE = new Set(['active', 'confirmed']);
const MAX_ATTEMPTS = 3;
const STALE_LOCK_MS = 2 * 60 * 1000;
const POLL_MS = 5000;
const OPEN = ['pending', 'running'];
/** Invites stay unique after a successful send; failed/cancelled can retry. */
export function dedupeStatusesForStep(step) {
if (step?.flag === 'invite') return ['pending', 'running', 'done'];
return OPEN;
}
let ticking = false;
let nextAllowedAt = 0;
let timer = null;
export function randomGapMs(settings) {
const min = Number(settings?.whatsappTaskGapMinMs) || 15000;
const max = Number(settings?.whatsappTaskGapMaxMs) || 40000;
const lo = Math.min(min, max);
const hi = Math.max(min, max);
return lo + Math.floor(Math.random() * (hi - lo + 1));
}
function personName(user) {
return [user?.firstName, user?.lastName].filter(Boolean).join(' ') || 'your therapist';
}
function textKey(cohortId, text) {
const hash = createHash('sha1').update(String(text || '')).digest('hex').slice(0, 12);
return `text:${cohortId}:${hash}`;
}
async function staffContacts(cohort) {
const settings = await getAppSettings();
const ids = [...(settings.whatsappAdminIds || [])];
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
if (prtId) ids.push(prtId);
const users = await User.find({ _id: { $in: ids }, isActive: true }).select('firstName lastName phone');
const byId = new Map(users.map((user) => [String(user._id), user]));
const ordered = [];
const seen = new Set();
for (const id of [prtId, ...(settings.whatsappAdminIds || [])].filter(Boolean).map(String)) {
const user = byId.get(id);
const phone = toWhatsappDigits(user?.phone);
if (!phone || seen.has(phone)) continue;
seen.add(phone);
ordered.push({ id, phone, name: personName(user) });
}
return ordered;
}
async function confirmedPatients(cohort) {
const ids = (cohort.patients || []).map((item) => item._id || item);
if (!ids.length) return [];
return OnboardedPatient.find({ _id: { $in: ids } }).select('name mobile reviewStatus whatsappOptOut');
}
function patientStep(patient) {
const pii = readOnboardedPii(patient);
const phone = toWhatsappDigits(pii.mobile);
return {
phone,
name: pii.name || 'Patient',
patient: patient._id,
};
}
async function nextSequence(cohortId) {
const last = await WhatsAppTask.findOne({ cohort: cohortId }).sort({ sequence: -1 }).select('sequence');
return (last?.sequence || 0) + 1;
}
export async function cancelOpenWhatsappTasks(reason = 'WhatsApp messaging is disabled') {
return WhatsAppTask.updateMany(
{ status: { $in: OPEN } },
{ $set: { status: 'cancelled', lockedAt: null, lastError: reason } },
);
}
async function enqueueMany(cohortId, steps) {
if (!steps.length) return;
const settings = await getAppSettings();
if (!isWhatsappEnabled(settings)) return;
const latest = await WhatsAppTask.findOne({ status: { $in: OPEN } }).sort({ runAt: -1 }).select('runAt');
let cursor = Date.now();
const queuedAhead = latest?.runAt && latest.runAt.getTime() > cursor;
if (queuedAhead) cursor = latest.runAt.getTime();
let placed = 0;
for (const step of steps) {
const dedupeKey = step.dedupeKey || `${cohortId}:${step.kind}:${step.phone || ''}`;
const existing = await WhatsAppTask.findOne({
dedupeKey,
status: { $in: dedupeStatusesForStep(step) },
}).select('_id');
if (existing) continue;
if (placed > 0 || queuedAhead) cursor += randomGapMs(settings);
placed += 1;
try {
await WhatsAppTask.create({
cohort: cohortId,
kind: step.kind,
phone: step.phone || '',
name: step.name || '',
patient: step.patient || null,
user: step.user || null,
text: step.text || '',
buttonText: step.buttonText || '',
url: step.url || '',
subject: step.subject || '',
description: step.description || '',
flag: step.flag || '',
session: step.session || null,
ruleId: step.ruleId || '',
sequence: await nextSequence(cohortId),
runAt: new Date(cursor),
status: 'pending',
dedupeKey,
});
} catch (err) {
if (err?.code !== 11000) throw err;
}
}
}
function inviteStep(cohortId, person) {
return {
kind: 'send_text',
phone: person.phone,
name: person.name,
user: person.id || null,
patient: person.patient || null,
flag: 'invite',
dedupeKey: `${cohortId}:invite:${person.phone}`,
};
}
function inviteSteps(cohortId, people) {
return people.filter((person) => person.phone).map((person) => inviteStep(cohortId, person));
}
const PRT_ADMIN_MISSING_PHONE = 'Assigned therapist needs a mobile number before they can be a WhatsApp group admin';
// True for old patient add/remove tasks. Therapist admin steps and leave steps still run.
export function isRetiredMembershipTask(task) {
if (task?.flag === 'prt' && (task.kind === 'add_member' || task.kind === 'promote_member')) return false;
if (task?.flag === 'leave' && task.kind === 'remove_member') return false;
return ['ensure_contact', 'add_member', 'promote_member', 'remove_member'].includes(task?.kind);
}
// Removes one phone from the cohort group.
function leaveStep(cohortId, person) {
return {
kind: 'remove_member',
phone: person.phone,
name: person.name || '',
patient: person.patient || null,
user: person.user || null,
flag: 'leave',
dedupeKey: `${cohortId}:leave:${person.phone}`,
};
}
// True when this phone is still the therapist or a ticked staff admin.
async function phoneKeptInGroup(cohort, phone) {
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
const prt = cohort.virtualPrt?.phone != null
? cohort.virtualPrt
: prtId ? await User.findById(prtId).select('phone') : null;
if (toWhatsappDigits(prt?.phone) === phone) return true;
const settings = await getAppSettings();
const admins = await User.find({ _id: { $in: settings.whatsappAdminIds || [] }, isActive: true }).select('phone');
return admins.some((user) => toWhatsappDigits(user.phone) === phone);
}
// Add then promote the conducting therapist when this cohort does not already record them as admin.
async function prtAdminSteps(cohort) {
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
if (!prtId || String(cohort.whatsappAdminUser || '') === String(prtId)) return [];
const user = cohort.virtualPrt?.phone != null
? cohort.virtualPrt
: await User.findById(prtId).select('firstName lastName phone');
const phone = toWhatsappDigits(user?.phone);
if (!phone) {
if (cohort.whatsappError !== PRT_ADMIN_MISSING_PHONE) {
cohort.whatsappError = PRT_ADMIN_MISSING_PHONE;
await cohort.save();
}
return [];
}
if (cohort.whatsappError === PRT_ADMIN_MISSING_PHONE) {
cohort.whatsappError = '';
await cohort.save();
}
return [
{
kind: 'add_member',
phone,
name: personName(user),
user: prtId,
flag: 'prt',
dedupeKey: `${cohort._id}:prt_add:${prtId}:${phone}`,
},
{
kind: 'promote_member',
phone,
name: personName(user),
user: prtId,
flag: 'prt',
dedupeKey: `${cohort._id}:prt_promote:${prtId}:${phone}`,
},
];
}
export async function enqueueCohortGroup(cohortId) {
const cohort = await Cohort.findById(cohortId).populate('virtualPrt', 'firstName lastName phone');
if (!cohort || !LIVE.has(cohort.status)) return cohort;
const staff = await staffContacts(cohort);
const patients = await confirmedPatients(cohort);
const steps = [];
if (!cohort.whatsappGroupJid || !cohort.whatsappInviteUrl) {
if (!cohort.whatsappGroupJid) {
cohort.whatsappStatus = 'pending';
cohort.whatsappError = '';
await cohort.save();
}
steps.push({
kind: 'create_group',
subject: groupSubject(cohort),
description: groupDescription(cohort, toYmd(cohort.startDate)),
dedupeKey: `${cohort._id}:create_group`,
});
}
steps.push(...inviteSteps(cohort._id, staff));
for (const patient of patients) {
if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut) continue;
const step = patientStep(patient);
if (!step.phone) continue;
steps.push(inviteStep(cohort._id, step));
}
steps.push(...await prtAdminSteps(cohort));
await enqueueMany(cohort._id, steps);
return cohort;
}
export async function enqueuePatientAdd(cohort, patientId) {
if (!cohort?._id || !LIVE.has(cohort.status)) return;
const fresh = await Cohort.findById(cohort._id);
if (!fresh?.whatsappGroupJid || !fresh.whatsappInviteUrl) {
await enqueueCohortGroup(cohort._id);
}
if (!fresh?.whatsappGroupJid) return;
const patient = await OnboardedPatient.findById(patientId).select('name mobile reviewStatus whatsappOptOut');
if (!patient || patient.reviewStatus !== 'confirmed') return;
const step = patientStep(patient);
if (patient.whatsappOptOut) {
await enqueuePatientRemove(fresh._id, patientId);
return;
}
if (!step.phone) return;
await enqueueMany(fresh._id, [inviteStep(fresh._id, { ...step, patient: patient._id })]);
}
export async function enqueuePatientRemove(cohortId, patientId) {
if (!cohortId || !patientId) return;
const patient = await OnboardedPatient.findById(patientId).select('name mobile');
if (!patient) return;
const phone = toWhatsappDigits(readOnboardedPii(patient).mobile);
if (phone) {
await WhatsAppTask.updateMany(
{
cohort: cohortId,
phone,
status: 'pending',
$or: [
{ kind: { $in: ['ensure_contact', 'add_member', 'promote_member', 'remove_member'] } },
{ kind: 'send_text', flag: 'invite' },
],
},
{ $set: { status: 'cancelled', lastError: 'Cancelled because this person left the cohort' } },
);
const cohort = await Cohort.findById(cohortId).select('whatsappGroupJid virtualPrt');
if (!cohort?.whatsappGroupJid || await phoneKeptInGroup(cohort, phone)) return;
const pii = readOnboardedPii(patient);
await enqueueMany(cohortId, [leaveStep(cohortId, { phone, name: pii.name || 'Patient', patient: patientId })]);
}
}
export async function enqueuePrtSwap(cohortOrId, previousPrtId) {
const cohort = cohortOrId?._id
? await Cohort.findById(cohortOrId._id).populate('virtualPrt', 'firstName lastName phone')
: await Cohort.findById(cohortOrId).populate('virtualPrt', 'firstName lastName phone');
if (!cohort?.whatsappGroupJid || !LIVE.has(cohort.status)) return;
const next = cohort.virtualPrt?.phone != null
? cohort.virtualPrt
: await User.findById(cohort.virtualPrt).select('firstName lastName phone');
const nextPhone = toWhatsappDigits(next?.phone);
const steps = [];
const previous = previousPrtId
? await User.findById(previousPrtId).select('firstName lastName phone')
: null;
const previousPhone = toWhatsappDigits(previous?.phone);
if (previousPhone && previousPhone !== nextPhone && !await phoneKeptInGroup(cohort, previousPhone)) {
steps.push(leaveStep(cohort._id, {
phone: previousPhone,
name: personName(previous),
user: previousPrtId,
}));
}
if (nextPhone) {
steps.push(inviteStep(cohort._id, { id: String(next._id), phone: nextPhone, name: personName(next) }));
const text = `Your therapist for this group is now ${personName(next)}.`;
steps.push({ kind: 'send_text', text, flag: 'prt', dedupeKey: textKey(cohort._id, text) });
}
await enqueueMany(cohort._id, steps);
}
export async function enqueueRename(cohortId) {
const cohort = await Cohort.findById(cohortId);
if (!cohort?.whatsappGroupJid) return;
const subject = groupSubject(cohort);
const description = groupDescription(cohort, toYmd(cohort.startDate));
await enqueueMany(cohortId, [{
kind: 'rename_group',
subject,
description,
dedupeKey: `rename:${cohortId}:${subject}`,
}]);
}
export async function enqueueText(cohortId, text, extra = {}) {
const body = String(text || '').trim();
if (!cohortId || !body) return;
await enqueueMany(cohortId, [{
kind: 'send_text',
text: body,
phone: extra.phone || '',
name: extra.name || '',
patient: extra.patient || null,
user: extra.user || null,
buttonText: extra.buttonText || '',
url: extra.url || '',
flag: extra.flag || '',
session: extra.session || null,
ruleId: extra.ruleId || '',
dedupeKey: extra.dedupeKey || textKey(cohortId, body),
}]);
}
function upsertMember(cohort, patientId, status, error = '') {
const id = String(patientId);
const list = [...(cohort.whatsappMembers || [])];
const index = list.findIndex((row) => String(row.patient) === id);
const next = { patient: patientId, status, error: error || '', updatedAt: new Date() };
if (index >= 0) list[index] = next;
else list.push(next);
cohort.whatsappMembers = list;
cohort.markModified('whatsappMembers');
}
async function noteCohortError(task, message) {
const cohort = await Cohort.findById(task.cohort);
if (!cohort) return;
cohort.whatsappError = message || task.lastError || 'WhatsApp task failed';
if (task.kind === 'create_group') cohort.whatsappStatus = 'failed';
if (task.patient && task.flag === 'invite') upsertMember(cohort, task.patient, 'failed', cohort.whatsappError);
await cohort.save();
}
async function clearCohortError(cohortId) {
const failed = await WhatsAppTask.exists({ cohort: cohortId, status: 'failed' });
if (failed) return;
await Cohort.updateOne({ _id: cohortId }, { $set: { whatsappError: '' } });
}
function participantAlreadyUpdated(action, err) {
const message = String(err?.message || '').toLowerCase();
if (!message.includes('already') && !message.includes('409')) return false;
return action === 'add' || action === 'promote';
}
function participantAlreadyGone(err) {
const message = String(err?.message || '').toLowerCase();
return message.includes('not a participant') || message.includes('not in') || message.includes('404') || message.includes('already');
}
// Removes the therapist or patient from the WhatsApp group.
async function runLeaveStep(task) {
const cohort = await Cohort.findById(task.cohort);
if (!cohort?.whatsappGroupJid) {
const waiting = await WhatsAppTask.exists({
cohort: task.cohort,
kind: 'create_group',
status: { $in: OPEN },
});
if (waiting) {
const error = new Error('Waiting for the WhatsApp group');
error.defer = true;
throw error;
}
throw new Error('This cohort has no WhatsApp group');
}
if (!task.phone) throw new Error('Missing phone number');
try {
await updateParticipants(cohort.whatsappGroupJid, 'remove', [task.phone]);
} catch (err) {
if (!participantAlreadyGone(err)) throw err;
}
if (task.patient) {
upsertMember(cohort, task.patient, 'removed', '');
await cohort.save();
}
}
// Adds the conducting therapist to the group, or promotes them once they are a member.
async function runPrtAdminStep(task) {
const cohort = await Cohort.findById(task.cohort);
if (!cohort?.whatsappGroupJid) {
const waiting = await WhatsAppTask.exists({
cohort: task.cohort,
kind: 'create_group',
status: { $in: OPEN },
});
if (waiting) {
const error = new Error('Waiting for the WhatsApp group');
error.defer = true;
throw error;
}
throw new Error('This cohort has no WhatsApp group');
}
if (!task.phone) throw new Error(PRT_ADMIN_MISSING_PHONE);
const action = task.kind === 'promote_member' ? 'promote' : 'add';
try {
await updateParticipants(cohort.whatsappGroupJid, action, [task.phone]);
} catch (err) {
if (!participantAlreadyUpdated(action, err)) throw err;
}
if (action === 'promote' && task.user) {
cohort.whatsappAdminUser = task.user;
if (cohort.whatsappError === PRT_ADMIN_MISSING_PHONE) cohort.whatsappError = '';
await cohort.save();
}
}
async function execute(task) {
if (isRetiredMembershipTask(task)) {
task.status = 'cancelled';
task.lastError = 'Membership updates are no longer sent to WhatsApp';
task.lockedAt = null;
await task.save();
return;
}
if (task.flag === 'prt' && (task.kind === 'add_member' || task.kind === 'promote_member')) {
await runPrtAdminStep(task);
return;
}
if (task.flag === 'leave' && task.kind === 'remove_member') {
await runLeaveStep(task);
return;
}
if (task.kind === 'create_group') {
const cohort = await Cohort.findById(task.cohort);
if (!cohort) return;
if (!cohort.whatsappGroupJid) {
const created = await createGroup({
subject: task.subject || groupSubject(cohort),
description: task.description || groupDescription(cohort, toYmd(cohort.startDate)),
participants: [],
});
if (!created.groupJid) throw new Error('Wastra did not return a WhatsApp group id');
cohort.whatsappGroupJid = created.groupJid;
await cohort.save();
}
if (!cohort.whatsappInviteUrl) {
const url = await fetchInvite(cohort.whatsappGroupJid);
if (!url) throw new Error('Wastra did not return a WhatsApp invite link');
cohort.whatsappInviteUrl = url;
}
cohort.whatsappStatus = 'ready';
cohort.whatsappError = '';
await cohort.save();
return;
}
const cohort = await Cohort.findById(task.cohort);
const needsGroup = task.kind === 'rename_group'
|| (task.kind === 'send_text' && (!task.phone || task.flag === 'invite'));
if (needsGroup && !cohort?.whatsappGroupJid) {
const waiting = await WhatsAppTask.exists({
cohort: task.cohort,
kind: 'create_group',
status: { $in: OPEN },
});
if (waiting) {
const error = new Error('Waiting for the WhatsApp group');
error.defer = true;
throw error;
}
throw new Error('This cohort has no WhatsApp group');
}
if (task.kind === 'rename_group') {
await updateGroup(cohort.whatsappGroupJid, {
subject: task.subject || groupSubject(cohort),
description: task.description || '',
});
return;
}
if (task.kind === 'send_text') {
let text = task.text;
let to = cohort?.whatsappGroupJid || '';
if (task.flag === 'invite') {
if (!task.phone) throw new Error('Missing phone number');
if (!cohort.whatsappInviteUrl) {
const waiting = await WhatsAppTask.exists({
cohort: task.cohort,
kind: 'create_group',
status: { $in: OPEN },
});
if (waiting) {
const error = new Error('Waiting for the WhatsApp invite link');
error.defer = true;
throw error;
}
throw new Error('This cohort has no WhatsApp invite link');
}
text = inviteMessage({
name: task.name,
cohortName: cohort.name,
role: task.patient ? 'patient' : 'staff',
inviteUrl: cohort.whatsappInviteUrl,
});
to = task.phone;
if (!String(text || '').trim()) throw new Error('Message is empty');
await deliverText(to, text, task);
if (task.patient) {
upsertMember(cohort, task.patient, 'invited', '');
await cohort.save();
}
await clearCohortError(cohort._id);
return;
} else if (task.phone) {
to = task.phone;
}
if (!String(text || '').trim()) throw new Error('Message is empty');
await deliverText(to, text, task);
if (task.flag === 'meet') {
cohort.whatsappMeetNotified = true;
await cohort.save();
}
if (task.flag === 'closed') {
cohort.whatsappClosedNotified = true;
await cohort.save();
}
if (task.flag === 'reminder' && task.session && task.ruleId) {
await WhatsAppReminderSend.findOneAndUpdate(
{ session: task.session, ruleId: task.ruleId, patient: task.patient || null },
{ status: 'sent', error: '' },
{ upsert: true },
);
}
}
}
function isWhatsappInviteUrl(url) {
return String(url || '').includes('chat.whatsapp.com');
}
async function deliverText(to, text, task) {
const buttonText = String(task.buttonText || '').trim();
const url = String(task.url || '').trim();
// Wastra CTA only accepts WhatsApp group invite links, not Meet URLs.
if (buttonText && url && isWhatsappInviteUrl(url)) {
await sendCta(to, { text, buttonText, url });
return;
}
let body = String(text || '');
if (url && !body.includes(url)) {
body = `${body.trim()}\n\n${buttonText || 'Join'}: ${url}`;
}
await sendText(to, body);
}
async function failOrRetry(task, err) {
if (err?.defer) {
const settings = await getAppSettings();
task.status = 'pending';
task.lockedAt = null;
task.runAt = new Date(Date.now() + randomGapMs(settings));
await task.save();
return false;
}
task.attempts += 1;
task.lastError = err?.message || 'WhatsApp task failed';
task.lockedAt = null;
if (task.attempts >= MAX_ATTEMPTS) {
task.status = 'failed';
await task.save();
await noteCohortError(task, task.lastError);
console.error(`[whatsapp] ${task.kind} failed for ${task.cohort}: ${task.lastError}`);
return true;
}
const settings = await getAppSettings();
task.status = 'pending';
task.runAt = new Date(Date.now() + randomGapMs(settings));
await task.save();
return true;
}
async function claimTask() {
await WhatsAppTask.updateMany(
{ status: 'running', lockedAt: { $lt: new Date(Date.now() - STALE_LOCK_MS) } },
{ $set: { status: 'pending', lockedAt: null } },
);
const candidates = await WhatsAppTask.find({ status: 'pending', runAt: { $lte: new Date() } })
.sort({ runAt: 1, sequence: 1 })
.limit(20);
for (const candidate of candidates) {
const blocked = await WhatsAppTask.exists({
cohort: candidate.cohort,
sequence: { $lt: candidate.sequence },
status: { $in: OPEN },
});
if (blocked) continue;
const claimed = await WhatsAppTask.findOneAndUpdate(
{ _id: candidate._id, status: 'pending' },
{ $set: { status: 'running', lockedAt: new Date() } },
{ new: true },
);
if (claimed) return claimed;
}
return null;
}
async function runOne() {
const settings = await getAppSettings();
if (!isWhatsappEnabled(settings)) {
await cancelOpenWhatsappTasks();
return;
}
const task = await claimTask();
if (!task) return;
let called = true;
try {
await execute(task);
if (task.status === 'running') {
task.status = 'done';
task.lastError = '';
task.lockedAt = null;
await task.save();
}
} catch (err) {
called = !err?.defer;
await failOrRetry(task, err);
}
if (called) {
nextAllowedAt = Date.now() + randomGapMs(settings);
}
}
function cancelMembershipTasks() {
return WhatsAppTask.updateMany(
{
status: { $in: ['pending', 'running'] },
$or: [
{ kind: 'ensure_contact' },
{ kind: 'remove_member', flag: { $ne: 'leave' } },
{ kind: { $in: ['add_member', 'promote_member'] }, flag: { $ne: 'prt' } },
],
},
{ $set: { status: 'cancelled', lockedAt: null, lastError: 'Membership updates are no longer sent to WhatsApp' } },
);
}
export function startWhatsappWorker() {
if (timer) return;
cancelMembershipTasks().catch((err) => console.error('[whatsapp] could not cancel membership tasks', err));
timer = setInterval(() => {
if (ticking || Date.now() < nextAllowedAt) return;
ticking = true;
runOne()
.catch((err) => console.error('[whatsapp] worker failed', err))
.finally(() => {
ticking = false;
});
}, POLL_MS);
timer.unref?.();
console.log('[whatsapp] task worker started');
}