import mongoose from 'mongoose'; import { env } from '../src/config/env.js'; import { CohortSession } from '../src/models/CohortSession.js'; import { WhatsAppTask } from '../src/models/WhatsAppTask.js'; import { getAppSettings } from '../src/services/settings.js'; import { sendSessionReminder } from '../src/services/whatsapp.js'; import { startWhatsappWorker } from '../src/services/whatsappQueue.js'; import { todayYmd } from '../src/services/schedule.js'; const LIVE = new Set(['active', 'confirmed']); async function waitForTasks(dedupeKeys, timeoutMs = 180000) { const started = Date.now(); while (Date.now() - started < timeoutMs) { const open = await WhatsAppTask.countDocuments({ dedupeKey: { $in: dedupeKeys }, status: { $in: ['pending', 'running'] }, }); if (!open) { return WhatsAppTask.find({ dedupeKey: { $in: dedupeKeys } }) .sort({ createdAt: -1 }) .select('status phone lastError dedupeKey createdAt') .lean(); } await new Promise((resolve) => setTimeout(resolve, 2000)); } throw new Error('Timed out waiting for WhatsApp reminder tasks to finish'); } async function main() { await mongoose.connect(env.MONGODB_URI); const settings = await getAppSettings(); const rule = (settings.whatsappReminderRules || []).find((item) => item.id === 'morning-session' && item.enabled); if (!rule) throw new Error('morning-session rule is missing or disabled'); const today = todayYmd(env.APP_TIMEZONE); const sessions = await CohortSession.find({ date: today, status: 'scheduled' }).populate({ path: 'cohort', populate: { path: 'virtualPrt', select: 'firstName lastName' }, }); startWhatsappWorker(); const results = []; const dedupeKeys = []; for (const session of sessions) { const cohort = session.cohort; if (!cohort || !LIVE.has(cohort.status)) { results.push({ session: String(session._id), skipped: 'cohort not live' }); continue; } if (!session.meetUrl) { results.push({ session: String(session._id), skipped: 'no meetUrl' }); continue; } const result = await sendSessionReminder(session, { rule }); results.push({ session: String(session._id), cohort: cohort.name, queuedCount: result.queuedCount || 0, ok: result.ok, error: result.error || '', }); if (result.queuedCount) { const patients = cohort.patients || []; // Keys are built per phone inside sendSessionReminder; collect latest pending/running reminder tasks. const tasks = await WhatsAppTask.find({ session: session._id, ruleId: 'morning-session', flag: 'reminder', status: { $in: ['pending', 'running'] }, }).select('dedupeKey'); for (const task of tasks) dedupeKeys.push(task.dedupeKey); } } console.log(JSON.stringify({ today, ruleTemplateHasMeet: String(rule.template || '').includes('{{meetUrl}}'), results }, null, 2)); if (!dedupeKeys.length) { console.log('Nothing queued to send.'); await mongoose.disconnect(); process.exit(0); } const finished = await waitForTasks([...new Set(dedupeKeys)]); console.log(JSON.stringify({ finished }, null, 2)); const failed = finished.filter((row) => row.status === 'failed'); await mongoose.disconnect(); process.exit(failed.length ? 1 : 0); } main().catch(async (err) => { console.error(err); try { await mongoose.disconnect(); } catch {} process.exit(1); });