diff --git a/backend/src/models/OnboardedPatient.js b/backend/src/models/OnboardedPatient.js index 1c8d9ad..6c72854 100644 --- a/backend/src/models/OnboardedPatient.js +++ b/backend/src/models/OnboardedPatient.js @@ -48,6 +48,12 @@ const onboardedPatientSchema = new mongoose.Schema( enum: ['Unpaid', 'Paid', 'Partial'], default: 'Unpaid', }, + sessionsPaid: { type: Number, default: 30 }, // sessions covered by payment; default 30 when blank + patientStatus: { + type: String, + enum: ['active', 'deactivated'], + default: 'active', + }, paymentScreenshot: { filename: { type: String, default: '' }, originalName: { type: String, default: '' }, @@ -74,6 +80,11 @@ const onboardedPatientSchema = new mongoose.Schema( { timestamps: true }, ); +// Turns a stored return_pool value into deactivated before the record is saved. +onboardedPatientSchema.pre('validate', function convertOldPatientStatus() { + if (this.patientStatus === 'return_pool') this.patientStatus = 'deactivated'; +}); + onboardedPatientSchema.index({ onboardedBy: 1, createdAt: -1 }); onboardedPatientSchema.index({ mobileHash: 1 }); onboardedPatientSchema.index({ assignedEducator: 1 }); diff --git a/backend/src/routes/cohorts.js b/backend/src/routes/cohorts.js index 3b301fb..5958c9c 100644 --- a/backend/src/routes/cohorts.js +++ b/backend/src/routes/cohorts.js @@ -9,7 +9,7 @@ import { toCohortDto, userLanguages } from '../utils/serialize.js'; import { assertCohortStartDate, buildCohortName, scheduleSessionCount, scheduleWeekdays, toYmd, upcomingSessionDates, ymdToDate } from '../services/schedule.js'; import { releaseCohortPatients, syncCohortPatients, applyCohortToPatients, applyPatientEdits, createManualCohortPatients } from '../services/cohorts.js'; import { activateManualCohort, cancelCohort, startCohortMeetings } from '../services/matching.js'; -import { ensureSessionRecords, persistCohortSessions, rescheduleOpenSessions } from '../services/programSessions.js'; +import { attachCohortPatientProgress, ensureSessionRecords, meetingWeekdays, persistCohortSessions, rescheduleOpenSessions } from '../services/programSessions.js'; import { CohortSession } from '../models/CohortSession.js'; import { assertConfiguredSlot, getAppSettings } from '../services/settings.js'; import { reminderAuditText, writeAudit } from '../services/audit.js'; @@ -57,6 +57,8 @@ const cohortPayload = Joi.object({ whatsappOptOut: Joi.boolean().optional(), offlineSessions: Joi.number().integer().min(0).required(), // sessions already done offline before joining offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null).optional(), // first offline session, if known + sessionsPaid: Joi.alternatives().try(Joi.number().integer().min(0), Joi.string().allow('')).optional(), // sessions covered by payment + patientStatus: Joi.string().valid('active', 'deactivated').optional(), })).default([]), /* Replaced by patientEdits, which also carries name, mobile, age, and gender. patientOffline: Joi.array().items(Joi.object({ @@ -73,6 +75,8 @@ const cohortPayload = Joi.object({ gender: Joi.string().trim().allow('').optional(), offlineSessions: Joi.number().integer().min(0).required(), offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null), + sessionsPaid: Joi.alternatives().try(Joi.number().integer().min(0), Joi.string().allow('')).optional(), + patientStatus: Joi.string().valid('active', 'deactivated').optional(), })).default([]), }); @@ -135,7 +139,7 @@ async function findCohort(request) { .populate('virtualPrt', 'firstName lastName email') // .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' }); // .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut offlineSessions offlineStartDate' }); - .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate' }); + .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate sessionsPaid patientStatus' }); if (!cohort) throw Boom.notFound('Cohort not found'); return cohort; } @@ -257,7 +261,10 @@ export function cohortRoutes(server) { pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'view') }], validate: { params: Joi.object({ id: objectId.required() }) }, }, - handler: async (request) => (await withSessionCounts(await findCohort(request)))[0], + handler: async (request) => { + const [dto] = await withSessionCounts(await findCohort(request)); + return attachCohortPatientProgress(dto); + }, }); server.route({ @@ -275,7 +282,7 @@ export function cohortRoutes(server) { const stored = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1 }); if (stored.length) return { items: stored.map(toCohortSessionDto) }; const ownCount = await scheduleSessionCount(cohort.scheduleId); - const dates = await upcomingSessionDates(toYmd(cohort.startDate), cohort.virtualPrt?._id || cohort.virtualPrt, ownCount || request.query.count, cohort.language, await scheduleWeekdays(cohort.scheduleId)); + const dates = await upcomingSessionDates(toYmd(cohort.startDate), cohort.virtualPrt?._id || cohort.virtualPrt, ownCount || request.query.count, cohort.language, await meetingWeekdays(cohort)); return { items: dates.map((date) => ({ date, slot: cohort.slot, status: 'scheduled' })) }; }, }); @@ -413,8 +420,8 @@ export function cohortRoutes(server) { const { ensureCohortGroup } = await import('../services/whatsapp.js'); const updated = await ensureCohortGroup(cohort._id); await updated?.populate?.('virtualPrt', 'firstName lastName email'); - await updated?.populate?.({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' }); - return toCohortDto(updated || cohort); + await updated?.populate?.({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate sessionsPaid patientStatus' }); + return attachCohortPatientProgress(toCohortDto(updated || cohort)); }, }); @@ -437,8 +444,8 @@ export function cohortRoutes(server) { console.error(`[whatsapp] closing notice failed: ${err?.message || err}`); }); await cohort.populate('virtualPrt', 'firstName lastName email'); - await cohort.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' }); - return toCohortDto(cohort); + await cohort.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate sessionsPaid patientStatus' }); + return attachCohortPatientProgress(toCohortDto(cohort)); }, }); diff --git a/backend/src/routes/onboarding.js b/backend/src/routes/onboarding.js index 13200a8..0bc95ef 100644 --- a/backend/src/routes/onboarding.js +++ b/backend/src/routes/onboarding.js @@ -7,7 +7,7 @@ import { Patient } from '../models/Patient.js'; import { Session } from '../models/Session.js'; import { Cohort } from '../models/Cohort.js'; import { User } from '../models/User.js'; -import { toOnboardedPatientDto, toCohortDto } from '../utils/serialize.js'; +import { normalizePatientStatus, normalizeSessionsPaid, toOnboardedPatientDto, toCohortDto } from '../utils/serialize.js'; import { saveOnboardingScreenshot, screenshotPath, safeDownloadName } from '../services/onboardingUpload.js'; import { applyOnboardedPii, hashMobile, hashName, isMobileNumber, readOnboardedPii } from '../services/cryptoPii.js'; import { deleteScreenshot, presignGet, s3Enabled } from '../services/s3.js'; @@ -157,6 +157,8 @@ function parseOnboardingFields(payload, settings, { requirePlacement = true, req diseaseType, preferredWeekday, paymentStatus, + sessionsPaid: normalizeSessionsPaid(hasPayloadKey(payload, 'sessionsPaid') ? textField(payload, 'sessionsPaid') : 30), + patientStatus: normalizePatientStatus(hasPayloadKey(payload, 'patientStatus') ? textField(payload, 'patientStatus') : 'active'), whatsappOptOut: ['true', '1', 'on', 'yes'].includes(textField(payload, 'whatsappOptOut').toLowerCase()), }; if (hasPayloadKey(payload, 'lungCondition')) fields.lungCondition = textField(payload, 'lungCondition'); @@ -398,6 +400,8 @@ export function onboardingRoutes(server) { slot: cohort?.slot || fields.slot || '', matchingStatus: cohort ? 'unassigned' : 'unassigned', paymentStatus: fields.paymentStatus, + sessionsPaid: fields.sessionsPaid, + patientStatus: fields.patientStatus, paymentScreenshot, sourcePatientId: fields.sourcePatientId || '', onboardedBy: creds.user._id, @@ -491,10 +495,22 @@ export function onboardingRoutes(server) { } applyOnboardedPii(item, fields); item.paymentStatus = fields.paymentStatus; + item.sessionsPaid = fields.sessionsPaid; + const previousPatientStatus = normalizePatientStatus(item.patientStatus); + item.patientStatus = fields.patientStatus; item.whatsappOptOut = fields.whatsappOptOut; if (confirmed) { await item.save(); await writeAudit(request, { action: 'patient.updated', resourceType: 'onboarding', resourceId: item._id }); + if (previousPatientStatus !== 'active' && fields.patientStatus === 'active' && item.cohort) { + const { addPatientToWhatsapp } = await import('../services/whatsapp.js'); + const cohort = await Cohort.findById(item.cohort); + if (cohort) { + await addPatientToWhatsapp(cohort, item._id).catch((err) => { + console.error(`[whatsapp] reactivate sync failed: ${err?.message || err}`); + }); + } + } await item.populate('onboardedBy', 'firstName lastName email'); await item.populate('reviewedBy', 'firstName lastName'); await item.populate('cohort', 'name startDate slot language'); diff --git a/backend/src/services/audit.js b/backend/src/services/audit.js index 636ca4e..9c9377f 100644 --- a/backend/src/services/audit.js +++ b/backend/src/services/audit.js @@ -1,8 +1,8 @@ import { AuditEvent } from '../models/AuditEvent.js'; export function clientIp(request) { - return request.headers['x-forwarded-for']?.split(',')[0]?.trim() - || request.info?.remoteAddress + return request?.headers?.['x-forwarded-for']?.split(',')[0]?.trim() + || request?.info?.remoteAddress || ''; } @@ -19,11 +19,11 @@ export function reminderAuditText(rules = []) { export async function writeAudit(request, { action, resourceType = '', resourceId = '', actor } = {}) { try { await AuditEvent.create({ - actor: actor || request.auth?.credentials?.user?._id || null, + actor: actor || request?.auth?.credentials?.user?._id || null, action, resourceType, resourceId: resourceId ? String(resourceId) : '', - ip: request ? clientIp(request) : '', + ip: clientIp(request), at: new Date(), }); } catch (err) { diff --git a/backend/src/services/cohorts.js b/backend/src/services/cohorts.js index 23677f1..504c362 100644 --- a/backend/src/services/cohorts.js +++ b/backend/src/services/cohorts.js @@ -6,6 +6,7 @@ import { writeAudit } from './audit.js'; import { applyOnboardedPii, hashMobile, isMobileNumber, readOnboardedPii } from './cryptoPii.js'; import { env } from '../config/env.js'; import { toYmd, todayYmd, weekdayOf } from './schedule.js'; +import { normalizePatientStatus, normalizeSessionsPaid } from '../utils/serialize.js'; import Boom from '@hapi/boom'; async function safeWhatsapp(label, fn) { @@ -16,17 +17,34 @@ async function safeWhatsapp(label, fn) { } } +// Matching status for a patient placed on this cohort. +function placedMatchingStatus(cohort) { + return cohort.status === 'proposed' ? 'proposed' : 'assigned'; +} + +// A patient can join a cohort only while active. Someone already on it keeps their status. +export function assertCanPlacePatient(patient, cohort) { + const current = patient?.cohort ? String(patient.cohort._id || patient.cohort) : ''; + if (current && current === String(cohort._id)) return; + if (normalizePatientStatus(patient?.patientStatus) === 'active') return; + throw Boom.badRequest('Only an active patient can be moved or added to a cohort.'); +} + export async function syncCohortPatients(cohort, previousPatientIds = []) { const nextIds = (cohort.patients || []).map((id) => String(id)); const prevIds = (previousPatientIds || []).map((id) => String(id)); + const added = nextIds.filter((id) => !prevIds.includes(id)); + const joining = added.length + ? await OnboardedPatient.find({ _id: { $in: added } }).select('cohort patientStatus') + : []; + for (const patient of joining) assertCanPlacePatient(patient, cohort); if (nextIds.length) { await OnboardedPatient.updateMany( { _id: { $in: nextIds } }, - { $set: { assignedEducator: cohort.virtualPrt, cohort: cohort._id, matchingStatus: 'assigned' } }, + { $set: { assignedEducator: cohort.virtualPrt, cohort: cohort._id, matchingStatus: placedMatchingStatus(cohort) } }, ); } - const added = nextIds.filter((id) => !prevIds.includes(id)); if (added.length) { await OnboardedPatient.updateMany({ _id: { $in: added } }, { $set: { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } }); } @@ -64,6 +82,8 @@ export async function addPatientToCohort(cohort, patientId, actorId = null) { const id = String(patientId); const current = (cohort.patients || []).map((item) => String(item._id || item)); const joined = !current.includes(id); + const existing = await OnboardedPatient.findById(patientId).select('cohort patientStatus'); + if (existing) assertCanPlacePatient(existing, cohort); if (joined) { cohort.patients.push(patientId); await cohort.save(); @@ -74,7 +94,7 @@ export async function addPatientToCohort(cohort, patientId, actorId = null) { { $set: { assignedEducator: cohort.virtualPrt, cohort: cohort._id, - matchingStatus: 'assigned', + matchingStatus: placedMatchingStatus(cohort), ...(joined ? { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } : {}), } }, ); @@ -146,13 +166,26 @@ export async function applyPatientEdits(cohort, rows = []) { if (age !== current.age) fields.age = age; const gender = String(row.gender || ''); if (gender !== current.gender) fields.gender = gender; - ready.push({ patient, fields, offlineSessions: row.offlineSessions, offlineStartDate: row.offlineStartDate || '' }); + ready.push({ + patient, + fields, + offlineSessions: row.offlineSessions, + offlineStartDate: row.offlineStartDate || '', + sessionsPaid: normalizeSessionsPaid(row.sessionsPaid), + patientStatus: normalizePatientStatus(row.patientStatus), + }); } - for (const { patient, fields, offlineSessions, offlineStartDate } of ready) { + for (const { patient, fields, offlineSessions, offlineStartDate, sessionsPaid, patientStatus } of ready) { + const previousStatus = normalizePatientStatus(patient.patientStatus); applyOnboardedPii(patient, fields); patient.offlineSessions = offlineSessions; patient.offlineStartDate = offlineStartDate; + patient.sessionsPaid = sessionsPaid; + patient.patientStatus = patientStatus; await patient.save(); + if (previousStatus !== 'active' && patientStatus === 'active' && cohort?._id) { + await safeWhatsapp('reactivate patient', () => addPatientToWhatsapp(cohort, patient._id)); + } } } @@ -166,6 +199,8 @@ export async function createManualCohortPatients(cohort, rows, userId) { whatsappOptOut: Boolean(row?.whatsappOptOut), offlineSessions: Math.max(0, Number(row?.offlineSessions) || 0), offlineStartDate: String(row?.offlineStartDate || '').trim(), + sessionsPaid: normalizeSessionsPaid(row?.sessionsPaid), + patientStatus: normalizePatientStatus(row?.patientStatus), })).filter((row) => row.name || row.mobile); if (!list.length) return []; if (list.some((row) => !row.name || !isMobileNumber(row.mobile))) throw Boom.badRequest('Each patient needs a name and a 10 digit mobile.'); @@ -189,6 +224,8 @@ export async function createManualCohortPatients(cohort, rows, userId) { whatsappOptOut: row.whatsappOptOut, offlineSessions: row.offlineSessions, offlineStartDate: row.offlineStartDate, + sessionsPaid: row.sessionsPaid, + patientStatus: row.patientStatus, }); created.push(doc._id); } diff --git a/backend/src/services/matching.js b/backend/src/services/matching.js index 89af68c..d7870b6 100644 --- a/backend/src/services/matching.js +++ b/backend/src/services/matching.js @@ -4,7 +4,7 @@ import { OnboardedPatient } from '../models/OnboardedPatient.js'; import { ReassignmentEvent } from '../models/ReassignmentEvent.js'; import { Role } from '../models/Role.js'; import { User } from '../models/User.js'; -import { addPatientToCohort, releaseCohortPatients, removePatientFromCohort, syncCohortPatients } from './cohorts.js'; +import { addPatientToCohort, assertCanPlacePatient, releaseCohortPatients, removePatientFromCohort, syncCohortPatients } from './cohorts.js'; import { writeAudit } from './audit.js'; import { CohortSession } from '../models/CohortSession.js'; import { notifyCohortConfirmed, notifyReassignment } from './notify.js'; @@ -398,6 +398,7 @@ export async function movePatient(patientId, toCohortId) { throw Boom.badRequest('That proposed cohort is full.'); } const previous = patient.cohort; + assertCanPlacePatient(patient, target); if (previous) await removePatientFromCohort(previous, patient._id); await addPatientToCohort(target, patient._id); patient.matchingStatus = 'proposed'; @@ -629,6 +630,7 @@ export async function migratePatient(patient, { cohortId, slot, preferredWeekday throw err; } const previous = patient.cohort; + assertCanPlacePatient(patient, target); if (previous && String(previous) !== String(target._id)) { await removePatientFromCohort(previous, patient._id); } @@ -640,7 +642,7 @@ export async function migratePatient(patient, { cohortId, slot, preferredWeekday patient.sessionLanguage = target.language || patient.sessionLanguage; patient.diseaseType = target.diseaseType || patient.diseaseType; patient.preferredWeekday = weekdayOf(toYmd(target.startDate)); - patient.matchingStatus = 'assigned'; + patient.matchingStatus = target.status === 'proposed' ? 'proposed' : 'assigned'; await persistCohortSessions(target); const { ensureSessionRecords } = await import('./programSessions.js'); await ensureSessionRecords(target); diff --git a/backend/src/services/programSessions.js b/backend/src/services/programSessions.js index ea82ccc..55cc263 100644 --- a/backend/src/services/programSessions.js +++ b/backend/src/services/programSessions.js @@ -181,7 +181,7 @@ async function syncExistingMeetSeries(cohort, sessions) { const host = await sessionHost(linked, cohort); if (!host?.google?.refreshToken && !host?.google?.accessToken) return; const settings = await getAppSettings(); - const weekdays = await scheduleWeekdays(cohort.scheduleId); + const weekdays = await meetingWeekdays(cohort); const first = active[0]; const last = active[active.length - 1]; const times = slotDateTimes(first.date, first.slot || cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60); @@ -294,6 +294,16 @@ export async function ensureSessionRecords(cohort) { for (const session of dirty) await session.save(); } +const ALL_WEEKDAYS = [1, 2, 3, 4, 5, 6]; + +// Days this cohort meets. An extra schedule wins. All weekdays is Monday–Saturday. Otherwise the repeat interval. +export async function meetingWeekdays(cohort) { + const scheduled = await scheduleWeekdays(cohort?.scheduleId); + if (scheduled) return scheduled; + if (cohort?.sixDayWeek) return ALL_WEEKDAYS; + return null; +} + // Next date for an extra schedule, skipping unticked days, Sunday, holiday, and leave. async function nextWeekdayAppendDate(cohort, weekdays) { const settings = await getAppSettings(); @@ -316,9 +326,9 @@ async function nextWeekdayAppendDate(cohort, weekdays) { return cursor; } -// Next date after the last session. Extra schedules use weekdays. Normal uses the interval. +// Next date after the last session. A schedule or all-weekdays uses those days. Otherwise the repeat interval. export async function nextAppendDate(cohort) { - const weekdays = await scheduleWeekdays(cohort.scheduleId); + const weekdays = await meetingWeekdays(cohort); if (weekdays) return nextWeekdayAppendDate(cohort, weekdays); const settings = await getAppSettings(); const interval = Math.max(1, Number(settings.repeatIntervalDays) || 2); @@ -339,10 +349,10 @@ export async function nextAppendDate(cohort) { return cursor; } -// True when the cohort may meet on this date: its schedule weekdays if set, never Sunday, and not a holiday or PRT leave. +// True when the cohort may meet on this date: its meeting days if set, never Sunday, and not a holiday or PRT leave. async function canMeetOn(cohort, date) { if (weekdayOf(date) === 0) return false; - const weekdays = await scheduleWeekdays(cohort.scheduleId); + const weekdays = await meetingWeekdays(cohort); if (weekdays && !weekdays.map(Number).includes(weekdayOf(date))) return false; const settings = await getAppSettings(); if (settings.skipHolidays !== false && (await holidayDatesBetween(date, date, cohort.language)).has(date)) return false; @@ -481,7 +491,7 @@ export async function shiftApprovedLeaveSessions(prtId, startYmd, endYmd) { if (!hit) continue; const tail = sessions.filter((session) => session.status === 'scheduled' && session.date >= hit.date); if (!tail.length) continue; - const weekdays = await scheduleWeekdays(cohort.scheduleId); + const weekdays = await meetingWeekdays(cohort); const blocked = new Set( sessions.filter((session) => session.status === 'completed').map((session) => session.date), ); @@ -569,7 +579,7 @@ export async function ensureMeetForCohort(cohort) { } const settings = await getAppSettings(); - const weekdays = await scheduleWeekdays(cohort.scheduleId); + const weekdays = await meetingWeekdays(cohort); const firstDate = sessions[0]?.date || toYmd(cohort.startDate); const times = slotDateTimes(firstDate, cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60); try { @@ -888,6 +898,19 @@ export async function moveSessionEvent(session, nextDate) { return session; } +// Adds sessionsCompleted onto each patient in a cohort DTO for paid-session red checks. +export async function attachCohortPatientProgress(dto) { + if (!dto?.patients?.length) return dto; + const stats = await patientProgramStats(dto.patients.map((patient) => patient.id).filter(Boolean)); + return { + ...dto, + patients: dto.patients.map((patient) => ({ + ...patient, + sessionsCompleted: stats.get(String(patient.id))?.completed || 0, + })), + }; +} + export async function patientProgramStats(patientIds) { const ids = patientIds.map((id) => String(id)); const sessions = await CohortSession.find({ 'records.patient': { $in: ids }, status: { $in: ['scheduled', 'completed'] } }); diff --git a/backend/src/services/whatsapp.js b/backend/src/services/whatsapp.js index 6f2d102..049c393 100644 --- a/backend/src/services/whatsapp.js +++ b/backend/src/services/whatsapp.js @@ -22,6 +22,7 @@ import { toDmy, toWhatsappDigits, } from './whatsappFormat.js'; +import { isPatientMessagingActive } from '../utils/serialize.js'; const LIVE = new Set(['active', 'confirmed']); const DEFAULT_REMINDER = 'Reminder: {{cohort}} on {{date}} at {{time}}.\nTap Join Meet when you are ready.'; @@ -146,7 +147,7 @@ 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'); + .select('name mobile reviewStatus whatsappOptOut sessionLanguage patientStatus'); } export async function sendSessionReminder(session, { rule, manual = false } = {}) { @@ -172,7 +173,7 @@ export async function sendSessionReminder(session, { rule, manual = false } = {} const patients = await cohortPatientsForReminder(cohort); let queued = 0; for (const patient of patients) { - if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut) continue; + if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut || !isPatientMessagingActive(patient)) continue; const pii = readOnboardedPii(patient); const phone = toWhatsappDigits(pii.mobile); if (!phone) continue; diff --git a/backend/src/services/whatsappQueue.js b/backend/src/services/whatsappQueue.js index 1f0b796..a51ea4b 100644 --- a/backend/src/services/whatsappQueue.js +++ b/backend/src/services/whatsappQueue.js @@ -8,6 +8,7 @@ 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 { isPatientMessagingActive } from '../utils/serialize.js'; import { createGroup, fetchInvite, sendCta, sendText, updateGroup, updateParticipants } from './wastra.js'; const LIVE = new Set(['active', 'confirmed']); @@ -16,9 +17,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. */ +const ADD_FLAGS = new Set(['patient', 'prt', 'staff']); + +/** Invites and direct adds stay unique after success; failed/cancelled can retry. */ export function dedupeStatusesForStep(step) { if (step?.flag === 'invite') return ['pending', 'running', 'done']; + if (step?.kind === 'add_member' && ADD_FLAGS.has(step?.flag)) return ['pending', 'running', 'done']; return OPEN; } @@ -65,7 +69,7 @@ async function staffContacts(cohort) { 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'); + return OnboardedPatient.find({ _id: { $in: ids } }).select('name mobile reviewStatus whatsappOptOut patientStatus'); } function patientStep(patient) { @@ -147,15 +151,30 @@ function inviteStep(cohortId, person) { }; } -function inviteSteps(cohortId, people) { - return people.filter((person) => person.phone).map((person) => inviteStep(cohortId, person)); +// Adds the person to the cohort WhatsApp group without sending an invite message. +function addMemberStep(cohortId, person) { + const flag = person.flag || (person.patient ? 'patient' : 'staff'); + return { + kind: 'add_member', + phone: person.phone, + name: person.name || '', + user: person.id || person.user || null, + patient: person.patient || null, + flag, + dedupeKey: `${cohortId}:add:${flag}:${person.phone}`, + }; +} + +function addMemberSteps(cohortId, people) { + return people.filter((person) => person.phone).map((person) => addMemberStep(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. Leave steps still run. +// True for old membership tasks. Direct patient/PRT/staff adds 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?.kind === 'add_member' && ADD_FLAGS.has(task?.flag)) return false; if (task?.flag === 'leave' && task.kind === 'remove_member') return false; return ['ensure_contact', 'add_member', 'promote_member', 'remove_member'].includes(task?.kind); } @@ -243,12 +262,16 @@ export async function enqueueCohortGroup(cohortId) { dedupeKey: `${cohort._id}:create_group`, }); } - steps.push(...inviteSteps(cohort._id, staff)); + const prtId = String(cohort.virtualPrt?._id || cohort.virtualPrt || ''); + steps.push(...addMemberSteps(cohort._id, staff.map((person) => ({ + ...person, + flag: String(person.id) === prtId ? 'prt' : 'staff', + })))); for (const patient of patients) { - if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut) continue; + if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut || !isPatientMessagingActive(patient)) continue; const step = patientStep(patient); if (!step.phone) continue; - steps.push(inviteStep(cohort._id, step)); + steps.push(addMemberStep(cohort._id, { ...step, flag: 'patient' })); } // steps.push(...await prtAdminSteps(cohort)); await enqueueMany(cohort._id, steps); @@ -262,15 +285,16 @@ export async function enqueuePatientAdd(cohort, patientId) { await enqueueCohortGroup(cohort._id); } if (!fresh?.whatsappGroupJid) return; - const patient = await OnboardedPatient.findById(patientId).select('name mobile reviewStatus whatsappOptOut'); + const patient = await OnboardedPatient.findById(patientId).select('name mobile reviewStatus whatsappOptOut patientStatus'); if (!patient || patient.reviewStatus !== 'confirmed') return; const step = patientStep(patient); if (patient.whatsappOptOut) { await enqueuePatientRemove(fresh._id, patientId); return; } + if (!isPatientMessagingActive(patient)) return; if (!step.phone) return; - await enqueueMany(fresh._id, [inviteStep(fresh._id, { ...step, patient: patient._id })]); + await enqueueMany(fresh._id, [addMemberStep(fresh._id, { ...step, patient: patient._id, flag: 'patient' })]); } export async function enqueuePatientRemove(cohortId, patientId) { @@ -320,7 +344,12 @@ export async function enqueuePrtSwap(cohortOrId, previousPrtId) { })); } if (nextPhone) { - steps.push(inviteStep(cohort._id, { id: String(next._id), phone: nextPhone, name: personName(next) })); + steps.push(addMemberStep(cohort._id, { + id: String(next._id), + phone: nextPhone, + name: personName(next), + flag: 'prt', + })); const text = `Your therapist for this group is now ${personName(next)}.`; steps.push({ kind: 'send_text', text, flag: 'prt', dedupeKey: textKey(cohort._id, text) }); } @@ -375,7 +404,9 @@ async function noteCohortError(task, message) { 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); + if (task.patient && (task.flag === 'invite' || task.flag === 'patient')) { + upsertMember(cohort, task.patient, 'failed', cohort.whatsappError); + } await cohort.save(); } @@ -385,11 +416,11 @@ async function clearCohortError(cohortId) { 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 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(); @@ -454,6 +485,35 @@ async function runLeaveStep(task) { // } // } +// Adds a patient, PRT, or staff number to the cohort WhatsApp group. +async function runAddMemberStep(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, 'add', [task.phone]); + } catch (err) { + if (!participantAlreadyUpdated('add', err)) throw err; + } + if (task.patient) { + upsertMember(cohort, task.patient, 'added', ''); + await cohort.save(); + } + await clearCohortError(cohort._id); +} + async function execute(task) { if (isRetiredMembershipTask(task)) { task.status = 'cancelled'; @@ -466,6 +526,10 @@ async function execute(task) { // await runPrtAdminStep(task); // return; // } + if (task.kind === 'add_member' && ADD_FLAGS.has(task.flag)) { + await runAddMemberStep(task); + return; + } if (task.flag === 'leave' && task.kind === 'remove_member') { await runLeaveStep(task); return; @@ -675,7 +739,8 @@ function cancelMembershipTasks() { $or: [ { kind: 'ensure_contact' }, { kind: 'remove_member', flag: { $ne: 'leave' } }, - { kind: { $in: ['add_member', 'promote_member'] } }, + { kind: 'promote_member' }, + { kind: 'add_member', flag: { $nin: [...ADD_FLAGS] } }, ], }, { $set: { status: 'cancelled', lockedAt: null, lastError: 'Membership updates are no longer sent to WhatsApp' } }, diff --git a/backend/src/services/whatsappQueue.test.js b/backend/src/services/whatsappQueue.test.js index 4280490..7271fa7 100644 --- a/backend/src/services/whatsappQueue.test.js +++ b/backend/src/services/whatsappQueue.test.js @@ -10,17 +10,20 @@ test('draws each WhatsApp gap from 15 to 40 seconds', () => { } }); -test('keeps the conducting therapist admin steps and drops old membership tasks', () => { - // assert.equal(isRetiredMembershipTask({ kind: 'promote_member', flag: 'prt' }), false); - // assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'prt' }), false); +test('keeps direct add and leave steps and drops old membership tasks', () => { + assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'patient' }), false); + assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'prt' }), false); + assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'staff' }), false); + assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: '' }), true); assert.equal(isRetiredMembershipTask({ kind: 'promote_member', flag: '' }), true); assert.equal(isRetiredMembershipTask({ kind: 'remove_member', flag: 'leave' }), false); assert.equal(isRetiredMembershipTask({ kind: 'remove_member' }), true); assert.equal(isRetiredMembershipTask({ kind: 'send_text', flag: 'invite' }), false); }); -test('invite steps treat a done send as already delivered', () => { +test('invite and direct add steps treat a done send as already delivered', () => { assert.deepEqual(dedupeStatusesForStep({ flag: 'invite' }), ['pending', 'running', 'done']); + assert.deepEqual(dedupeStatusesForStep({ kind: 'add_member', flag: 'patient' }), ['pending', 'running', 'done']); assert.deepEqual(dedupeStatusesForStep({ flag: 'reminder' }), ['pending', 'running']); assert.deepEqual(dedupeStatusesForStep({ kind: 'send_text' }), ['pending', 'running']); }); diff --git a/backend/src/utils/serialize.js b/backend/src/utils/serialize.js index 7824725..b0ce73b 100644 --- a/backend/src/utils/serialize.js +++ b/backend/src/utils/serialize.js @@ -165,6 +165,26 @@ export function toSessionDto(session) { }; } +// Blank or invalid paid-session counts become 30. +export function normalizeSessionsPaid(value) { + if (value === '' || value == null) return 30; + const n = Number(value); + if (Number.isNaN(n)) return 30; + return Math.max(0, Math.floor(n)); +} + +// Patient status is active or deactivated. Old return_pool values count as deactivated. +export function normalizePatientStatus(value) { + const next = String(value || 'active'); + if (next === 'deactivated' || next === 'return_pool') return 'deactivated'; + return 'active'; +} + +// True when the patient can receive WhatsApp reminders and membership updates. +export function isPatientMessagingActive(patient) { + return normalizePatientStatus(patient?.patientStatus) === 'active'; +} + export function toOnboardedPatientDto(item) { if (!item) return null; const pii = readOnboardedPii(item); @@ -191,6 +211,8 @@ export function toOnboardedPatientDto(item) { matchingStatus: item.matchingStatus || 'unassigned', rejectReason: item.rejectReason || '', paymentStatus: item.paymentStatus || 'Unpaid', + sessionsPaid: normalizeSessionsPaid(item.sessionsPaid), + patientStatus: normalizePatientStatus(item.patientStatus), hasScreenshot: Boolean(item.paymentScreenshot?.filename), onboardedBy: by ? { @@ -268,7 +290,18 @@ export function toCohortDto(cohort) { p && typeof p === 'object' // ? { id: String(p._id), name: readOnboardedPii(p).name, mobile: readOnboardedPii(p).mobile, whatsappOptOut: Boolean(p.whatsappOptOut) } // ? { id: String(p._id), name: readOnboardedPii(p).name, mobile: readOnboardedPii(p).mobile, whatsappOptOut: Boolean(p.whatsappOptOut), offlineSessions: p.offlineSessions || 0, offlineStartDate: p.offlineStartDate || '' } - ? { id: String(p._id), name: readOnboardedPii(p).name, mobile: readOnboardedPii(p).mobile, age: readOnboardedPii(p).age ?? '', gender: readOnboardedPii(p).gender, whatsappOptOut: Boolean(p.whatsappOptOut), offlineSessions: p.offlineSessions || 0, offlineStartDate: p.offlineStartDate || '' } + ? { + id: String(p._id), + name: readOnboardedPii(p).name, + mobile: readOnboardedPii(p).mobile, + age: readOnboardedPii(p).age ?? '', + gender: readOnboardedPii(p).gender, + whatsappOptOut: Boolean(p.whatsappOptOut), + offlineSessions: p.offlineSessions || 0, + offlineStartDate: p.offlineStartDate || '', + sessionsPaid: normalizeSessionsPaid(p.sessionsPaid), + patientStatus: normalizePatientStatus(p.patientStatus), + } : { id: String(p) } )), patientCount: patients.length, diff --git a/frontend/src/components/table/DataTable.jsx b/frontend/src/components/table/DataTable.jsx index 4d323e1..06af2ed 100644 --- a/frontend/src/components/table/DataTable.jsx +++ b/frontend/src/components/table/DataTable.jsx @@ -28,7 +28,7 @@ const DataTable = ({ )} } - {table.getRowModel().rows?.length ? table.getRowModel().rows.map(row => + {table.getRowModel().rows?.length ? table.getRowModel().rows.map(row => {row.getVisibleCells().map(cell => {flexRender(cell.column.columnDef.cell, cell.getContext())})} ) : diff --git a/frontend/src/views/virtualpr/cohorts/index.jsx b/frontend/src/views/virtualpr/cohorts/index.jsx index 581ef4e..87015cf 100644 --- a/frontend/src/views/virtualpr/cohorts/index.jsx +++ b/frontend/src/views/virtualpr/cohorts/index.jsx @@ -98,7 +98,20 @@ export default function CohortsPage() { id: 'whatsapp', header: 'WhatsApp', cell: ({ row, getValue }) => ( - ), @@ -228,9 +241,15 @@ export default function CohortsPage() {