VirtualPR/backend/src/services/programSessions.js

1015 lines
43 KiB
JavaScript

import { env } from '../config/env.js';
import { Cohort } from '../models/Cohort.js';
import { CohortSession } from '../models/CohortSession.js';
import { OnboardedPatient } from '../models/OnboardedPatient.js';
import { Role } from '../models/Role.js';
import { User } from '../models/User.js';
import { createCalendarEvent, deleteCalendarEvent, updateCalendarEvent } from './google.js';
import { notifySessionPushed, notifySessionReminder } from './notify.js';
import {
addDays,
holidayDatesBetween,
leaveCoversDate,
sessionRecurrence,
slotDateTimes,
toYmd,
todayYmd,
upcomingSessionDates,
scheduleSessionCount,
scheduleWeekdays,
weekdayOf,
} from './schedule.js';
import { getAppSettings } from './settings.js';
import { toDmy } from './whatsappFormat.js';
import { toCohortSessionDto } from '../utils/serialize.js';
const LIVE_STATUSES = ['confirmed', 'active'];
export function isLiveCohortStatus(status) {
return !status || LIVE_STATUSES.includes(status);
}
export function liveCohortFilter(virtualPrtId) {
const filter = { status: { $nin: ['proposed', 'completed', 'cancelled'] } };
if (virtualPrtId) filter.virtualPrt = virtualPrtId;
return filter;
}
export async function countLiveCohorts(prtId) {
return Cohort.countDocuments({
virtualPrt: prtId,
status: { $in: ['proposed', 'confirmed', 'active'] },
});
}
export function prtCapacity(prt, settings) {
const configured = Number(prt?.maxCohorts);
if (Number.isFinite(configured) && configured > 0) return configured;
return Number(settings?.maxCohortsPerPrt) || 3;
}
export async function assertPrtCapacity(prt, settings, extra = 1) {
const used = await countLiveCohorts(prt._id);
const max = prtCapacity(prt, settings);
if (used + extra > max) {
throw new Error(`${prt.firstName} ${prt.lastName} already has ${used} of ${max} cohorts.`);
}
}
function patientIds(cohort) {
return (cohort.patients || []).map((item) => item._id || item);
}
function recordsFor(ids) {
return ids.map((patient) => ({ patient, attended: false, pre: {}, post: {} }));
}
// Add PRT cohorts use 60 meetings when all weekdays is yes, otherwise 30.
function manualSessionCount(cohort) {
if (cohort?.createdAs !== 'manual_cohorts') return 0;
return cohort.sixDayWeek ? 60 : 30;
}
// Program length for a cohort: its schedule count, otherwise the settings count, or 60 for a six-day manual cohort.
export async function cohortProgramLength(cohort, settings) {
const ownCount = cohort ? await scheduleSessionCount(cohort.scheduleId) : null;
return Math.min(Math.max(Number(manualSessionCount(cohort) || ownCount || settings?.upcomingSessionCount) || 30, 1), 60);
}
// Completed sessions this patient was on, across every cohort.
async function finishedSessionCounts(patientIds) {
const ids = patientIds.map(String);
const counts = new Map(ids.map((id) => [id, 0]));
if (!ids.length) return counts;
const sessions = await CohortSession.find({ 'records.patient': { $in: ids }, status: 'completed' }).select('records.patient');
for (const session of sessions) {
for (const record of session.records || []) {
const id = String(record.patient);
if (counts.has(id)) counts.set(id, counts.get(id) + 1);
}
}
return counts;
}
// 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);
const weekdays = await scheduleWeekdays(cohort.scheduleId);
const existing = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1, date: 1 });
const active = existing.filter((session) => session.status !== 'cancelled');
const patients = patientIds(cohort);
if (!existing.length) {
const dates = await upcomingSessionDates(
toYmd(cohort.startDate),
cohort.virtualPrt?._id || cohort.virtualPrt,
needed,
cohort.language,
weekdays,
);
if (!dates.length) return [];
await CohortSession.insertMany(dates.map((date, index) => ({
cohort: cohort._id,
index: index + 1,
date,
slot: cohort.slot,
status: 'scheduled',
records: recordsFor(patients),
})));
} else if (active.length < needed) {
let lastIndex = existing.reduce((max, session) => Math.max(max, session.index || 0), 0);
while (active.length < needed) {
const date = await nextAppendDate(cohort);
lastIndex += 1;
const created = await CohortSession.create({
cohort: cohort._id,
index: lastIndex,
date,
slot: cohort.slot,
status: 'scheduled',
records: recordsFor(patients),
});
existing.push(created);
active.push(created);
}
}
*/
await ensureSessionRecords(cohort);
return CohortSession.find({ cohort: cohort._id }).sort({ index: 1 });
}
// Next dates from today or the new start, skipping Sunday, holiday, leave, and completed dates.
async function collectSessionDates(from, cohort, count, weekdays, blocked) {
const dates = [];
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
let cursor = from;
for (let guard = 0; dates.length < count && guard < 8; guard += 1) {
const batch = await upcomingSessionDates(
cursor,
prtId,
Math.min(60, count - dates.length + blocked.size + 5),
cohort.language,
weekdays,
);
if (!batch.length) break;
for (const date of batch) {
if (date < from || blocked.has(date) || dates.includes(date)) continue;
dates.push(date);
if (dates.length >= count) break;
}
const next = addDays(batch[batch.length - 1], 1);
if (next <= cursor) break;
cursor = next;
}
return dates.slice(0, count);
}
// Updates the cohort's Google event to cover every held and upcoming session. The Meet link stays.
async function syncExistingMeetSeries(cohort, sessions) {
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)));
if (!active.length) return;
const host = await sessionHost(linked, cohort);
if (!host?.google?.refreshToken && !host?.google?.accessToken) return;
const settings = await getAppSettings();
const weekdays = await scheduleWeekdays(cohort.scheduleId);
const first = active[0];
const last = active[active.length - 1];
const times = slotDateTimes(first.date, first.slot || cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
try {
await updateCalendarEvent(host, eventId, {
title: `PR Session · ${cohort.name}`,
description: `Pulmonary rehab repeat meetings for ${cohort.name} (${active.length} sessions).`,
start: times.start,
end: times.end,
timeZone: env.APP_TIMEZONE,
recurrence: sessionRecurrence({
firstDate: first.date,
lastDate: last.date,
interval: settings.repeatIntervalDays,
startTime: times.startTime,
timeZone: env.APP_TIMEZONE,
includeDates: active.map((session) => session.date),
weekdays,
}),
});
} catch (err) {
console.error(`[meet] series update failed: ${err?.message || err}`);
}
}
// 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);
const weekdays = await scheduleWeekdays(cohort.scheduleId);
const existing = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1, date: 1 });
const completed = existing.filter((session) => session.status === 'completed');
const open = existing.filter((session) => session.status !== 'completed');
const remaining = Math.max(0, cap - completed.length);
const today = todayYmd(env.APP_TIMEZONE);
const startYmd = toYmd(cohort.startDate);
const from = startYmd >= today ? startYmd : today;
const blocked = new Set(completed.map((session) => session.date));
const dates = remaining
? await collectSessionDates(from, cohort, remaining, weekdays, blocked)
: [];
const link = existing.find((session) => session.googleEventId) || {};
if (open.length) await CohortSession.deleteMany({ _id: { $in: open.map((session) => session._id) } });
let index = completed.reduce((max, session) => Math.max(max, session.index || 0), 0);
if (dates.length) {
await CohortSession.insertMany(dates.map((date) => {
index += 1;
return {
cohort: cohort._id,
index,
date,
slot: cohort.slot,
status: 'scheduled',
googleEventId: link.googleEventId || '',
meetUrl: link.meetUrl || '',
htmlLink: link.htmlLink || '',
records: recordsFor(patientIds(cohort)),
};
}));
}
*/
await ensureSessionRecords(cohort);
const sessions = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1 });
await syncExistingMeetSeries(cohort, sessions);
return sessions;
}
// 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) {
const index = (session.records || []).findIndex((record) => String(record.patient) === id);
const should = keep.has(String(session._id));
if (should && index < 0) {
session.records.push({ patient: id, attended: false, pre: {}, post: {} });
dirty.add(session);
} else if (!should && index >= 0) {
session.records.splice(index, 1);
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();
}
// Next date for an extra schedule, skipping unticked days, Sunday, holiday, and leave.
async function nextWeekdayAppendDate(cohort, weekdays) {
const settings = await getAppSettings();
const allowed = new Set(weekdays.map(Number));
const last = await CohortSession.findOne({ cohort: cohort._id }).sort({ date: -1, index: -1 });
let cursor = last?.date ? addDays(last.date, 1) : toYmd(cohort.startDate);
const horizon = addDays(cursor, 80);
const holidays = settings.skipHolidays !== false
? await holidayDatesBetween(cursor, horizon, cohort.language)
: new Set();
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
for (let guard = 0; guard < 400; guard += 1) {
const weekdayBlocked = !allowed.has(weekdayOf(cursor));
const sundayBlocked = weekdayOf(cursor) === 0;
const holidayBlocked = settings.skipHolidays !== false && holidays.has(cursor);
const leaveBlocked = settings.skipPrtLeave !== false && await leaveCoversDate(prtId, cursor);
if (!weekdayBlocked && !sundayBlocked && !holidayBlocked && !leaveBlocked) return cursor;
cursor = addDays(cursor, 1);
}
return cursor;
}
// Next date after the last session. Extra schedules use weekdays. Normal uses the interval.
export async function nextAppendDate(cohort) {
const weekdays = await scheduleWeekdays(cohort.scheduleId);
if (weekdays) return nextWeekdayAppendDate(cohort, weekdays);
const settings = await getAppSettings();
const interval = Math.max(1, Number(settings.repeatIntervalDays) || 2);
const last = await CohortSession.findOne({ cohort: cohort._id }).sort({ date: -1, index: -1 });
let cursor = last?.date ? addDays(last.date, interval) : toYmd(cohort.startDate);
const horizon = addDays(cursor, interval * 80);
const holidays = settings.skipHolidays !== false
? await holidayDatesBetween(cursor, horizon, cohort.language)
: new Set();
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
for (let guard = 0; guard < 400; guard += 1) {
const sundayBlocked = weekdayOf(cursor) === 0;
const holidayBlocked = settings.skipHolidays !== false && holidays.has(cursor);
const leaveBlocked = settings.skipPrtLeave !== false && await leaveCoversDate(prtId, cursor);
if (!sundayBlocked && !holidayBlocked && !leaveBlocked) return cursor;
cursor = addDays(cursor, interval);
}
return cursor;
}
// True when the cohort may meet on this date: its schedule weekdays if set, never Sunday, and not a holiday or PRT leave.
async function canMeetOn(cohort, date) {
if (weekdayOf(date) === 0) return false;
const weekdays = await scheduleWeekdays(cohort.scheduleId);
if (weekdays && !weekdays.map(Number).includes(weekdayOf(date))) return false;
const settings = await getAppSettings();
if (settings.skipHolidays !== false && (await holidayDatesBetween(date, date, cohort.language)).has(date)) return false;
if (settings.skipPrtLeave !== false && await leaveCoversDate(cohort.virtualPrt?._id || cohort.virtualPrt, date)) return false;
return true;
}
// Adds today's session to open cohorts with no future session left, when today is their next meeting day.
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);
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 = cohort.meetUrl ? cohort : (await CohortSession.findOne({ cohort: cohort._id, meetUrl: { $ne: '' } }) || {});
await CohortSession.create({
cohort: cohort._id,
index: (last?.index || 0) + 1,
date,
slot: cohort.slot,
status: 'scheduled',
googleEventId: link.googleEventId || '',
meetUrl: link.meetUrl || '',
htmlLink: link.htmlLink || '',
records: [],
});
await ensureSessionRecords(cohort);
await syncExistingMeetSeries(cohort, await CohortSession.find({ cohort: cohort._id }));
added += 1;
}
return added;
}
async function sessionHost(session, cohort) {
const coverId = session.coverPrt?._id || session.coverPrt;
if (coverId) {
const cover = await User.findById(coverId);
if (cover) return cover;
}
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
return User.findById(prtId);
}
async function adminUsers() {
const roles = await Role.find({ systemKey: { $in: ['admin', 'super_admin'] } });
if (!roles.length) return [];
return User.find({ role: { $in: roles.map((role) => role._id) }, isActive: true }).select('firstName lastName email');
}
export async function pushSession(session, reason, { notifyAdmins = false } = {}) {
const cohort = await Cohort.findById(session.cohort).populate('virtualPrt', 'firstName lastName email google');
if (!cohort) return null;
const fromDate = session.date;
session.status = 'cancelled';
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({
cohort: cohort._id,
index: (last?.index || 0) + 1,
date: nextDate,
slot: session.slot || cohort.slot,
status: 'scheduled',
googleEventId: session.googleEventId || '',
meetUrl: session.meetUrl || '',
htmlLink: session.htmlLink || '',
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({
prt: cohort.virtualPrt,
admins,
cohort,
fromDate,
toDate: nextNote,
reason,
});
const { notifyGroupSessionChange } = await import('./whatsapp.js');
await notifyGroupSessionChange(
cohort._id,
// `The ${fromDate} session for ${cohort.name} was ${reason || 'cancelled'}. The next session will be on the next meeting day.`,
`The ${toDmy(fromDate)} session for ${cohort.name} was ${reason || 'cancelled'}. The next session will be on the next meeting day.`,
);
return { cancelled: session, appended: null };
}
export async function pushSessionsOnDate(ymd, reason, { prtId, notifyAdmins = false, languages = null } = {}) {
const sessions = await CohortSession.find({ date: ymd, status: 'scheduled' });
const only = (languages || []).map((item) => String(item).trim()).filter(Boolean);
const results = [];
for (const session of sessions) {
const cohort = await Cohort.findById(session.cohort);
if (!cohort || !isLiveCohortStatus(cohort.status)) continue;
if (prtId && String(cohort.virtualPrt) !== String(prtId)) continue;
if (only.length && !only.includes(cohort.language || '')) continue;
results.push(await pushSession(session, reason, { notifyAdmins }));
}
return results;
}
// Slides scheduled sessions off approved leave. Earlier meetings stay, and the meeting count stays the same.
export async function shiftApprovedLeaveSessions(prtId, startYmd, endYmd) {
const settings = await getAppSettings();
if (settings.skipPrtLeave === false) return { shifted: [] };
const cohorts = await Cohort.find({
virtualPrt: prtId,
status: { $in: ['confirmed', 'active'] },
}).populate('virtualPrt', 'firstName lastName email google');
const shifted = [];
for (const cohort of cohorts) {
const sessions = await CohortSession.find({ cohort: cohort._id }).sort({ date: 1, index: 1 });
const hit = sessions.find((session) => (
session.status === 'scheduled' && session.date >= startYmd && session.date <= endYmd
));
if (!hit) continue;
const tail = sessions.filter((session) => session.status === 'scheduled' && session.date >= hit.date);
if (!tail.length) continue;
const weekdays = await scheduleWeekdays(cohort.scheduleId);
const blocked = new Set(
sessions.filter((session) => session.status === 'completed').map((session) => session.date),
);
const dates = await collectSessionDates(hit.date, cohort, tail.length, weekdays, blocked);
if (!dates.length) continue;
const fromDate = tail[0].date;
const toDate = dates[0];
const count = Math.min(tail.length, dates.length);
let changed = false;
for (let i = count - 1; i >= 0; i -= 1) { // later dates move first so two rows never share a date
if (tail[i].date === dates[i]) continue;
tail[i].date = dates[i];
await tail[i].save();
changed = true;
}
if (!changed) continue;
const updated = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1 });
await syncExistingMeetSeries(cohort, updated);
const admins = await adminUsers();
await notifySessionPushed({
prt: cohort.virtualPrt,
admins,
cohort,
fromDate,
toDate,
reason: 'Approved PRT leave',
});
const { notifyGroupSessionChange } = await import('./whatsapp.js');
await notifyGroupSessionChange(
cohort._id,
// `The ${fromDate} session for ${cohort.name} was Approved PRT leave. The replacement date is ${toDate}.`,
`The ${toDmy(fromDate)} session for ${cohort.name} was Approved PRT leave. The replacement date is ${toDmy(toDate)}.`,
);
shifted.push({ cohortId: String(cohort._id), fromDate, toDate });
}
return { shifted };
}
async function applyMeetToSessions(sessions, event, slot) {
for (const session of sessions) {
session.googleEventId = event.id || session.googleEventId || '';
session.meetUrl = event.meetUrl || session.meetUrl || '';
session.htmlLink = event.htmlLink || session.htmlLink || '';
if (slot) session.slot = session.slot || slot;
await session.save();
}
}
// 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' };
}
const sessions = await CohortSession.find({ cohort: cohort._id, status: 'scheduled' }).sort({ index: 1, date: 1 });
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' };
}
const host = await sessionHost(sessions[0] || {}, cohort);
if (!host || !host.isActive) {
return { outcome: 'failed', error: 'Virtual PRT account is missing or inactive' };
}
if (!host.google?.refreshToken && !host.google?.accessToken) {
return { outcome: 'failed', error: 'Connect Google Calendar on Profile to create Meet links' };
}
const settings = await getAppSettings();
const weekdays = await scheduleWeekdays(cohort.scheduleId);
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 meetings for ${cohort.name}.`,
start: times.start,
end: times.end,
timeZone: env.APP_TIMEZONE,
autoAdmit: true,
allowMicVideo: true,
recurrence: sessionRecurrence({
firstDate,
lastDate: firstDate,
interval: settings.repeatIntervalDays,
startTime: times.startTime,
timeZone: env.APP_TIMEZONE,
includeDates: [firstDate],
weekdays,
}),
});
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) => {
console.error(`[whatsapp] meet link notice failed: ${err?.message || err}`);
});
}
return { outcome: 'created', event, startTime: times.startTime, endTime: times.endTime };
} catch (err) {
return { outcome: 'failed', error: err?.message || 'Could not create Google Meet' };
}
}
export async function ensureMeetForSession(session) {
const cohort = session.cohort && typeof session.cohort === 'object'
? session.cohort
: await Cohort.findById(session.cohort).populate('virtualPrt');
if (!cohort || !isLiveCohortStatus(cohort.status)) {
return { session, outcome: 'skipped' };
}
if (session.status !== 'scheduled') return { session, outcome: 'skipped' };
const result = await ensureMeetForCohort(cohort);
const refreshed = await CohortSession.findById(session._id);
const times = slotDateTimes(session.date, session.slot || cohort.slot, cohort.durationMinutes || 60);
return {
session: refreshed || session,
outcome: result.outcome,
error: result.error,
startTime: times.startTime,
endTime: times.endTime,
};
}
function meetingShape(session, extras = {}) {
const dto = toCohortSessionDto(session);
const cohort = dto.cohort;
const times = slotDateTimes(session.date, session.slot || cohort?.slot, 60);
return {
id: dto.id,
date: dto.date,
slot: dto.slot,
startTime: extras.startTime || times.startTime,
endTime: extras.endTime || times.endTime,
title: cohort?.name ? `PR Session · ${cohort.name}` : 'PR Session',
meetUrl: dto.meetUrl,
htmlLink: dto.htmlLink,
status: extras.outcome === 'failed' ? 'failed' : (dto.meetUrl ? 'created' : extras.outcome || 'pending'),
error: extras.error || '',
cohort,
virtualPrt: session.coverPrt && typeof session.coverPrt === 'object'
? session.coverPrt
: cohort?.virtualPrt || null,
session: dto,
};
}
async function ensureLiveCohortSessions(virtualPrtId) {
const filter = liveCohortFilter(virtualPrtId);
const cohorts = await Cohort.find(filter);
for (const cohort of cohorts) {
await persistCohortSessions(cohort);
}
}
async function loadDaySessions(date, virtualPrtId) {
await ensureLiveCohortSessions(virtualPrtId);
const sessions = await CohortSession.find({ date, status: { $ne: 'cancelled' } })
.populate({
path: 'cohort',
populate: { path: 'virtualPrt', select: 'firstName lastName email' },
})
.populate('coverPrt', 'firstName lastName email')
.sort({ slot: 1, index: 1 });
return sessions.filter((session) => {
const cohort = session.cohort;
if (!cohort || !isLiveCohortStatus(cohort.status)) return false;
if (virtualPrtId && String(cohort.virtualPrt?._id || cohort.virtualPrt) !== String(virtualPrtId)
&& String(session.coverPrt?._id || session.coverPrt || '') !== String(virtualPrtId)) {
return false;
}
return true;
});
}
export async function generateMeetsForDate(dateYmd, { virtualPrtId } = {}) {
const date = dateYmd || todayYmd(env.APP_TIMEZONE);
await ensureLiveCohortSessions(virtualPrtId);
const cohorts = await Cohort.find(liveCohortFilter(virtualPrtId)).populate('virtualPrt');
const byCohort = new Map();
for (const cohort of cohorts) {
byCohort.set(String(cohort._id), await ensureMeetForCohort(cohort));
}
const sessions = await loadDaySessions(date, virtualPrtId);
const summary = { date, created: 0, skipped: 0, failed: 0, sessions: sessions.length };
const meetings = [];
for (const session of sessions) {
const result = byCohort.get(String(session.cohort?._id || session.cohort)) || { outcome: 'skipped' };
summary[result.outcome] = (summary[result.outcome] || 0) + 1;
const refreshed = await CohortSession.findById(session._id)
.populate({ path: 'cohort', populate: { path: 'virtualPrt', select: 'firstName lastName email' } })
.populate('coverPrt', 'firstName lastName email');
meetings.push(meetingShape(refreshed, result));
}
return { ...summary, meetings };
}
export async function getSessionsForDate(dateYmd, { virtualPrtId } = {}) {
const date = dateYmd || todayYmd(env.APP_TIMEZONE);
const sessions = await loadDaySessions(date, virtualPrtId);
return {
date,
meetings: sessions.map((session) => meetingShape(session)),
items: sessions.map(toCohortSessionDto),
};
}
export async function listSessions({ from, to, virtualPrtId, cohortId } = {}) {
const filter = {};
if (from || to) {
filter.date = {};
if (from) filter.date.$gte = from;
if (to) filter.date.$lte = to;
}
if (cohortId) filter.cohort = cohortId;
const sessions = await CohortSession.find(filter)
.populate({
path: 'cohort',
populate: { path: 'virtualPrt', select: 'firstName lastName email' },
})
.populate('coverPrt', 'firstName lastName email')
.populate('records.patient', 'name mobile')
.sort({ date: 1, slot: 1, index: 1 });
return sessions.filter((session) => {
const cohort = session.cohort;
if (!cohort) return false;
if (virtualPrtId && String(cohort.virtualPrt?._id || cohort.virtualPrt) !== String(virtualPrtId)
&& String(session.coverPrt?._id || session.coverPrt || '') !== String(virtualPrtId)) {
return false;
}
if (!cohortId && !isLiveCohortStatus(cohort.status) && cohort.status !== 'proposed') return false;
return true;
});
}
export async function attendanceProgress(patientId) {
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.
export async function patientSessionNumbers(sessions) {
const ids = [...new Set(sessions.flatMap((session) => (session.records || []).map((record) => String(record.patient?._id || record.patient))))];
const numbers = new Map();
if (!ids.length) return numbers;
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.has(id) ? seen.get(id) : (offline.get(id) || 0)) + 1;
seen.set(id, next);
numbers.set(`${session._id}:${id}`, next);
}
}
return numbers;
}
// export async function saveSessionRecords(session, records = [], { completed } = {}) {
export async function saveSessionRecords(session, records = [], { completed, userId } = {}) {
const numbers = await patientSessionNumbers([session]);
let prtId = session.coverPrt?._id || session.coverPrt || session.cohort?.virtualPrt?._id || session.cohort?.virtualPrt || null;
if (!prtId) prtId = (await Cohort.findById(session.cohort?._id || session.cohort).select('virtualPrt'))?.virtualPrt || null;
const byPatient = new Map((session.records || []).map((record) => [String(record.patient._id || record.patient), record]));
for (const incoming of records) {
const id = String(incoming.patientId || incoming.patient);
const current = byPatient.get(id) || { patient: id, attended: false, pre: {}, post: {} };
if (incoming.attended != null) current.attended = Boolean(incoming.attended);
if (incoming.pre) {
current.pre = {
bp: incoming.pre.bp ?? current.pre?.bp ?? '',
spo2: incoming.pre.spo2 ?? current.pre?.spo2 ?? null,
pulse: incoming.pre.pulse ?? current.pre?.pulse ?? null,
};
}
if (incoming.post) {
current.post = {
bp: incoming.post.bp ?? current.post?.bp ?? '',
spo2: incoming.post.spo2 ?? current.post?.spo2 ?? null,
pulse: incoming.post.pulse ?? current.post?.pulse ?? null,
};
}
if (incoming.assessment && [15, 30].includes(numbers.get(`${session._id}:${id}`))) {
const previous = current.assessment || {};
current.assessment = {
fev1: incoming.assessment.fev1 ?? previous.fev1 ?? '',
fvc: incoming.assessment.fvc ?? previous.fvc ?? '',
sixMwt: incoming.assessment.sixMwt ?? previous.sixMwt ?? '',
eq5d3l: incoming.assessment.eq5d3l ?? previous.eq5d3l ?? '',
sgrq: incoming.assessment.sgrq ?? previous.sgrq ?? '',
sitToStand: incoming.assessment.sitToStand ?? previous.sitToStand ?? '',
rpeRest: incoming.assessment.rpeRest ?? previous.rpeRest ?? '',
rpeActivity: incoming.assessment.rpeActivity ?? previous.rpeActivity ?? '',
o2Regular: incoming.assessment.o2Regular ?? previous.o2Regular ?? '',
o2WithExercise: incoming.assessment.o2WithExercise ?? previous.o2WithExercise ?? '',
};
}
current.prt = prtId;
if (userId) current.recordedBy = userId;
current.recordedAt = new Date();
byPatient.set(id, current);
}
session.records = [...byPatient.values()];
if (completed || session.records.some((record) => record.attended)) {
session.status = 'completed';
}
await session.save();
return session;
}
export async function sendDueReminders(now = new Date()) {
const date = todayYmd(env.APP_TIMEZONE);
const sessions = await CohortSession.find({ date, status: 'scheduled', reminderSentAt: null })
.populate({ path: 'cohort', populate: { path: 'virtualPrt', select: 'firstName lastName email google' } })
.populate('coverPrt', 'firstName lastName email google');
let sent = 0;
for (const session of sessions) {
const cohort = session.cohort;
if (!cohort || !isLiveCohortStatus(cohort.status)) continue;
const { start } = slotDateTimes(session.date, session.slot || cohort.slot, cohort.durationMinutes || 60);
const startAt = new Date(`${start}+05:30`);
const minutes = (startAt.getTime() - now.getTime()) / 60000;
if (minutes < 90 || minutes > 150) continue;
const host = session.coverPrt || cohort.virtualPrt;
await notifySessionReminder({ prt: host, session, cohort });
session.reminderSentAt = now;
await session.save();
sent += 1;
}
try {
const { sendDueWhatsappReminders } = await import('./whatsapp.js');
sent += await sendDueWhatsappReminders(now);
} catch (err) {
console.error('[whatsapp] reminder pass failed', err);
}
return sent;
}
export async function moveSessionEvent(session, nextDate) {
const cohort = await Cohort.findById(session.cohort).populate('virtualPrt');
if (!cohort) return session;
const host = await sessionHost(session, cohort);
if (!host || !session.googleEventId) return session;
const seriesCount = await CohortSession.countDocuments({
googleEventId: session.googleEventId,
_id: { $ne: session._id },
});
if (seriesCount) return session;
const { start, end } = slotDateTimes(nextDate, session.slot || cohort.slot, cohort.durationMinutes || 60);
try {
await updateCalendarEvent(host, session.googleEventId, {
title: `PR Session · ${cohort.name}`,
start,
end,
timeZone: env.APP_TIMEZONE,
});
} catch {
await deleteCalendarEvent(host, session.googleEventId);
session.googleEventId = '';
session.meetUrl = '';
}
return session;
}
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, 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; // 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) {
row.vitals.push({
date: session.date,
pre: record.pre,
post: record.post,
});
}
}
}
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();
for (const person of people) {
const id = String(person._id);
const row = byPatient.get(id);
if (!row) continue;
const key = person.cohort ? String(person.cohort._id) : '';
if (!lengths.has(key)) lengths.set(key, await cohortProgramLength(person.cohort, settings));
const total = lengths.get(key);
row.total = total;
row.assigned = Math.max(0, total - row.completed);
}
*/
return byPatient;
}
export async function listOnboardedForReports({ virtualPrtId, diseaseType, cohortId } = {}) {
const filter = { reviewStatus: 'confirmed' };
if (virtualPrtId) filter.assignedEducator = virtualPrtId;
if (diseaseType) filter.diseaseType = diseaseType;
if (cohortId) filter.cohort = cohortId;
return OnboardedPatient.find(filter)
.populate('cohort', 'name slot language diseaseType virtualPrt startDate')
.populate('assignedEducator', 'firstName lastName email')
.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 = []) {
export async function savePatientVitals(patientId, rows = [], userId = null) {
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 || {} });
offline.set(number, { number, attended: row.attended !== false, pre: vitalsIn(row.pre), post: vitalsIn(row.post), assessment: row.assessment || {}, recordedBy: userId, recordedAt: new Date() });
continue;
}
if (!row.sessionId) continue;
const session = await CohortSession.findOne({ _id: row.sessionId, 'records.patient': patient._id, status: 'completed' });
if (!session) continue;
// await saveSessionRecords(session, [{ patientId: String(patient._id), attended: Boolean(row.attended), pre: row.pre, post: row.post, assessment: row.assessment }]);
await saveSessionRecords(session, [{ patientId: String(patient._id), attended: Boolean(row.attended), pre: row.pre, post: row.post, assessment: row.assessment }], { userId });
}
patient.offlineRecords = [...offline.values()].sort((a, b) => a.number - b.number);
await patient.save();
return patientVitalsRows(patient._id);
}