changes 11-11-report changes and some fields editable

This commit is contained in:
Abhijit 2026-11-11 19:04:03 +05:30
parent 96e04b111e
commit 9cddf60047
12 changed files with 395 additions and 63 deletions

View File

@ -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 },
);

View File

@ -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 },
);

View File

@ -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}`);

View File

@ -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) };
},
});

View File

@ -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]));

View File

@ -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,

View File

@ -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) => ({

View File

@ -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();

View File

@ -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,

View File

@ -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 }) {
<Col md={6} key={when}>
<div className="text-muted text-uppercase small mb-1">{when}</div>
<Row className="g-2">
<Col><FormControl placeholder="BP" value={blank(row[when]?.bp)} onChange={(e) => setRow(index, { [when]: { ...row[when], bp: e.target.value } })} /></Col>
<Col><FormControl placeholder="SpO2" type="number" value={blank(row[when]?.spo2)} onChange={(e) => setRow(index, { [when]: { ...row[when], spo2: e.target.value } })} /></Col>
<Col><FormControl placeholder="Pulse" type="number" value={blank(row[when]?.pulse)} onChange={(e) => setRow(index, { [when]: { ...row[when], pulse: e.target.value } })} /></Col>
{/* <Col><FormControl placeholder="BP" value={blank(row[when]?.bp)} onChange={(e) => setRow(index, { [when]: { ...row[when], bp: e.target.value } })} /></Col> */}
{/* <Col><FormControl placeholder="SBP" type="number" value={blank(row[when]?.sbp)} disabled={!row.attended} onChange={(e) => setRow(index, { [when]: { ...row[when], sbp: e.target.value } })} /></Col> */}
{/* <Col><FormControl placeholder="DBP" type="number" value={blank(row[when]?.dbp)} disabled={!row.attended} onChange={(e) => setRow(index, { [when]: { ...row[when], dbp: e.target.value } })} /></Col> */}
<Col xs={6}><BpInput value={row[when]} disabled={!row.attended} onChange={(next) => setRow(index, { [when]: next })} /></Col>
<Col><FormControl placeholder="SpO2" type="number" value={blank(row[when]?.spo2)} disabled={!row.attended} onChange={(e) => setRow(index, { [when]: { ...row[when], spo2: e.target.value } })} /></Col>
<Col><FormControl placeholder="Pulse" type="number" value={blank(row[when]?.pulse)} disabled={!row.attended} onChange={(e) => setRow(index, { [when]: { ...row[when], pulse: e.target.value } })} /></Col>
</Row>
</Col>
))}
@ -74,7 +95,7 @@ export default function PatientVitalsModal({ patient, onClose }) {
<Row className="g-2 mt-2">
{ASSESSMENT_FIELDS.map(([key, label]) => (
<Col md={4} key={key}>
<FormControl placeholder={label} value={row.assessment?.[key] || ''} onChange={(e) => setRow(index, { assessment: { ...row.assessment, [key]: e.target.value } })} />
<FormControl placeholder={label} value={row.assessment?.[key] || ''} disabled={!row.attended} onChange={(e) => setRow(index, { assessment: { ...row.assessment, [key]: e.target.value } })} />
</Col>
))}
</Row>

View File

@ -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 (
<InputGroup>
<FormControl placeholder="SBP" type="number" value={value?.sbp ?? ''} disabled={disabled} onChange={(e) => onChange({ ...value, sbp: e.target.value })} />
<InputGroup.Text>/</InputGroup.Text>
<FormControl placeholder="DBP" type="number" value={value?.dbp ?? ''} disabled={disabled} onChange={(e) => onChange({ ...value, dbp: e.target.value })} />
</InputGroup>
);
}
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
<Col md={6} key={when}>
<div className="text-muted text-uppercase small mb-1">{when}</div>
<Row className="g-2">
{/* Old single BP box.
<Col>
<FormControl
placeholder="BP"
@ -131,11 +179,40 @@ export default function SessionVitalsModal({ roster, onChange, onClose, onSaved
onChange={(e) => setRecord(index, { ...record, [when]: { ...record[when], bp: e.target.value } })}
/>
</Col>
*/}
{/* Separate SBP and DBP boxes, replaced by one BP box.
<Col>
<FormControl
placeholder="SBP"
type="number"
value={record[when].sbp}
disabled={!record.attended}
onChange={(e) => setRecord(index, { ...record, [when]: { ...record[when], sbp: e.target.value } })}
/>
</Col>
<Col>
<FormControl
placeholder="DBP"
type="number"
value={record[when].dbp}
disabled={!record.attended}
onChange={(e) => setRecord(index, { ...record, [when]: { ...record[when], dbp: e.target.value } })}
/>
</Col>
*/}
<Col xs={6}>
<BpInput
value={record[when]}
disabled={!record.attended}
onChange={(next) => setRecord(index, { ...record, [when]: next })}
/>
</Col>
<Col>
<FormControl
placeholder="SpO2"
type="number"
value={record[when].spo2}
disabled={!record.attended}
onChange={(e) => setRecord(index, { ...record, [when]: { ...record[when], spo2: e.target.value } })}
/>
</Col>
@ -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 } })}
/>
</Col>
@ -158,6 +236,7 @@ export default function SessionVitalsModal({ roster, onChange, onClose, onSaved
<FormControl
placeholder={label}
value={record.assessment?.[key] || ''}
disabled={!record.attended}
onChange={(e) => setRecord(index, {
...record,
assessment: { ...emptyAssessment(), ...record.assessment, [key]: e.target.value },

View File

@ -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 ? (
<>
{/* <div className="form-text mb-2">Fill one row per patient. Name and a 10 digit mobile are required. Empty rows are skipped. Save cohort creates them.</div> */}
<div className="form-text mb-2">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.</div>
{/* <div className="form-text mb-2">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.</div> */}
<div className="form-text mb-2">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.</div>
<div className="table-responsive border rounded">
<table className="table table-sm align-middle mb-0">
<thead>
@ -332,7 +363,8 @@ export default function PrtCohortForm() {
<th>Mobile</th>
<th style={{ width: 110 }}>Age</th>
<th style={{ width: 160 }}>Gender</th>
<th style={{ width: 140 }}>Sessions completed</th>
{/* <th style={{ width: 140 }}>Sessions completed</th> */}
<th style={{ width: 140 }}>Offline completed</th>
<th style={{ width: 170 }}>Start date</th>
<th style={{ width: 48 }} />
</tr>
@ -343,7 +375,7 @@ export default function PrtCohortForm() {
<td>
<FormControl
value={row.name}
readOnly={row.existing}
// readOnly={row.existing}
onChange={(e) => updateRow(row.key, { name: e.target.value })}
/>
</td>
@ -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) })}
/>
</td>
@ -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 })}
/>
</td>
<td>
<OptionsSelect
value={row.gender}
disabled={row.existing}
// disabled={row.existing}
onChange={(gender) => updateRow(row.key, { gender })}
options={settings?.genders}
placeholder="Select"
/>
</td>
<td>
{row.existing ? <span className="text-muted">—</span> : (
<FormControl
type="number"
min={0}
value={row.offlineSessions}
placeholder="0"
onChange={(e) => updateRow(row.key, { offlineSessions: e.target.value })}
/>
)}
{/* {row.existing ? <span className="text-muted">—</span> : ( */}
{/* {row.existing ? <span>{row.offlineSessions ?? '—'}</span> : ( */}
<FormControl
type="number"
min={0}
value={row.offlineSessions}
placeholder="0"
onChange={(e) => updateRow(row.key, { offlineSessions: e.target.value })}
/>
</td>
<td>
{row.existing ? <span className="text-muted">—</span> : (
<FormControl
type="date"
value={row.offlineStartDate}
onChange={(e) => updateRow(row.key, { offlineStartDate: e.target.value })}
/>
)}
{/* {row.existing ? <span className="text-muted">—</span> : ( */}
{/* {row.existing ? <span>{row.offlineStartDate || '—'}</span> : ( */}
<FormControl
type="date"
value={row.offlineStartDate}
onChange={(e) => updateRow(row.key, { offlineStartDate: e.target.value })}
/>
</td>
<td>
<Button