change 11-11 for offline patients and other changes
This commit is contained in:
parent
5f3920891e
commit
96e04b111e
|
|
@ -12,13 +12,16 @@ const cohortSchema = new mongoose.Schema(
|
|||
diseaseType: { type: String, default: '', trim: true },
|
||||
status: {
|
||||
type: String,
|
||||
enum: ['proposed', 'confirmed', 'active', 'completed'],
|
||||
enum: ['proposed', 'confirmed', 'active', 'completed', 'cancelled'],
|
||||
default: 'active',
|
||||
},
|
||||
needsReassignment: { type: Boolean, default: false },
|
||||
virtualPrt: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
|
||||
patients: [{ type: mongoose.Schema.Types.ObjectId, ref: 'OnboardedPatient' }],
|
||||
durationMinutes: { type: Number, default: 60 },
|
||||
googleEventId: { type: String, default: '' }, // one Google event for the whole cohort
|
||||
meetUrl: { type: String, default: '' }, // fixed Meet link, created once
|
||||
htmlLink: { type: String, default: '' },
|
||||
whatsappGroupJid: { type: String, default: '' },
|
||||
whatsappInviteUrl: { type: String, default: '' },
|
||||
whatsappStatus: { type: String, enum: ['', 'pending', 'ready', 'failed'], default: '' },
|
||||
|
|
|
|||
|
|
@ -1,5 +1,25 @@
|
|||
import mongoose from 'mongoose';
|
||||
|
||||
const offlineVitalsSchema = new mongoose.Schema(
|
||||
{
|
||||
bp: { type: String, default: '', trim: true },
|
||||
spo2: { type: Number, default: null },
|
||||
pulse: { type: Number, default: null },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const offlineRecordSchema = new mongoose.Schema(
|
||||
{
|
||||
number: { type: Number, required: true }, // offline session number, 1 to offlineSessions
|
||||
attended: { type: Boolean, default: true },
|
||||
pre: { type: offlineVitalsSchema, default: () => ({}) },
|
||||
post: { type: offlineVitalsSchema, default: () => ({}) },
|
||||
assessment: { type: mongoose.Schema.Types.Mixed, default: () => ({}) },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const onboardedPatientSchema = new mongoose.Schema(
|
||||
{
|
||||
name: { type: mongoose.Schema.Types.Mixed, required: true },
|
||||
|
|
@ -35,6 +55,9 @@ const onboardedPatientSchema = new mongoose.Schema(
|
|||
assignedEducator: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null },
|
||||
cohort: { type: mongoose.Schema.Types.ObjectId, ref: 'Cohort', default: null },
|
||||
cohortJoinedOn: { type: String, default: '' }, // date the patient was added to the current cohort
|
||||
offlineSessions: { type: Number, default: 0 }, // sessions done offline before joining online
|
||||
offlineStartDate: { type: String, default: '' }, // first offline session date, if known
|
||||
offlineRecords: { type: [offlineRecordSchema], default: [] }, // vitals for each offline session
|
||||
reviewStatus: {
|
||||
type: String,
|
||||
enum: ['pending', 'confirmed', 'rejected'],
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ 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 { activateManualCohort } from '../services/matching.js';
|
||||
import { activateManualCohort, cancelCohort, startCohortMeetings } from '../services/matching.js';
|
||||
import { ensureSessionRecords, persistCohortSessions, rescheduleOpenSessions } from '../services/programSessions.js';
|
||||
import { CohortSession } from '../models/CohortSession.js';
|
||||
import { assertConfiguredSlot, getAppSettings } from '../services/settings.js';
|
||||
|
|
@ -34,6 +34,8 @@ const cohortPayload = Joi.object({
|
|||
age: Joi.alternatives().try(Joi.number(), Joi.string().allow('')).optional(),
|
||||
gender: Joi.string().trim().allow('').optional(),
|
||||
whatsappOptOut: Joi.boolean().optional(),
|
||||
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([]),
|
||||
});
|
||||
|
||||
|
|
@ -108,9 +110,15 @@ export function cohortRoutes(server) {
|
|||
const { search = '', page = 1, limit = 20, status } = request.query;
|
||||
const filter = { ...cohortScopeFilter(request) };
|
||||
const creds = credentials(request);
|
||||
// if (creds.role?.systemKey === 'educator') filter.status = { $in: ['confirmed', 'active'] };
|
||||
// else if (status === 'proposed') filter.status = 'proposed';
|
||||
// else if (status === 'active') filter.status = { $nin: ['proposed'] };
|
||||
// else if (status === 'completed' || status === 'cancelled') filter.status = status;
|
||||
if (creds.role?.systemKey === 'educator') filter.status = { $in: ['confirmed', 'active'] };
|
||||
else if (status === 'proposed') filter.status = 'proposed';
|
||||
else if (status === 'active') filter.status = { $nin: ['proposed'] };
|
||||
else if (status === 'active') filter.status = { $in: ['confirmed', 'active'] };
|
||||
else if (status === 'completed' || status === 'cancelled') filter.status = status;
|
||||
else if (status !== 'all') filter.status = { $in: ['proposed', 'confirmed', 'active'] }; // default "All live"
|
||||
if (search) {
|
||||
const rx = new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
|
||||
filter.name = rx;
|
||||
|
|
@ -292,6 +300,7 @@ export function cohortRoutes(server) {
|
|||
if (scheduleChanged) await rescheduleOpenSessions(cohort);
|
||||
else if (await CohortSession.countDocuments({ cohort: cohort._id })) await ensureSessionRecords(cohort);
|
||||
else await persistCohortSessions(cohort);
|
||||
await startCohortMeetings(cohort);
|
||||
if ((cohort.createdAs || '') === 'manual_cohorts') await applyCohortToPatients(cohort);
|
||||
const ready = await Cohort.findById(cohort._id)
|
||||
.populate('virtualPrt', 'firstName lastName email')
|
||||
|
|
@ -356,6 +365,52 @@ export function cohortRoutes(server) {
|
|||
return toCohortDto(cohort);
|
||||
},
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: 'POST',
|
||||
path: '/api/cohorts/{id}/status',
|
||||
options: {
|
||||
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'edit') }],
|
||||
validate: {
|
||||
params: Joi.object({ id: objectId.required() }),
|
||||
payload: Joi.object({
|
||||
status: Joi.string().valid('active', 'completed', 'cancelled').required(),
|
||||
patientAction: Joi.string().valid('pool', 'move').default('pool'), // cancelled only: where the patients go
|
||||
targetCohortId: objectId.allow('', null),
|
||||
force: Joi.boolean().default(false), // move anyway when the target does not match
|
||||
check: Joi.boolean().default(false), // only return warnings, change nothing
|
||||
}),
|
||||
},
|
||||
},
|
||||
handler: async (request) => {
|
||||
const cohort = await findCohort(request);
|
||||
const { status, patientAction, targetCohortId, force, check } = request.payload;
|
||||
if (cohort.status === 'proposed') throw Boom.badRequest('Confirm this cohort from Matching first.');
|
||||
if (check) {
|
||||
if (status !== 'cancelled') return { warnings: [] };
|
||||
return cancelCohort(cohort, { patientAction, targetCohortId, check: true });
|
||||
}
|
||||
if (cohort.status === status) throw Boom.badRequest(`This cohort is already ${status}.`);
|
||||
if (status === 'active') {
|
||||
cohort.status = 'active';
|
||||
await cohort.save();
|
||||
await startCohortMeetings(cohort);
|
||||
} else if (status === 'completed') {
|
||||
cohort.status = 'completed';
|
||||
await cohort.save();
|
||||
const { notifyGroupClosed } = await import('../services/whatsapp.js');
|
||||
await notifyGroupClosed(cohort._id).catch((err) => {
|
||||
console.error(`[whatsapp] closing notice failed: ${err?.message || err}`);
|
||||
});
|
||||
} else {
|
||||
await cancelCohort(cohort, { patientAction, targetCohortId, force });
|
||||
}
|
||||
const ready = await Cohort.findById(cohort._id)
|
||||
.populate('virtualPrt', 'firstName lastName email')
|
||||
.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
|
||||
return (await withSessionCounts(ready))[0];
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function virtualPrtRoutes(server) {
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import { writeAudit } from '../services/audit.js';
|
|||
import { addPatientToCohort, removePatientFromCohort } from '../services/cohorts.js';
|
||||
import { migratePatient } from '../services/matching.js';
|
||||
import { notifyPaymentReview } from '../services/notify.js';
|
||||
import { attendanceProgress, ensureSessionRecords, patientProgramStats } from '../services/programSessions.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';
|
||||
|
||||
|
|
@ -211,7 +211,7 @@ async function findAssignableCohort(cohortId, currentCohortId) {
|
|||
const cohort = await Cohort.findById(cohortId);
|
||||
if (!cohort) throw Boom.badRequest('Select an ongoing or upcoming cohort.');
|
||||
const isCurrent = currentCohortId && String(cohort._id) === String(currentCohortId);
|
||||
if (!isCurrent && cohort.status === 'completed') throw Boom.badRequest('Select an ongoing or upcoming cohort.');
|
||||
if (!isCurrent && ['completed', 'cancelled'].includes(cohort.status)) throw Boom.badRequest('Select an ongoing or upcoming cohort.');
|
||||
return cohort;
|
||||
}
|
||||
|
||||
|
|
@ -285,8 +285,8 @@ export function onboardingRoutes(server) {
|
|||
const addedBy = await User.find({ _id: { $in: addedByIds } }).select('firstName lastName').sort({ firstName: 1, lastName: 1 });
|
||||
return {
|
||||
items: items.map((item) => {
|
||||
const progress = stats.get(String(item._id)) || { attended: 0, total: 0 };
|
||||
return { ...toOnboardedPatientDto(item), progress: { attended: progress.attended, total: progress.total, firstDate: progress.firstDate || '' } };
|
||||
const progress = stats.get(String(item._id)) || { attended: 0, completed: 0 };
|
||||
return { ...toOnboardedPatientDto(item), progress: { attended: progress.attended, completed: progress.completed, firstDate: progress.firstDate || '' } };
|
||||
}),
|
||||
total,
|
||||
page: Number(page),
|
||||
|
|
@ -308,7 +308,7 @@ export function onboardingRoutes(server) {
|
|||
handler: async (request) => {
|
||||
const language = String(request.query.language || '').trim();
|
||||
const include = String(request.query.include || '').trim();
|
||||
const filter = { status: { $nin: ['proposed', 'completed'] } };
|
||||
const filter = { status: { $nin: ['proposed', 'completed', 'cancelled'] } };
|
||||
if (language) filter.language = language;
|
||||
const items = await Cohort.find(filter)
|
||||
.populate('virtualPrt', 'firstName lastName email')
|
||||
|
|
@ -612,6 +612,7 @@ export function onboardingRoutes(server) {
|
|||
cohortId: objectId.allow(null),
|
||||
slot: Joi.string().allow('', null),
|
||||
preferredWeekday: Joi.number().integer().min(0).max(6).allow(null),
|
||||
force: Joi.boolean().default(false),
|
||||
}),
|
||||
},
|
||||
},
|
||||
|
|
@ -629,6 +630,51 @@ export function onboardingRoutes(server) {
|
|||
},
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: 'GET',
|
||||
path: '/api/onboarding/{id}/vitals',
|
||||
options: {
|
||||
pre: [{ method: requirePermission('onboarding', 'view') }],
|
||||
validate: { params: Joi.object({ id: objectId.required() }) },
|
||||
},
|
||||
handler: async (request) => {
|
||||
const item = await findOnboarded(request);
|
||||
return { items: await patientVitalsRows(item._id) };
|
||||
},
|
||||
});
|
||||
|
||||
const vitalsShape = Joi.object({
|
||||
bp: Joi.string().allow('', null),
|
||||
spo2: Joi.number().allow(null, ''),
|
||||
pulse: Joi.number().allow(null, ''),
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: 'PUT',
|
||||
path: '/api/onboarding/{id}/vitals',
|
||||
options: {
|
||||
pre: [{ method: requirePermission('onboarding', 'edit') }],
|
||||
validate: {
|
||||
params: Joi.object({ id: objectId.required() }),
|
||||
payload: Joi.object({
|
||||
rows: Joi.array().items(Joi.object({
|
||||
kind: Joi.string().valid('offline', 'online').required(),
|
||||
number: Joi.number().integer().allow(null),
|
||||
sessionId: objectId.allow(''),
|
||||
attended: Joi.boolean(),
|
||||
pre: vitalsShape,
|
||||
post: vitalsShape,
|
||||
assessment: Joi.object().unknown(true),
|
||||
}).unknown(true)).default([]),
|
||||
}),
|
||||
},
|
||||
},
|
||||
handler: async (request) => {
|
||||
const item = await findOnboarded(request);
|
||||
return { items: await savePatientVitals(item._id, request.payload.rows) };
|
||||
},
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: 'PATCH',
|
||||
path: '/api/onboarding/{id}/whatsapp',
|
||||
|
|
|
|||
|
|
@ -43,6 +43,23 @@ function vitalValue(value) {
|
|||
return value == null || value === '' ? '' : value;
|
||||
}
|
||||
|
||||
// Completed sessions per patient across all cohorts, oldest first.
|
||||
async function heldSessionsByPatient(patientIds) {
|
||||
const byPatient = new Map(patientIds.map((id) => [String(id), []]));
|
||||
if (!patientIds.length) return byPatient;
|
||||
const sessions = await CohortSession.find({ 'records.patient': { $in: patientIds }, status: 'completed' })
|
||||
.select('cohort index date records.patient records.attended records.pre records.post')
|
||||
.populate('cohort', 'name')
|
||||
.sort({ date: 1, index: 1 });
|
||||
for (const session of sessions) {
|
||||
for (const record of session.records || []) {
|
||||
const list = byPatient.get(String(record.patient));
|
||||
if (list) list.push(session);
|
||||
}
|
||||
}
|
||||
return byPatient;
|
||||
}
|
||||
|
||||
export function reportRoutes(server) {
|
||||
server.route({
|
||||
method: 'GET',
|
||||
|
|
@ -68,7 +85,7 @@ export function reportRoutes(server) {
|
|||
const stats = await patientProgramStats(patients.map((item) => item._id));
|
||||
return {
|
||||
items: patients.map((patient) => {
|
||||
const progress = stats.get(String(patient._id)) || { attended: 0, total: 0, completed: 0, assigned: 0, firstDate: '', vitals: [] };
|
||||
const progress = stats.get(String(patient._id)) || { attended: 0, completed: 0, firstDate: '', vitals: [] };
|
||||
const pii = readOnboardedPii(patient);
|
||||
return {
|
||||
id: String(patient._id),
|
||||
|
|
@ -83,10 +100,10 @@ export function reportRoutes(server) {
|
|||
: null,
|
||||
firstSession: progress.firstDate || '',
|
||||
completed: progress.completed || 0,
|
||||
assigned: progress.assigned || 0,
|
||||
// assigned: progress.assigned || 0, // assigned count is off
|
||||
attended: progress.attended,
|
||||
total: progress.total,
|
||||
completion: progress.total ? `${progress.attended}/${progress.total}` : '0/0',
|
||||
// total: progress.total, // total is off
|
||||
completion: progress.completed ? `${progress.attended}/${progress.completed}` : '0/0',
|
||||
vitals: progress.vitals,
|
||||
};
|
||||
}),
|
||||
|
|
@ -211,6 +228,7 @@ export function reportRoutes(server) {
|
|||
}
|
||||
rows = [['PRT', 'Used', 'Max', 'Idle', 'Sessions', 'Cancelled'], ...items];
|
||||
} else if (type === 'vitals') {
|
||||
/* Old: sessions from the current cohort only.
|
||||
const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined });
|
||||
const cohortIds = [...new Set(patients.map((patient) => patient.cohort?._id).filter(Boolean))];
|
||||
const sessions = cohortIds.length
|
||||
|
|
@ -273,7 +291,47 @@ export function reportRoutes(server) {
|
|||
[...blank, 'BP', 'SpO2', 'Pulse', 'BP', 'SpO2', 'Pulse'],
|
||||
...lines.map((line) => line.row),
|
||||
];
|
||||
*/
|
||||
const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined });
|
||||
const held = await heldSessionsByPatient(patients.map((item) => item._id));
|
||||
const vitals = (record) => [
|
||||
vitalValue(record?.pre?.bp), vitalValue(record?.pre?.spo2), vitalValue(record?.pre?.pulse),
|
||||
vitalValue(record?.post?.bp), vitalValue(record?.post?.spo2), vitalValue(record?.post?.pulse),
|
||||
];
|
||||
const lines = [];
|
||||
for (const patient of patients) {
|
||||
const id = String(patient._id);
|
||||
const pii = readOnboardedPii(patient);
|
||||
const base = [pii.name, pii.mobile, patient.diseaseType || ''];
|
||||
const startDate = patient.cohort?.startDate ? toYmd(patient.cohort.startDate) : '';
|
||||
const offlineCount = Number(patient.offlineSessions) || 0;
|
||||
const offline = new Map((patient.offlineRecords || []).map((record) => [record.number, record]));
|
||||
for (let number = 1; number <= offlineCount; number += 1) {
|
||||
const record = offline.get(number);
|
||||
const date = number === 1 ? patient.offlineStartDate || '' : '';
|
||||
lines.push({
|
||||
name: pii.name || '',
|
||||
number,
|
||||
row: [...base, 'Offline', startDate, number, `${date || 'Offline'} (${record?.attended === false ? 'A' : 'P'})`, ...vitals(record)],
|
||||
});
|
||||
}
|
||||
(held.get(id) || []).forEach((session, index) => {
|
||||
const number = offlineCount + index + 1;
|
||||
lines.push({
|
||||
name: pii.name || '',
|
||||
number,
|
||||
row: [...base, session.cohort?.name || '', startDate, number, `${session.date} (${sessionMark(session, id)})`, ...vitals(sessionRecord(session, id))],
|
||||
});
|
||||
});
|
||||
}
|
||||
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),
|
||||
];
|
||||
} else {
|
||||
/* Old: sessions from the current cohort only.
|
||||
const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined });
|
||||
const cohortIds = [...new Set(patients.map((patient) => patient.cohort?._id).filter(Boolean))];
|
||||
const sessions = cohortIds.length
|
||||
|
|
@ -290,7 +348,7 @@ export function reportRoutes(server) {
|
|||
}
|
||||
const stats = await patientProgramStats(patients.map((item) => item._id));
|
||||
const widest = [...byCohort.values()].reduce((max, list) => Math.max(max, list.length), 0);
|
||||
const headers = ['Name', 'Mobile', 'Disease', 'Cohort', 'PRT', 'Start date', 'First session', 'Completed', 'Assigned', ...Array.from({ length: widest }, (_, index) => `Session ${index + 1}`)];
|
||||
const headers = ['Name', 'Mobile', 'Disease', 'Cohort', 'PRT', 'Start date', 'First session', 'Completed', ('Assigned' was here) ...Array.from({ length: widest }, (_, index) => `Session ${index + 1}`)];
|
||||
rows = [headers, ...patients.map((patient) => {
|
||||
const pii = readOnboardedPii(patient);
|
||||
const progress = stats.get(String(patient._id)) || {};
|
||||
|
|
@ -308,7 +366,34 @@ export function reportRoutes(server) {
|
|||
patient.cohort?.startDate ? toYmd(patient.cohort.startDate) : '',
|
||||
progress.firstDate || '',
|
||||
progress.completed || 0,
|
||||
progress.assigned || 0,
|
||||
// progress.assigned || 0, // assigned count is off
|
||||
...marks,
|
||||
];
|
||||
})];
|
||||
*/
|
||||
const patients = await listOnboardedForReports({ virtualPrtId: scopedPrt(request), diseaseType: request.query.diseaseType || undefined });
|
||||
const held = await heldSessionsByPatient(patients.map((item) => item._id));
|
||||
const stats = await patientProgramStats(patients.map((item) => item._id));
|
||||
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))),
|
||||
]);
|
||||
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}`)];
|
||||
rows = [headers, ...patients.map((patient, index) => {
|
||||
const pii = readOnboardedPii(patient);
|
||||
const progress = stats.get(String(patient._id)) || {};
|
||||
const marks = [...allMarks[index]];
|
||||
while (marks.length < widest) marks.push(''); // patients with fewer sessions leave the extra cells blank
|
||||
return [
|
||||
pii.name,
|
||||
pii.mobile,
|
||||
patient.diseaseType || '',
|
||||
patient.cohort?.name || '',
|
||||
patient.assignedEducator ? `${patient.assignedEducator.firstName} ${patient.assignedEducator.lastName}` : '',
|
||||
patient.cohort?.startDate ? toYmd(patient.cohort.startDate) : '',
|
||||
progress.firstDate || '',
|
||||
progress.completed || 0,
|
||||
...marks,
|
||||
];
|
||||
})];
|
||||
|
|
|
|||
|
|
@ -123,6 +123,8 @@ export async function createManualCohortPatients(cohort, rows, userId) {
|
|||
age: row?.age ?? '',
|
||||
gender: String(row?.gender || '').trim(),
|
||||
whatsappOptOut: Boolean(row?.whatsappOptOut),
|
||||
offlineSessions: Math.max(0, Number(row?.offlineSessions) || 0),
|
||||
offlineStartDate: String(row?.offlineStartDate || '').trim(),
|
||||
})).filter((row) => row.name || row.mobile);
|
||||
if (!list.length) return [];
|
||||
if (list.some((row) => !row.name || !isMobileNumber(row.mobile))) throw Boom.badRequest('Each patient needs a name and a 10 digit mobile.');
|
||||
|
|
@ -144,6 +146,8 @@ export async function createManualCohortPatients(cohort, rows, userId) {
|
|||
reviewedBy: userId,
|
||||
reviewedAt: new Date(),
|
||||
whatsappOptOut: row.whatsappOptOut,
|
||||
offlineSessions: row.offlineSessions,
|
||||
offlineStartDate: row.offlineStartDate,
|
||||
});
|
||||
created.push(doc._id);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,9 +4,10 @@ import { OnboardedPatient } from '../models/OnboardedPatient.js';
|
|||
import { ReassignmentEvent } from '../models/ReassignmentEvent.js';
|
||||
import { Role } from '../models/Role.js';
|
||||
import { User } from '../models/User.js';
|
||||
import { addPatientToCohort, removePatientFromCohort, syncCohortPatients } from './cohorts.js';
|
||||
import { addPatientToCohort, releaseCohortPatients, removePatientFromCohort, syncCohortPatients } from './cohorts.js';
|
||||
import { CohortSession } from '../models/CohortSession.js';
|
||||
import { notifyCohortConfirmed, notifyReassignment } from './notify.js';
|
||||
import { persistCohortSessions } from './programSessions.js';
|
||||
import { appendTodaySessions, ensureMeetForCohort, persistCohortSessions } from './programSessions.js';
|
||||
import { addDays, assertCohortStartDate, buildCohortName, scheduleWeekdays, toYmd, todayYmd, upcomingSessionDates, weekdayOf, ymdToDate } from './schedule.js';
|
||||
import { assertConfiguredSlot, getAppSettings, slotLabel, WEEKDAY_LABELS } from './settings.js';
|
||||
import { readOnboardedPii } from './cryptoPii.js';
|
||||
|
|
@ -448,6 +449,12 @@ export async function setProposalSchedule(proposalId, scheduleId) {
|
|||
return toCohortDto(ready);
|
||||
}
|
||||
|
||||
// Creates today's session if the cohort meets today, then its one Meet link. Failures are logged, not thrown.
|
||||
export async function startCohortMeetings(cohort) {
|
||||
await appendTodaySessions(todayYmd(env.APP_TIMEZONE), { cohortId: cohort._id }).catch((err) => console.error(`[cohort] first session failed: ${err?.message || err}`));
|
||||
await ensureMeetForCohort(cohort).catch((err) => console.error(`[meet] cohort link failed: ${err?.message || err}`));
|
||||
}
|
||||
|
||||
// Confirms a proposal, moves a Sunday or past start onto a valid day, then creates sessions.
|
||||
export async function confirmCohort(cohortId) {
|
||||
const cohort = await Cohort.findById(cohortId).populate('virtualPrt').populate('patients');
|
||||
|
|
@ -474,6 +481,7 @@ export async function confirmCohort(cohortId) {
|
|||
{ $set: { matchingStatus: 'assigned', assignedEducator: cohort.virtualPrt, cohort: cohort._id, sessionDate: cohort.startDate } },
|
||||
);
|
||||
await persistCohortSessions(cohort);
|
||||
await startCohortMeetings(cohort);
|
||||
const fieldNotices = await fieldNoticesForCohort(cohort);
|
||||
await notifyCohortConfirmed({ prt: cohort.virtualPrt, fieldNotices, cohort });
|
||||
const { ensureCohortGroup } = await import('./whatsapp.js');
|
||||
|
|
@ -580,11 +588,12 @@ export async function openLeaveReassignment(cohort, fromPrtId) {
|
|||
});
|
||||
}
|
||||
|
||||
export async function migratePatient(patient, { cohortId, slot, preferredWeekday }, settings) {
|
||||
export async function migratePatient(patient, { cohortId, slot, preferredWeekday, force = false }, settings) {
|
||||
if (cohortId) {
|
||||
const target = await Cohort.findById(cohortId);
|
||||
if (!target) throw Boom.badRequest('Select a valid cohort.');
|
||||
if (!LIVE_OR_PROPOSED(target.status)) throw Boom.badRequest('Patients can only move into a live or proposed cohort.');
|
||||
/* Old hard blocks, now warnings that can be confirmed.
|
||||
if ((target.patients || []).length >= (settings.maxPatientsPerCohort || 10)) {
|
||||
throw Boom.badRequest('The target cohort is full.');
|
||||
}
|
||||
|
|
@ -594,6 +603,21 @@ export async function migratePatient(patient, { cohortId, slot, preferredWeekday
|
|||
if (patient.diseaseType && target.diseaseType && patient.diseaseType !== target.diseaseType) {
|
||||
throw Boom.badRequest('Category does not match the target cohort.');
|
||||
}
|
||||
*/
|
||||
const warnings = [];
|
||||
const max = settings.maxPatientsPerCohort || 10;
|
||||
if ((target.patients || []).length >= max) warnings.push(`${target.name} is full (${(target.patients || []).length} of ${max} patients).`);
|
||||
if (patient.sessionLanguage && target.language && patient.sessionLanguage !== target.language) {
|
||||
warnings.push(`Language does not match (patient ${patient.sessionLanguage}, cohort ${target.language}).`);
|
||||
}
|
||||
if (patient.diseaseType && target.diseaseType && patient.diseaseType !== target.diseaseType) {
|
||||
warnings.push(`Category does not match (patient ${patient.diseaseType}, cohort ${target.diseaseType}).`);
|
||||
}
|
||||
if (warnings.length && !force) {
|
||||
const err = Boom.conflict('This move needs confirmation.');
|
||||
err.output.payload.warnings = warnings;
|
||||
throw err;
|
||||
}
|
||||
const previous = patient.cohort;
|
||||
if (previous && String(previous) !== String(target._id)) {
|
||||
await removePatientFromCohort(previous, patient._id);
|
||||
|
|
@ -619,11 +643,65 @@ export async function migratePatient(patient, { cohortId, slot, preferredWeekday
|
|||
return patient;
|
||||
}
|
||||
|
||||
// Cancels a cohort: stops its upcoming sessions, then sends its patients to the pool or into another live cohort.
|
||||
export async function cancelCohort(cohort, { patientAction = 'pool', targetCohortId = '', force = false, check = false } = {}) {
|
||||
const ids = (cohort.patients || []).map((item) => String(item._id || item));
|
||||
let target = null;
|
||||
const warnings = [];
|
||||
if (patientAction === 'move' && ids.length) {
|
||||
target = await Cohort.findById(targetCohortId);
|
||||
if (!target || String(target._id) === String(cohort._id) || !['confirmed', 'active'].includes(target.status)) {
|
||||
throw Boom.badRequest('Select another live cohort to move the patients into.');
|
||||
}
|
||||
const settings = await getAppSettings();
|
||||
const seats = (settings.maxPatientsPerCohort || 10) - (target.patients || []).length;
|
||||
/* Old hard blocks, now warnings that can be confirmed.
|
||||
if (seats < ids.length) throw Boom.badRequest(`${target.name} has ${Math.max(seats, 0)} free seat(s) for ${ids.length} patient(s).`);
|
||||
if (cohort.language && target.language && cohort.language !== target.language) throw Boom.badRequest('Language must match the target cohort.');
|
||||
if (cohort.diseaseType && target.diseaseType && cohort.diseaseType !== target.diseaseType) throw Boom.badRequest('Category must match the target cohort.');
|
||||
*/
|
||||
if (seats < ids.length) warnings.push(`Not enough seats (${target.name} has ${Math.max(seats, 0)} free for ${ids.length} patients).`);
|
||||
if (cohort.language && target.language && cohort.language !== target.language) {
|
||||
warnings.push(`Language does not match (cohort ${cohort.language}, target ${target.language}).`);
|
||||
}
|
||||
if (cohort.diseaseType && target.diseaseType && cohort.diseaseType !== target.diseaseType) {
|
||||
warnings.push(`Category does not match (cohort ${cohort.diseaseType}, target ${target.diseaseType}).`);
|
||||
}
|
||||
}
|
||||
if (check) return { warnings };
|
||||
if (warnings.length && !force) {
|
||||
const err = Boom.conflict('Moving the patients needs confirmation.');
|
||||
err.output.payload.warnings = warnings;
|
||||
throw err;
|
||||
}
|
||||
const today = todayYmd(env.APP_TIMEZONE);
|
||||
await CohortSession.updateMany(
|
||||
{ cohort: cohort._id, status: 'scheduled', date: { $gte: today } },
|
||||
{ $set: { status: 'cancelled', cancelReason: 'Cohort cancelled' } },
|
||||
);
|
||||
const { notifyGroupSessionChange } = await import('./whatsapp.js');
|
||||
await notifyGroupSessionChange(cohort._id, `${cohort.name} has been cancelled. Session reminders will stop.`).catch((err) => {
|
||||
console.error(`[whatsapp] cancel notice failed: ${err?.message || err}`);
|
||||
});
|
||||
if (target) {
|
||||
const settings = await getAppSettings();
|
||||
const patients = await OnboardedPatient.find({ _id: { $in: ids } });
|
||||
for (const patient of patients) await migratePatient(patient, { cohortId: target._id, force: true }, settings);
|
||||
} else if (ids.length) {
|
||||
await releaseCohortPatients(cohort);
|
||||
cohort.patients = [];
|
||||
}
|
||||
cohort.status = 'cancelled';
|
||||
await cohort.save();
|
||||
return cohort;
|
||||
}
|
||||
|
||||
export async function activateManualCohort(cohort) {
|
||||
if (cohort.status === 'proposed') return cohort;
|
||||
cohort.status = cohort.status === 'completed' ? 'completed' : 'active';
|
||||
await cohort.save();
|
||||
await persistCohortSessions(cohort);
|
||||
await startCohortMeetings(cohort);
|
||||
await cohort.populate('virtualPrt', 'firstName lastName email');
|
||||
const patients = await OnboardedPatient.find({ _id: { $in: cohort.patients || [] } }).populate('onboardedBy', 'firstName lastName email');
|
||||
await OnboardedPatient.updateMany(
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ export function isLiveCohortStatus(status) {
|
|||
}
|
||||
|
||||
export function liveCohortFilter(virtualPrtId) {
|
||||
const filter = { status: { $nin: ['proposed', 'completed'] } };
|
||||
const filter = { status: { $nin: ['proposed', 'completed', 'cancelled'] } };
|
||||
if (virtualPrtId) filter.virtualPrt = virtualPrtId;
|
||||
return filter;
|
||||
}
|
||||
|
|
@ -90,8 +90,9 @@ async function finishedSessionCounts(patientIds) {
|
|||
return counts;
|
||||
}
|
||||
|
||||
// Creates the session list once. If rows exist, only adds dates when the list is short.
|
||||
// Books current patients onto existing sessions. New sessions come only from the 5:30 daily job.
|
||||
export async function persistCohortSessions(cohort) {
|
||||
/* Advance creation is off: sessions are created day by day by appendTodaySessions.
|
||||
const settings = await getAppSettings();
|
||||
const ownCount = await scheduleSessionCount(cohort.scheduleId);
|
||||
const needed = Math.min(Math.max(Number(manualSessionCount(cohort) || ownCount || settings.upcomingSessionCount) || 30, 1), 60);
|
||||
|
|
@ -134,6 +135,7 @@ export async function persistCohortSessions(cohort) {
|
|||
active.push(created);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
await ensureSessionRecords(cohort);
|
||||
return CohortSession.find({ cohort: cohort._id }).sort({ index: 1 });
|
||||
|
|
@ -167,8 +169,9 @@ async function collectSessionDates(from, cohort, count, weekdays, blocked) {
|
|||
|
||||
// Updates the cohort's Google event to cover every held and upcoming session. The Meet link stays.
|
||||
async function syncExistingMeetSeries(cohort, sessions) {
|
||||
const linked = sessions.find((session) => session.googleEventId);
|
||||
if (!linked) return;
|
||||
const eventId = cohort.googleEventId || sessions.find((session) => session.googleEventId)?.googleEventId;
|
||||
if (!eventId) return;
|
||||
const linked = sessions.find((session) => session.googleEventId === eventId) || {};
|
||||
const active = sessions
|
||||
.filter((session) => session.status !== 'cancelled')
|
||||
.sort((a, b) => String(a.date).localeCompare(String(b.date)));
|
||||
|
|
@ -181,7 +184,7 @@ async function syncExistingMeetSeries(cohort, sessions) {
|
|||
const last = active[active.length - 1];
|
||||
const times = slotDateTimes(first.date, first.slot || cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
|
||||
try {
|
||||
await updateCalendarEvent(host, linked.googleEventId, {
|
||||
await updateCalendarEvent(host, eventId, {
|
||||
title: `PR Session · ${cohort.name}`,
|
||||
description: `Pulmonary rehab repeat meetings for ${cohort.name} (${active.length} sessions).`,
|
||||
start: times.start,
|
||||
|
|
@ -202,8 +205,15 @@ async function syncExistingMeetSeries(cohort, sessions) {
|
|||
}
|
||||
}
|
||||
|
||||
// Replaces sessions that are not completed. Completed sessions stay.
|
||||
// Removes future scheduled sessions after a schedule change. The 5:30 job creates dates from the new schedule.
|
||||
export async function rescheduleOpenSessions(cohort) {
|
||||
const today = todayYmd(env.APP_TIMEZONE);
|
||||
await CohortSession.deleteMany({
|
||||
cohort: cohort._id,
|
||||
status: 'scheduled',
|
||||
$or: [{ date: { $gt: today } }, { date: { $lt: toYmd(cohort.startDate) } }],
|
||||
});
|
||||
/* Old rebuild of planned dates up to the cap.
|
||||
const settings = await getAppSettings();
|
||||
const ownCount = await scheduleSessionCount(cohort.scheduleId);
|
||||
const cap = Math.min(Math.max(Number(manualSessionCount(cohort) || ownCount || settings.upcomingSessionCount) || 30, 1), 60);
|
||||
|
|
@ -238,23 +248,27 @@ export async function rescheduleOpenSessions(cohort) {
|
|||
};
|
||||
}));
|
||||
}
|
||||
*/
|
||||
await ensureSessionRecords(cohort);
|
||||
const sessions = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1 });
|
||||
await syncExistingMeetSeries(cohort, sessions);
|
||||
return sessions;
|
||||
}
|
||||
|
||||
// Books each patient onto the upcoming sessions they still have left. Finished sessions are not changed.
|
||||
// Books every current patient onto scheduled sessions from today. Held sessions are not changed.
|
||||
export async function ensureSessionRecords(cohort) {
|
||||
const patients = patientIds(cohort).map(String);
|
||||
if (!patients.length) return;
|
||||
/* Per-patient limit is off: patients stay until the cohort is completed or cancelled.
|
||||
const settings = await getAppSettings();
|
||||
const length = await cohortProgramLength(cohort, settings);
|
||||
const finished = await finishedSessionCounts(patients);
|
||||
*/
|
||||
const today = todayYmd(env.APP_TIMEZONE);
|
||||
const sessions = await CohortSession.find({ cohort: cohort._id, status: 'scheduled', date: { $gte: today } }).sort({ date: 1, index: 1 });
|
||||
const dirty = new Set();
|
||||
for (const id of patients) {
|
||||
/* Old limited booking.
|
||||
const remaining = Math.max(0, length - (finished.get(id) || 0));
|
||||
const keep = new Set(sessions.slice(0, remaining).map((session) => String(session._id)));
|
||||
for (const session of sessions) {
|
||||
|
|
@ -268,6 +282,12 @@ export async function ensureSessionRecords(cohort) {
|
|||
dirty.add(session);
|
||||
}
|
||||
}
|
||||
*/
|
||||
for (const session of sessions) {
|
||||
if ((session.records || []).some((record) => String(record.patient) === id)) continue;
|
||||
session.records.push({ patient: id, attended: false, pre: {}, post: {} });
|
||||
dirty.add(session);
|
||||
}
|
||||
}
|
||||
for (const session of dirty) await session.save();
|
||||
}
|
||||
|
|
@ -329,21 +349,25 @@ async function canMeetOn(cohort, date) {
|
|||
}
|
||||
|
||||
// Adds today's session to open cohorts with no future session left, when today is their next meeting day.
|
||||
export async function appendTodaySessions(date) {
|
||||
const cohorts = await Cohort.find(liveCohortFilter());
|
||||
export async function appendTodaySessions(date, { cohortId } = {}) {
|
||||
const filter = liveCohortFilter();
|
||||
if (cohortId) filter._id = cohortId;
|
||||
const cohorts = await Cohort.find(filter);
|
||||
let added = 0;
|
||||
for (const cohort of cohorts) {
|
||||
if (date < toYmd(cohort.startDate)) continue; // not started yet
|
||||
if (await CohortSession.exists({ cohort: cohort._id, date })) continue;
|
||||
if (await CohortSession.exists({ cohort: cohort._id, status: 'scheduled', date: { $gt: date } })) continue;
|
||||
const next = await nextAppendDate(cohort);
|
||||
if (next > date) continue;
|
||||
if (next < date && !(await canMeetOn(cohort, date))) continue; // catching up after missed meeting days
|
||||
const ids = patientIds(cohort).map(String);
|
||||
const length = await cohortProgramLength(cohort, await getAppSettings());
|
||||
const finished = await finishedSessionCounts(ids);
|
||||
if (!ids.some((id) => (finished.get(id) || 0) < length)) continue; // everyone already finished their sessions
|
||||
if (!ids.length) continue; // no patients yet
|
||||
// const length = await cohortProgramLength(cohort, await getAppSettings()); // per-patient limit is off
|
||||
// const finished = await finishedSessionCounts(ids);
|
||||
// if (!ids.some((id) => (finished.get(id) || 0) < length)) continue; // everyone already finished their sessions
|
||||
const last = await CohortSession.findOne({ cohort: cohort._id }).sort({ index: -1 });
|
||||
const link = await CohortSession.findOne({ cohort: cohort._id, meetUrl: { $ne: '' } }) || {};
|
||||
const link = cohort.meetUrl ? cohort : (await CohortSession.findOne({ cohort: cohort._id, meetUrl: { $ne: '' } }) || {});
|
||||
await CohortSession.create({
|
||||
cohort: cohort._id,
|
||||
index: (last?.index || 0) + 1,
|
||||
|
|
@ -386,6 +410,7 @@ export async function pushSession(session, reason, { notifyAdmins = false } = {}
|
|||
session.cancelReason = reason || 'Cancelled';
|
||||
await session.save();
|
||||
|
||||
/* No replacement date: the 5:30 job creates the next session on the next meeting day.
|
||||
const nextDate = await nextAppendDate(cohort);
|
||||
const last = await CohortSession.findOne({ cohort: cohort._id }).sort({ index: -1 });
|
||||
const created = await CohortSession.create({
|
||||
|
|
@ -400,7 +425,9 @@ export async function pushSession(session, reason, { notifyAdmins = false } = {}
|
|||
records: recordsFor(patientIds(cohort)),
|
||||
});
|
||||
await ensureSessionRecords(cohort);
|
||||
*/
|
||||
await syncExistingMeetSeries(cohort, await CohortSession.find({ cohort: cohort._id }));
|
||||
const nextNote = 'next meeting day (created automatically)';
|
||||
|
||||
const admins = notifyAdmins ? await adminUsers() : [];
|
||||
await notifySessionPushed({
|
||||
|
|
@ -408,15 +435,15 @@ export async function pushSession(session, reason, { notifyAdmins = false } = {}
|
|||
admins,
|
||||
cohort,
|
||||
fromDate,
|
||||
toDate: nextDate,
|
||||
toDate: nextNote,
|
||||
reason,
|
||||
});
|
||||
const { notifyGroupSessionChange } = await import('./whatsapp.js');
|
||||
await notifyGroupSessionChange(
|
||||
cohort._id,
|
||||
`The ${fromDate} session for ${cohort.name} was ${reason || 'rescheduled'}. The replacement date is ${nextDate}.`,
|
||||
`The ${fromDate} session for ${cohort.name} was ${reason || 'cancelled'}. The next session will be on the next meeting day.`,
|
||||
);
|
||||
return { cancelled: session, appended: created };
|
||||
return { cancelled: session, appended: null };
|
||||
}
|
||||
|
||||
export async function pushSessionsOnDate(ymd, reason, { prtId, notifyAdmins = false, languages = null } = {}) {
|
||||
|
|
@ -498,25 +525,29 @@ async function applyMeetToSessions(sessions, event, slot) {
|
|||
}
|
||||
}
|
||||
|
||||
// Creates the cohort's one Google event and Meet link once, then puts that link on its scheduled sessions.
|
||||
export async function ensureMeetForCohort(cohort) {
|
||||
if (!cohort || !isLiveCohortStatus(cohort.status)) {
|
||||
return { outcome: 'skipped' };
|
||||
}
|
||||
await persistCohortSessions(cohort);
|
||||
const sessions = await CohortSession.find({ cohort: cohort._id, status: 'scheduled' }).sort({ index: 1, date: 1 });
|
||||
if (!sessions.length) return { outcome: 'skipped' };
|
||||
|
||||
const existing = sessions.find((session) => session.googleEventId && session.meetUrl);
|
||||
if (existing) {
|
||||
await applyMeetToSessions(sessions, {
|
||||
id: existing.googleEventId,
|
||||
meetUrl: existing.meetUrl,
|
||||
htmlLink: existing.htmlLink,
|
||||
if (!cohort.meetUrl) {
|
||||
const legacy = await CohortSession.findOne({ cohort: cohort._id, googleEventId: { $ne: '' }, meetUrl: { $ne: '' } });
|
||||
if (legacy) {
|
||||
Object.assign(cohort, { googleEventId: legacy.googleEventId, meetUrl: legacy.meetUrl, htmlLink: legacy.htmlLink });
|
||||
await Cohort.updateOne({ _id: cohort._id }, { $set: { googleEventId: legacy.googleEventId, meetUrl: legacy.meetUrl, htmlLink: legacy.htmlLink } });
|
||||
}
|
||||
}
|
||||
if (cohort.meetUrl) {
|
||||
await applyMeetToSessions(sessions.filter((session) => !session.meetUrl), {
|
||||
id: cohort.googleEventId,
|
||||
meetUrl: cohort.meetUrl,
|
||||
htmlLink: cohort.htmlLink,
|
||||
}, cohort.slot);
|
||||
return { outcome: 'skipped', event: existing };
|
||||
return { outcome: 'skipped' };
|
||||
}
|
||||
|
||||
const host = await sessionHost(sessions[0], cohort);
|
||||
const host = await sessionHost(sessions[0] || {}, cohort);
|
||||
if (!host || !host.isActive) {
|
||||
return { outcome: 'failed', error: 'Virtual PRT account is missing or inactive' };
|
||||
}
|
||||
|
|
@ -526,29 +557,31 @@ export async function ensureMeetForCohort(cohort) {
|
|||
|
||||
const settings = await getAppSettings();
|
||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
||||
const first = sessions[0];
|
||||
const last = sessions[sessions.length - 1];
|
||||
const times = slotDateTimes(first.date, first.slot || cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
|
||||
const firstDate = sessions[0]?.date || toYmd(cohort.startDate);
|
||||
const times = slotDateTimes(firstDate, cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
|
||||
try {
|
||||
const event = await createCalendarEvent(host, {
|
||||
title: `PR Session · ${cohort.name}`,
|
||||
description: `Pulmonary rehab repeat meetings for ${cohort.name} (${sessions.length} sessions).`,
|
||||
description: `Pulmonary rehab meetings for ${cohort.name}.`,
|
||||
start: times.start,
|
||||
end: times.end,
|
||||
timeZone: env.APP_TIMEZONE,
|
||||
autoAdmit: true,
|
||||
allowMicVideo: true,
|
||||
recurrence: sessionRecurrence({
|
||||
firstDate: first.date,
|
||||
lastDate: last.date,
|
||||
firstDate,
|
||||
lastDate: firstDate,
|
||||
interval: settings.repeatIntervalDays,
|
||||
startTime: times.startTime,
|
||||
timeZone: env.APP_TIMEZONE,
|
||||
includeDates: sessions.map((session) => session.date),
|
||||
includeDates: [firstDate],
|
||||
weekdays,
|
||||
}),
|
||||
});
|
||||
await applyMeetToSessions(sessions, event, first.slot || cohort.slot);
|
||||
const link = { googleEventId: event.id || '', meetUrl: event.meetUrl || '', htmlLink: event.htmlLink || '' };
|
||||
Object.assign(cohort, link);
|
||||
await Cohort.updateOne({ _id: cohort._id }, { $set: link });
|
||||
await applyMeetToSessions(sessions, event, cohort.slot);
|
||||
if (event.meetUrl) {
|
||||
const { notifyGroupMeetLink } = await import('./whatsapp.js');
|
||||
await notifyGroupMeetLink(cohort._id, event.meetUrl).catch((err) => {
|
||||
|
|
@ -693,17 +726,22 @@ export async function listSessions({ from, to, virtualPrtId, cohortId } = {}) {
|
|||
}
|
||||
|
||||
export async function attendanceProgress(patientId) {
|
||||
const sessions = await CohortSession.find({ 'records.patient': patientId, status: { $in: ['scheduled', 'completed'] } });
|
||||
const sessions = await CohortSession.find({ 'records.patient': patientId, status: 'completed' });
|
||||
let attended = 0;
|
||||
for (const session of sessions) {
|
||||
if ((session.records || []).some((record) => String(record.patient) === String(patientId) && record.attended)) {
|
||||
attended += 1;
|
||||
}
|
||||
}
|
||||
/* Total from program length is off.
|
||||
const patient = await OnboardedPatient.findById(patientId).populate('cohort', 'createdAs sixDayWeek scheduleId');
|
||||
const settings = await getAppSettings();
|
||||
const total = await cohortProgramLength(patient?.cohort, settings);
|
||||
return { attended, total };
|
||||
*/
|
||||
// return { attended, completed: sessions.length };
|
||||
const person = await OnboardedPatient.findById(patientId).select('offlineSessions').lean();
|
||||
return { attended, completed: sessions.length + (Number(person?.offlineSessions) || 0) };
|
||||
}
|
||||
|
||||
// Each patient's own session number on each session, counted by date across all their cohorts.
|
||||
|
|
@ -714,12 +752,15 @@ export async function patientSessionNumbers(sessions) {
|
|||
const all = await CohortSession.find({ 'records.patient': { $in: ids }, status: { $ne: 'cancelled' } })
|
||||
.select('_id date index records.patient')
|
||||
.sort({ date: 1, index: 1 });
|
||||
const offline = new Map((await OnboardedPatient.find({ _id: { $in: ids } }).select('offlineSessions').lean())
|
||||
.map((person) => [String(person._id), Number(person.offlineSessions) || 0]));
|
||||
const seen = new Map();
|
||||
for (const session of all) {
|
||||
for (const record of session.records || []) {
|
||||
const id = String(record.patient);
|
||||
if (!ids.includes(id)) continue;
|
||||
const next = (seen.get(id) || 0) + 1;
|
||||
// const next = (seen.get(id) || 0) + 1;
|
||||
const next = (seen.has(id) ? seen.get(id) : (offline.get(id) || 0)) + 1;
|
||||
seen.set(id, next);
|
||||
numbers.set(`${session._id}:${id}`, next);
|
||||
}
|
||||
|
|
@ -830,14 +871,14 @@ export async function moveSessionEvent(session, nextDate) {
|
|||
export async function patientProgramStats(patientIds) {
|
||||
const ids = patientIds.map((id) => String(id));
|
||||
const sessions = await CohortSession.find({ 'records.patient': { $in: ids }, status: { $in: ['scheduled', 'completed'] } });
|
||||
const byPatient = new Map(ids.map((id) => [id, { attended: 0, total: 0, completed: 0, assigned: 0, firstDate: '', vitals: [] }]));
|
||||
const byPatient = new Map(ids.map((id) => [id, { attended: 0, completed: 0, firstDate: '', vitals: [] }]));
|
||||
for (const session of sessions) {
|
||||
for (const record of session.records || []) {
|
||||
const id = String(record.patient);
|
||||
const row = byPatient.get(id);
|
||||
if (!row) continue;
|
||||
if (session.status === 'completed') row.completed += 1;
|
||||
else row.assigned += 1;
|
||||
// else row.assigned += 1; // assigned count is off
|
||||
if (!row.firstDate || session.date < row.firstDate) row.firstDate = session.date;
|
||||
if (record.attended) row.attended += 1;
|
||||
if (record.pre?.spo2 != null || record.post?.spo2 != null || record.pre?.pulse != null) {
|
||||
|
|
@ -849,6 +890,14 @@ export async function patientProgramStats(patientIds) {
|
|||
}
|
||||
}
|
||||
}
|
||||
const offline = await OnboardedPatient.find({ _id: { $in: ids } }).select('offlineSessions offlineStartDate').lean();
|
||||
for (const person of offline) {
|
||||
const row = byPatient.get(String(person._id));
|
||||
if (!row) continue;
|
||||
row.completed += Number(person.offlineSessions) || 0; // offline sessions count as completed
|
||||
if (person.offlineStartDate && (!row.firstDate || person.offlineStartDate < row.firstDate)) row.firstDate = person.offlineStartDate;
|
||||
}
|
||||
/* Total and assigned from program length are off.
|
||||
const settings = await getAppSettings();
|
||||
const people = await OnboardedPatient.find({ _id: { $in: ids } }).populate('cohort', 'createdAs sixDayWeek scheduleId');
|
||||
const lengths = new Map();
|
||||
|
|
@ -862,6 +911,7 @@ export async function patientProgramStats(patientIds) {
|
|||
row.total = total;
|
||||
row.assigned = Math.max(0, total - row.completed);
|
||||
}
|
||||
*/
|
||||
return byPatient;
|
||||
}
|
||||
|
||||
|
|
@ -876,3 +926,77 @@ export async function listOnboardedForReports({ virtualPrtId, diseaseType, cohor
|
|||
.populate('onboardedBy', 'firstName lastName email')
|
||||
.sort({ name: 1 });
|
||||
}
|
||||
|
||||
function vitalsOut(value) {
|
||||
return { bp: value?.bp || '', spo2: value?.spo2 ?? null, pulse: value?.pulse ?? null };
|
||||
}
|
||||
|
||||
function vitalsIn(value) {
|
||||
const num = (v) => (v === '' || v == null ? null : Number(v));
|
||||
return { bp: String(value?.bp || '').trim(), spo2: num(value?.spo2), pulse: num(value?.pulse) };
|
||||
}
|
||||
|
||||
// Every session of one patient in order: offline sessions first, then completed online sessions across cohorts.
|
||||
export async function patientVitalsRows(patientId) {
|
||||
const patient = await OnboardedPatient.findById(patientId).select('offlineSessions offlineStartDate offlineRecords');
|
||||
if (!patient) return null;
|
||||
const rows = [];
|
||||
const offlineCount = Number(patient.offlineSessions) || 0;
|
||||
const saved = new Map((patient.offlineRecords || []).map((record) => [record.number, record]));
|
||||
for (let number = 1; number <= offlineCount; number += 1) {
|
||||
const record = saved.get(number) || {};
|
||||
rows.push({
|
||||
number,
|
||||
kind: 'offline',
|
||||
sessionId: '',
|
||||
date: number === 1 ? patient.offlineStartDate || '' : '',
|
||||
cohort: 'Offline',
|
||||
attended: record.attended ?? true,
|
||||
pre: vitalsOut(record.pre),
|
||||
post: vitalsOut(record.post),
|
||||
assessment: record.assessment || {},
|
||||
});
|
||||
}
|
||||
const sessions = await CohortSession.find({ 'records.patient': patient._id, status: 'completed' })
|
||||
.populate('cohort', 'name')
|
||||
.sort({ date: 1, index: 1 });
|
||||
const numbers = await patientSessionNumbers(sessions);
|
||||
for (const session of sessions) {
|
||||
const record = (session.records || []).find((item) => String(item.patient) === String(patient._id)) || {};
|
||||
rows.push({
|
||||
number: numbers.get(`${session._id}:${patient._id}`) || null,
|
||||
kind: 'online',
|
||||
sessionId: String(session._id),
|
||||
date: session.date,
|
||||
cohort: session.cohort?.name || '',
|
||||
attended: Boolean(record.attended),
|
||||
pre: vitalsOut(record.pre),
|
||||
post: vitalsOut(record.post),
|
||||
assessment: record.assessment || {},
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Saves one patient's vitals rows: offline rows on the patient, online rows through saveSessionRecords.
|
||||
export async function savePatientVitals(patientId, rows = []) {
|
||||
const patient = await OnboardedPatient.findById(patientId);
|
||||
if (!patient) return null;
|
||||
const offlineCount = Number(patient.offlineSessions) || 0;
|
||||
const offline = new Map((patient.offlineRecords || []).map((record) => [record.number, record.toObject ? record.toObject() : record]));
|
||||
for (const row of 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 || {} });
|
||||
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 }]);
|
||||
}
|
||||
patient.offlineRecords = [...offline.values()].sort((a, b) => a.number - b.number);
|
||||
await patient.save();
|
||||
return patientVitalsRows(patient._id);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -185,6 +185,8 @@ export function toOnboardedPatientDto(item) {
|
|||
preferredWeekday: item.preferredWeekday ?? null,
|
||||
sessionDate: item.sessionDate || null,
|
||||
cohortJoinedOn: item.cohortJoinedOn || '',
|
||||
offlineSessions: item.offlineSessions || 0,
|
||||
offlineStartDate: item.offlineStartDate || '',
|
||||
slot: item.slot || '',
|
||||
matchingStatus: item.matchingStatus || 'unassigned',
|
||||
rejectReason: item.rejectReason || '',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,106 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { Button, FormCheck, FormLabel, Modal, ModalBody, ModalFooter, ModalHeader } from 'react-bootstrap';
|
||||
import { api } from '@/lib/api';
|
||||
|
||||
// Status select for an existing cohort; Cancelled also asks where the patients go.
|
||||
export default function CohortStatusField({ cohortId, value, onChange }) {
|
||||
const [targets, setTargets] = useState([]);
|
||||
const cancelling = value.status === 'cancelled' && value.original !== 'cancelled';
|
||||
|
||||
useEffect(() => {
|
||||
if (!cancelling) return undefined;
|
||||
let active = true;
|
||||
api('/api/cohorts?status=active&limit=100').then((data) => {
|
||||
if (active) setTargets((data.items || []).filter((item) => item.id !== cohortId));
|
||||
}).catch(() => {
|
||||
if (active) setTargets([]);
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [cancelling, cohortId]);
|
||||
|
||||
const set = (patch) => onChange({ ...value, ...patch });
|
||||
|
||||
return (
|
||||
<>
|
||||
<FormLabel>Status</FormLabel>
|
||||
<select className="form-select" value={value.status} onChange={(e) => set({ status: e.target.value })}>
|
||||
<option value="active">Active</option>
|
||||
<option value="completed">Completed</option>
|
||||
<option value="cancelled">Cancelled</option>
|
||||
</select>
|
||||
{cancelling ? (
|
||||
<div className="mt-2">
|
||||
<div className="form-text mb-1">Upcoming sessions stop. Where should the patients go?</div>
|
||||
<FormCheck type="radio" id="cancel-pool" name="cancelAction" label="Move all patients to the unassigned pool" checked={value.patientAction === 'pool'} onChange={() => set({ patientAction: 'pool' })} />
|
||||
<FormCheck type="radio" id="cancel-move" name="cancelAction" label="Move all patients to an existing cohort" checked={value.patientAction === 'move'} onChange={() => set({ patientAction: 'move' })} />
|
||||
{value.patientAction === 'move' ? (
|
||||
<select className="form-select mt-2" value={value.targetCohortId} onChange={(e) => set({ targetCohortId: e.target.value })}>
|
||||
<option value="">Select cohort</option>
|
||||
{targets.map((item) => <option key={item.id} value={item.id}>{item.name} · {item.patientCount} patients</option>)}
|
||||
</select>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Starting status value for a loaded cohort.
|
||||
export function cohortStatusValue(cohort) {
|
||||
const status = cohort?.status === 'confirmed' ? 'active' : (cohort?.status || 'active');
|
||||
return { original: status, status, patientAction: 'pool', targetCohortId: '' };
|
||||
}
|
||||
|
||||
// Problem with the chosen status before saving, or an empty string.
|
||||
export function cohortStatusError(value) {
|
||||
if (value?.status === 'cancelled' && value.original !== 'cancelled' && value.patientAction === 'move' && !value.targetCohortId) {
|
||||
return 'Select the cohort to move the patients into.';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/* Old save without the force option.
|
||||
export async function saveCohortStatus(cohortId, value) {
|
||||
if (!value || value.status === value.original) return;
|
||||
await api(`/api/cohorts/${cohortId}/status`, {
|
||||
method: 'POST',
|
||||
body: { status: value.status, patientAction: value.patientAction, targetCohortId: value.targetCohortId || null },
|
||||
});
|
||||
}
|
||||
*/
|
||||
|
||||
// Saves a changed status after the cohort itself is saved. Does nothing when unchanged.
|
||||
export async function saveCohortStatus(cohortId, value, { force = false } = {}) {
|
||||
if (!value || value.status === value.original) return;
|
||||
await api(`/api/cohorts/${cohortId}/status`, {
|
||||
method: 'POST',
|
||||
body: { status: value.status, patientAction: value.patientAction, targetCohortId: value.targetCohortId || null, force },
|
||||
});
|
||||
}
|
||||
|
||||
// Warnings for moving the patients of a cancelled cohort, checked before anything is saved.
|
||||
export async function cohortStatusWarnings(cohortId, value) {
|
||||
if (!value || value.status === value.original || value.status !== 'cancelled' || value.patientAction !== 'move') return [];
|
||||
const data = await api(`/api/cohorts/${cohortId}/status`, {
|
||||
method: 'POST',
|
||||
body: { status: value.status, patientAction: value.patientAction, targetCohortId: value.targetCohortId || null, check: true },
|
||||
});
|
||||
return data?.warnings || [];
|
||||
}
|
||||
|
||||
// Confirmation box listing why the target cohort does not match.
|
||||
export function CohortStatusConfirm({ warnings, busy, onCancel, onConfirm }) {
|
||||
return (
|
||||
<Modal show={warnings.length > 0} onHide={onCancel}>
|
||||
<ModalHeader closeButton><h5 className="modal-title">Target cohort does not fully match</h5></ModalHeader>
|
||||
<ModalBody>
|
||||
<ul className="mb-2 ps-3">{warnings.map((warning) => <li key={warning}>{warning}</li>)}</ul>
|
||||
Do you still want to move the patients?
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button variant="light" onClick={onCancel}>Cancel</Button>
|
||||
<Button variant="warning" disabled={busy} onClick={onConfirm}>{busy ? 'Saving…' : 'Move anyway'}</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
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 { api } from '@/lib/api';
|
||||
|
||||
const blank = (value) => (value == null ? '' : value);
|
||||
|
||||
// Every session of one patient (offline first), with vitals to view, fill, and save.
|
||||
export default function PatientVitalsModal({ patient, onClose }) {
|
||||
const [rows, setRows] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!patient?.id) return undefined;
|
||||
let active = true;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
api(`/api/onboarding/${patient.id}/vitals`).then((data) => {
|
||||
if (active) setRows(data.items || []);
|
||||
}).catch((err) => {
|
||||
if (active) setError(err.message);
|
||||
}).finally(() => {
|
||||
if (active) setLoading(false);
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [patient?.id]);
|
||||
|
||||
const setRow = (index, patch) => setRows((current) => current.map((row, i) => (i === index ? { ...row, ...patch } : row)));
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
setError('');
|
||||
try {
|
||||
await api(`/api/onboarding/${patient.id}/vitals`, { method: 'PUT', body: { rows } });
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal show={Boolean(patient)} onHide={onClose} size="lg">
|
||||
<ModalHeader closeButton><h5 className="modal-title">Vitals · {patient?.name}</h5></ModalHeader>
|
||||
<ModalBody>
|
||||
{error ? <div className="alert alert-danger">{error}</div> : null}
|
||||
{loading ? <p className="text-muted mb-0">Loading…</p> : null}
|
||||
{!loading && !rows.length ? <p className="text-muted mb-0">No completed sessions yet.</p> : null}
|
||||
{rows.map((row, index) => (
|
||||
<div key={`${row.kind}-${row.sessionId || row.number}`} className="border rounded p-3 mb-3">
|
||||
<div className="d-flex justify-content-between align-items-center mb-2">
|
||||
<strong>
|
||||
Session {row.number || '—'}
|
||||
<span className="text-muted small ms-2">{[row.date, row.cohort].filter(Boolean).join(' · ')}</span>
|
||||
</strong>
|
||||
<FormCheck type="switch" label="Attended" checked={Boolean(row.attended)} onChange={(e) => setRow(index, { attended: e.target.checked })} />
|
||||
</div>
|
||||
<Row className="g-2">
|
||||
{['pre', 'post'].map((when) => (
|
||||
<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>
|
||||
</Row>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
{[15, 30].includes(Number(row.number)) ? (
|
||||
<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 } })} />
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button variant="light" onClick={onClose}>Close</Button>
|
||||
<Button onClick={save} disabled={saving || !rows.length}>{saving ? 'Saving…' : 'Save vitals'}</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -21,7 +21,8 @@ function emptyAssessment() {
|
|||
};
|
||||
}
|
||||
|
||||
const ASSESSMENT_FIELDS = [
|
||||
// const ASSESSMENT_FIELDS = [
|
||||
export const ASSESSMENT_FIELDS = [
|
||||
['fev1', 'FEV1'],
|
||||
['fvc', 'FVC'],
|
||||
['sixMwt', '6-minute walk'],
|
||||
|
|
|
|||
|
|
@ -4,8 +4,10 @@ import { Button, Card, CardBody, Col, Container, FormCheck, FormControl, FormLab
|
|||
import DateField from '@/components/DateField';
|
||||
import PageBreadcrumb from '@/components/PageBreadcrumb';
|
||||
import SlotSelect from '@/components/SlotSelect';
|
||||
import { buildCohortName, formatInterval, formatWeekdays, useSettings } from '@/hooks/useSettings';
|
||||
// import { buildCohortName, formatInterval, formatWeekdays, useSettings } from '@/hooks/useSettings'; // formatInterval was only for the session list
|
||||
import { buildCohortName, formatWeekdays, useSettings } from '@/hooks/useSettings';
|
||||
import { api } from '@/lib/api';
|
||||
import CohortStatusField, { CohortStatusConfirm, cohortStatusError, cohortStatusValue, cohortStatusWarnings, saveCohortStatus } from '@/components/CohortStatusField';
|
||||
|
||||
const empty = {
|
||||
name: '',
|
||||
|
|
@ -49,16 +51,18 @@ export default function CohortForm() {
|
|||
const [patientHits, setPatientHits] = useState([]);
|
||||
const [selectedDetails, setSelectedDetails] = useState([]);
|
||||
const [patientSearch, setPatientSearch] = useState('');
|
||||
const [sessions, setSessions] = useState([]);
|
||||
const [sessionSummary, setSessionSummary] = useState({ completed: 0, planned: 0 });
|
||||
// const [sessions, setSessions] = useState([]); // session list is off: sessions are created daily now
|
||||
// const [sessionSummary, setSessionSummary] = useState({ completed: 0, planned: 0 });
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [statusValue, setStatusValue] = useState(null);
|
||||
const [statusWarnings, setStatusWarnings] = useState([]);
|
||||
const { settings } = useSettings();
|
||||
const startWeekdays = settings?.cohortStartWeekdays || [1, 2];
|
||||
const schedules = settings?.cohortSchedules || [];
|
||||
const chosenSchedule = schedules.find((item) => item.id === form.scheduleId);
|
||||
const allowedDays = (chosenSchedule?.weekdays?.length ? chosenSchedule.weekdays.map(Number) : startWeekdays).filter((day) => day !== 0);
|
||||
const sessionCount = chosenSchedule?.upcomingSessionCount || settings?.upcomingSessionCount || 30;
|
||||
// const sessionCount = chosenSchedule?.upcomingSessionCount || settings?.upcomingSessionCount || 30;
|
||||
|
||||
useEffect(() => {
|
||||
api('/api/users/virtual-prts').then((d) => setPrts(d.items || [])).catch(() => {});
|
||||
|
|
@ -90,13 +94,15 @@ export default function CohortForm() {
|
|||
patients: (c.patients || []).map((p) => p.id),
|
||||
});
|
||||
setSelectedDetails((c.patients || []).map((p) => ({ id: p.id, name: p.name, mobile: p.mobile, whatsappOptOut: p.whatsappOptOut })));
|
||||
setSessionSummary({ completed: c.sessionsCompleted || 0, planned: c.sessionsPlanned || 0 });
|
||||
setStatusValue(cohortStatusValue(c));
|
||||
// setSessionSummary({ completed: c.sessionsCompleted || 0, planned: c.sessionsPlanned || 0 });
|
||||
}).catch((err) => {
|
||||
if (active) setError(err.message);
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [id, isEdit]);
|
||||
|
||||
/* Session list is off: sessions are created daily now.
|
||||
useEffect(() => {
|
||||
if (!isEdit) return undefined;
|
||||
let active = true;
|
||||
|
|
@ -107,6 +113,7 @@ export default function CohortForm() {
|
|||
});
|
||||
return () => { active = false; };
|
||||
}, [id, isEdit, sessionCount]);
|
||||
*/
|
||||
|
||||
useEffect(() => {
|
||||
const prt = prts.find((item) => item.id === form.virtualPrt);
|
||||
|
|
@ -149,18 +156,37 @@ export default function CohortForm() {
|
|||
}));
|
||||
};
|
||||
|
||||
const save = async (e) => {
|
||||
e.preventDefault();
|
||||
const save = async (e, confirmed = false) => {
|
||||
e?.preventDefault();
|
||||
setError('');
|
||||
const max = settings?.maxPatientsPerCohort || 10;
|
||||
if (form.patients.length > max) {
|
||||
setError(`A cohort can have at most ${max} patients.`);
|
||||
return;
|
||||
}
|
||||
const statusProblem = cohortStatusError(statusValue);
|
||||
if (statusProblem) {
|
||||
setError(statusProblem);
|
||||
return;
|
||||
}
|
||||
if (isEdit && !confirmed) {
|
||||
try {
|
||||
const warnings = await cohortStatusWarnings(id, statusValue);
|
||||
if (warnings.length) {
|
||||
setStatusWarnings(warnings);
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setSaving(true);
|
||||
const payload = isEdit ? { ...form } : { ...form, createdAs: 'cohorts' };
|
||||
try {
|
||||
if (isEdit) await api(`/api/cohorts/${id}`, { method: 'PATCH', body: payload });
|
||||
// if (isEdit) await saveCohortStatus(id, statusValue);
|
||||
if (isEdit) await saveCohortStatus(id, statusValue, { force: confirmed });
|
||||
else await api('/api/cohorts', { method: 'POST', body: payload });
|
||||
navigate('/cohorts');
|
||||
} catch (err) {
|
||||
|
|
@ -177,9 +203,15 @@ export default function CohortForm() {
|
|||
<CardBody>
|
||||
{error ? <div className="alert alert-danger">{error}</div> : null}
|
||||
<p className="text-muted">
|
||||
{/* Old text with meeting count and repeat:
|
||||
{chosenSchedule
|
||||
? `This schedule meets on ${formatWeekdays(allowedDays)} and plans ${chosenSchedule.upcomingSessionCount || sessionCount} meetings.`
|
||||
: `Start date must be ${formatWeekdays(startWeekdays) || 'a configured weekday'}. Meetings then repeat ${formatInterval(settings?.repeatIntervalDays)}.`}
|
||||
*/}
|
||||
{chosenSchedule
|
||||
? `This schedule meets on ${formatWeekdays(allowedDays)}.`
|
||||
: `Start date must be ${formatWeekdays(startWeekdays) || 'a configured weekday'}.`}
|
||||
{' Sessions are created each meeting day.'}
|
||||
{settings?.skipHolidays !== false || settings?.skipPrtLeave !== false
|
||||
? ` Skipped ${[settings?.skipHolidays !== false ? 'holidays' : null, settings?.skipPrtLeave !== false ? 'Virtual PRT leave' : null].filter(Boolean).join(' and ')} do not count as a meeting.`
|
||||
: ''}
|
||||
|
|
@ -223,6 +255,11 @@ export default function CohortForm() {
|
|||
placeholder={formatWeekdays(allowedDays) || 'Select date'}
|
||||
/>
|
||||
</Col>
|
||||
{isEdit && statusValue && statusValue.original !== 'proposed' ? (
|
||||
<Col md={3}>
|
||||
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
|
||||
</Col>
|
||||
) : null}
|
||||
<Col md={3}>
|
||||
<FormLabel>Slot</FormLabel>
|
||||
<SlotSelect value={form.slot} onChange={(slot) => setForm((f) => ({ ...f, slot }))} required />
|
||||
|
|
@ -287,6 +324,7 @@ export default function CohortForm() {
|
|||
</div>
|
||||
</Col>
|
||||
</Row>
|
||||
{/* Session count and list are off: sessions are created daily now.
|
||||
{isEdit ? (
|
||||
<p className="text-muted mt-4 mb-0">Sessions: {sessionSummary.completed} of {sessionSummary.planned}</p>
|
||||
) : null}
|
||||
|
|
@ -306,6 +344,7 @@ export default function CohortForm() {
|
|||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
*/}
|
||||
<div className="d-flex gap-2 mt-4">
|
||||
<Button type="submit" disabled={saving}>{saving ? 'Saving...' : 'Save cohort'}</Button>
|
||||
<Link className="btn btn-light" to="/cohorts">Cancel</Link>
|
||||
|
|
@ -313,6 +352,12 @@ export default function CohortForm() {
|
|||
</form>
|
||||
</CardBody>
|
||||
</Card>
|
||||
<CohortStatusConfirm
|
||||
warnings={statusWarnings}
|
||||
busy={saving}
|
||||
onCancel={() => setStatusWarnings([])}
|
||||
onConfirm={() => { setStatusWarnings([]); save(null, true); }}
|
||||
/>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
// import { Button, Card, CardFooter, CardHeader, Col, Container, Dropdown, FormCheck, Modal, ModalBody, ModalFooter, ModalHeader, Row } from 'react-bootstrap';
|
||||
import { Button, Card, CardFooter, CardHeader, Col, Container, Modal, ModalBody, ModalFooter, ModalHeader, Row } from 'react-bootstrap';
|
||||
import { createColumnHelper, getCoreRowModel, getSortedRowModel, useReactTable } from '@tanstack/react-table';
|
||||
import { LuSearch } from 'react-icons/lu';
|
||||
|
|
@ -33,8 +34,22 @@ export default function CohortsPage() {
|
|||
const [waCohort, setWaCohort] = useState(null);
|
||||
const [waError, setWaError] = useState('');
|
||||
const [waBusy, setWaBusy] = useState('');
|
||||
/* Status is changed inside the cohort's Edit page now.
|
||||
const [statusEdit, setStatusEdit] = useState(null);
|
||||
const [statusTargets, setStatusTargets] = useState([]);
|
||||
*/
|
||||
const columnHelper = createColumnHelper();
|
||||
|
||||
/* Status is changed inside the cohort's Edit page now.
|
||||
// Opens the status window; cancelling also loads live cohorts the patients can move into.
|
||||
const openStatus = async (cohort, status) => {
|
||||
setStatusEdit({ cohort, status, patientAction: 'pool', targetCohortId: '', error: '', busy: false });
|
||||
if (status !== 'cancelled') return;
|
||||
const data = await api('/api/cohorts?status=active&limit=100').catch(() => ({ items: [] }));
|
||||
setStatusTargets((data.items || []).filter((item) => item.id !== cohort.id && ['active', 'confirmed'].includes(item.status)));
|
||||
};
|
||||
*/
|
||||
|
||||
const load = async () => {
|
||||
const params = new URLSearchParams({
|
||||
search: query,
|
||||
|
|
@ -73,7 +88,9 @@ export default function CohortsPage() {
|
|||
}),
|
||||
columnHelper.accessor((r) => r.diseaseType || '—', { id: 'diseaseType', header: 'Category' }),
|
||||
columnHelper.accessor('patientCount', { header: 'Patients' }),
|
||||
columnHelper.accessor((r) => `${r.sessionsCompleted || 0} of ${r.sessionsPlanned || 0}`, {
|
||||
// columnHelper.accessor((r) => `${r.sessionsCompleted || 0} of ${r.sessionsPlanned || 0}`, {
|
||||
// columnHelper.accessor((r) => `${r.sessionsCompleted || 0} held`, { // sessions are created daily now
|
||||
columnHelper.accessor((r) => r.sessionsCompleted || 0, { // completed sessions
|
||||
id: 'sessions',
|
||||
header: 'Sessions',
|
||||
}),
|
||||
|
|
@ -87,9 +104,42 @@ export default function CohortsPage() {
|
|||
),
|
||||
}),
|
||||
{
|
||||
// header: 'Cohort actions',
|
||||
header: 'Actions',
|
||||
cell: ({ row }) => (
|
||||
<div className="d-flex gap-1">
|
||||
{/* Status dropdown replaced by the Actions menu below.
|
||||
{canFor(row.original.createdAs, 'edit') && row.original.status !== 'proposed' ? (
|
||||
<select
|
||||
className="form-select form-select-sm"
|
||||
style={{ width: 120 }}
|
||||
value={row.original.status === 'confirmed' ? 'active' : (row.original.status || 'active')}
|
||||
onChange={(e) => openStatus(row.original, e.target.value)}
|
||||
>
|
||||
<option value="active">Active</option>
|
||||
<option value="completed">Completed</option>
|
||||
<option value="cancelled">Cancelled</option>
|
||||
</select>
|
||||
) : null}
|
||||
*/}
|
||||
{/* Status is changed inside the cohort's Edit page now.
|
||||
{canFor(row.original.createdAs, 'edit') && row.original.status !== 'proposed' ? (
|
||||
<Dropdown align="end">
|
||||
<Dropdown.Toggle variant="light" size="sm">Cohort action</Dropdown.Toggle>
|
||||
<Dropdown.Menu popperConfig={{ strategy: 'fixed' }}>
|
||||
{!['active', 'confirmed'].includes(row.original.status) ? (
|
||||
<Dropdown.Item onClick={() => openStatus(row.original, 'active')}>Active</Dropdown.Item>
|
||||
) : null}
|
||||
{row.original.status !== 'completed' ? (
|
||||
<Dropdown.Item onClick={() => openStatus(row.original, 'completed')}>Completed</Dropdown.Item>
|
||||
) : null}
|
||||
{row.original.status !== 'cancelled' ? (
|
||||
<Dropdown.Item className="text-danger" onClick={() => openStatus(row.original, 'cancelled')}>Cancelled</Dropdown.Item>
|
||||
) : null}
|
||||
</Dropdown.Menu>
|
||||
</Dropdown>
|
||||
) : null}
|
||||
*/}
|
||||
{canFor(row.original.createdAs, 'edit') ? <Link className="btn btn-default btn-icon btn-sm" to={`/cohorts/${row.original.id}/edit`}><TbEdit className="fs-lg" /></Link> : null}
|
||||
{canFor(row.original.createdAs, 'delete') ? (
|
||||
<Button variant="default" size="sm" className="btn-icon" onClick={() => setDeleteId(row.original.id)}>
|
||||
|
|
@ -129,6 +179,9 @@ export default function CohortsPage() {
|
|||
<option value="">All live</option>
|
||||
<option value="proposed">Proposed</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="completed">Completed</option>
|
||||
<option value="cancelled">Cancelled</option>
|
||||
<option value="all">All</option>
|
||||
</select>
|
||||
</form>
|
||||
{can('prt_cohorts', 'add') ? (
|
||||
|
|
@ -256,6 +309,50 @@ export default function CohortsPage() {
|
|||
<Button variant="light" onClick={() => setWaCohort(null)}>Close</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
{/* Status is changed inside the cohort's Edit page now.
|
||||
<Modal show={Boolean(statusEdit)} onHide={() => setStatusEdit(null)}>
|
||||
<ModalHeader closeButton><h5 className="modal-title text-capitalize">Set {statusEdit?.cohort?.name} to {statusEdit?.status}</h5></ModalHeader>
|
||||
<ModalBody>
|
||||
{statusEdit?.error ? <div className="alert alert-danger">{statusEdit.error}</div> : null}
|
||||
{statusEdit?.status === 'cancelled' ? (
|
||||
<>
|
||||
<p>Upcoming sessions stop. Where should the patients go?</p>
|
||||
<FormCheck type="radio" id="cancel-pool" name="cancelAction" label="Move all patients to the unassigned pool" checked={statusEdit.patientAction === 'pool'} onChange={() => setStatusEdit((s) => ({ ...s, patientAction: 'pool' }))} />
|
||||
<FormCheck type="radio" id="cancel-move" name="cancelAction" label="Move all patients to an existing cohort" checked={statusEdit.patientAction === 'move'} onChange={() => setStatusEdit((s) => ({ ...s, patientAction: 'move' }))} />
|
||||
{statusEdit.patientAction === 'move' ? (
|
||||
<select className="form-select mt-2" value={statusEdit.targetCohortId} onChange={(e) => setStatusEdit((s) => ({ ...s, targetCohortId: e.target.value }))}>
|
||||
<option value="">Select cohort</option>
|
||||
{statusTargets.map((item) => <option key={item.id} value={item.id}>{item.name} · {item.patientCount} patients</option>)}
|
||||
</select>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<p className="mb-0">This cohort will be marked <strong className="text-capitalize">{statusEdit?.status}</strong>.</p>
|
||||
)}
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button variant="light" onClick={() => setStatusEdit(null)}>Cancel</Button>
|
||||
<Button
|
||||
disabled={statusEdit?.busy || (statusEdit?.status === 'cancelled' && statusEdit?.patientAction === 'move' && !statusEdit?.targetCohortId)}
|
||||
onClick={async () => {
|
||||
setStatusEdit((s) => ({ ...s, busy: true, error: '' }));
|
||||
try {
|
||||
await api(`/api/cohorts/${statusEdit.cohort.id}/status`, {
|
||||
method: 'POST',
|
||||
body: { status: statusEdit.status, patientAction: statusEdit.patientAction, targetCohortId: statusEdit.targetCohortId || null },
|
||||
});
|
||||
setStatusEdit(null);
|
||||
await load();
|
||||
} catch (err) {
|
||||
setStatusEdit((s) => ({ ...s, busy: false, error: err.message }));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{statusEdit?.busy ? 'Saving…' : 'Confirm'}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
*/}
|
||||
<DeleteConfirmationModal
|
||||
show={Boolean(deleteId)}
|
||||
onHide={() => setDeleteId(null)}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { useEffect, useMemo, useState } from 'react';
|
||||
// import { useEffect, useMemo, useState } from 'react'; // useMemo was only for the session preview
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import { Button, Card, CardBody, Col, Container, FormCheck, FormControl, FormLabel, Row } from 'react-bootstrap';
|
||||
import { TbPlus, TbTrash } from 'react-icons/tb';
|
||||
|
|
@ -7,8 +8,10 @@ import OptionsSelect from '@/components/OptionsSelect';
|
|||
import PageBreadcrumb from '@/components/PageBreadcrumb';
|
||||
import SlotSelect from '@/components/SlotSelect';
|
||||
import { useAuth } from '@/context/useAuthContext';
|
||||
import { formatInterval, useSettings } from '@/hooks/useSettings';
|
||||
// import { formatInterval, useSettings } from '@/hooks/useSettings'; // formatInterval was only for the session preview
|
||||
import { useSettings } from '@/hooks/useSettings';
|
||||
import { api } from '@/lib/api';
|
||||
import CohortStatusField, { CohortStatusConfirm, cohortStatusError, cohortStatusValue, cohortStatusWarnings, saveCohortStatus } from '@/components/CohortStatusField';
|
||||
import { isMobileNumber, mobileDigits } from '@/lib/mobile';
|
||||
|
||||
function prtLanguages(user) {
|
||||
|
|
@ -16,16 +19,19 @@ function prtLanguages(user) {
|
|||
return user?.language ? [user.language] : [];
|
||||
}
|
||||
|
||||
const emptyPatient = { name: '', mobile: '', age: '', gender: '' };
|
||||
// const emptyPatient = { name: '', mobile: '', age: '', gender: '' };
|
||||
const emptyPatient = { name: '', mobile: '', age: '', gender: '', offlineSessions: '', offlineStartDate: '' };
|
||||
|
||||
function blankRow() {
|
||||
return { key: `${Date.now()}-${Math.random()}`, id: '', existing: false, ...emptyPatient };
|
||||
}
|
||||
|
||||
/* Session preview helpers are off: sessions are created daily now.
|
||||
function toYmd(date) {
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
}
|
||||
*/
|
||||
|
||||
// True when this calendar day can be the start date for the yes or no choice.
|
||||
function dateAllowed(date, sixDayWeek) {
|
||||
|
|
@ -36,6 +42,7 @@ function dateAllowed(date, sixDayWeek) {
|
|||
return false;
|
||||
}
|
||||
|
||||
/* Session preview is off: sessions are created daily now.
|
||||
// Meeting dates from the start date, using the normal repeat. Sunday is skipped.
|
||||
function previewSessionDates(startDate, interval, count) {
|
||||
const needed = Math.min(Math.max(Number(count) || 30, 1), 60);
|
||||
|
|
@ -49,6 +56,7 @@ function previewSessionDates(startDate, interval, count) {
|
|||
}
|
||||
return dates;
|
||||
}
|
||||
*/
|
||||
|
||||
export default function PrtCohortForm() {
|
||||
const { id } = useParams();
|
||||
|
|
@ -67,16 +75,18 @@ export default function PrtCohortForm() {
|
|||
const [rows, setRows] = useState([]);
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const meetingCount = sixDayWeek === 'yes' ? 60 : 30;
|
||||
const interval = settings?.repeatIntervalDays || 2;
|
||||
const [statusValue, setStatusValue] = useState(null);
|
||||
const [statusWarnings, setStatusWarnings] = useState([]);
|
||||
// const meetingCount = sixDayWeek === 'yes' ? 60 : 30; // preview only; sessions are created daily now
|
||||
// const interval = settings?.repeatIntervalDays || 2;
|
||||
const selectedPrt = isVirtualPrt ? user : prts.find((item) => item.id === virtualPrt);
|
||||
const languages = prtLanguages(selectedPrt);
|
||||
const prtId = isVirtualPrt ? user?.id : virtualPrt;
|
||||
const chosenLanguage = languages.includes(language) ? language : (languages[0] || '');
|
||||
const sessions = useMemo(
|
||||
() => previewSessionDates(startDate, interval, meetingCount),
|
||||
[startDate, interval, meetingCount],
|
||||
);
|
||||
// const sessions = useMemo(
|
||||
// () => previewSessionDates(startDate, interval, meetingCount),
|
||||
// [startDate, interval, meetingCount],
|
||||
// );
|
||||
|
||||
useEffect(() => {
|
||||
if (isVirtualPrt) return undefined;
|
||||
|
|
@ -100,6 +110,7 @@ export default function PrtCohortForm() {
|
|||
setDiseaseType(cohort.diseaseType || '');
|
||||
setVirtualPrt(cohort.virtualPrt?.id || '');
|
||||
setSixDayWeek(cohort.sixDayWeek ? 'yes' : 'no');
|
||||
setStatusValue(cohortStatusValue(cohort));
|
||||
setRows((cohort.patients || []).map((patient) => ({
|
||||
key: patient.id,
|
||||
id: patient.id,
|
||||
|
|
@ -126,8 +137,8 @@ export default function PrtCohortForm() {
|
|||
setRows((current) => current.map((row) => (row.key === key ? { ...row, ...patch } : row)));
|
||||
};
|
||||
|
||||
const save = async (e) => {
|
||||
e.preventDefault();
|
||||
const save = async (e, confirmed = false) => {
|
||||
e?.preventDefault();
|
||||
setError('');
|
||||
if (!prtId) {
|
||||
setError('Select a Virtual PRT.');
|
||||
|
|
@ -151,13 +162,37 @@ export default function PrtCohortForm() {
|
|||
setError(`Row ${rows.indexOf(started[badRow]) + 1} needs a name and a 10 digit mobile.`);
|
||||
return;
|
||||
}
|
||||
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).`);
|
||||
return;
|
||||
}
|
||||
const fresh = started.map((row) => ({
|
||||
name: row.name.trim(),
|
||||
mobile: row.mobile.trim(),
|
||||
age: row.age === '' || row.age == null ? '' : row.age,
|
||||
gender: row.gender || '',
|
||||
whatsappOptOut: false,
|
||||
offlineSessions: Number(row.offlineSessions),
|
||||
offlineStartDate: row.offlineStartDate || '',
|
||||
}));
|
||||
const statusProblem = cohortStatusError(statusValue);
|
||||
if (statusProblem) {
|
||||
setError(statusProblem);
|
||||
return;
|
||||
}
|
||||
if (isEdit && !confirmed) {
|
||||
try {
|
||||
const warnings = await cohortStatusWarnings(id, statusValue);
|
||||
if (warnings.length) {
|
||||
setStatusWarnings(warnings);
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setSaving(true);
|
||||
const payload = {
|
||||
startDate,
|
||||
|
|
@ -173,6 +208,8 @@ export default function PrtCohortForm() {
|
|||
};
|
||||
try {
|
||||
if (isEdit) await api(`/api/cohorts/${id}`, { method: 'PATCH', body: payload });
|
||||
// if (isEdit) await saveCohortStatus(id, statusValue);
|
||||
if (isEdit) await saveCohortStatus(id, statusValue, { force: confirmed });
|
||||
else await api('/api/cohorts', { method: 'POST', body: payload });
|
||||
navigate('/cohorts');
|
||||
} catch (err) {
|
||||
|
|
@ -244,6 +281,11 @@ export default function PrtCohortForm() {
|
|||
placeholder={sixDayWeek === 'yes' ? 'Any day except Sunday' : (sixDayWeek === 'no' ? 'Monday or Tuesday' : 'Choose all weekdays first')}
|
||||
/>
|
||||
</Col>
|
||||
{isEdit && statusValue && statusValue.original !== 'proposed' ? (
|
||||
<Col md={3}>
|
||||
<CohortStatusField cohortId={id} value={statusValue} onChange={setStatusValue} />
|
||||
</Col>
|
||||
) : null}
|
||||
<div className="w-100" />
|
||||
<Col md={6}>
|
||||
<FormLabel>Category</FormLabel>
|
||||
|
|
@ -280,7 +322,8 @@ export default function PrtCohortForm() {
|
|||
</div>
|
||||
{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 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="table-responsive border rounded">
|
||||
<table className="table table-sm align-middle mb-0">
|
||||
<thead>
|
||||
|
|
@ -289,6 +332,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: 170 }}>Start date</th>
|
||||
<th style={{ width: 48 }} />
|
||||
</tr>
|
||||
</thead>
|
||||
|
|
@ -329,6 +374,26 @@ export default function PrtCohortForm() {
|
|||
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 })}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{row.existing ? <span className="text-muted">—</span> : (
|
||||
<FormControl
|
||||
type="date"
|
||||
value={row.offlineStartDate}
|
||||
onChange={(e) => updateRow(row.key, { offlineStartDate: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<Button
|
||||
type="button"
|
||||
|
|
@ -349,6 +414,7 @@ export default function PrtCohortForm() {
|
|||
) : null}
|
||||
</Col>
|
||||
</Row>
|
||||
{/* Session preview is off: sessions are created daily now.
|
||||
{sessions.length ? (
|
||||
<div className="mt-4">
|
||||
<h6>Sessions from the start date</h6>
|
||||
|
|
@ -363,6 +429,7 @@ export default function PrtCohortForm() {
|
|||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
*/}
|
||||
<div className="d-flex gap-2 mt-4">
|
||||
<Button type="submit" disabled={saving}>{saving ? 'Saving...' : 'Save cohort'}</Button>
|
||||
<Link className="btn btn-light" to="/cohorts">Cancel</Link>
|
||||
|
|
@ -370,6 +437,12 @@ export default function PrtCohortForm() {
|
|||
</form>
|
||||
</CardBody>
|
||||
</Card>
|
||||
<CohortStatusConfirm
|
||||
warnings={statusWarnings}
|
||||
busy={saving}
|
||||
onCancel={() => setStatusWarnings([])}
|
||||
onConfirm={() => { setStatusWarnings([]); save(null, true); }}
|
||||
/>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { createColumnHelper, getCoreRowModel, getSortedRowModel, useReactTable }
|
|||
import { LuSearch } from 'react-icons/lu';
|
||||
import { TbCheck, TbEdit, TbPlus, TbTrash, TbX } from 'react-icons/tb';
|
||||
import PageBreadcrumb from '@/components/PageBreadcrumb';
|
||||
import PatientVitalsModal from '@/components/PatientVitalsModal';
|
||||
import DataTable from '@/components/table/DataTable';
|
||||
import DeleteConfirmationModal from '@/components/table/DeleteConfirmationModal';
|
||||
import TablePagination from '@/components/table/TablePagination';
|
||||
|
|
@ -40,6 +41,8 @@ async function loadScreenshot(id) {
|
|||
return { url: URL.createObjectURL(blob), blob: true };
|
||||
}
|
||||
|
||||
const emptyMigrate = { id: '', cohortId: '', warnings: [], error: '', busy: false };
|
||||
|
||||
export default function OnboardingPage() {
|
||||
const { can, permissions, user } = useAuth();
|
||||
const [searchParams] = useSearchParams();
|
||||
|
|
@ -57,7 +60,9 @@ export default function OnboardingPage() {
|
|||
const [addedByOptions, setAddedByOptions] = useState([]);
|
||||
const { settings } = useSettings();
|
||||
const [reject, setReject] = useState({ id: '', reason: '' });
|
||||
const [migrate, setMigrate] = useState({ id: '', cohortId: '', slot: '', preferredWeekday: '' });
|
||||
// const [migrate, setMigrate] = useState({ id: '', cohortId: '', slot: '', preferredWeekday: '' });
|
||||
const [migrate, setMigrate] = useState(emptyMigrate);
|
||||
const [vitalsPatient, setVitalsPatient] = useState(null);
|
||||
const [cohorts, setCohorts] = useState([]);
|
||||
const [deleteId, setDeleteId] = useState(null);
|
||||
const [busyId, setBusyId] = useState(null);
|
||||
|
|
@ -80,6 +85,22 @@ export default function OnboardingPage() {
|
|||
if (Array.isArray(data.addedBy)) setAddedByOptions(data.addedBy);
|
||||
};
|
||||
|
||||
// Moves the patient. The server returns warnings when the cohort does not match; force moves anyway.
|
||||
const submitMigrate = async (force) => {
|
||||
setMigrate((current) => ({ ...current, busy: true, error: '' }));
|
||||
try {
|
||||
await api(`/api/onboarding/${migrate.id}/migrate`, { method: 'POST', body: { cohortId: migrate.cohortId, force } });
|
||||
setMigrate(emptyMigrate);
|
||||
await load();
|
||||
} catch (err) {
|
||||
if (err.status === 409 && err.data?.warnings?.length) {
|
||||
setMigrate((current) => ({ ...current, busy: false, warnings: err.data.warnings }));
|
||||
} else {
|
||||
setMigrate((current) => ({ ...current, busy: false, error: err.message }));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load().catch(() => {});
|
||||
}, [page, query, list, paymentStatus, category, addedBy]);
|
||||
|
|
@ -124,10 +145,13 @@ export default function OnboardingPage() {
|
|||
columnHelper.accessor('mobile', { header: 'Mobile' }),
|
||||
columnHelper.accessor((r) => r.cohort?.name || (r.matchingStatus === 'held' ? 'Held' : 'Pool'), { id: 'cohort', header: 'Cohort' }),
|
||||
columnHelper.accessor((r) => r.diseaseType || '—', { id: 'diseaseType', header: 'Category' }),
|
||||
columnHelper.accessor((r) => formatDate(r.progress?.firstDate || r.sessionDate), { id: 'sessionDate', header: 'Start date' }),
|
||||
// columnHelper.accessor((r) => formatDate(r.progress?.firstDate || r.sessionDate), { id: 'sessionDate', header: 'Start date' }),
|
||||
columnHelper.accessor((r) => formatDate(r.progress?.firstDate || r.cohort?.startDate || r.sessionDate), { id: 'sessionDate', header: 'Start date' }),
|
||||
columnHelper.accessor('slot', { header: 'Slot' }),
|
||||
columnHelper.accessor('paymentStatus', { header: 'Payment' }),
|
||||
columnHelper.accessor((r) => r.progress ? `${r.progress.attended}/${r.progress.total}` : '—', { id: 'progress', header: 'Sessions' }),
|
||||
// columnHelper.accessor((r) => r.progress ? `${r.progress.attended}/${r.progress.total}` : '—', { id: 'progress', header: 'Sessions' }),
|
||||
// columnHelper.accessor((r) => r.progress ? `${r.progress.attended}/${r.progress.completed}` : '—', { id: 'progress', header: 'Attended / held' }),
|
||||
columnHelper.accessor((r) => r.progress?.completed ?? 0, { id: 'progress', header: 'Sessions completed' }),
|
||||
columnHelper.accessor((r) => r.reviewStatus || 'pending', {
|
||||
id: 'reviewStatus',
|
||||
header: 'Status',
|
||||
|
|
@ -176,8 +200,13 @@ export default function OnboardingPage() {
|
|||
<TbX className="fs-lg" />
|
||||
</Button>
|
||||
) : null}
|
||||
{item.reviewStatus === 'confirmed' ? (
|
||||
<Button variant="outline-primary" size="sm" onClick={() => setVitalsPatient({ id: item.id, name: item.name })}>
|
||||
Vitals
|
||||
</Button>
|
||||
) : null}
|
||||
{canReview && item.reviewStatus === 'confirmed' ? (
|
||||
<Button variant="outline-secondary" size="sm" onClick={() => setMigrate({ id: item.id, cohortId: item.cohort?.id || '', slot: item.slot || '', preferredWeekday: item.preferredWeekday ?? '' })}>
|
||||
<Button variant="outline-secondary" size="sm" onClick={() => setMigrate({ ...emptyMigrate, id: item.id, cohortId: item.cohort?.id || '' })}>
|
||||
Move
|
||||
</Button>
|
||||
) : null}
|
||||
|
|
@ -320,6 +349,7 @@ export default function OnboardingPage() {
|
|||
<Button variant="danger" disabled={!reject.reason.trim()} onClick={() => review(reject.id, 'rejected', reject.reason)}>Reject</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
{/* Old Move window with slot and weekday fields.
|
||||
<Modal show={Boolean(migrate.id)} onHide={() => setMigrate({ id: '', cohortId: '', slot: '', preferredWeekday: '' })}>
|
||||
<ModalHeader closeButton><h5 className="modal-title">Move patient</h5></ModalHeader>
|
||||
<ModalBody>
|
||||
|
|
@ -353,6 +383,37 @@ export default function OnboardingPage() {
|
|||
}}>Move</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
*/}
|
||||
<Modal show={Boolean(migrate.id)} onHide={() => setMigrate(emptyMigrate)}>
|
||||
<ModalHeader closeButton><h5 className="modal-title">Move patient</h5></ModalHeader>
|
||||
<ModalBody>
|
||||
{migrate.error ? <div className="alert alert-danger">{migrate.error}</div> : null}
|
||||
<label className="form-label">Target cohort</label>
|
||||
<select className="form-select" value={migrate.cohortId} onChange={(e) => setMigrate((current) => ({ ...current, cohortId: e.target.value, warnings: [], error: '' }))}>
|
||||
<option value="">Select cohort</option>
|
||||
{cohorts.map((cohort) => <option key={cohort.id} value={cohort.id}>{cohort.name}</option>)}
|
||||
</select>
|
||||
<div className="form-text">The patient takes this cohort's slot, day and PRT.</div>
|
||||
{migrate.warnings.length ? (
|
||||
<div className="alert alert-warning mt-3 mb-0">
|
||||
<div className="fw-semibold mb-1">This cohort does not fully match:</div>
|
||||
<ul className="mb-1 ps-3">{migrate.warnings.map((warning) => <li key={warning}>{warning}</li>)}</ul>
|
||||
Do you still want to move this patient?
|
||||
</div>
|
||||
) : null}
|
||||
</ModalBody>
|
||||
<div className="modal-footer">
|
||||
<Button variant="light" onClick={() => setMigrate(emptyMigrate)}>Cancel</Button>
|
||||
<Button
|
||||
variant={migrate.warnings.length ? 'warning' : 'primary'}
|
||||
disabled={!migrate.cohortId || migrate.busy}
|
||||
onClick={() => submitMigrate(migrate.warnings.length > 0)}
|
||||
>
|
||||
{migrate.warnings.length ? 'Move anyway' : 'Move'}
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
<PatientVitalsModal patient={vitalsPatient} onClose={() => setVitalsPatient(null)} />
|
||||
<DeleteConfirmationModal
|
||||
show={Boolean(deleteId)}
|
||||
onHide={() => setDeleteId(null)}
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ export default function ReportsPage() {
|
|||
<CardBody>
|
||||
<h5 className="mb-3">Patient progress</h5>
|
||||
<Table responsive size="sm" className="mb-0">
|
||||
<thead><tr><th>Patient</th><th>Cohort</th><th>PRT</th><th>First session</th><th>Completed</th><th>Assigned</th><th>Attendance</th></tr></thead>
|
||||
<thead><tr><th>Patient</th><th>Cohort</th><th>PRT</th><th>First session</th><th>Completed</th>{/* <th>Assigned</th> */}{/* <th>Attended / held</th> */}</tr></thead>
|
||||
<tbody>
|
||||
{patients.map((item) => (
|
||||
<tr key={item.id}>
|
||||
|
|
@ -59,11 +59,11 @@ export default function ReportsPage() {
|
|||
<td>{item.prt ? `${item.prt.firstName} ${item.prt.lastName}` : '—'}</td>
|
||||
<td>{item.firstSession || '—'}</td>
|
||||
<td>{item.completed}</td>
|
||||
<td>{item.assigned}</td>
|
||||
<td>{item.completion}</td>
|
||||
{/* <td>{item.assigned}</td> */}
|
||||
{/* <td>{item.completion}</td> */}
|
||||
</tr>
|
||||
))}
|
||||
{!patients.length ? <tr><td colSpan={7} className="text-muted">No confirmed patients.</td></tr> : null}
|
||||
{!patients.length ? <tr><td colSpan={5} className="text-muted">No confirmed patients.</td></tr> : null}
|
||||
</tbody>
|
||||
</Table>
|
||||
</CardBody>
|
||||
|
|
|
|||
Loading…
Reference in New Issue