VirtualPR/backend/src/routes/cohorts.js

516 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Joi from 'joi';
import Boom from '@hapi/boom';
import { requireAnyPermission, cohortScopeFilter, credentials } from '../plugins/auth.js';
import { Cohort } from '../models/Cohort.js';
import { Role } from '../models/Role.js';
import { User } from '../models/User.js';
import { OnboardedPatient } from '../models/OnboardedPatient.js';
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 { CohortSession } from '../models/CohortSession.js';
import { assertConfiguredSlot, getAppSettings } from '../services/settings.js';
import { reminderAuditText, writeAudit } from '../services/audit.js';
import { toCohortSessionDto } from '../utils/serialize.js';
const objectId = Joi.string().hex().length(24);
function idList(items) {
return (items || []).map((item) => String(item?._id || item)).filter(Boolean);
}
// Writes one shallow row for each patient who joined or left this cohort.
async function auditPatientMembership(request, cohortId, previousIds, nextIds) {
const previous = new Set(previousIds);
const next = new Set(nextIds);
for (const id of nextIds) {
if (!previous.has(id)) {
await writeAudit(request, { action: 'cohort.patient_added', resourceType: 'cohort', resourceId: cohortId });
}
}
for (const id of previousIds) {
if (!next.has(id)) {
await writeAudit(request, { action: 'cohort.patient_removed', resourceType: 'cohort', resourceId: cohortId });
}
}
}
const cohortPayload = Joi.object({
name: Joi.string().trim().allow('', null),
startDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).required(),
slot: Joi.string().pattern(/^\d{2}:\d{2}-\d{2}:\d{2}$/).required(),
virtualPrt: objectId.required(),
language: Joi.string().trim().allow('', null),
diseaseType: Joi.string().trim().allow('', null),
patients: Joi.array().items(objectId).default([]),
durationMinutes: Joi.number().min(15).max(180).optional(),
scheduleId: Joi.string().trim().allow('', null),
createdAs: Joi.string().valid('cohorts', 'manual_cohorts'),
sixDayWeek: Joi.boolean(),
newPatients: Joi.array().items(Joi.object({
name: Joi.string().trim().required(),
mobile: Joi.string().trim().pattern(/^\d{10}$/).required(),
age: Joi.alternatives().try(Joi.number(), Joi.string().allow('')).optional(),
gender: Joi.string().trim().allow('').optional(),
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
})).default([]),
/* Replaced by patientEdits, which also carries name, mobile, age, and gender.
patientOffline: Joi.array().items(Joi.object({
id: objectId.required(),
offlineSessions: Joi.number().integer().min(0).required(), // corrected offline count for an existing patient
offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null), // corrected first offline session date
})).default([]),
*/
patientEdits: Joi.array().items(Joi.object({
id: objectId.required(),
name: Joi.string().trim().allow(''), // corrected name
mobile: Joi.string().trim().allow(''), // corrected mobile, checked only when it changed
age: Joi.alternatives().try(Joi.number(), Joi.string().allow('')).optional(),
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),
})).default([]),
});
// Manual cohorts start on Monday–Saturday, or only Monday and Tuesday.
function startWeekdaysFor(payload, scheduleDays) {
if (payload.createdAs !== 'manual_cohorts') return scheduleDays;
return payload.sixDayWeek ? [1, 2, 3, 4, 5, 6] : [1, 2];
}
// Saved extra-schedule id to its weekdays. Blank means Normal.
async function chosenWeekdays(scheduleId) {
const id = String(scheduleId || '').trim();
if (!id) return null;
const days = await scheduleWeekdays(id);
if (!days) throw Boom.badRequest('Select a schedule from Settings.');
return days;
}
async function assertVirtualPrt(userId) {
const user = await User.findById(userId).populate('role');
if (!user || !user.isActive) throw Boom.badRequest('Invalid Virtual PRT');
if (user.role?.systemKey !== 'educator') throw Boom.badRequest('Cohorts can only be assigned to a Virtual PRT');
return user;
}
async function assertPatients(ids) {
if (!ids.length) return;
const count = await OnboardedPatient.countDocuments({ _id: { $in: ids }, reviewStatus: 'confirmed' });
if (count !== ids.length) throw Boom.badRequest('Cohorts can only include confirmed onboarded patients.');
}
async function withSessionCounts(cohorts) {
const list = Array.isArray(cohorts) ? cohorts : [cohorts];
const ids = list.map((cohort) => cohort._id).filter(Boolean);
const rows = ids.length
? await CohortSession.aggregate([
{ $match: { cohort: { $in: ids }, status: { $ne: 'cancelled' } } },
{
$group: {
_id: '$cohort',
planned: { $sum: 1 },
completed: { $sum: { $cond: [{ $eq: ['$status', 'completed'] }, 1, 0] } },
},
},
])
: [];
const byId = new Map(rows.map((row) => [String(row._id), row]));
return list.map((cohort) => {
const row = byId.get(String(cohort._id));
return {
...toCohortDto(cohort),
sessionsCompleted: row?.completed || 0,
sessionsPlanned: row?.planned || 0,
};
});
}
async function findCohort(request) {
const cohort = await Cohort.findOne({ _id: request.params.id, ...cohortScopeFilter(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' });
if (!cohort) throw Boom.notFound('Cohort not found');
return cohort;
}
export function cohortRoutes(server) {
server.route({
method: 'GET',
path: '/api/cohorts',
options: { pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'view') }] },
handler: async (request) => {
const { search = '', page = 1, limit = 20, status } = request.query;
const filter = { ...cohortScopeFilter(request) };
const creds = credentials(request);
// if (creds.role?.systemKey === 'educator') filter.status = { $in: ['confirmed', 'active'] };
// else if (status === 'proposed') filter.status = 'proposed';
// else if (status === 'active') filter.status = { $nin: ['proposed'] };
// else if (status === 'completed' || status === 'cancelled') filter.status = status;
if (creds.role?.systemKey === 'educator') filter.status = { $in: ['confirmed', 'active'] };
else if (status === 'proposed') filter.status = 'proposed';
else if (status === 'active') filter.status = { $in: ['confirmed', 'active'] };
else if (status === 'completed' || status === 'cancelled') filter.status = status;
else if (status !== 'all') filter.status = { $in: ['proposed', 'confirmed', 'active'] }; // default "All live"
if (search) {
const rx = new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
filter.name = rx;
}
const skip = (Number(page) - 1) * Number(limit);
const [items, total] = await Promise.all([
Cohort.find(filter)
.populate('virtualPrt', 'firstName lastName email')
.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' })
.sort({ startDate: -1, createdAt: -1 })
.skip(skip)
.limit(Number(limit)),
Cohort.countDocuments(filter),
]);
return { items: await withSessionCounts(items), total, page: Number(page), limit: Number(limit) };
},
});
server.route({
method: 'POST',
path: '/api/cohorts',
options: {
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'add') }],
validate: { payload: cohortPayload },
},
handler: async (request) => {
const { startDate, slot, virtualPrt, patients } = request.payload;
const scheduleId = String(request.payload.scheduleId || '').trim();
const settings = await getAppSettings();
const durationMinutes = request.payload.durationMinutes || settings.defaultDurationMinutes || 60;
await assertConfiguredSlot(slot);
const prt = await assertVirtualPrt(virtualPrt);
const prtLanguages = userLanguages(prt);
if (!prtLanguages.length) throw Boom.badRequest('Assign a language to this Virtual PRT before creating a cohort.');
const language = request.payload.language || prtLanguages[0];
if (!prtLanguages.includes(language)) throw Boom.badRequest('Select a language this Virtual PRT can teach.');
await assertPatients(patients);
if (request.payload.createdAs !== 'manual_cohorts' && patients.length > (settings.maxPatientsPerCohort || 10)) {
throw Boom.badRequest(`A cohort can have at most ${settings.maxPatientsPerCohort || 10} patients.`);
}
try {
await assertCohortStartDate(startDate, virtualPrt, language, startWeekdaysFor(request.payload, await chosenWeekdays(scheduleId)));
} catch (err) {
throw Boom.badRequest(err.message);
}
const name = buildCohortName({ slot, language, startDate });
let createdIds = [];
const cohort = await Cohort.create({
name,
startDate: ymdToDate(startDate),
slot,
language,
scheduleId,
diseaseType: request.payload.diseaseType || '',
createdAs: request.payload.createdAs || 'cohorts',
sixDayWeek: Boolean(request.payload.sixDayWeek),
status: 'active',
virtualPrt,
patients,
durationMinutes,
});
if (cohort.createdAs === 'manual_cohorts') {
try {
createdIds = await createManualCohortPatients(cohort, request.payload.newPatients, request.auth.credentials.user._id);
if (createdIds.length) {
cohort.patients = [...(cohort.patients || []), ...createdIds];
await cohort.save();
}
} catch (err) {
if (createdIds.length) await OnboardedPatient.deleteMany({ _id: { $in: createdIds } });
await Cohort.deleteOne({ _id: cohort._id });
throw err;
}
}
await syncCohortPatients(cohort, []);
await writeAudit(request, { action: 'cohort.created', resourceType: 'cohort', resourceId: cohort._id });
await auditPatientMembership(request, cohort._id, [], idList(cohort.patients));
for (const id of createdIds || []) {
await writeAudit(request, { action: 'patient.created', resourceType: 'onboarding', resourceId: id, actor: request.auth.credentials.user._id });
}
if (reminderAuditText(settings.whatsappReminderRules)) {
await writeAudit(request, { action: 'reminder.saved', resourceType: 'cohort', resourceId: cohort._id });
}
await activateManualCohort(cohort);
if (cohort.createdAs === 'manual_cohorts') await applyCohortToPatients(cohort);
const ready = await Cohort.findById(cohort._id)
.populate('virtualPrt', 'firstName lastName email')
.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
return toCohortDto(ready);
},
});
server.route({
method: 'GET',
path: '/api/cohorts/{id}',
options: {
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'view') }],
validate: { params: Joi.object({ id: objectId.required() }) },
},
handler: async (request) => (await withSessionCounts(await findCohort(request)))[0],
});
server.route({
method: 'GET',
path: '/api/cohorts/{id}/sessions',
options: {
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'view') }],
validate: {
params: Joi.object({ id: objectId.required() }),
query: Joi.object({ count: Joi.number().min(1).max(60) }),
},
},
handler: async (request) => {
const cohort = await findCohort(request);
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));
return { items: dates.map((date) => ({ date, slot: cohort.slot, status: 'scheduled' })) };
},
});
server.route({
method: 'PATCH',
path: '/api/cohorts/{id}',
options: {
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'edit') }],
validate: {
params: Joi.object({ id: objectId.required() }),
payload: cohortPayload,
},
},
handler: async (request) => {
const cohort = await findCohort(request);
const previous = (cohort.patients || []).map((p) => String(p._id || p));
const previousName = cohort.name;
const previousPrtId = String(cohort.virtualPrt?._id || cohort.virtualPrt || '');
const hadGroup = Boolean(cohort.whatsappGroupJid);
const previousStart = toYmd(cohort.startDate);
const previousSchedule = String(cohort.scheduleId || '').trim();
const previousSlot = String(cohort.slot || '');
const { startDate, slot, virtualPrt, patients } = request.payload;
const scheduleId = String(request.payload.scheduleId || '').trim();
const scheduleChanged = previousStart !== String(startDate)
|| previousSchedule !== scheduleId
|| previousSlot !== String(slot || '');
const settings = await getAppSettings();
const durationMinutes = request.payload.durationMinutes || settings.defaultDurationMinutes || 60;
await assertConfiguredSlot(slot);
const prt = await assertVirtualPrt(virtualPrt);
const prtLanguages = userLanguages(prt);
if (!prtLanguages.length) throw Boom.badRequest('Assign a language to this Virtual PRT before creating a cohort.');
const language = request.payload.language || prtLanguages[0];
if (!prtLanguages.includes(language)) throw Boom.badRequest('Select a language this Virtual PRT can teach.');
await assertPatients(patients);
if (request.payload.createdAs !== 'manual_cohorts' && patients.length > (settings.maxPatientsPerCohort || 10)) {
throw Boom.badRequest(`A cohort can have at most ${settings.maxPatientsPerCohort || 10} patients.`);
}
try {
await assertCohortStartDate(startDate, virtualPrt, language, startWeekdaysFor(request.payload, await chosenWeekdays(scheduleId)));
} catch (err) {
throw Boom.badRequest(err.message);
}
cohort.name = buildCohortName({ slot, language, startDate });
cohort.startDate = ymdToDate(startDate);
cohort.slot = slot;
cohort.language = language;
cohort.scheduleId = scheduleId;
cohort.diseaseType = request.payload.diseaseType || cohort.diseaseType || '';
if (request.payload.createdAs) cohort.createdAs = request.payload.createdAs;
if (request.payload.sixDayWeek !== undefined) cohort.sixDayWeek = Boolean(request.payload.sixDayWeek);
cohort.virtualPrt = virtualPrt;
cohort.patients = patients;
cohort.durationMinutes = durationMinutes;
if (cohort.status === 'proposed') cohort.status = 'active';
await applyPatientEdits(cohort, request.payload.patientEdits);
const manual = (cohort.createdAs || request.payload.createdAs) === 'manual_cohorts';
let createdIds = [];
if (manual) {
createdIds = await createManualCohortPatients(cohort, request.payload.newPatients, request.auth.credentials.user._id);
if (createdIds.length) cohort.patients = [...patients, ...createdIds];
}
await cohort.save();
const cohortChanged = previousStart !== String(startDate)
|| previousSchedule !== scheduleId
|| previousSlot !== String(slot || '')
|| previousPrtId !== String(virtualPrt || '');
if (cohortChanged) {
await writeAudit(request, { action: 'cohort.saved', resourceType: 'cohort', resourceId: cohort._id });
}
if (previousPrtId !== String(virtualPrt || '')) {
await writeAudit(request, { action: 'cohort.prt_changed', resourceType: 'cohort', resourceId: cohort._id });
}
await auditPatientMembership(request, cohort._id, previous, idList(cohort.patients));
for (const row of request.payload.patientEdits || []) {
if (idList(cohort.patients).includes(String(row.id))) {
await writeAudit(request, { action: 'patient.updated', resourceType: 'onboarding', resourceId: row.id });
}
}
if (manual && createdIds?.length) {
for (const id of createdIds) {
await writeAudit(request, { action: 'patient.created', resourceType: 'onboarding', resourceId: id });
}
}
await syncCohortPatients(cohort, previous);
/* Replaced by applyPatientEdits before the cohort is saved.
for (const row of request.payload.patientOffline || []) {
if (!(cohort.patients || []).some((p) => String(p._id || p) === row.id)) continue; // only patients in this cohort
await OnboardedPatient.updateOne({ _id: row.id }, { $set: { offlineSessions: row.offlineSessions, offlineStartDate: row.offlineStartDate || '' } });
}
*/
const { onCohortUpdated } = await import('../services/whatsapp.js');
await onCohortUpdated(cohort._id, { previousName, previousPrtId, hadGroup }).catch((err) => {
console.error(`[whatsapp] cohort update failed: ${err?.message || err}`);
});
if (scheduleChanged) await rescheduleOpenSessions(cohort);
else if (await CohortSession.countDocuments({ cohort: cohort._id })) await ensureSessionRecords(cohort);
else await persistCohortSessions(cohort);
await startCohortMeetings(cohort);
if ((cohort.createdAs || '') === 'manual_cohorts') await applyCohortToPatients(cohort);
const ready = await Cohort.findById(cohort._id)
.populate('virtualPrt', 'firstName lastName email')
.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
return toCohortDto(ready);
},
});
server.route({
method: 'DELETE',
path: '/api/cohorts/{id}',
options: {
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'delete') }],
validate: { params: Joi.object({ id: objectId.required() }) },
},
handler: async (request) => {
const cohort = await findCohort(request);
await releaseCohortPatients(cohort, request.auth.credentials.user._id);
await CohortSession.deleteMany({ cohort: cohort._id });
await cohort.deleteOne();
return { ok: true };
},
});
server.route({
method: 'POST',
path: '/api/cohorts/{id}/whatsapp/retry',
options: {
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'edit') }],
validate: { params: Joi.object({ id: objectId.required() }) },
},
handler: async (request) => {
const cohort = await findCohort(request);
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);
},
});
server.route({
method: 'POST',
path: '/api/cohorts/{id}/complete',
options: {
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'edit') }],
validate: { params: Joi.object({ id: objectId.required() }) },
},
handler: async (request) => {
const cohort = await findCohort(request);
if (!['active', 'confirmed'].includes(cohort.status)) {
throw Boom.badRequest('Only a live cohort can be completed.');
}
cohort.status = 'completed';
await cohort.save();
const { notifyGroupClosed } = await import('../services/whatsapp.js');
await notifyGroupClosed(cohort._id).catch((err) => {
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);
},
});
server.route({
method: 'POST',
path: '/api/cohorts/{id}/status',
options: {
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'edit') }],
validate: {
params: Joi.object({ id: objectId.required() }),
payload: Joi.object({
status: Joi.string().valid('active', 'completed', 'cancelled').required(),
patientAction: Joi.string().valid('pool', 'move').default('pool'), // cancelled only: where the patients go
targetCohortId: objectId.allow('', null),
force: Joi.boolean().default(false), // move anyway when the target does not match
check: Joi.boolean().default(false), // only return warnings, change nothing
}),
},
},
handler: async (request) => {
const cohort = await findCohort(request);
const { status, patientAction, targetCohortId, force, check } = request.payload;
if (cohort.status === 'proposed') throw Boom.badRequest('Confirm this cohort from Matching first.');
if (check) {
if (status !== 'cancelled') return { warnings: [] };
return cancelCohort(cohort, { patientAction, targetCohortId, check: true });
}
if (cohort.status === status) throw Boom.badRequest(`This cohort is already ${status}.`);
if (status === 'active') {
cohort.status = 'active';
await cohort.save();
await startCohortMeetings(cohort);
} else if (status === 'completed') {
cohort.status = 'completed';
await cohort.save();
const { notifyGroupClosed } = await import('../services/whatsapp.js');
await notifyGroupClosed(cohort._id).catch((err) => {
console.error(`[whatsapp] closing notice failed: ${err?.message || err}`);
});
} else {
await cancelCohort(cohort, { patientAction, targetCohortId, force, actorId: request.auth.credentials.user._id });
}
const ready = await Cohort.findById(cohort._id)
.populate('virtualPrt', 'firstName lastName email')
.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
return (await withSessionCounts(ready))[0];
},
});
}
export function virtualPrtRoutes(server) {
server.route({
method: 'GET',
path: '/api/users/virtual-prts',
options: { pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'view') }] },
handler: async () => {
const role = await Role.findOne({ systemKey: 'educator' });
if (!role) return { items: [] };
const items = await User.find({ role: role._id, isActive: true }).populate('role').sort({ firstName: 1 });
return { items: items.map((u) => ({
id: String(u._id),
firstName: u.firstName,
lastName: u.lastName,
email: u.email,
languages: userLanguages(u),
language: userLanguages(u)[0] || '',
specializations: u.specializations || [],
availableSlots: u.availableSlots || [],
availableStartWeekdays: u.availableStartWeekdays || [],
maxCohorts: u.maxCohorts ?? null,
})) };
},
});
}