Changes
This commit is contained in:
parent
9cddf60047
commit
1ce8043168
|
|
@ -24,6 +24,8 @@ const reminderRuleSchema = new mongoose.Schema(
|
|||
minutesBefore: { type: Number, default: 120 },
|
||||
fixedTime: { type: String, default: '18:00', trim: true },
|
||||
dayOffset: { type: Number, default: 0 },
|
||||
audience: { type: String, enum: ['patients', 'group'], default: 'patients' },
|
||||
buttonText: { type: String, default: 'Join Meet', trim: true },
|
||||
template: { type: String, default: '' },
|
||||
templatesByLanguage: { type: [reminderLanguageSchema], default: [] },
|
||||
},
|
||||
|
|
|
|||
|
|
@ -4,12 +4,13 @@ const whatsAppReminderSendSchema = new mongoose.Schema(
|
|||
{
|
||||
session: { type: mongoose.Schema.Types.ObjectId, ref: 'CohortSession', required: true },
|
||||
ruleId: { type: String, required: true, trim: true },
|
||||
patient: { type: mongoose.Schema.Types.ObjectId, ref: 'OnboardedPatient', default: null },
|
||||
status: { type: String, enum: ['sent', 'failed'], default: 'sent' },
|
||||
error: { type: String, default: '' },
|
||||
},
|
||||
{ timestamps: true },
|
||||
);
|
||||
|
||||
whatsAppReminderSendSchema.index({ session: 1, ruleId: 1 }, { unique: true });
|
||||
whatsAppReminderSendSchema.index({ session: 1, ruleId: 1, patient: 1 }, { unique: true });
|
||||
|
||||
export const WhatsAppReminderSend = mongoose.model('WhatsAppReminderSend', whatsAppReminderSendSchema);
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ const whatsAppTaskSchema = new mongoose.Schema(
|
|||
patient: { type: mongoose.Schema.Types.ObjectId, ref: 'OnboardedPatient', default: null },
|
||||
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null },
|
||||
text: { type: String, default: '' },
|
||||
buttonText: { type: String, default: '' },
|
||||
url: { type: String, default: '' },
|
||||
subject: { type: String, default: '' },
|
||||
description: { type: String, default: '' },
|
||||
flag: { type: String, default: '' },
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ const ruleSchema = Joi.object({
|
|||
minutesBefore: Joi.number().integer().min(1).max(10080).allow(null),
|
||||
fixedTime: Joi.string().pattern(TIME).allow('', null),
|
||||
dayOffset: Joi.number().valid(0, -1).default(0),
|
||||
audience: Joi.string().valid('patients', 'group').default('patients'),
|
||||
buttonText: Joi.string().trim().max(40).allow(''),
|
||||
template: Joi.string().trim().max(1000).allow(''),
|
||||
templatesByLanguage: Joi.array().items(Joi.object({
|
||||
language: Joi.string().trim().allow(''),
|
||||
|
|
@ -32,6 +34,8 @@ function ruleDto(rule) {
|
|||
minutesBefore: rule.minutesBefore || 120,
|
||||
fixedTime: rule.fixedTime || '18:00',
|
||||
dayOffset: Number(rule.dayOffset) || 0,
|
||||
audience: rule.audience === 'group' ? 'group' : 'patients',
|
||||
buttonText: rule.buttonText || 'Join Meet',
|
||||
template: rule.template || '',
|
||||
templatesByLanguage: (rule.templatesByLanguage || []).map((row) => ({
|
||||
language: row.language || '',
|
||||
|
|
@ -110,6 +114,8 @@ export function whatsappRoutes(server) {
|
|||
minutesBefore: Number(rule.minutesBefore) || 120,
|
||||
fixedTime: rule.fixedTime || '18:00',
|
||||
dayOffset: Number(rule.dayOffset) || 0,
|
||||
audience: rule.audience === 'group' ? 'group' : 'patients',
|
||||
buttonText: String(rule.buttonText || 'Join Meet').trim() || 'Join Meet',
|
||||
template: rule.template || '',
|
||||
templatesByLanguage: (rule.templatesByLanguage || [])
|
||||
.filter((row) => row.language && String(row.body || '').trim())
|
||||
|
|
|
|||
|
|
@ -21,6 +21,59 @@ export const DEFAULT_SLOTS = [
|
|||
{ start: '19:00', end: '20:00' },
|
||||
];
|
||||
|
||||
export const MORNING_REMINDER_TEMPLATE = [
|
||||
'Good morning {{name}} — your pulmonary rehab session is today.',
|
||||
'',
|
||||
'Cohort: {{cohort}}',
|
||||
'When: {{date}} at {{time}}',
|
||||
'Therapist: {{prtName}}',
|
||||
'',
|
||||
'Join Meet when it\'s time:',
|
||||
'{{meetUrl}}',
|
||||
'',
|
||||
'Arrive a few minutes early and keep your camera/mic ready.',
|
||||
].join('\n');
|
||||
|
||||
export const PRE_SESSION_REMINDER_TEMPLATE = [
|
||||
'Hi {{name}}, your pulmonary rehab session starts in 30 minutes.',
|
||||
'',
|
||||
'Cohort: {{cohort}}',
|
||||
'When: {{date}} at {{time}}',
|
||||
'Therapist: {{prtName}}',
|
||||
'',
|
||||
'Join Meet now:',
|
||||
'{{meetUrl}}',
|
||||
'',
|
||||
'Arrive a minute early if you can.',
|
||||
].join('\n');
|
||||
|
||||
export const DEFAULT_WHATSAPP_REMINDER_RULES = [
|
||||
{
|
||||
id: 'morning-session',
|
||||
enabled: true,
|
||||
timing: 'fixed_time',
|
||||
minutesBefore: 120,
|
||||
fixedTime: '08:00',
|
||||
dayOffset: 0,
|
||||
audience: 'patients',
|
||||
buttonText: 'Join Meet',
|
||||
template: MORNING_REMINDER_TEMPLATE,
|
||||
templatesByLanguage: [],
|
||||
},
|
||||
{
|
||||
id: 'pre-session-30',
|
||||
enabled: true,
|
||||
timing: 'minutes_before',
|
||||
minutesBefore: 30,
|
||||
fixedTime: '18:00',
|
||||
dayOffset: 0,
|
||||
audience: 'patients',
|
||||
buttonText: 'Join Meet',
|
||||
template: PRE_SESSION_REMINDER_TEMPLATE,
|
||||
templatesByLanguage: [],
|
||||
},
|
||||
];
|
||||
|
||||
export const DEFAULT_SETTINGS = {
|
||||
slots: DEFAULT_SLOTS,
|
||||
slotDurationMinutes: 60,
|
||||
|
|
@ -46,6 +99,37 @@ export const DEFAULT_SETTINGS = {
|
|||
whatsappTaskGapMaxMs: 40000,
|
||||
};
|
||||
|
||||
/** Adds missing seeded reminder rules by stable id; never overwrites edited copies. */
|
||||
export function ensureDefaultWhatsappReminderRules(rules = []) {
|
||||
const list = [...(rules || [])];
|
||||
const present = new Set(list.map((rule) => String(rule?.id || '')));
|
||||
for (const seed of DEFAULT_WHATSAPP_REMINDER_RULES) {
|
||||
if (present.has(seed.id)) continue;
|
||||
list.push({ ...seed, templatesByLanguage: [] });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/** Upgrades seeded rule copy when Meet URL is still missing from the template. */
|
||||
export function refreshSeededReminderTemplates(rules = []) {
|
||||
const seeds = new Map(DEFAULT_WHATSAPP_REMINDER_RULES.map((rule) => [rule.id, rule]));
|
||||
let changed = false;
|
||||
const next = (rules || []).map((rule) => {
|
||||
const seed = seeds.get(String(rule?.id || ''));
|
||||
if (!seed) return rule;
|
||||
const template = String(rule.template || '');
|
||||
if (template.includes('{{meetUrl}}')) return rule;
|
||||
changed = true;
|
||||
return {
|
||||
...rule,
|
||||
template: seed.template,
|
||||
buttonText: rule.buttonText || seed.buttonText,
|
||||
audience: rule.audience || seed.audience,
|
||||
};
|
||||
});
|
||||
return { rules: next, changed };
|
||||
}
|
||||
|
||||
export function slotLabel(slot) {
|
||||
if (!slot) return '';
|
||||
if (typeof slot === 'string') return slot;
|
||||
|
|
@ -176,6 +260,16 @@ export async function getAppSettings() {
|
|||
settings.upcomingSessionCount = 30;
|
||||
dirty = true;
|
||||
}
|
||||
const ensuredRules = ensureDefaultWhatsappReminderRules(settings.whatsappReminderRules);
|
||||
const refreshed = refreshSeededReminderTemplates(ensuredRules);
|
||||
if (
|
||||
refreshed.changed
|
||||
|| refreshed.rules.length !== (settings.whatsappReminderRules || []).length
|
||||
) {
|
||||
settings.whatsappReminderRules = refreshed.rules;
|
||||
settings.markModified('whatsappReminderRules');
|
||||
dirty = true;
|
||||
}
|
||||
if (dirty) await settings.save();
|
||||
return settings;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { env } from '../config/env.js';
|
||||
import { Cohort } from '../models/Cohort.js';
|
||||
import { CohortSession } from '../models/CohortSession.js';
|
||||
import { OnboardedPatient } from '../models/OnboardedPatient.js';
|
||||
import { WhatsAppReminderSend } from '../models/WhatsAppReminderSend.js';
|
||||
import { readOnboardedPii } from './cryptoPii.js';
|
||||
import { slotDateTimes, todayYmd, addDays } from './schedule.js';
|
||||
import { getAppSettings } from './settings.js';
|
||||
import {
|
||||
|
|
@ -17,15 +19,21 @@ import {
|
|||
reminderFireAt,
|
||||
renderTemplate,
|
||||
templateBody,
|
||||
toWhatsappDigits,
|
||||
} from './whatsappFormat.js';
|
||||
|
||||
const LIVE = new Set(['active', 'confirmed']);
|
||||
const DEFAULT_REMINDER = 'Reminder: {{cohort}} on {{date}} at {{time}}.\n{{meetUrl}}';
|
||||
const DEFAULT_REMINDER = 'Reminder: {{cohort}} on {{date}} at {{time}}.\nTap Join Meet when you are ready.';
|
||||
|
||||
function personName(user) {
|
||||
return [user?.firstName, user?.lastName].filter(Boolean).join(' ') || 'your therapist';
|
||||
}
|
||||
|
||||
function firstName(fullName) {
|
||||
const first = String(fullName || '').trim().split(/\s+/)[0];
|
||||
return first || '';
|
||||
}
|
||||
|
||||
export function ensureCohortGroup(cohortId) {
|
||||
return enqueueCohortGroup(cohortId);
|
||||
}
|
||||
|
|
@ -111,10 +119,11 @@ export async function applyPatientOptOut(patient) {
|
|||
await enqueuePatientAdd(cohort, patient._id);
|
||||
}
|
||||
|
||||
function sessionVars(session, cohort) {
|
||||
function sessionVars(session, cohort, { name = '' } = {}) {
|
||||
const prt = cohort.virtualPrt;
|
||||
const { startTime } = slotDateTimes(session.date, session.slot || cohort.slot, cohort.durationMinutes || 60);
|
||||
return {
|
||||
name: firstName(name),
|
||||
cohort: cohort.name || '',
|
||||
date: session.date || '',
|
||||
time: session.slot || startTime || '',
|
||||
|
|
@ -123,6 +132,21 @@ function sessionVars(session, cohort) {
|
|||
};
|
||||
}
|
||||
|
||||
function reminderAudience(rule) {
|
||||
return rule?.audience === 'group' ? 'group' : 'patients';
|
||||
}
|
||||
|
||||
function reminderButtonText(rule) {
|
||||
return String(rule?.buttonText || 'Join Meet').trim() || 'Join Meet';
|
||||
}
|
||||
|
||||
async function cohortPatientsForReminder(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 sessionLanguage');
|
||||
}
|
||||
|
||||
export async function sendSessionReminder(session, { rule, manual = false } = {}) {
|
||||
const cohort = session.cohort && session.cohort.name != null
|
||||
? session.cohort
|
||||
|
|
@ -132,16 +156,71 @@ export async function sendSessionReminder(session, { rule, manual = false } = {}
|
|||
if (session.status === 'cancelled') return { ok: false, skipped: true, error: 'Session is cancelled' };
|
||||
const settings = await getAppSettings();
|
||||
const chosen = rule || (settings.whatsappReminderRules || []).find((item) => item.enabled);
|
||||
if (!chosen && !manual) return { ok: false, skipped: true, error: 'No reminder rule' };
|
||||
|
||||
const meetUrl = String(session.meetUrl || '').trim();
|
||||
const audience = reminderAudience(chosen);
|
||||
const buttonText = reminderButtonText(chosen);
|
||||
|
||||
if (audience === 'patients') {
|
||||
if (!meetUrl) return { ok: false, skipped: true, error: 'Meet link not ready' };
|
||||
const patients = await cohortPatientsForReminder(cohort);
|
||||
let queued = 0;
|
||||
for (const patient of patients) {
|
||||
if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut) continue;
|
||||
const pii = readOnboardedPii(patient);
|
||||
const phone = toWhatsappDigits(pii.mobile);
|
||||
if (!phone) continue;
|
||||
if (!manual) {
|
||||
const existing = await WhatsAppReminderSend.findOne({
|
||||
session: session._id,
|
||||
ruleId: chosen.id,
|
||||
patient: patient._id,
|
||||
});
|
||||
if (existing?.status === 'sent') continue;
|
||||
}
|
||||
const language = patient.sessionLanguage || cohort.language;
|
||||
const body = templateBody(chosen, language) || DEFAULT_REMINDER;
|
||||
const text = renderTemplate(body, sessionVars(session, cohort, { name: pii.name })).trim();
|
||||
if (!text) continue;
|
||||
await enqueueText(cohort._id, text, {
|
||||
phone,
|
||||
name: pii.name || '',
|
||||
patient: patient._id,
|
||||
buttonText,
|
||||
url: meetUrl,
|
||||
flag: manual ? '' : 'reminder',
|
||||
session: manual ? null : session._id,
|
||||
ruleId: manual ? '' : (chosen?.id || ''),
|
||||
dedupeKey: manual
|
||||
? `manual:${session._id}:${phone}:${Date.now()}`
|
||||
: `reminder:${session._id}:${chosen.id}:${phone}`,
|
||||
});
|
||||
queued += 1;
|
||||
}
|
||||
return { ok: true, queued: queued > 0, queuedCount: queued, skipped: queued === 0 };
|
||||
}
|
||||
|
||||
const body = templateBody(chosen, cohort.language) || DEFAULT_REMINDER;
|
||||
const text = renderTemplate(body, sessionVars(session, cohort)).trim();
|
||||
if (!text) return { ok: false, skipped: true, error: 'Reminder template is empty' };
|
||||
if (!manual) {
|
||||
const existing = await WhatsAppReminderSend.findOne({
|
||||
session: session._id,
|
||||
ruleId: chosen.id,
|
||||
patient: null,
|
||||
});
|
||||
if (existing?.status === 'sent') return { ok: true, queued: false, queuedCount: 0, skipped: true };
|
||||
}
|
||||
const cta = meetUrl ? { buttonText, url: meetUrl } : {};
|
||||
await enqueueText(cohort._id, text, {
|
||||
...cta,
|
||||
flag: manual ? '' : 'reminder',
|
||||
session: manual ? null : session._id,
|
||||
ruleId: manual ? '' : (chosen?.id || ''),
|
||||
dedupeKey: manual ? `manual:${session._id}:${Date.now()}` : `reminder:${session._id}:${chosen?.id || 'default'}`,
|
||||
});
|
||||
return { ok: true, queued: true };
|
||||
return { ok: true, queued: true, queuedCount: 1 };
|
||||
}
|
||||
|
||||
export async function sendDueWhatsappReminders(now = new Date()) {
|
||||
|
|
@ -166,14 +245,12 @@ export async function sendDueWhatsappReminders(now = new Date()) {
|
|||
for (const rule of rules) {
|
||||
const fireAt = reminderFireAt({ sessionDate: session.date, startAt, rule });
|
||||
if (!isReminderDue(fireAt, now)) continue;
|
||||
const existing = await WhatsAppReminderSend.findOne({ session: session._id, ruleId: rule.id });
|
||||
if (existing?.status === 'sent') continue;
|
||||
try {
|
||||
await sendSessionReminder(session, { rule });
|
||||
sent += 1;
|
||||
const result = await sendSessionReminder(session, { rule });
|
||||
sent += Number(result.queuedCount) || 0;
|
||||
} catch (err) {
|
||||
await WhatsAppReminderSend.findOneAndUpdate(
|
||||
{ session: session._id, ruleId: rule.id },
|
||||
{ session: session._id, ruleId: rule.id, patient: null },
|
||||
{ status: 'failed', error: err.message || 'Could not send reminder' },
|
||||
{ upsert: true },
|
||||
);
|
||||
|
|
@ -207,6 +284,11 @@ export async function backfillWhatsappGroups() {
|
|||
export async function reconcileWhatsappGroups() {
|
||||
const cohorts = await Cohort.find({
|
||||
status: { $in: ['active', 'confirmed'] },
|
||||
$or: [
|
||||
{ whatsappGroupJid: { $in: ['', null] } },
|
||||
{ whatsappInviteUrl: { $in: ['', null] } },
|
||||
{ whatsappStatus: { $in: ['', 'failed', 'pending'] } },
|
||||
],
|
||||
}).select('_id');
|
||||
for (const cohort of cohorts) {
|
||||
await enqueueCohortGroup(cohort._id);
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ export function groupDescription(cohort, startYmd = '') {
|
|||
}
|
||||
|
||||
export function renderTemplate(template, vars) {
|
||||
return String(template || '').replace(/\{\{\s*(cohort|date|time|meetUrl|prtName|inviteUrl)\s*\}\}/g, (_, key) => (
|
||||
return String(template || '').replace(/\{\{\s*(cohort|date|time|meetUrl|prtName|inviteUrl|name)\s*\}\}/g, (_, key) => (
|
||||
vars?.[key] == null ? '' : String(vars[key])
|
||||
));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,6 +50,14 @@ test('renders reminder placeholders and language bodies', () => {
|
|||
renderTemplate('Hi {{cohort}} {{meetUrl}}', { cohort: 'Morning', meetUrl: 'https://meet' }),
|
||||
'Hi Morning https://meet',
|
||||
);
|
||||
assert.equal(
|
||||
renderTemplate('Good morning {{name}} — {{cohort}} at {{time}}', {
|
||||
name: 'Abhijeet',
|
||||
cohort: 'Morning Hindi',
|
||||
time: '09:00-10:00',
|
||||
}),
|
||||
'Good morning Abhijeet — Morning Hindi at 09:00-10:00',
|
||||
);
|
||||
assert.equal(templateBody({
|
||||
template: 'English',
|
||||
templatesByLanguage: [{ language: 'Hindi', body: 'Namaste {{cohort}}' }],
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { readOnboardedPii } from './cryptoPii.js';
|
|||
import { groupDescription, groupSubject, inviteMessage, toWhatsappDigits } from './whatsappFormat.js';
|
||||
import { toYmd } from './schedule.js';
|
||||
import { getAppSettings } from './settings.js';
|
||||
import { createGroup, fetchInvite, sendText, updateGroup } from './wastra.js';
|
||||
import { createGroup, fetchInvite, sendCta, sendText, updateGroup } from './wastra.js';
|
||||
|
||||
const LIVE = new Set(['active', 'confirmed']);
|
||||
const MAX_ATTEMPTS = 3;
|
||||
|
|
@ -16,6 +16,12 @@ 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;
|
||||
|
|
@ -87,7 +93,10 @@ async function enqueueMany(cohortId, steps) {
|
|||
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: OPEN } }).select('_id');
|
||||
const existing = await WhatsAppTask.findOne({
|
||||
dedupeKey,
|
||||
status: { $in: dedupeStatusesForStep(step) },
|
||||
}).select('_id');
|
||||
if (existing) continue;
|
||||
if (placed > 0 || queuedAhead) cursor += randomGapMs(settings);
|
||||
placed += 1;
|
||||
|
|
@ -100,6 +109,8 @@ async function enqueueMany(cohortId, steps) {
|
|||
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 || '',
|
||||
|
|
@ -238,6 +249,12 @@ export async function enqueueText(cohortId, text, extra = {}) {
|
|||
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 || '',
|
||||
|
|
@ -303,7 +320,9 @@ async function execute(task) {
|
|||
return;
|
||||
}
|
||||
const cohort = await Cohort.findById(task.cohort);
|
||||
if (!cohort?.whatsappGroupJid) {
|
||||
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',
|
||||
|
|
@ -325,7 +344,7 @@ async function execute(task) {
|
|||
}
|
||||
if (task.kind === 'send_text') {
|
||||
let text = task.text;
|
||||
let to = cohort.whatsappGroupJid;
|
||||
let to = cohort?.whatsappGroupJid || '';
|
||||
if (task.flag === 'invite') {
|
||||
if (!task.phone) throw new Error('Missing phone number');
|
||||
if (!cohort.whatsappInviteUrl) {
|
||||
|
|
@ -349,7 +368,7 @@ async function execute(task) {
|
|||
});
|
||||
to = task.phone;
|
||||
if (!String(text || '').trim()) throw new Error('Message is empty');
|
||||
await sendText(to, text);
|
||||
await deliverText(to, text, task);
|
||||
if (task.patient) {
|
||||
upsertMember(cohort, task.patient, 'invited', '');
|
||||
await cohort.save();
|
||||
|
|
@ -360,7 +379,7 @@ async function execute(task) {
|
|||
to = task.phone;
|
||||
}
|
||||
if (!String(text || '').trim()) throw new Error('Message is empty');
|
||||
await sendText(to, text);
|
||||
await deliverText(to, text, task);
|
||||
if (task.flag === 'meet') {
|
||||
cohort.whatsappMeetNotified = true;
|
||||
await cohort.save();
|
||||
|
|
@ -371,7 +390,7 @@ async function execute(task) {
|
|||
}
|
||||
if (task.flag === 'reminder' && task.session && task.ruleId) {
|
||||
await WhatsAppReminderSend.findOneAndUpdate(
|
||||
{ session: task.session, ruleId: task.ruleId },
|
||||
{ session: task.session, ruleId: task.ruleId, patient: task.patient || null },
|
||||
{ status: 'sent', error: '' },
|
||||
{ upsert: true },
|
||||
);
|
||||
|
|
@ -379,6 +398,25 @@ async function execute(task) {
|
|||
}
|
||||
}
|
||||
|
||||
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();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { randomGapMs } from './whatsappQueue.js';
|
||||
import { dedupeStatusesForStep, randomGapMs } from './whatsappQueue.js';
|
||||
|
||||
test('draws each WhatsApp gap from 15 to 40 seconds', () => {
|
||||
const settings = { whatsappTaskGapMinMs: 15000, whatsappTaskGapMaxMs: 40000 };
|
||||
|
|
@ -9,3 +9,9 @@ test('draws each WhatsApp gap from 15 to 40 seconds', () => {
|
|||
assert.ok(gap >= 15000 && gap <= 40000, `gap ${gap} is outside 15–40s`);
|
||||
}
|
||||
});
|
||||
|
||||
test('invite steps treat a done send as already delivered', () => {
|
||||
assert.deepEqual(dedupeStatusesForStep({ flag: 'invite' }), ['pending', 'running', 'done']);
|
||||
assert.deepEqual(dedupeStatusesForStep({ flag: 'reminder' }), ['pending', 'running']);
|
||||
assert.deepEqual(dedupeStatusesForStep({ kind: 'send_text' }), ['pending', 'running']);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -13,7 +13,9 @@ function emptyRule() {
|
|||
minutesBefore: 120,
|
||||
fixedTime: '18:00',
|
||||
dayOffset: 0,
|
||||
template: 'Reminder: {{cohort}} on {{date}} at {{time}}.\nJoin: {{meetUrl}}',
|
||||
audience: 'patients',
|
||||
buttonText: 'Join Meet',
|
||||
template: 'Hi {{name}}, reminder for {{cohort}} on {{date}} at {{time}}.\n\nJoin Meet:\n{{meetUrl}}',
|
||||
templatesByLanguage: [],
|
||||
};
|
||||
}
|
||||
|
|
@ -94,7 +96,7 @@ export default function WhatsappPage() {
|
|||
<Card className="mb-3">
|
||||
<CardBody>
|
||||
<h5 className="mb-2">Group admins</h5>
|
||||
<p className="text-muted">These people, plus the cohort Virtual PRT, are added as WhatsApp group admins. Each person needs a mobile number on their user profile.</p>
|
||||
<p className="text-muted">These people, plus the cohort Virtual PRT, receive the WhatsApp group invite. Each person needs a mobile number on their user profile.</p>
|
||||
{staff.map((user) => (
|
||||
<FormCheck
|
||||
key={user.id}
|
||||
|
|
@ -117,7 +119,10 @@ export default function WhatsappPage() {
|
|||
<TbPlus className="me-1" /> Add reminder
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-muted">Placeholders: {'{{cohort}} {{date}} {{time}} {{meetUrl}} {{prtName}}'}. The cohort language picks a language body when one is filled in.</p>
|
||||
<p className="text-muted">
|
||||
Placeholders: {'{{name}} {{cohort}} {{date}} {{time}} {{meetUrl}} {{prtName}}'}.
|
||||
Patient reminders send a personal WhatsApp with a Join Meet button when the Meet link is ready.
|
||||
</p>
|
||||
{rules.map((rule, index) => (
|
||||
<div key={rule.id || index} className="border rounded p-3 mb-3">
|
||||
<div className="d-flex justify-content-between">
|
||||
|
|
@ -159,9 +164,24 @@ export default function WhatsappPage() {
|
|||
<FormControl type="number" min={1} value={rule.minutesBefore} onChange={(e) => updateRule(index, { minutesBefore: Number(e.target.value) })} required />
|
||||
</Col>
|
||||
)}
|
||||
<Col md={4}>
|
||||
<FormLabel>Send to</FormLabel>
|
||||
<select className="form-select" value={rule.audience || 'patients'} onChange={(e) => updateRule(index, { audience: e.target.value })}>
|
||||
<option value="patients">Each patient (personal message)</option>
|
||||
<option value="group">Cohort WhatsApp group</option>
|
||||
</select>
|
||||
</Col>
|
||||
<Col md={4}>
|
||||
<FormLabel>Button label</FormLabel>
|
||||
<FormControl
|
||||
value={rule.buttonText || 'Join Meet'}
|
||||
onChange={(e) => updateRule(index, { buttonText: e.target.value })}
|
||||
placeholder="Join Meet"
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={12}>
|
||||
<FormLabel>Message</FormLabel>
|
||||
<FormControl as="textarea" rows={3} value={rule.template} onChange={(e) => updateRule(index, { template: e.target.value })} />
|
||||
<FormControl as="textarea" rows={5} value={rule.template} onChange={(e) => updateRule(index, { template: e.target.value })} />
|
||||
</Col>
|
||||
{(rule.templatesByLanguage || []).map((row, languageIndex) => (
|
||||
<Col xs={12} key={`${index}-${languageIndex}`}>
|
||||
|
|
@ -216,7 +236,7 @@ export default function WhatsappPage() {
|
|||
</Row>
|
||||
</div>
|
||||
))}
|
||||
{!rules.length ? <div className="text-muted">No reminders yet. Add one to message each cohort group before a session.</div> : null}
|
||||
{!rules.length ? <div className="text-muted">No reminders yet. Defaults appear after the server loads WhatsApp settings.</div> : null}
|
||||
</CardBody>
|
||||
</Card>
|
||||
<div className="d-flex gap-2">
|
||||
|
|
@ -225,7 +245,7 @@ export default function WhatsappPage() {
|
|||
{working === 'backfill' ? 'Working…' : 'Create missing groups'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline-secondary" disabled={Boolean(working)} onClick={() => run('/api/whatsapp/reconcile', 'reconcile')}>
|
||||
{working === 'reconcile' ? 'Working…' : 'Reconcile members'}
|
||||
{working === 'reconcile' ? 'Working…' : 'Heal missing groups'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
|
|
|||
Loading…
Reference in New Issue