VirtualPR/backend/src/services/cohorts.js

195 lines
8.0 KiB
JavaScript

import { Cohort } from '../models/Cohort.js';
import { CohortSession } from '../models/CohortSession.js';
import { OnboardedPatient } from '../models/OnboardedPatient.js';
import { addPatientToWhatsapp, removePatientFromWhatsapp, syncWhatsappMembership } from './whatsapp.js';
import { applyOnboardedPii, hashMobile, isMobileNumber, readOnboardedPii } from './cryptoPii.js';
import { env } from '../config/env.js';
import { toYmd, todayYmd, weekdayOf } from './schedule.js';
import Boom from '@hapi/boom';
async function safeWhatsapp(label, fn) {
try {
await fn();
} catch (err) {
console.error(`[whatsapp] ${label} failed: ${err?.message || err}`);
}
}
export async function syncCohortPatients(cohort, previousPatientIds = []) {
const nextIds = (cohort.patients || []).map((id) => String(id));
const prevIds = (previousPatientIds || []).map((id) => String(id));
if (nextIds.length) {
await OnboardedPatient.updateMany(
{ _id: { $in: nextIds } },
{ $set: { assignedEducator: cohort.virtualPrt, cohort: cohort._id, matchingStatus: 'assigned' } },
);
}
const added = nextIds.filter((id) => !prevIds.includes(id));
if (added.length) {
await OnboardedPatient.updateMany({ _id: { $in: added } }, { $set: { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } });
}
const removed = prevIds.filter((id) => !nextIds.includes(id));
for (const id of removed) {
await CohortSession.updateMany(
{ cohort: cohort._id, status: 'scheduled', date: { $gte: todayYmd(env.APP_TIMEZONE) } },
{ $pull: { records: { patient: id } } },
);
const other = await Cohort.findOne({ _id: { $ne: cohort._id }, patients: id });
if (other) {
await OnboardedPatient.updateOne(
{ _id: id },
{ $set: { assignedEducator: other.virtualPrt, cohort: other._id, matchingStatus: 'assigned' } },
);
} else {
await OnboardedPatient.updateOne(
{ _id: id },
{ $set: { assignedEducator: null, cohort: null, matchingStatus: 'unassigned' } },
);
}
}
if (cohort._id && cohort.virtualPrt) {
await OnboardedPatient.updateMany(
{ cohort: cohort._id },
{ $set: { assignedEducator: cohort.virtualPrt } },
);
}
await safeWhatsapp('membership sync', () => syncWhatsappMembership(cohort, previousPatientIds));
}
export async function addPatientToCohort(cohort, patientId) {
const id = String(patientId);
const current = (cohort.patients || []).map((item) => String(item._id || item));
const joined = !current.includes(id);
if (joined) {
cohort.patients.push(patientId);
await cohort.save();
}
await OnboardedPatient.updateOne(
{ _id: patientId },
{ $set: {
assignedEducator: cohort.virtualPrt,
cohort: cohort._id,
matchingStatus: 'assigned',
...(joined ? { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } : {}),
} },
);
await safeWhatsapp('add patient', () => addPatientToWhatsapp(cohort, patientId));
}
export async function removePatientFromCohort(cohortId, patientId) {
if (!cohortId || !patientId) return;
await Cohort.updateOne({ _id: cohortId }, { $pull: { patients: patientId } });
await CohortSession.updateMany(
{ cohort: cohortId, status: 'scheduled', date: { $gte: todayYmd(env.APP_TIMEZONE) } },
{ $pull: { records: { patient: patientId } } },
);
await safeWhatsapp('remove patient', () => removePatientFromWhatsapp(cohortId, patientId));
}
export async function releaseCohortPatients(cohort) {
const previous = (cohort.patients || []).map((p) => String(p._id || p));
await syncCohortPatients({ ...cohort.toObject?.() || cohort, patients: [] }, previous);
}
// Cohort placement copied onto each patient so the record matches the cohort.
export function cohortPatientFields(cohort) {
const start = toYmd(cohort.startDate);
return {
matchingStatus: 'assigned',
assignedEducator: cohort.virtualPrt?._id || cohort.virtualPrt,
cohort: cohort._id,
slot: cohort.slot || '',
preferredWeekday: start ? weekdayOf(start) : null,
sessionDate: cohort.startDate || null,
sessionLanguage: cohort.language || '',
diseaseType: cohort.diseaseType || '',
};
}
export async function applyCohortToPatients(cohort) {
const ids = (cohort.patients || []).map((item) => item._id || item).filter(Boolean);
if (!ids.length || !cohort._id) return;
await OnboardedPatient.updateMany({ _id: { $in: ids } }, { $set: cohortPatientFields(cohort) });
}
// Saves corrected details for patients already in this cohort. Checks every row first, then saves only fields that changed.
export async function applyPatientEdits(cohort, rows = []) {
const inCohort = new Set((cohort.patients || []).map((p) => String(p._id || p)));
const ready = [];
for (const row of rows) {
if (!inCohort.has(row.id)) continue;
const patient = await OnboardedPatient.findById(row.id);
if (!patient) continue;
const current = readOnboardedPii(patient);
const name = String(row.name ?? '').trim();
const label = name || current.name || 'Patient';
if (!name) throw Boom.badRequest(`${label}: name is required.`);
const fields = {};
if (name !== current.name) fields.name = name;
const mobile = String(row.mobile ?? '').trim();
if (mobile !== current.mobile) {
if (!isMobileNumber(mobile)) throw Boom.badRequest(`${label}: enter a 10 digit mobile.`);
const taken = await OnboardedPatient.findOne({ _id: { $ne: patient._id }, mobileHash: hashMobile(mobile) }).select('_id');
if (taken) throw Boom.badRequest(`${label}: that mobile is already used by another patient.`);
fields.mobile = mobile;
}
const age = row.age === '' || row.age == null ? null : Number(row.age);
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 || '' });
}
for (const { patient, fields, offlineSessions, offlineStartDate } of ready) {
applyOnboardedPii(patient, fields);
patient.offlineSessions = offlineSessions;
patient.offlineStartDate = offlineStartDate;
await patient.save();
}
}
// Creates confirmed patients for a manual cohort and returns their ids.
export async function createManualCohortPatients(cohort, rows, userId) {
const list = (Array.isArray(rows) ? rows : []).map((row) => ({
name: String(row?.name || '').trim(),
mobile: String(row?.mobile || '').trim(),
age: row?.age ?? '',
gender: String(row?.gender || '').trim(),
whatsappOptOut: Boolean(row?.whatsappOptOut),
offlineSessions: Math.max(0, Number(row?.offlineSessions) || 0),
offlineStartDate: String(row?.offlineStartDate || '').trim(),
})).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.');
const hashes = list.map((row) => hashMobile(row.mobile));
if (hashes.some((hash) => !hash)) throw Boom.badRequest('Each patient needs a mobile number.');
if (new Set(hashes).size !== hashes.length) throw Boom.badRequest('Each patient needs a different mobile.');
const taken = await OnboardedPatient.find({ mobileHash: { $in: hashes } }).select('_id');
if (taken.length) throw Boom.badRequest('A patient with that mobile is already in the system.');
const placement = cohortPatientFields(cohort);
const created = [];
try {
for (const row of list) {
const doc = await OnboardedPatient.create({
...applyOnboardedPii({}, row),
...placement,
paymentStatus: 'Paid',
onboardedBy: userId,
reviewStatus: 'confirmed',
reviewedBy: userId,
reviewedAt: new Date(),
whatsappOptOut: row.whatsappOptOut,
offlineSessions: row.offlineSessions,
offlineStartDate: row.offlineStartDate,
});
created.push(doc._id);
}
} catch (err) {
if (created.length) await OnboardedPatient.deleteMany({ _id: { $in: created } });
throw err;
}
return created;
}