import Joi from 'joi'; import { credentials, requirePermission } from '../plugins/auth.js'; import { Cohort } from '../models/Cohort.js'; import { CohortSession } from '../models/CohortSession.js'; import { ReassignmentEvent } from '../models/ReassignmentEvent.js'; import { Role } from '../models/Role.js'; import { User } from '../models/User.js'; import { listOnboardedForReports, patientProgramStats, prtCapacity, countLiveCohorts } from '../services/programSessions.js'; import { getAppSettings } from '../services/settings.js'; import { toYmd } from '../services/schedule.js'; import { toDmy } from '../services/whatsappFormat.js'; import { readOnboardedPii } from '../services/cryptoPii.js'; import { writeAudit } from '../services/audit.js'; import { normalizePatientStatus } from '../utils/serialize.js'; // import { env } from '../config/env.js'; // was for the Recorded at column const objectId = Joi.string().hex().length(24); function scopedPrt(request) { const creds = credentials(request); if (creds.role?.systemKey === 'educator') return String(creds.user._id); return request.query.prt || undefined; } function csvEscape(value) { const text = value == null ? '' : String(value); if (/[",\n]/.test(text)) return `"${text.replace(/"/g, '""')}"`; return text; } function toCsv(rows) { return rows.map((row) => row.map(csvEscape).join(',')).join('\n'); } // P when that patient attended the meeting, A when they did not. function sessionMark(session, patientId) { const record = (session.records || []).find((item) => String(item.patient?._id || item.patient) === patientId); return record?.attended ? 'P' : 'A'; } function sessionRecord(session, patientId) { return (session.records || []).find((item) => String(item.patient?._id || item.patient) === patientId); } /* Was for the Recorded at column. // Date and time in the app's timezone, e.g. 11/11/2026, 6:05 pm. function stamp(value) { return value ? new Date(value).toLocaleString('en-IN', { timeZone: env.APP_TIMEZONE, dateStyle: 'short', timeStyle: 'short' }) : ''; } */ // "120/80" to ['120', '80']; a value without "/" goes in SBP. function bpParts(bp) { const [sbp = '', dbp = ''] = String(bp || '').split('/').map((part) => part.trim()); return [sbp, dbp]; } function vitalValue(value) { return value == null || value === '' ? '' : value; } // Completed sessions per patient across all cohorts, oldest first. async function heldSessionsByPatient(patientIds) { const byPatient = new Map(patientIds.map((id) => [String(id), []])); if (!patientIds.length) return byPatient; const sessions = await CohortSession.find({ 'records.patient': { $in: patientIds }, status: 'completed' }) // .select('cohort index date records.patient records.attended records.pre records.post') // .populate('cohort', 'name') .select('cohort index date coverPrt records.patient records.attended records.pre records.post records.prt records.recordedBy records.recordedAt') .populate('cohort', 'name virtualPrt') .sort({ date: 1, index: 1 }); for (const session of sessions) { for (const record of session.records || []) { const list = byPatient.get(String(record.patient)); if (list) list.push(session); } } return byPatient; } // Each patient's PRT from their last held session in a different cohort than their current one. async function previousPrtNames(patients, held) { const prevPrtIds = new Map(); for (const patient of patients) { const current = String(patient.cohort?._id || ''); const earlier = (held.get(String(patient._id)) || []).filter((session) => String(session.cohort?._id || session.cohort) !== current); const last = earlier[earlier.length - 1]; if (!last) continue; const record = sessionRecord(last, String(patient._id)); const prt = record?.prt || last.coverPrt || last.cohort?.virtualPrt; if (prt) prevPrtIds.set(String(patient._id), String(prt)); } const users = prevPrtIds.size ? await User.find({ _id: { $in: [...new Set(prevPrtIds.values())] } }).select('firstName lastName') : []; const names = new Map(users.map((user) => [String(user._id), `${user.firstName || ''} ${user.lastName || ''}`.trim()])); return new Map([...prevPrtIds].map(([patientId, prtId]) => [patientId, names.get(prtId) || ''])); } const currentPrtName = (patient) => (patient.assignedEducator ? `${patient.assignedEducator.firstName} ${patient.assignedEducator.lastName}` : ''); function patientStatusLabel(patient) { return normalizePatientStatus(patient?.patientStatus) === 'deactivated' ? 'Deactivated' : 'Active'; } export function reportRoutes(server) { server.route({ method: 'GET', path: '/api/reports/patients', options: { pre: [{ method: requirePermission('reports', 'view') }], validate: { query: Joi.object({ prt: objectId, diseaseType: Joi.string().allow('', null), cohortId: objectId, from: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/), to: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/), }), }, }, handler: async (request) => { const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined, cohortId: request.query.cohortId, }); const stats = await patientProgramStats(patients.map((item) => item._id)); return { items: patients.map((patient) => { const progress = stats.get(String(patient._id)) || { attended: 0, completed: 0, firstDate: '', vitals: [] }; const pii = readOnboardedPii(patient); return { id: String(patient._id), name: pii.name, mobile: pii.mobile, diseaseType: patient.diseaseType || '', slot: patient.slot || '', language: patient.sessionLanguage || '', cohort: patient.cohort ? { id: String(patient.cohort._id), name: patient.cohort.name } : null, prt: patient.assignedEducator ? { id: String(patient.assignedEducator._id), firstName: patient.assignedEducator.firstName, lastName: patient.assignedEducator.lastName } : null, firstSession: progress.firstDate || '', completed: progress.completed || 0, // assigned: progress.assigned || 0, // assigned count is off attended: progress.attended, // total: progress.total, // total is off completion: progress.completed ? `${progress.attended}/${progress.completed}` : '0/0', vitals: progress.vitals, }; }), }; }, }); server.route({ method: 'GET', path: '/api/reports/utilization', options: { pre: [{ method: requirePermission('reports', 'view') }], }, handler: async (request) => { const settings = await getAppSettings(); const role = await Role.findOne({ systemKey: 'educator' }); const prtFilter = { role: role?._id, isActive: true }; const scoped = scopedPrt(request); if (scoped) prtFilter._id = scoped; const prts = role ? await User.find(prtFilter).sort({ firstName: 1 }) : []; const cancelled = await CohortSession.countDocuments({ status: 'cancelled' }); const items = []; for (const prt of prts) { const used = await countLiveCohorts(prt._id); const max = prtCapacity(prt, settings); const sessions = await CohortSession.countDocuments({ status: { $in: ['scheduled', 'completed'] } }); const ownCohorts = await Cohort.find({ virtualPrt: prt._id }).select('_id'); const ownIds = ownCohorts.map((item) => item._id); const run = await CohortSession.countDocuments({ cohort: { $in: ownIds }, status: { $in: ['scheduled', 'completed'] } }); const cancelledOwn = await CohortSession.countDocuments({ cohort: { $in: ownIds }, status: 'cancelled' }); items.push({ id: String(prt._id), name: `${prt.firstName} ${prt.lastName}`, used, max, idle: Math.max(0, max - used), sessions: run, cancelled: cancelledOwn, }); } return { items, cancelled, maxPatientsPerCohort: settings.maxPatientsPerCohort }; }, }); server.route({ method: 'GET', path: '/api/reports/productivity', options: { pre: [{ method: requirePermission('reports', 'view') }], validate: { query: Joi.object({ prt: objectId, from: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/), to: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/), }), }, }, handler: async (request) => { const dateFilter = {}; if (request.query.from) dateFilter.$gte = request.query.from; if (request.query.to) dateFilter.$lte = request.query.to; const sessionFilter = { status: 'completed' }; if (Object.keys(dateFilter).length) sessionFilter.date = dateFilter; const sessions = await CohortSession.find(sessionFilter) .populate({ path: 'cohort', populate: { path: 'virtualPrt', select: 'firstName lastName' } }); const scoped = scopedPrt(request); const filtered = sessions.filter((session) => { if (!scoped) return true; return String(session.cohort?.virtualPrt?._id || session.cohort?.virtualPrt) === String(scoped); }); const reassignments = await ReassignmentEvent.find({}) .populate('cohort', 'name') .populate('fromPrt', 'firstName lastName') .populate('toPrt', 'firstName lastName') .sort({ createdAt: -1 }) .limit(50); return { sessionsRun: filtered.length, attendance: filtered.reduce((sum, session) => ( sum + (session.records || []).filter((record) => record.attended).length ), 0), possibleAttendance: filtered.reduce((sum, session) => sum + (session.records || []).length, 0), reassignments: reassignments.map((event) => ({ id: String(event._id), reason: event.reason, status: event.status, date: toYmd(event.createdAt), cohort: event.cohort?.name || '', from: event.fromPrt ? `${event.fromPrt.firstName} ${event.fromPrt.lastName}` : '', to: event.toPrt ? `${event.toPrt.firstName} ${event.toPrt.lastName}` : '', })), }; }, }); server.route({ method: 'GET', path: '/api/reports/export', options: { pre: [{ method: requirePermission('reports', 'view') }], }, handler: async (request, h) => { await writeAudit(request, { action: 'report.export', resourceType: 'report', resourceId: request.query.type || 'patients' }); const type = String(request.query.type || 'patients'); let rows = []; if (type === 'utilization') { const settings = await getAppSettings(); const role = await Role.findOne({ systemKey: 'educator' }); const prtFilter = { role: role?._id, isActive: true }; const scoped = scopedPrt(request); if (scoped) prtFilter._id = scoped; const prts = role ? await User.find(prtFilter).sort({ firstName: 1 }) : []; const items = []; for (const prt of prts) { const used = await countLiveCohorts(prt._id); const max = prtCapacity(prt, settings); const ownCohorts = await Cohort.find({ virtualPrt: prt._id }).select('_id'); const ownIds = ownCohorts.map((item) => item._id); const run = await CohortSession.countDocuments({ cohort: { $in: ownIds }, status: { $in: ['scheduled', 'completed'] } }); const cancelledOwn = await CohortSession.countDocuments({ cohort: { $in: ownIds }, status: 'cancelled' }); items.push([`${prt.firstName} ${prt.lastName}`, prt.email || '', used, max, Math.max(0, max - used), run, cancelledOwn]); } rows = [['PRT', 'Email', 'Used', 'Max', 'Idle', 'Sessions', 'Cancelled'], ...items]; } else if (type === 'vitals') { /* Old: sessions from the current cohort only. const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined }); const cohortIds = [...new Set(patients.map((patient) => patient.cohort?._id).filter(Boolean))]; const sessions = cohortIds.length ? await CohortSession.find({ cohort: { $in: cohortIds }, status: 'completed' }) .select('cohort index date records.patient records.attended records.pre records.post') .sort({ date: 1, index: 1 }) : []; const byCohort = new Map(); for (const session of sessions) { const id = String(session.cohort); const list = byCohort.get(id) || []; list.push(session); byCohort.set(id, list); } const included = patients.filter((patient) => { const cohortId = patient.cohort?._id ? String(patient.cohort._id) : ''; const meetings = cohortId ? (byCohort.get(cohortId) || []) : []; return meetings.some((session) => sessionRecord(session, String(patient._id))); }); const groups = included.map((patient) => { const cohortId = patient.cohort?._id ? String(patient.cohort._id) : ''; const meetings = (cohortId ? (byCohort.get(cohortId) || []) : []) .filter((session) => sessionRecord(session, String(patient._id))); return { patient, meetings }; }); const blank = ['', '', '', '', '', '']; const lines = []; for (const { patient, meetings } of groups) { const pii = readOnboardedPii(patient); const identity = [ pii.name, pii.mobile, patient.diseaseType || '', patient.cohort?.name || '', patient.cohort?.startDate ? toYmd(patient.cohort.startDate) : '', ]; for (const session of meetings) { const record = sessionRecord(session, String(patient._id)); const pre = record?.pre || {}; const post = record?.post || {}; lines.push({ date: session.date, name: pii.name || '', row: [ ...identity, `${session.date} (${sessionMark(session, String(patient._id))})`, vitalValue(pre.bp), vitalValue(pre.spo2), vitalValue(pre.pulse), vitalValue(post.bp), vitalValue(post.spo2), vitalValue(post.pulse), ], }); } } lines.sort((a, b) => a.date.localeCompare(b.date) || a.name.localeCompare(b.name)); rows = [ ['Name', 'Mobile', 'Disease', 'Cohort', 'Start date', 'Session date', 'Pre', '', '', 'Post', '', ''], [...blank, 'BP', 'SpO2', 'Pulse', 'BP', 'SpO2', 'Pulse'], ...lines.map((line) => line.row), ]; */ const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined }); const held = await heldSessionsByPatient(patients.map((item) => item._id)); // const vitals = (record) => [ // vitalValue(record?.pre?.bp), vitalValue(record?.pre?.spo2), vitalValue(record?.pre?.pulse), // vitalValue(record?.post?.bp), vitalValue(record?.post?.spo2), vitalValue(record?.post?.pulse), // ]; const vitals = (record) => [ ...bpParts(record?.pre?.bp), vitalValue(record?.pre?.spo2), vitalValue(record?.pre?.pulse), ...bpParts(record?.post?.bp), vitalValue(record?.post?.spo2), vitalValue(record?.post?.pulse), ]; /* Session PRT and Recorded by names, replaced by Current PRT and Previous PRT. const userIds = new Set(); for (const list of held.values()) { for (const session of list) { if (session.coverPrt) userIds.add(String(session.coverPrt)); if (session.cohort?.virtualPrt) userIds.add(String(session.cohort.virtualPrt)); for (const record of session.records || []) { if (record.prt) userIds.add(String(record.prt)); if (record.recordedBy) userIds.add(String(record.recordedBy)); } } } for (const patient of patients) { for (const record of patient.offlineRecords || []) { if (record.recordedBy) userIds.add(String(record.recordedBy)); } } const users = userIds.size ? await User.find({ _id: { $in: [...userIds] } }).select('firstName lastName') : []; const names = new Map(users.map((user) => [String(user._id), `${user.firstName || ''} ${user.lastName || ''}`.trim()])); const nameOf = (userId) => (userId ? names.get(String(userId)) || '' : ''); */ const previousPrt = await previousPrtNames(patients, held); const lines = []; for (const patient of patients) { const id = String(patient._id); const pii = readOnboardedPii(patient); const base = [pii.name, pii.mobile, patient.diseaseType || '']; const startDate = patient.cohort?.startDate ? toDmy(toYmd(patient.cohort.startDate)) : ''; const offlineCount = Number(patient.offlineSessions) || 0; const offline = new Map((patient.offlineRecords || []).map((record) => [record.number, record])); for (let number = 1; number <= offlineCount; number += 1) { const record = offline.get(number); const date = number === 1 ? toDmy(patient.offlineStartDate) : ''; lines.push({ name: pii.name || '', number, // row: [...base, 'Offline', startDate, number, `${date || 'Offline'} (${record?.attended === false ? 'A' : 'P'})`, ...vitals(record)], // row: [...base, 'Offline', startDate, number, date || 'Offline', record?.attended === false ? 'A' : 'P', ...vitals(record)], // row: [...base, 'Offline', '', startDate, number, date || 'Offline', record?.attended === false ? 'A' : 'P', ...vitals(record), nameOf(record?.recordedBy), stamp(record?.recordedAt)], // row: [...base, 'Offline', currentPrtName(patient), previousPrt.get(id) || '', startDate, number, date || 'Offline', record?.attended === false ? 'A' : 'P', ...vitals(record)], row: [...base, 'Offline', '', '', startDate, number, date || 'Offline', record?.attended === false ? 'A' : 'P', ...vitals(record)], }); } (held.get(id) || []).forEach((session, index) => { const number = offlineCount + index + 1; lines.push({ name: pii.name || '', number, // row: [...base, session.cohort?.name || '', startDate, number, `${session.date} (${sessionMark(session, id)})`, ...vitals(sessionRecord(session, id))], // row: [...base, session.cohort?.name || '', startDate, number, session.date, sessionMark(session, id), ...vitals(sessionRecord(session, id))], /* Row with session PRT and Recorded by / at. row: [ ...base, session.cohort?.name || '', nameOf(sessionRecord(session, id)?.prt || session.coverPrt || session.cohort?.virtualPrt), startDate, number, session.date, sessionMark(session, id), ...vitals(sessionRecord(session, id)), nameOf(sessionRecord(session, id)?.recordedBy), stamp(sessionRecord(session, id)?.recordedAt), ], */ row: [...base, session.cohort?.name || '', currentPrtName(patient), previousPrt.get(id) || '', startDate, number, toDmy(session.date), sessionMark(session, id), ...vitals(sessionRecord(session, id))], }); }); } lines.sort((a, b) => a.name.localeCompare(b.name) || a.number - b.number); // rows = [ // ['Name', 'Mobile', 'Disease', 'Cohort', 'Start date', 'Session', 'Session date', 'Pre', '', '', 'Post', '', ''], // ['', '', '', '', '', '', '', 'BP', 'SpO2', 'Pulse', 'BP', 'SpO2', 'Pulse'], // ...lines.map((line) => line.row), // ]; // rows = [ // ['Name', 'Mobile', 'Disease', 'Cohort', 'Start date', 'Session', 'Session date', 'Attendance', // 'Pre-SBP', 'Pre-DBP', 'Pre-SpO2', 'Pre-Pulse', 'Post-SBP', 'Post-DBP', 'Post-SpO2', 'Post-Pulse'], // ...lines.map((line) => line.row), // ]; // rows = [ // ['Name', 'Mobile', 'Disease', 'Cohort', 'PRT', 'Start date', 'Session', 'Session date', 'Attendance', // 'Pre-SBP', 'Pre-DBP', 'Pre-SpO2', 'Pre-Pulse', 'Post-SBP', 'Post-DBP', 'Post-SpO2', 'Post-Pulse', 'Recorded by', 'Recorded at'], // ...lines.map((line) => line.row), // ]; rows = [ ['Name', 'Mobile', 'Disease', 'Cohort', 'Current PRT', 'Previous PRT', 'Start date', 'Session', 'Session date', 'Attendance', 'Pre-SBP', 'Pre-DBP', 'Pre-SpO2', 'Pre-Pulse', 'Post-SBP', 'Post-DBP', 'Post-SpO2', 'Post-Pulse'], ...lines.map((line) => line.row), ]; } else { /* Old: sessions from the current cohort only. const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined }); const cohortIds = [...new Set(patients.map((patient) => patient.cohort?._id).filter(Boolean))]; const sessions = cohortIds.length ? await CohortSession.find({ cohort: { $in: cohortIds }, status: 'completed' }) .select('cohort index date records.patient records.attended') .sort({ index: 1, date: 1 }) : []; const byCohort = new Map(); for (const session of sessions) { const id = String(session.cohort); const list = byCohort.get(id) || []; list.push(session); byCohort.set(id, list); } const stats = await patientProgramStats(patients.map((item) => item._id)); const widest = [...byCohort.values()].reduce((max, list) => Math.max(max, list.length), 0); const headers = ['Name', 'Mobile', 'Disease', 'Cohort', 'PRT', 'Start date', 'First session', 'Completed', ('Assigned' was here) ...Array.from({ length: widest }, (_, index) => `Session ${index + 1}`)]; rows = [headers, ...patients.map((patient) => { const pii = readOnboardedPii(patient); const progress = stats.get(String(patient._id)) || {}; const cohortId = patient.cohort?._id ? String(patient.cohort._id) : ''; const meetings = (cohortId ? (byCohort.get(cohortId) || []) : []) .filter((session) => sessionRecord(session, String(patient._id))); const marks = meetings.map((session) => sessionMark(session, String(patient._id))); while (marks.length < widest) marks.push(''); // shorter cohorts leave the extra session cells blank return [ pii.name, pii.mobile, patient.diseaseType || '', patient.cohort?.name || '', patient.assignedEducator ? `${patient.assignedEducator.firstName} ${patient.assignedEducator.lastName}` : '', patient.cohort?.startDate ? toYmd(patient.cohort.startDate) : '', progress.firstDate || '', progress.completed || 0, // progress.assigned || 0, // assigned count is off ...marks, ]; })]; */ const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined }); const held = await heldSessionsByPatient(patients.map((item) => item._id)); const stats = await patientProgramStats(patients.map((item) => item._id)); /* Moved into previousPrtNames so the vitals CSV can use it too. const prevPrtIds = new Map(); for (const patient of patients) { const current = String(patient.cohort?._id || ''); const earlier = (held.get(String(patient._id)) || []).filter((session) => String(session.cohort?._id || session.cohort) !== current); const last = earlier[earlier.length - 1]; if (!last) continue; const record = sessionRecord(last, String(patient._id)); const prt = record?.prt || last.coverPrt || last.cohort?.virtualPrt; if (prt) prevPrtIds.set(String(patient._id), String(prt)); } const prevUsers = prevPrtIds.size ? await User.find({ _id: { $in: [...new Set(prevPrtIds.values())] } }).select('firstName lastName') : []; const prevNames = new Map(prevUsers.map((user) => [String(user._id), `${user.firstName || ''} ${user.lastName || ''}`.trim()])); */ const previousPrt = await previousPrtNames(patients, held); const allMarks = patients.map((patient) => { const offline = new Map((patient.offlineRecords || []).map((record) => [record.number, record])); return [ // ...Array.from({ length: Number(patient.offlineSessions) || 0 }, () => 'Offline'), ...Array.from({ length: Number(patient.offlineSessions) || 0 }, (_, i) => (offline.get(i + 1)?.attended === false ? 'A' : 'P')), ...(held.get(String(patient._id)) || []).map((session) => sessionMark(session, String(patient._id))), ]; }); const widest = allMarks.reduce((max, marks) => Math.max(max, marks.length), 0); const headers = [ // 'Name', 'Mobile', 'Disease', 'Cohort', 'PRT', 'Name', 'Mobile', 'Disease', 'Cohort', 'Status', 'Current PRT', 'Previous PRT', 'Start date', 'First session', 'Completed', ...Array.from({ length: widest }, (_, index) => `Session ${index + 1}`), ]; rows = [headers, ...patients.map((patient, index) => { const pii = readOnboardedPii(patient); const progress = stats.get(String(patient._id)) || {}; const marks = [...allMarks[index]]; while (marks.length < widest) marks.push(''); // patients with fewer sessions leave the extra cells blank return [ pii.name, pii.mobile, patient.diseaseType || '', patient.cohort?.name || '', patientStatusLabel(patient), patient.assignedEducator ? `${patient.assignedEducator.firstName} ${patient.assignedEducator.lastName}` : '', // prevNames.get(prevPrtIds.get(String(patient._id))) || '', previousPrt.get(String(patient._id)) || '', patient.cohort?.startDate ? toDmy(toYmd(patient.cohort.startDate)) : '', progress.firstDate ? toDmy(progress.firstDate) : '', progress.completed || 0, ...marks, ]; })]; } return h.response(toCsv(rows)) .type('text/csv') .header('content-disposition', `attachment; filename="${type}-report.csv"`); }, }); }