diff --git a/backend/src/routes/onboarding.js b/backend/src/routes/onboarding.js index 0bc95ef..0273e4b 100644 --- a/backend/src/routes/onboarding.js +++ b/backend/src/routes/onboarding.js @@ -18,6 +18,7 @@ import { notifyPaymentReview } from '../services/notify.js'; import { attendanceProgress, ensureSessionRecords, patientProgramStats, patientVitalsRows, savePatientVitals } from '../services/programSessions.js'; import { assertConfiguredSlot, getAppSettings, slotLabel } from '../services/settings.js'; import { toYmd, weekdayOf } from '../services/schedule.js'; +import { toDmy } from '../services/whatsappFormat.js'; const objectId = Joi.string().hex().length(24); function textField(payload, key) { @@ -224,6 +225,52 @@ function mergeFilters(...parts) { return { $and: filters }; } +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'); +} + +function patientStatusLabel(status) { + return normalizePatientStatus(status) === 'deactivated' ? 'Deactivated' : 'Active'; +} + +async function onboardingListFilter(request) { + const { search = '', reviewStatus, list, paymentStatus, diseaseType, onboardedBy } = request.query; + const extra = {}; + if (reviewStatus) extra.reviewStatus = reviewStatus; + if (list === 'pending') extra.reviewStatus = 'pending'; + if (list === 'confirmed') extra.reviewStatus = 'confirmed'; + if (list === 'rejected') extra.reviewStatus = 'rejected'; + if (list === 'assigned') { + extra.reviewStatus = 'confirmed'; + extra.matchingStatus = 'assigned'; + } + if (list === 'pool') { + extra.reviewStatus = 'confirmed'; + extra.matchingStatus = { $in: ['unassigned', 'held'] }; + extra.cohort = null; + } + if (paymentStatus) extra.paymentStatus = String(paymentStatus).trim(); + if (diseaseType) extra.diseaseType = String(diseaseType).trim(); + if (onboardedBy && objectId.validate(onboardedBy).error == null) extra.onboardedBy = onboardedBy; + const searchFilter = {}; + if (search) { + const term = String(search).trim(); + const mobileHash = hashMobile(term); + const nameHash = hashName(term); + searchFilter.$or = []; + if (mobileHash) searchFilter.$or.push({ mobileHash }); + if (nameHash) searchFilter.$or.push({ nameHash }); + if (!searchFilter.$or.length) searchFilter.$or.push({ _id: null }); + } + return mergeFilters(await onboardingScopeFilter(request), extra, searchFilter); +} + async function findOnboarded(request) { const item = await OnboardedPatient.findOne(mergeFilters( { _id: request.params.id }, @@ -242,35 +289,8 @@ export function onboardingRoutes(server) { path: '/api/onboarding', options: { pre: [{ method: requirePermission('onboarding', 'view') }] }, handler: async (request) => { - const { search = '', page = 1, limit = 20, reviewStatus, list, paymentStatus, diseaseType, onboardedBy } = request.query; - const extra = {}; - if (reviewStatus) extra.reviewStatus = reviewStatus; - if (list === 'pending') extra.reviewStatus = 'pending'; - if (list === 'confirmed') extra.reviewStatus = 'confirmed'; - if (list === 'rejected') extra.reviewStatus = 'rejected'; - if (list === 'assigned') { - extra.reviewStatus = 'confirmed'; - extra.matchingStatus = 'assigned'; - } - if (list === 'pool') { - extra.reviewStatus = 'confirmed'; - extra.matchingStatus = { $in: ['unassigned', 'held'] }; - extra.cohort = null; - } - if (paymentStatus) extra.paymentStatus = String(paymentStatus).trim(); - if (diseaseType) extra.diseaseType = String(diseaseType).trim(); - if (onboardedBy && objectId.validate(onboardedBy).error == null) extra.onboardedBy = onboardedBy; - const searchFilter = {}; - if (search) { - const term = String(search).trim(); - const mobileHash = hashMobile(term); - const nameHash = hashName(term); - searchFilter.$or = []; - if (mobileHash) searchFilter.$or.push({ mobileHash }); - if (nameHash) searchFilter.$or.push({ nameHash }); - if (!searchFilter.$or.length) searchFilter.$or.push({ _id: null }); - } - const filter = mergeFilters(await onboardingScopeFilter(request), extra, searchFilter); + const { page = 1, limit = 20 } = request.query; + const filter = await onboardingListFilter(request); const skip = (Number(page) - 1) * Number(limit); const [items, total] = await Promise.all([ OnboardedPatient.find(filter) @@ -303,6 +323,46 @@ export function onboardingRoutes(server) { }, }); + server.route({ + method: 'GET', + path: '/api/onboarding/export', + options: { pre: [{ method: requirePermission('onboarding', 'view') }] }, + handler: async (request, h) => { + await writeAudit(request, { action: 'onboarding.exported', resourceType: 'onboardedPatient', resourceId: '' }); + const items = await OnboardedPatient.find(await onboardingListFilter(request)) + .populate('onboardedBy', 'firstName lastName email') + .populate('cohort', 'name startDate slot language') + .sort({ createdAt: -1 }); + const stats = await patientProgramStats(items.map((item) => item._id)); + const rows = [ + ['Patient ID', 'Name', 'Mobile', 'Cohort', 'Category', 'Start date', 'Slot', 'Payment', 'Sessions completed', 'Sessions paid', 'Patient status', 'Review', 'Added by'], + ...items.map((item) => { + const patient = toOnboardedPatientDto(item); + const progress = stats.get(String(item._id)) || {}; + const start = progress.firstDate || patient.cohort?.startDate || (patient.sessionDate ? toYmd(patient.sessionDate) : ''); + return [ + patient.id, + patient.name, + patient.mobile, + patient.cohort?.name || (patient.matchingStatus === 'held' ? 'Held' : 'Pool'), + patient.diseaseType, + start ? toDmy(start) : '', + patient.slot, + patient.paymentStatus, + progress.completed || 0, + patient.sessionsPaid, + patientStatusLabel(patient.patientStatus), + patient.reviewStatus === 'confirmed' ? 'Confirmed' : (patient.reviewStatus === 'rejected' ? 'Rejected' : 'Pending'), + patient.onboardedBy ? `${patient.onboardedBy.firstName || ''} ${patient.onboardedBy.lastName || ''}`.trim() : '', + ]; + }), + ]; + return h.response(toCsv(rows)) + .type('text/csv') + .header('content-disposition', 'attachment; filename="patients.csv"'); + }, + }); + server.route({ method: 'GET', path: '/api/onboarding/available-cohorts', diff --git a/backend/src/routes/reports.js b/backend/src/routes/reports.js index 1534c9e..64d268e 100644 --- a/backend/src/routes/reports.js +++ b/backend/src/routes/reports.js @@ -11,6 +11,7 @@ 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); @@ -96,6 +97,10 @@ async function previousPrtNames(patients, held) { 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', @@ -497,7 +502,7 @@ export function reportRoutes(server) { const widest = allMarks.reduce((max, marks) => Math.max(max, marks.length), 0); const headers = [ // 'Name', 'Mobile', 'Disease', 'Cohort', 'PRT', - 'Name', 'Mobile', 'Disease', 'Cohort', 'Current PRT', + 'Name', 'Mobile', 'Disease', 'Cohort', 'Status', 'Current PRT', 'Previous PRT', 'Start date', 'First session', 'Completed', ...Array.from({ length: widest }, (_, index) => `Session ${index + 1}`), ]; @@ -511,6 +516,7 @@ export function reportRoutes(server) { 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)) || '', diff --git a/frontend/src/components/CohortStatusField.jsx b/frontend/src/components/CohortStatusField.jsx index d6fa60b..5715122 100644 --- a/frontend/src/components/CohortStatusField.jsx +++ b/frontend/src/components/CohortStatusField.jsx @@ -36,7 +36,11 @@ export default function CohortStatusField({ cohortId, value, onChange }) { {value.patientAction === 'move' ? ( ) : null} diff --git a/frontend/src/views/virtualpr/cohorts/form.jsx b/frontend/src/views/virtualpr/cohorts/form.jsx index 30d12f5..685c9fb 100644 --- a/frontend/src/views/virtualpr/cohorts/form.jsx +++ b/frontend/src/views/virtualpr/cohorts/form.jsx @@ -256,7 +256,7 @@ export default function CohortForm() { /> {isEdit && statusValue && statusValue.original !== 'proposed' ? ( - + ) : null} diff --git a/frontend/src/views/virtualpr/cohorts/prt-form.jsx b/frontend/src/views/virtualpr/cohorts/prt-form.jsx index d141996..a2206fb 100644 --- a/frontend/src/views/virtualpr/cohorts/prt-form.jsx +++ b/frontend/src/views/virtualpr/cohorts/prt-form.jsx @@ -319,7 +319,7 @@ export default function PrtCohortForm() { /> {isEdit && statusValue && statusValue.original !== 'proposed' ? ( - + ) : null} diff --git a/frontend/src/views/virtualpr/onboarding/index.jsx b/frontend/src/views/virtualpr/onboarding/index.jsx index d4ff750..714ac96 100644 --- a/frontend/src/views/virtualpr/onboarding/index.jsx +++ b/frontend/src/views/virtualpr/onboarding/index.jsx @@ -52,7 +52,12 @@ async function loadScreenshot(id) { return { url: URL.createObjectURL(blob), blob: true }; } -const emptyMigrate = { id: '', cohortId: '', warnings: [], error: '', busy: false }; +const emptyMigrate = { id: '', cohortId: '', prtId: '', warnings: [], error: '', busy: false }; + +function prtName(prt) { + if (!prt) return ''; + return `${prt.firstName || ''} ${prt.lastName || ''}`.trim(); +} export default function OnboardingPage() { const { can, permissions, user } = useAuth(); @@ -75,6 +80,7 @@ export default function OnboardingPage() { const [migrate, setMigrate] = useState(emptyMigrate); const [vitalsPatient, setVitalsPatient] = useState(null); const [cohorts, setCohorts] = useState([]); + const [prts, setPrts] = useState([]); const [deleteId, setDeleteId] = useState(null); const [busyId, setBusyId] = useState(null); const [receipt, setReceipt] = useState({ url: '', title: '', loading: false }); @@ -119,8 +125,14 @@ export default function OnboardingPage() { useEffect(() => { if (!canReview) return; api('/api/onboarding/available-cohorts').then((data) => setCohorts(data.items || [])).catch(() => {}); + api('/api/users/virtual-prts').then((data) => setPrts(data.items || [])).catch(() => {}); }, [canReview]); + const moveCohorts = useMemo(() => { + if (!migrate.prtId) return cohorts; + return cohorts.filter((cohort) => cohort.virtualPrt?.id === migrate.prtId); + }, [cohorts, migrate.prtId]); + const closeReceipt = () => { if (receipt.blob && receipt.url) URL.revokeObjectURL(receipt.url); setReceipt({ url: '', title: '', loading: false, blob: false }); @@ -326,6 +338,36 @@ export default function OnboardingPage() { ))} + {can('onboarding', 'add') ? ( Add patient @@ -416,10 +458,27 @@ export default function OnboardingPage() {
Move patient
{migrate.error ?
{migrate.error}
: null} + +
The patient takes this cohort's slot, day and PRT.
{migrate.warnings.length ? ( diff --git a/frontend/src/views/virtualpr/program-sessions/index.jsx b/frontend/src/views/virtualpr/program-sessions/index.jsx index d689e59..7bb7fb0 100644 --- a/frontend/src/views/virtualpr/program-sessions/index.jsx +++ b/frontend/src/views/virtualpr/program-sessions/index.jsx @@ -41,6 +41,7 @@ export default function ProgramSessionsPage() { Date + PRT Cohort Slot Status @@ -52,6 +53,7 @@ export default function ProgramSessionsPage() { {items.map((session) => ( {showDate(session.date)} #{session.index} + {[session.cohort?.virtualPrt?.firstName, session.cohort?.virtualPrt?.lastName].filter(Boolean).join(' ') || '—'} {session.cohort?.name || '—'} {session.slot} {session.status} @@ -89,7 +91,7 @@ export default function ProgramSessionsPage() { ))} - {!items.length ? No sessions this week. : null} + {!items.length ? No sessions this week. : null}