From 9cddf60047551ba41c71e89d9320116901a4d90b Mon Sep 17 00:00:00 2001 From: Abhijit Date: Wed, 11 Nov 2026 19:04:03 +0530 Subject: [PATCH] changes 11-11-report changes and some fields editable --- backend/src/models/CohortSession.js | 3 + backend/src/models/OnboardedPatient.js | 2 + backend/src/routes/cohorts.js | 29 +++- backend/src/routes/onboarding.js | 3 +- backend/src/routes/programSessions.js | 11 +- backend/src/routes/reports.js | 148 ++++++++++++++++-- backend/src/services/cohorts.js | 37 ++++- backend/src/services/programSessions.js | 17 +- backend/src/utils/serialize.js | 4 +- .../src/components/PatientVitalsModal.jsx | 35 ++++- .../src/components/SessionVitalsModal.jsx | 87 +++++++++- .../src/views/virtualpr/cohorts/prt-form.jsx | 82 +++++++--- 12 files changed, 395 insertions(+), 63 deletions(-) diff --git a/backend/src/models/CohortSession.js b/backend/src/models/CohortSession.js index 7be5faf..8630873 100644 --- a/backend/src/models/CohortSession.js +++ b/backend/src/models/CohortSession.js @@ -32,6 +32,9 @@ const sessionRecordSchema = new mongoose.Schema( pre: { type: vitalsSchema, default: () => ({}) }, post: { type: vitalsSchema, default: () => ({}) }, assessment: { type: assessmentSchema, default: () => ({}) }, + prt: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null }, // PRT running the session when vitals were saved + recordedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null }, // user who last saved this patient's vitals + recordedAt: { type: Date, default: null }, // when this patient's vitals were last saved }, { _id: false }, ); diff --git a/backend/src/models/OnboardedPatient.js b/backend/src/models/OnboardedPatient.js index 53d3331..1c8d9ad 100644 --- a/backend/src/models/OnboardedPatient.js +++ b/backend/src/models/OnboardedPatient.js @@ -16,6 +16,8 @@ const offlineRecordSchema = new mongoose.Schema( pre: { type: offlineVitalsSchema, default: () => ({}) }, post: { type: offlineVitalsSchema, default: () => ({}) }, assessment: { type: mongoose.Schema.Types.Mixed, default: () => ({}) }, + recordedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null }, // user who last saved this offline session + recordedAt: { type: Date, default: null }, // when this offline session was last saved }, { _id: false }, ); diff --git a/backend/src/routes/cohorts.js b/backend/src/routes/cohorts.js index b1e7e9d..28c8b96 100644 --- a/backend/src/routes/cohorts.js +++ b/backend/src/routes/cohorts.js @@ -7,7 +7,7 @@ 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, createManualCohortPatients } from '../services/cohorts.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'; @@ -37,6 +37,22 @@ const cohortPayload = Joi.object({ 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. @@ -96,7 +112,9 @@ async function withSessionCounts(cohorts) { 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' }); + // .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; } @@ -286,6 +304,7 @@ export function cohortRoutes(server) { 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'; if (manual) { const createdIds = await createManualCohortPatients(cohort, request.payload.newPatients, request.auth.credentials.user._id); @@ -293,6 +312,12 @@ export function cohortRoutes(server) { } await cohort.save(); 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}`); diff --git a/backend/src/routes/onboarding.js b/backend/src/routes/onboarding.js index bd52e96..bd817ea 100644 --- a/backend/src/routes/onboarding.js +++ b/backend/src/routes/onboarding.js @@ -671,7 +671,8 @@ export function onboardingRoutes(server) { }, handler: async (request) => { const item = await findOnboarded(request); - return { items: await savePatientVitals(item._id, request.payload.rows) }; + // return { items: await savePatientVitals(item._id, request.payload.rows) }; + return { items: await savePatientVitals(item._id, request.payload.rows, credentials(request).user._id) }; }, }); diff --git a/backend/src/routes/programSessions.js b/backend/src/routes/programSessions.js index e07a170..16bf5a1 100644 --- a/backend/src/routes/programSessions.js +++ b/backend/src/routes/programSessions.js @@ -168,13 +168,13 @@ export function programSessionRoutes(server) { attended: Joi.boolean(), pre: Joi.object({ bp: Joi.string().allow('', null), - spo2: Joi.number().allow(null), - pulse: Joi.number().allow(null), + spo2: Joi.number().allow(null, ''), // '' clears the saved value + pulse: Joi.number().allow(null, ''), }), post: Joi.object({ bp: Joi.string().allow('', null), - spo2: Joi.number().allow(null), - pulse: Joi.number().allow(null), + spo2: Joi.number().allow(null, ''), + pulse: Joi.number().allow(null, ''), }), assessment: Joi.object({ fev1: Joi.string().allow('', null), @@ -195,7 +195,8 @@ export function programSessionRoutes(server) { handler: async (request) => { const session = await findScopedSession(request); if (session.status === 'cancelled') throw Boom.badRequest('Cannot record vitals on a cancelled session.'); - const saved = await saveSessionRecords(session, request.payload.records, { completed: request.payload.completed }); + // const saved = await saveSessionRecords(session, request.payload.records, { completed: request.payload.completed }); + const saved = await saveSessionRecords(session, request.payload.records, { completed: request.payload.completed, userId: credentials(request).user._id }); await saved.populate('records.patient', 'name mobile'); await saved.populate({ path: 'cohort', populate: { path: 'virtualPrt', select: 'firstName lastName email' } }); return toCohortSessionDto(saved, await patientSessionNumbers([saved])); diff --git a/backend/src/routes/reports.js b/backend/src/routes/reports.js index 09b71d1..d6cba9d 100644 --- a/backend/src/routes/reports.js +++ b/backend/src/routes/reports.js @@ -10,6 +10,7 @@ import { getAppSettings } from '../services/settings.js'; import { toYmd } from '../services/schedule.js'; import { readOnboardedPii } from '../services/cryptoPii.js'; import { writeAudit } from '../services/audit.js'; +// import { env } from '../config/env.js'; // was for the Recorded at column const objectId = Joi.string().hex().length(24); @@ -39,6 +40,19 @@ 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; } @@ -48,8 +62,10 @@ 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 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 || []) { @@ -60,6 +76,25 @@ async function heldSessionsByPatient(patientIds) { 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}` : ''); + export function reportRoutes(server) { server.route({ method: 'GET', @@ -294,10 +329,36 @@ export function reportRoutes(server) { */ 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) => [ - vitalValue(record?.pre?.bp), vitalValue(record?.pre?.spo2), vitalValue(record?.pre?.pulse), - vitalValue(record?.post?.bp), vitalValue(record?.post?.spo2), vitalValue(record?.post?.pulse), + ...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); @@ -312,7 +373,11 @@ export function reportRoutes(server) { 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)], + // 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) => { @@ -320,14 +385,45 @@ export function reportRoutes(server) { 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: [...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, 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', 'Start date', 'Session', 'Session date', 'Pre', '', '', 'Post', '', ''], - ['', '', '', '', '', '', '', 'BP', 'SpO2', 'Pulse', 'BP', 'SpO2', 'Pulse'], + ['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 { @@ -374,12 +470,36 @@ export function reportRoutes(server) { 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)); - const allMarks = patients.map((patient) => [ - ...Array.from({ length: Number(patient.offlineSessions) || 0 }, () => 'Offline'), - ...(held.get(String(patient._id)) || []).map((session) => sessionMark(session, String(patient._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', 'Start date', 'First session', 'Completed', ...Array.from({ length: widest }, (_, index) => `Session ${index + 1}`)]; + const headers = [ + // 'Name', 'Mobile', 'Disease', 'Cohort', 'PRT', + 'Name', 'Mobile', 'Disease', 'Cohort', '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)) || {}; @@ -391,6 +511,8 @@ export function reportRoutes(server) { patient.diseaseType || '', patient.cohort?.name || '', patient.assignedEducator ? `${patient.assignedEducator.firstName} ${patient.assignedEducator.lastName}` : '', + // prevNames.get(prevPrtIds.get(String(patient._id))) || '', + previousPrt.get(String(patient._id)) || '', patient.cohort?.startDate ? toYmd(patient.cohort.startDate) : '', progress.firstDate || '', progress.completed || 0, diff --git a/backend/src/services/cohorts.js b/backend/src/services/cohorts.js index 3010f30..05715ac 100644 --- a/backend/src/services/cohorts.js +++ b/backend/src/services/cohorts.js @@ -2,7 +2,7 @@ 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 } from './cryptoPii.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'; @@ -115,6 +115,41 @@ export async function applyCohortToPatients(cohort) { 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) => ({ diff --git a/backend/src/services/programSessions.js b/backend/src/services/programSessions.js index bbfa477..016bb12 100644 --- a/backend/src/services/programSessions.js +++ b/backend/src/services/programSessions.js @@ -768,8 +768,11 @@ export async function patientSessionNumbers(sessions) { return numbers; } -export async function saveSessionRecords(session, records = [], { completed } = {}) { +// export async function saveSessionRecords(session, records = [], { completed } = {}) { +export async function saveSessionRecords(session, records = [], { completed, userId } = {}) { const numbers = await patientSessionNumbers([session]); + let prtId = session.coverPrt?._id || session.coverPrt || session.cohort?.virtualPrt?._id || session.cohort?.virtualPrt || null; + if (!prtId) prtId = (await Cohort.findById(session.cohort?._id || session.cohort).select('virtualPrt'))?.virtualPrt || null; const byPatient = new Map((session.records || []).map((record) => [String(record.patient._id || record.patient), record])); for (const incoming of records) { const id = String(incoming.patientId || incoming.patient); @@ -804,6 +807,9 @@ export async function saveSessionRecords(session, records = [], { completed } = o2WithExercise: incoming.assessment.o2WithExercise ?? previous.o2WithExercise ?? '', }; } + current.prt = prtId; + if (userId) current.recordedBy = userId; + current.recordedAt = new Date(); byPatient.set(id, current); } session.records = [...byPatient.values()]; @@ -979,7 +985,8 @@ export async function patientVitalsRows(patientId) { } // Saves one patient's vitals rows: offline rows on the patient, online rows through saveSessionRecords. -export async function savePatientVitals(patientId, rows = []) { +// export async function savePatientVitals(patientId, rows = []) { +export async function savePatientVitals(patientId, rows = [], userId = null) { const patient = await OnboardedPatient.findById(patientId); if (!patient) return null; const offlineCount = Number(patient.offlineSessions) || 0; @@ -988,13 +995,15 @@ export async function savePatientVitals(patientId, rows = []) { if (row.kind === 'offline') { const number = Number(row.number); if (!(number >= 1 && number <= offlineCount)) continue; - offline.set(number, { number, attended: row.attended !== false, pre: vitalsIn(row.pre), post: vitalsIn(row.post), assessment: row.assessment || {} }); + // offline.set(number, { number, attended: row.attended !== false, pre: vitalsIn(row.pre), post: vitalsIn(row.post), assessment: row.assessment || {} }); + offline.set(number, { number, attended: row.attended !== false, pre: vitalsIn(row.pre), post: vitalsIn(row.post), assessment: row.assessment || {}, recordedBy: userId, recordedAt: new Date() }); continue; } if (!row.sessionId) continue; const session = await CohortSession.findOne({ _id: row.sessionId, 'records.patient': patient._id, status: 'completed' }); if (!session) continue; - await saveSessionRecords(session, [{ patientId: String(patient._id), attended: Boolean(row.attended), pre: row.pre, post: row.post, assessment: row.assessment }]); + // await saveSessionRecords(session, [{ patientId: String(patient._id), attended: Boolean(row.attended), pre: row.pre, post: row.post, assessment: row.assessment }]); + await saveSessionRecords(session, [{ patientId: String(patient._id), attended: Boolean(row.attended), pre: row.pre, post: row.post, assessment: row.assessment }], { userId }); } patient.offlineRecords = [...offline.values()].sort((a, b) => a.number - b.number); await patient.save(); diff --git a/backend/src/utils/serialize.js b/backend/src/utils/serialize.js index 514a3be..7824725 100644 --- a/backend/src/utils/serialize.js +++ b/backend/src/utils/serialize.js @@ -266,7 +266,9 @@ export function toCohortDto(cohort) { virtualPrt: userBrief(cohort.virtualPrt), patients: patients.map((p) => ( 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) } + // ? { 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) } )), patientCount: patients.length, diff --git a/frontend/src/components/PatientVitalsModal.jsx b/frontend/src/components/PatientVitalsModal.jsx index b254fd7..d814ad4 100644 --- a/frontend/src/components/PatientVitalsModal.jsx +++ b/frontend/src/components/PatientVitalsModal.jsx @@ -1,6 +1,7 @@ import { useEffect, useState } from 'react'; import { Button, Col, FormCheck, FormControl, Modal, ModalBody, ModalFooter, ModalHeader, Row } from 'react-bootstrap'; -import { ASSESSMENT_FIELDS } from '@/components/SessionVitalsModal'; +// import { ASSESSMENT_FIELDS } from '@/components/SessionVitalsModal'; +import { ASSESSMENT_FIELDS, BpInput, emptyAssessment, splitBp, vitalsPayload } from '@/components/SessionVitalsModal'; import { api } from '@/lib/api'; const blank = (value) => (value == null ? '' : value); @@ -18,7 +19,14 @@ export default function PatientVitalsModal({ patient, onClose }) { setLoading(true); setError(''); api(`/api/onboarding/${patient.id}/vitals`).then((data) => { - if (active) setRows(data.items || []); + // if (active) setRows(data.items || []); + if (active) { + setRows((data.items || []).map((row) => ({ + ...row, + pre: { ...row.pre, ...splitBp(row.pre?.bp) }, + post: { ...row.post, ...splitBp(row.post?.bp) }, + }))); + } }).catch((err) => { if (active) setError(err.message); }).finally(() => { @@ -33,7 +41,17 @@ export default function PatientVitalsModal({ patient, onClose }) { setSaving(true); setError(''); try { - await api(`/api/onboarding/${patient.id}/vitals`, { method: 'PUT', body: { rows } }); + // await api(`/api/onboarding/${patient.id}/vitals`, { method: 'PUT', body: { rows } }); + const payload = rows.map((row) => ({ + kind: row.kind, + number: row.number, + sessionId: row.sessionId, + attended: Boolean(row.attended), + pre: row.attended ? vitalsPayload(row.pre) : vitalsPayload({}), + post: row.attended ? vitalsPayload(row.post) : vitalsPayload({}), + assessment: row.attended ? row.assessment || {} : emptyAssessment(), + })); + await api(`/api/onboarding/${patient.id}/vitals`, { method: 'PUT', body: { rows: payload } }); onClose(); } catch (err) { setError(err.message); @@ -63,9 +81,12 @@ export default function PatientVitalsModal({ patient, onClose }) {
{when}
- setRow(index, { [when]: { ...row[when], bp: e.target.value } })} /> - setRow(index, { [when]: { ...row[when], spo2: e.target.value } })} /> - setRow(index, { [when]: { ...row[when], pulse: e.target.value } })} /> + {/* setRow(index, { [when]: { ...row[when], bp: e.target.value } })} /> */} + {/* setRow(index, { [when]: { ...row[when], sbp: e.target.value } })} /> */} + {/* setRow(index, { [when]: { ...row[when], dbp: e.target.value } })} /> */} + setRow(index, { [when]: next })} /> + setRow(index, { [when]: { ...row[when], spo2: e.target.value } })} /> + setRow(index, { [when]: { ...row[when], pulse: e.target.value } })} /> ))} @@ -74,7 +95,7 @@ export default function PatientVitalsModal({ patient, onClose }) { {ASSESSMENT_FIELDS.map(([key, label]) => ( - setRow(index, { assessment: { ...row.assessment, [key]: e.target.value } })} /> + setRow(index, { assessment: { ...row.assessment, [key]: e.target.value } })} /> ))} diff --git a/frontend/src/components/SessionVitalsModal.jsx b/frontend/src/components/SessionVitalsModal.jsx index d61e04f..10e60cd 100644 --- a/frontend/src/components/SessionVitalsModal.jsx +++ b/frontend/src/components/SessionVitalsModal.jsx @@ -1,12 +1,26 @@ import { useState } from 'react'; -import { Button, Col, FormCheck, FormControl, Modal, ModalBody, ModalFooter, ModalHeader, Row } from 'react-bootstrap'; +import { Button, Col, FormCheck, FormControl, InputGroup, Modal, ModalBody, ModalFooter, ModalHeader, Row } from 'react-bootstrap'; import { api } from '@/lib/api'; function emptyVitals() { return { bp: '', spo2: '', pulse: '' }; } -function emptyAssessment() { +// Splits a saved "120/80" into its two parts. +export function splitBp(bp) { + const [sbp = '', dbp = ''] = String(bp || '').split('/').map((part) => part.trim()); + return { sbp, dbp }; +} + +// Joins SBP and DBP back into the saved "120/80" form, or '' when both are empty. +export function joinBp(sbp, dbp) { + const a = String(sbp ?? '').trim(); + const b = String(dbp ?? '').trim(); + return a || b ? `${a}/${b}` : ''; +} + +// function emptyAssessment() { +export function emptyAssessment() { return { fev1: '', fvc: '', @@ -35,6 +49,28 @@ export const ASSESSMENT_FIELDS = [ ['o2WithExercise', 'Oxygen with exercise'], ]; +const clearVitals = { bp: '', spo2: '', pulse: '' }; + +// Vitals to save: BP joined from SBP/DBP, and '' for an empty box so it clears. +export function vitalsPayload(v) { + return { + bp: joinBp(v?.sbp, v?.dbp), + spo2: v?.spo2 === '' || v?.spo2 == null ? '' : Number(v.spo2), + pulse: v?.pulse === '' || v?.pulse == null ? '' : Number(v.pulse), + }; +} + +// One BP box with SBP and DBP inside, shown as SBP / DBP. +export function BpInput({ value, disabled, onChange }) { + return ( + + onChange({ ...value, sbp: e.target.value })} /> + / + onChange({ ...value, dbp: e.target.value })} /> + + ); +} + function isMilestone(index) { return Number(index) === 15 || Number(index) === 30; } @@ -48,8 +84,10 @@ export function rosterFromSession(session) { name: record.patient?.name || 'Patient', attended: Boolean(record.attended), sessionNo: record.patientSessionNo ?? null, - pre: { ...emptyVitals(), ...record.pre, spo2: record.pre?.spo2 ?? '', pulse: record.pre?.pulse ?? '' }, - post: { ...emptyVitals(), ...record.post, spo2: record.post?.spo2 ?? '', pulse: record.post?.pulse ?? '' }, + // pre: { ...emptyVitals(), ...record.pre, spo2: record.pre?.spo2 ?? '', pulse: record.pre?.pulse ?? '' }, + // post: { ...emptyVitals(), ...record.post, spo2: record.post?.spo2 ?? '', pulse: record.post?.pulse ?? '' }, + pre: { ...emptyVitals(), ...record.pre, ...splitBp(record.pre?.bp), spo2: record.pre?.spo2 ?? '', pulse: record.pre?.pulse ?? '' }, + post: { ...emptyVitals(), ...record.post, ...splitBp(record.post?.bp), spo2: record.post?.spo2 ?? '', pulse: record.post?.pulse ?? '' }, assessment: { ...emptyAssessment(), ...record.assessment }, })), }; @@ -73,6 +111,7 @@ export default function SessionVitalsModal({ roster, onChange, onClose, onSaved method: 'PATCH', body: { completed: true, + /* Old payload with one BP box and null for empty numbers. records: roster.records.map((record) => ({ patientId: record.patientId, attended: record.attended, @@ -88,6 +127,14 @@ export default function SessionVitalsModal({ roster, onChange, onClose, onSaved }, assessment: record.assessment, })), + */ + records: roster.records.map((record) => ({ + patientId: record.patientId, + attended: record.attended, + pre: record.attended ? vitalsPayload(record.pre) : clearVitals, + post: record.attended ? vitalsPayload(record.post) : clearVitals, + assessment: record.attended ? record.assessment : emptyAssessment(), + })), }, }); onSaved?.(); @@ -124,6 +171,7 @@ export default function SessionVitalsModal({ roster, onChange, onClose, onSaved
{when}
+ {/* Old single BP box. setRecord(index, { ...record, [when]: { ...record[when], bp: e.target.value } })} /> + */} + {/* Separate SBP and DBP boxes, replaced by one BP box. + + setRecord(index, { ...record, [when]: { ...record[when], sbp: e.target.value } })} + /> + + + setRecord(index, { ...record, [when]: { ...record[when], dbp: e.target.value } })} + /> + + */} + + setRecord(index, { ...record, [when]: next })} + /> + setRecord(index, { ...record, [when]: { ...record[when], spo2: e.target.value } })} /> @@ -144,6 +221,7 @@ export default function SessionVitalsModal({ roster, onChange, onClose, onSaved placeholder="Pulse" type="number" value={record[when].pulse} + disabled={!record.attended} onChange={(e) => setRecord(index, { ...record, [when]: { ...record[when], pulse: e.target.value } })} /> @@ -158,6 +236,7 @@ export default function SessionVitalsModal({ roster, onChange, onClose, onSaved setRecord(index, { ...record, assessment: { ...emptyAssessment(), ...record.assessment, [key]: e.target.value }, diff --git a/frontend/src/views/virtualpr/cohorts/prt-form.jsx b/frontend/src/views/virtualpr/cohorts/prt-form.jsx index 05b29b1..4228104 100644 --- a/frontend/src/views/virtualpr/cohorts/prt-form.jsx +++ b/frontend/src/views/virtualpr/cohorts/prt-form.jsx @@ -117,8 +117,13 @@ export default function PrtCohortForm() { existing: true, name: patient.name || '', mobile: patient.mobile || '', - age: '', - gender: '', + // age: '', + // gender: '', + age: patient.age ?? '', + gender: patient.gender || '', + originalMobile: patient.mobile || '', + offlineSessions: patient.offlineSessions ?? 0, + offlineStartDate: patient.offlineStartDate || '', }))); }).catch((err) => { if (active) setError(err.message); @@ -164,7 +169,18 @@ export default function PrtCohortForm() { } const badOffline = started.findIndex((row) => row.offlineSessions === '' || !(Number(row.offlineSessions) >= 0)); if (badOffline >= 0) { - setError(`Row ${rows.indexOf(started[badOffline]) + 1} needs Sessions completed (0 or more).`); + // setError(`Row ${rows.indexOf(started[badOffline]) + 1} needs Sessions completed (0 or more).`); + setError(`Row ${rows.indexOf(started[badOffline]) + 1} needs Offline completed (0 or more).`); + return; + } + const badExisting = rows.findIndex((row) => row.existing && (row.offlineSessions === '' || !(Number(row.offlineSessions) >= 0))); + if (badExisting >= 0) { + setError(`Row ${badExisting + 1} needs Offline completed (0 or more).`); + return; + } + const badDetails = rows.findIndex((row) => row.existing && (!row.name.trim() || (row.mobile !== row.originalMobile && !isMobileNumber(row.mobile)))); + if (badDetails >= 0) { + setError(`Row ${badDetails + 1} needs a name and a 10 digit mobile.`); return; } const fresh = started.map((row) => ({ @@ -202,6 +218,20 @@ export default function PrtCohortForm() { diseaseType, patients: rows.filter((row) => row.existing && row.id).map((row) => row.id), newPatients: fresh, + // patientOffline: rows.filter((row) => row.existing && row.id).map((row) => ({ + // id: row.id, + // offlineSessions: Number(row.offlineSessions) || 0, + // offlineStartDate: row.offlineStartDate || '', + // })), + patientEdits: rows.filter((row) => row.existing && row.id).map((row) => ({ + id: row.id, + name: row.name.trim(), + mobile: row.mobile.trim(), + age: row.age === '' || row.age == null ? '' : row.age, + gender: row.gender || '', + offlineSessions: Number(row.offlineSessions) || 0, + offlineStartDate: row.offlineStartDate || '', + })), scheduleId: '', createdAs: 'manual_cohorts', sixDayWeek: sixDayWeek === 'yes', @@ -323,7 +353,8 @@ export default function PrtCohortForm() { {rows.length ? ( <> {/*
Fill one row per patient. Name and a 10 digit mobile are required. Empty rows are skipped. Save cohort creates them.
*/} -
Fill one row per patient. Name, a 10 digit mobile and Sessions completed (sessions already done offline, 0 if none) are required. Start date is optional. Empty rows are skipped. Save cohort creates them.
+ {/*
Fill one row per patient. Name, a 10 digit mobile and Sessions completed (sessions already done offline, 0 if none) are required. Start date is optional. Empty rows are skipped. Save cohort creates them.
*/} +
Fill one row per patient. Name, a 10 digit mobile and Offline completed (sessions already done offline, 0 if none) are required. Start date is optional. Empty rows are skipped. Save cohort creates them.
@@ -332,7 +363,8 @@ export default function PrtCohortForm() { - + {/* */} + @@ -343,7 +375,7 @@ export default function PrtCohortForm() { @@ -352,7 +384,7 @@ export default function PrtCohortForm() { inputMode="numeric" maxLength={10} value={row.mobile} - readOnly={row.existing} + // readOnly={row.existing} onChange={(e) => updateRow(row.key, { mobile: mobileDigits(e.target.value) })} /> @@ -361,38 +393,38 @@ export default function PrtCohortForm() { type="number" min={0} value={row.age} - readOnly={row.existing} + // readOnly={row.existing} onChange={(e) => updateRow(row.key, { age: e.target.value })} />
Mobile Age GenderSessions completedSessions completedOffline completed Start date
updateRow(row.key, { name: e.target.value })} /> updateRow(row.key, { gender })} options={settings?.genders} placeholder="Select" /> - {row.existing ? — : ( - updateRow(row.key, { offlineSessions: e.target.value })} - /> - )} + {/* {row.existing ? — : ( */} + {/* {row.existing ? {row.offlineSessions ?? '—'} : ( */} + updateRow(row.key, { offlineSessions: e.target.value })} + /> - {row.existing ? — : ( - updateRow(row.key, { offlineStartDate: e.target.value })} - /> - )} + {/* {row.existing ? — : ( */} + {/* {row.existing ? {row.offlineStartDate || '—'} : ( */} + updateRow(row.key, { offlineStartDate: e.target.value })} + />