updated audit and whatapp admin changes
This commit is contained in:
parent
43842eaabd
commit
4d0060dcd2
|
|
@ -28,6 +28,7 @@ const cohortSchema = new mongoose.Schema(
|
|||
whatsappError: { type: String, default: '' },
|
||||
whatsappMeetNotified: { type: Boolean, default: false },
|
||||
whatsappClosedNotified: { type: Boolean, default: false },
|
||||
whatsappAdminUser: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null }, // therapist promoted as this group's WhatsApp admin
|
||||
whatsappMembers: {
|
||||
type: [{
|
||||
patient: { type: mongoose.Schema.Types.ObjectId, ref: 'OnboardedPatient', required: true },
|
||||
|
|
|
|||
|
|
@ -12,10 +12,31 @@ import { activateManualCohort, cancelCohort, startCohortMeetings } from '../serv
|
|||
import { ensureSessionRecords, persistCohortSessions, rescheduleOpenSessions } from '../services/programSessions.js';
|
||||
import { CohortSession } from '../models/CohortSession.js';
|
||||
import { assertConfiguredSlot, getAppSettings } from '../services/settings.js';
|
||||
import { reminderAuditText, writeAudit } from '../services/audit.js';
|
||||
import { toCohortSessionDto } from '../utils/serialize.js';
|
||||
|
||||
const objectId = Joi.string().hex().length(24);
|
||||
|
||||
function idList(items) {
|
||||
return (items || []).map((item) => String(item?._id || item)).filter(Boolean);
|
||||
}
|
||||
|
||||
// Writes one shallow row for each patient who joined or left this cohort.
|
||||
async function auditPatientMembership(request, cohortId, previousIds, nextIds) {
|
||||
const previous = new Set(previousIds);
|
||||
const next = new Set(nextIds);
|
||||
for (const id of nextIds) {
|
||||
if (!previous.has(id)) {
|
||||
await writeAudit(request, { action: 'cohort.patient_added', resourceType: 'cohort', resourceId: cohortId });
|
||||
}
|
||||
}
|
||||
for (const id of previousIds) {
|
||||
if (!next.has(id)) {
|
||||
await writeAudit(request, { action: 'cohort.patient_removed', resourceType: 'cohort', resourceId: cohortId });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cohortPayload = Joi.object({
|
||||
name: Joi.string().trim().allow('', null),
|
||||
startDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).required(),
|
||||
|
|
@ -183,6 +204,7 @@ export function cohortRoutes(server) {
|
|||
throw Boom.badRequest(err.message);
|
||||
}
|
||||
const name = buildCohortName({ slot, language, startDate });
|
||||
let createdIds = [];
|
||||
const cohort = await Cohort.create({
|
||||
name,
|
||||
startDate: ymdToDate(startDate),
|
||||
|
|
@ -198,7 +220,6 @@ export function cohortRoutes(server) {
|
|||
durationMinutes,
|
||||
});
|
||||
if (cohort.createdAs === 'manual_cohorts') {
|
||||
let createdIds = [];
|
||||
try {
|
||||
createdIds = await createManualCohortPatients(cohort, request.payload.newPatients, request.auth.credentials.user._id);
|
||||
if (createdIds.length) {
|
||||
|
|
@ -212,6 +233,14 @@ export function cohortRoutes(server) {
|
|||
}
|
||||
}
|
||||
await syncCohortPatients(cohort, []);
|
||||
await writeAudit(request, { action: 'cohort.created', resourceType: 'cohort', resourceId: cohort._id });
|
||||
await auditPatientMembership(request, cohort._id, [], idList(cohort.patients));
|
||||
for (const id of createdIds || []) {
|
||||
await writeAudit(request, { action: 'patient.created', resourceType: 'onboarding', resourceId: id, actor: request.auth.credentials.user._id });
|
||||
}
|
||||
if (reminderAuditText(settings.whatsappReminderRules)) {
|
||||
await writeAudit(request, { action: 'reminder.saved', resourceType: 'cohort', resourceId: cohort._id });
|
||||
}
|
||||
await activateManualCohort(cohort);
|
||||
if (cohort.createdAs === 'manual_cohorts') await applyCohortToPatients(cohort);
|
||||
const ready = await Cohort.findById(cohort._id)
|
||||
|
|
@ -306,11 +335,33 @@ export function cohortRoutes(server) {
|
|||
if (cohort.status === 'proposed') cohort.status = 'active';
|
||||
await applyPatientEdits(cohort, request.payload.patientEdits);
|
||||
const manual = (cohort.createdAs || request.payload.createdAs) === 'manual_cohorts';
|
||||
let createdIds = [];
|
||||
if (manual) {
|
||||
const createdIds = await createManualCohortPatients(cohort, request.payload.newPatients, request.auth.credentials.user._id);
|
||||
createdIds = await createManualCohortPatients(cohort, request.payload.newPatients, request.auth.credentials.user._id);
|
||||
if (createdIds.length) cohort.patients = [...patients, ...createdIds];
|
||||
}
|
||||
await cohort.save();
|
||||
const cohortChanged = previousStart !== String(startDate)
|
||||
|| previousSchedule !== scheduleId
|
||||
|| previousSlot !== String(slot || '')
|
||||
|| previousPrtId !== String(virtualPrt || '');
|
||||
if (cohortChanged) {
|
||||
await writeAudit(request, { action: 'cohort.saved', resourceType: 'cohort', resourceId: cohort._id });
|
||||
}
|
||||
if (previousPrtId !== String(virtualPrt || '')) {
|
||||
await writeAudit(request, { action: 'cohort.prt_changed', resourceType: 'cohort', resourceId: cohort._id });
|
||||
}
|
||||
await auditPatientMembership(request, cohort._id, previous, idList(cohort.patients));
|
||||
for (const row of request.payload.patientEdits || []) {
|
||||
if (idList(cohort.patients).includes(String(row.id))) {
|
||||
await writeAudit(request, { action: 'patient.updated', resourceType: 'onboarding', resourceId: row.id });
|
||||
}
|
||||
}
|
||||
if (manual && createdIds?.length) {
|
||||
for (const id of createdIds) {
|
||||
await writeAudit(request, { action: 'patient.created', resourceType: 'onboarding', resourceId: id });
|
||||
}
|
||||
}
|
||||
await syncCohortPatients(cohort, previous);
|
||||
/* Replaced by applyPatientEdits before the cohort is saved.
|
||||
for (const row of request.payload.patientOffline || []) {
|
||||
|
|
@ -343,7 +394,7 @@ export function cohortRoutes(server) {
|
|||
},
|
||||
handler: async (request) => {
|
||||
const cohort = await findCohort(request);
|
||||
await releaseCohortPatients(cohort);
|
||||
await releaseCohortPatients(cohort, request.auth.credentials.user._id);
|
||||
await CohortSession.deleteMany({ cohort: cohort._id });
|
||||
await cohort.deleteOne();
|
||||
return { ok: true };
|
||||
|
|
@ -428,7 +479,7 @@ export function cohortRoutes(server) {
|
|||
console.error(`[whatsapp] closing notice failed: ${err?.message || err}`);
|
||||
});
|
||||
} else {
|
||||
await cancelCohort(cohort, { patientAction, targetCohortId, force });
|
||||
await cancelCohort(cohort, { patientAction, targetCohortId, force, actorId: request.auth.credentials.user._id });
|
||||
}
|
||||
const ready = await Cohort.findById(cohort._id)
|
||||
.populate('virtualPrt', 'firstName lastName email')
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import Joi from 'joi';
|
||||
import Boom from '@hapi/boom';
|
||||
import { requirePermission } from '../plugins/auth.js';
|
||||
import { writeAudit } from '../services/audit.js';
|
||||
import { Cohort } from '../models/Cohort.js';
|
||||
import { OnboardedPatient } from '../models/OnboardedPatient.js';
|
||||
import { toOnboardedPatientDto, toReassignmentDto } from '../utils/serialize.js';
|
||||
|
|
@ -149,7 +150,7 @@ export function matchingRoutes(server) {
|
|||
}),
|
||||
},
|
||||
},
|
||||
handler: async (request) => setProposalSchedule(request.params.id, request.payload.scheduleId),
|
||||
handler: async (request) => setProposalSchedule(request.params.id, request.payload.scheduleId, request.auth.credentials.user._id),
|
||||
});
|
||||
|
||||
server.route({
|
||||
|
|
@ -159,14 +160,14 @@ export function matchingRoutes(server) {
|
|||
pre: [{ method: requirePermission('matching', 'edit') }],
|
||||
validate: { params: Joi.object({ id: objectId.required() }) },
|
||||
},
|
||||
handler: async (request) => confirmCohort(request.params.id),
|
||||
handler: async (request) => confirmCohort(request.params.id, request.auth.credentials.user._id),
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: 'POST',
|
||||
path: '/api/matching/confirm-all',
|
||||
options: { pre: [{ method: requirePermission('matching', 'edit') }] },
|
||||
handler: async () => confirmAllProposed(),
|
||||
handler: async (request) => confirmAllProposed(request.auth.credentials.user._id),
|
||||
});
|
||||
|
||||
server.route({
|
||||
|
|
@ -207,6 +208,11 @@ export function matchingRoutes(server) {
|
|||
payload: Joi.object({ toPrtId: objectId.required() }),
|
||||
},
|
||||
},
|
||||
handler: async (request) => toReassignmentDto(await resolveReassignment(request.params.id, request.payload.toPrtId)),
|
||||
handler: async (request) => {
|
||||
const event = await resolveReassignment(request.params.id, request.payload.toPrtId);
|
||||
const cohortId = event.cohort?._id || event.cohort;
|
||||
await writeAudit(request, { action: 'cohort.prt_changed', resourceType: 'cohort', resourceId: cohortId });
|
||||
return toReassignmentDto(event);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -408,6 +408,7 @@ export function onboardingRoutes(server) {
|
|||
});
|
||||
await item.populate('onboardedBy', 'firstName lastName email');
|
||||
await item.populate('cohort', 'name startDate slot language');
|
||||
await writeAudit(request, { action: 'patient.created', resourceType: 'onboarding', resourceId: item._id });
|
||||
return toOnboardedPatientDto(item);
|
||||
},
|
||||
});
|
||||
|
|
@ -493,6 +494,7 @@ export function onboardingRoutes(server) {
|
|||
item.whatsappOptOut = fields.whatsappOptOut;
|
||||
if (confirmed) {
|
||||
await item.save();
|
||||
await writeAudit(request, { action: 'patient.updated', resourceType: 'onboarding', resourceId: item._id });
|
||||
await item.populate('onboardedBy', 'firstName lastName email');
|
||||
await item.populate('reviewedBy', 'firstName lastName');
|
||||
await item.populate('cohort', 'name startDate slot language');
|
||||
|
|
@ -512,8 +514,9 @@ export function onboardingRoutes(server) {
|
|||
item.rejectReason = '';
|
||||
}
|
||||
await item.save();
|
||||
await writeAudit(request, { action: 'patient.updated', resourceType: 'onboarding', resourceId: item._id });
|
||||
if (previousCohortId && (!cohort || String(previousCohortId) !== String(cohort._id))) {
|
||||
await removePatientFromCohort(previousCohortId, item._id);
|
||||
await removePatientFromCohort(previousCohortId, item._id, request.auth.credentials.user._id);
|
||||
}
|
||||
await item.populate('onboardedBy', 'firstName lastName email');
|
||||
await item.populate('reviewedBy', 'firstName lastName');
|
||||
|
|
@ -532,9 +535,10 @@ export function onboardingRoutes(server) {
|
|||
handler: async (request) => {
|
||||
const item = await findOnboarded(request);
|
||||
assertCanDelete(item);
|
||||
await removePatientFromCohort(item.cohort?._id || item.cohort, item._id);
|
||||
await removePatientFromCohort(item.cohort?._id || item.cohort, item._id, request.auth.credentials.user._id);
|
||||
if (item.paymentScreenshot?.filename) await deleteScreenshot(item.paymentScreenshot.filename);
|
||||
await item.deleteOne();
|
||||
await writeAudit(request, { action: 'patient.deleted', resourceType: 'onboarding', resourceId: item._id });
|
||||
return { ok: true };
|
||||
},
|
||||
});
|
||||
|
|
@ -567,7 +571,7 @@ export function onboardingRoutes(server) {
|
|||
if (item.reviewStatus === 'confirmed' && cohortId) {
|
||||
const cohort = await Cohort.findById(cohortId);
|
||||
if (cohort) {
|
||||
await addPatientToCohort(cohort, item._id);
|
||||
await addPatientToCohort(cohort, item._id, creds.user._id);
|
||||
await ensureSessionRecords(cohort);
|
||||
}
|
||||
item.matchingStatus = 'assigned';
|
||||
|
|
@ -576,7 +580,7 @@ export function onboardingRoutes(server) {
|
|||
item.assignedEducator = null;
|
||||
}
|
||||
if (item.reviewStatus === 'rejected' && cohortId) {
|
||||
await removePatientFromCohort(cohortId, item._id);
|
||||
await removePatientFromCohort(cohortId, item._id, creds.user._id);
|
||||
item.cohort = null;
|
||||
item.assignedEducator = null;
|
||||
item.matchingStatus = 'unassigned';
|
||||
|
|
@ -690,6 +694,7 @@ export function onboardingRoutes(server) {
|
|||
const item = await findOnboarded(request);
|
||||
item.whatsappOptOut = request.payload.optOut;
|
||||
await item.save();
|
||||
await writeAudit(request, { action: 'patient.updated', resourceType: 'onboarding', resourceId: item._id });
|
||||
const { applyPatientOptOut } = await import('../services/whatsapp.js');
|
||||
await applyPatientOptOut(item).catch((err) => {
|
||||
console.error(`[whatsapp] opt-out sync failed: ${err?.message || err}`);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import { User } from '../models/User.js';
|
|||
import { listOnboardedForReports, patientProgramStats, prtCapacity, countLiveCohorts } from '../services/programSessions.js';
|
||||
import { getAppSettings } from '../services/settings.js';
|
||||
import { toYmd } from '../services/schedule.js';
|
||||
import { toDmy } from '../services/whatsappFormat.js';
|
||||
import { readOnboardedPii } from '../services/cryptoPii.js';
|
||||
import { writeAudit } from '../services/audit.js';
|
||||
// import { env } from '../config/env.js'; // was for the Recorded at column
|
||||
|
|
@ -364,12 +365,12 @@ export function reportRoutes(server) {
|
|||
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 startDate = patient.cohort?.startDate ? toDmy(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 || '' : '';
|
||||
const date = number === 1 ? toDmy(patient.offlineStartDate) : '';
|
||||
lines.push({
|
||||
name: pii.name || '',
|
||||
number,
|
||||
|
|
@ -401,7 +402,7 @@ export function reportRoutes(server) {
|
|||
stamp(sessionRecord(session, id)?.recordedAt),
|
||||
],
|
||||
*/
|
||||
row: [...base, session.cohort?.name || '', currentPrtName(patient), previousPrt.get(id) || '', startDate, number, session.date, sessionMark(session, id), ...vitals(sessionRecord(session, id))],
|
||||
row: [...base, session.cohort?.name || '', currentPrtName(patient), previousPrt.get(id) || '', startDate, number, toDmy(session.date), sessionMark(session, id), ...vitals(sessionRecord(session, id))],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -513,8 +514,8 @@ export function reportRoutes(server) {
|
|||
patient.assignedEducator ? `${patient.assignedEducator.firstName} ${patient.assignedEducator.lastName}` : '',
|
||||
// prevNames.get(prevPrtIds.get(String(patient._id))) || '',
|
||||
previousPrt.get(String(patient._id)) || '',
|
||||
patient.cohort?.startDate ? toYmd(patient.cohort.startDate) : '',
|
||||
progress.firstDate || '',
|
||||
patient.cohort?.startDate ? toDmy(toYmd(patient.cohort.startDate)) : '',
|
||||
progress.firstDate ? toDmy(progress.firstDate) : '',
|
||||
progress.completed || 0,
|
||||
...marks,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { Role } from '../models/Role.js';
|
|||
import { User } from '../models/User.js';
|
||||
import { ACL_ACTIONS, ACL_MODULES, normalizePermissions } from '../config/acl.js';
|
||||
import { toRoleDto } from '../utils/serialize.js';
|
||||
import { writeAudit } from '../services/audit.js';
|
||||
|
||||
const objectId = Joi.string().hex().length(24);
|
||||
|
||||
|
|
@ -74,6 +75,7 @@ export function roleRoutes(server) {
|
|||
role.permissions = normalizePermissions(request.payload.permissions);
|
||||
}
|
||||
await role.save();
|
||||
await writeAudit(request, { action: 'role.saved', resourceType: 'role', resourceId: role._id });
|
||||
const userCount = await User.countDocuments({ role: role._id });
|
||||
return toRoleDto(role, userCount);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import Boom from '@hapi/boom';
|
|||
import { credentials } from '../plugins/auth.js';
|
||||
import { Cohort } from '../models/Cohort.js';
|
||||
import { getAppSettings, normalizeSettingsPayload, toSettingsDto } from '../services/settings.js';
|
||||
import { writeAudit } from '../services/audit.js';
|
||||
|
||||
function requireSuperAdmin(request, h) {
|
||||
const creds = credentials(request);
|
||||
|
|
@ -65,6 +66,7 @@ export function settingsRoutes(server) {
|
|||
}
|
||||
Object.assign(settings, next);
|
||||
await settings.save();
|
||||
await writeAudit(request, { action: 'settings.saved', resourceType: 'settings', resourceId: settings._id });
|
||||
return toSettingsDto(settings);
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -140,6 +140,7 @@ export function userRoutes(server) {
|
|||
isActive: request.payload.isActive !== false,
|
||||
});
|
||||
await user.populate('role');
|
||||
await writeAudit(request, { action: 'user.created', resourceType: 'user', resourceId: user._id });
|
||||
return toUserDto(user);
|
||||
},
|
||||
});
|
||||
|
|
@ -227,6 +228,7 @@ export function userRoutes(server) {
|
|||
}
|
||||
await user.save();
|
||||
await user.populate('role');
|
||||
await writeAudit(request, { action: 'user.updated', resourceType: 'user', resourceId: user._id });
|
||||
return toUserDto(user);
|
||||
},
|
||||
});
|
||||
|
|
@ -249,6 +251,7 @@ export function userRoutes(server) {
|
|||
if (isSuperRole(user.role)) {
|
||||
throw Boom.forbidden('Super Admin accounts cannot be deleted.');
|
||||
}
|
||||
await writeAudit(request, { action: 'user.deleted', resourceType: 'user', resourceId: user._id });
|
||||
await user.deleteOne();
|
||||
return { ok: true };
|
||||
},
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ import { User } from '../models/User.js';
|
|||
import { getAppSettings } from '../services/settings.js';
|
||||
import { wastraConfigured } from '../services/wastra.js';
|
||||
import { toWhatsappDigits } from '../services/whatsappFormat.js';
|
||||
import { reminderAuditText, writeAudit } from '../services/audit.js';
|
||||
import { Cohort } from '../models/Cohort.js';
|
||||
|
||||
const TIME = /^\d{2}:\d{2}$/;
|
||||
|
||||
|
|
@ -106,6 +108,7 @@ export function whatsappRoutes(server) {
|
|||
throw Boom.badRequest('Each enabled reminder needs a message.');
|
||||
}
|
||||
}
|
||||
const previousReminder = reminderAuditText(settings.whatsappReminderRules);
|
||||
settings.whatsappAdminIds = ids;
|
||||
settings.whatsappReminderRules = (request.payload.rules || []).map((rule) => ({
|
||||
id: rule.id || randomUUID(),
|
||||
|
|
@ -123,6 +126,14 @@ export function whatsappRoutes(server) {
|
|||
}));
|
||||
settings.markModified('whatsappReminderRules');
|
||||
await settings.save();
|
||||
await writeAudit(request, { action: 'whatsapp.saved', resourceType: 'settings', resourceId: settings._id });
|
||||
const nextReminder = reminderAuditText(settings.whatsappReminderRules);
|
||||
if (nextReminder && nextReminder !== previousReminder) {
|
||||
const cohorts = await Cohort.find({ status: { $in: ['active', 'confirmed'] } }).select('_id');
|
||||
for (const cohort of cohorts) {
|
||||
await writeAudit(request, { action: 'reminder.saved', resourceType: 'cohort', resourceId: cohort._id });
|
||||
}
|
||||
}
|
||||
return {
|
||||
configured: wastraConfigured(),
|
||||
selectedAdminIds: settings.whatsappAdminIds.map(String),
|
||||
|
|
|
|||
|
|
@ -6,6 +6,16 @@ export function clientIp(request) {
|
|||
|| '';
|
||||
}
|
||||
|
||||
// Joins reminder rule text so a change can be detected without saving the message.
|
||||
export function reminderAuditText(rules = []) {
|
||||
return (rules || []).map((rule) => {
|
||||
const bodies = [rule.template, ...(rule.templatesByLanguage || []).map((row) => [row.language, row.body].filter(Boolean).join(': '))]
|
||||
.map((value) => String(value || '').trim())
|
||||
.filter(Boolean);
|
||||
return bodies.length ? `${rule.id}: ${bodies.join(' | ')}` : '';
|
||||
}).filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
export async function writeAudit(request, { action, resourceType = '', resourceId = '', actor } = {}) {
|
||||
try {
|
||||
await AuditEvent.create({
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { Cohort } from '../models/Cohort.js';
|
|||
import { CohortSession } from '../models/CohortSession.js';
|
||||
import { OnboardedPatient } from '../models/OnboardedPatient.js';
|
||||
import { addPatientToWhatsapp, removePatientFromWhatsapp, syncWhatsappMembership } from './whatsapp.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
import { applyOnboardedPii, hashMobile, isMobileNumber, readOnboardedPii } from './cryptoPii.js';
|
||||
import { env } from '../config/env.js';
|
||||
import { toYmd, todayYmd, weekdayOf } from './schedule.js';
|
||||
|
|
@ -59,13 +60,14 @@ export async function syncCohortPatients(cohort, previousPatientIds = []) {
|
|||
await safeWhatsapp('membership sync', () => syncWhatsappMembership(cohort, previousPatientIds));
|
||||
}
|
||||
|
||||
export async function addPatientToCohort(cohort, patientId) {
|
||||
export async function addPatientToCohort(cohort, patientId, actorId = null) {
|
||||
const id = String(patientId);
|
||||
const current = (cohort.patients || []).map((item) => String(item._id || item));
|
||||
const joined = !current.includes(id);
|
||||
if (joined) {
|
||||
cohort.patients.push(patientId);
|
||||
await cohort.save();
|
||||
await writeAudit(null, { action: 'cohort.patient_added', resourceType: 'cohort', resourceId: cohort._id, actor: actorId });
|
||||
}
|
||||
await OnboardedPatient.updateOne(
|
||||
{ _id: patientId },
|
||||
|
|
@ -79,7 +81,7 @@ export async function addPatientToCohort(cohort, patientId) {
|
|||
await safeWhatsapp('add patient', () => addPatientToWhatsapp(cohort, patientId));
|
||||
}
|
||||
|
||||
export async function removePatientFromCohort(cohortId, patientId) {
|
||||
export async function removePatientFromCohort(cohortId, patientId, actorId = null) {
|
||||
if (!cohortId || !patientId) return;
|
||||
await Cohort.updateOne({ _id: cohortId }, { $pull: { patients: patientId } });
|
||||
await CohortSession.updateMany(
|
||||
|
|
@ -87,11 +89,15 @@ export async function removePatientFromCohort(cohortId, patientId) {
|
|||
{ $pull: { records: { patient: patientId } } },
|
||||
);
|
||||
await safeWhatsapp('remove patient', () => removePatientFromWhatsapp(cohortId, patientId));
|
||||
await writeAudit(null, { action: 'cohort.patient_removed', resourceType: 'cohort', resourceId: cohortId, actor: actorId });
|
||||
}
|
||||
|
||||
export async function releaseCohortPatients(cohort) {
|
||||
export async function releaseCohortPatients(cohort, actorId = null) {
|
||||
const previous = (cohort.patients || []).map((p) => String(p._id || p));
|
||||
await syncCohortPatients({ ...cohort.toObject?.() || cohort, patients: [] }, previous);
|
||||
for (const id of previous) {
|
||||
await writeAudit(null, { action: 'cohort.patient_removed', resourceType: 'cohort', resourceId: cohort._id, actor: actorId });
|
||||
}
|
||||
}
|
||||
|
||||
// Cohort placement copied onto each patient so the record matches the cohort.
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { ReassignmentEvent } from '../models/ReassignmentEvent.js';
|
|||
import { Role } from '../models/Role.js';
|
||||
import { User } from '../models/User.js';
|
||||
import { addPatientToCohort, releaseCohortPatients, removePatientFromCohort, syncCohortPatients } from './cohorts.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
import { CohortSession } from '../models/CohortSession.js';
|
||||
import { notifyCohortConfirmed, notifyReassignment } from './notify.js';
|
||||
import { appendTodaySessions, ensureMeetForCohort, persistCohortSessions } from './programSessions.js';
|
||||
|
|
@ -427,10 +428,12 @@ async function fieldNoticesForCohort(cohort) {
|
|||
}
|
||||
|
||||
// Sets the schedule on a proposed cohort and moves the start if that weekday is not allowed.
|
||||
export async function setProposalSchedule(proposalId, scheduleId) {
|
||||
export async function setProposalSchedule(proposalId, scheduleId, actorId = null) {
|
||||
const cohort = await Cohort.findById(proposalId);
|
||||
if (!cohort) throw Boom.notFound('Proposed cohort not found');
|
||||
if (cohort.status !== 'proposed') throw Boom.badRequest('Only a proposed cohort can change schedule.');
|
||||
const previousSchedule = String(cohort.scheduleId || '');
|
||||
const previousStart = toYmd(cohort.startDate);
|
||||
const id = String(scheduleId || '').trim();
|
||||
const weekdays = id ? await scheduleWeekdays(id) : null;
|
||||
if (id && !weekdays) throw Boom.badRequest('Select a schedule from Settings.');
|
||||
|
|
@ -442,6 +445,9 @@ export async function setProposalSchedule(proposalId, scheduleId) {
|
|||
cohort.name = buildCohortName({ slot: cohort.slot, language: cohort.language, startDate: dates[0] });
|
||||
}
|
||||
await cohort.save();
|
||||
if (previousSchedule !== id || previousStart !== toYmd(cohort.startDate)) {
|
||||
await writeAudit(null, { action: 'cohort.saved', resourceType: 'cohort', resourceId: cohort._id, actor: actorId });
|
||||
}
|
||||
await OnboardedPatient.updateMany({ cohort: cohort._id }, { $set: { sessionDate: cohort.startDate } });
|
||||
const ready = await Cohort.findById(cohort._id)
|
||||
.populate('virtualPrt', 'firstName lastName email')
|
||||
|
|
@ -456,7 +462,7 @@ export async function startCohortMeetings(cohort) {
|
|||
}
|
||||
|
||||
// Confirms a proposal, moves a Sunday or past start onto a valid day, then creates sessions.
|
||||
export async function confirmCohort(cohortId) {
|
||||
export async function confirmCohort(cohortId, actorId = null) {
|
||||
const cohort = await Cohort.findById(cohortId).populate('virtualPrt').populate('patients');
|
||||
if (!cohort) throw Boom.notFound('Cohort not found');
|
||||
if (cohort.status !== 'proposed') throw Boom.badRequest('Only proposed cohorts can be confirmed from matching.');
|
||||
|
|
@ -474,6 +480,10 @@ export async function confirmCohort(cohortId) {
|
|||
cohort.startDate = ymdToDate(nextStartDateForWeekday(weekdayOf(startYmd)));
|
||||
cohort.name = buildCohortName({ slot: cohort.slot, language: cohort.language, startDate: toYmd(cohort.startDate) });
|
||||
}
|
||||
const nextStart = toYmd(cohort.startDate);
|
||||
if (nextStart !== startYmd) {
|
||||
await writeAudit(null, { action: 'cohort.saved', resourceType: 'cohort', resourceId: cohort._id, actor: actorId });
|
||||
}
|
||||
cohort.status = 'active';
|
||||
await cohort.save();
|
||||
await OnboardedPatient.updateMany(
|
||||
|
|
@ -495,11 +505,11 @@ export async function confirmCohort(cohortId) {
|
|||
return toCohortDto(ready);
|
||||
}
|
||||
|
||||
export async function confirmAllProposed() {
|
||||
export async function confirmAllProposed(actorId = null) {
|
||||
const items = await Cohort.find({ status: 'proposed' });
|
||||
const confirmed = [];
|
||||
for (const item of items) {
|
||||
confirmed.push(await confirmCohort(item._id));
|
||||
confirmed.push(await confirmCohort(item._id, actorId));
|
||||
}
|
||||
return { confirmed };
|
||||
}
|
||||
|
|
@ -644,7 +654,7 @@ export async function migratePatient(patient, { cohortId, slot, preferredWeekday
|
|||
}
|
||||
|
||||
// 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 } = {}) {
|
||||
export async function cancelCohort(cohort, { patientAction = 'pool', targetCohortId = '', force = false, check = false, actorId = null } = {}) {
|
||||
const ids = (cohort.patients || []).map((item) => String(item._id || item));
|
||||
let target = null;
|
||||
const warnings = [];
|
||||
|
|
@ -688,7 +698,7 @@ export async function cancelCohort(cohort, { patientAction = 'pool', targetCohor
|
|||
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);
|
||||
await releaseCohortPatients(cohort, actorId);
|
||||
cohort.patients = [];
|
||||
}
|
||||
cohort.status = 'cancelled';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { NotificationLog } from '../models/NotificationLog.js';
|
||||
import { brandedEmail, sendMail } from './mail.js';
|
||||
import { toDmy } from './whatsappFormat.js';
|
||||
|
||||
export async function notify({ kind, to, subject, text, html }) {
|
||||
const recipient = String(to || '').trim();
|
||||
|
|
@ -30,6 +31,13 @@ function prtLabel(user) {
|
|||
return name || 'your Virtual PRT';
|
||||
}
|
||||
|
||||
// Shows a stored day the same way as a cohort date, such as Fri Nov 13.
|
||||
function showWeekdayDate(value) {
|
||||
const match = String(value || '').trim().match(/^(\d{4})-(\d{2})-(\d{2})/);
|
||||
if (!match) return String(value || '').slice(0, 10);
|
||||
return String(new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]))).slice(0, 10);
|
||||
}
|
||||
|
||||
function cohortDetails(cohort) {
|
||||
return [
|
||||
{ label: 'Cohort', value: cohort?.name || '' },
|
||||
|
|
@ -118,7 +126,7 @@ export async function notifySessionReminder({ prt, session, cohort }) {
|
|||
intro: 'Your cohort session starts in about 2 hours.',
|
||||
details: [
|
||||
{ label: 'Cohort', value: cohort?.name || '' },
|
||||
{ label: 'Date', value: session.date || '' },
|
||||
{ label: 'Date', value: showWeekdayDate(session.date) },
|
||||
{ label: 'Time', value: session.slot || '' },
|
||||
],
|
||||
note: session.meetUrl ? 'Use the button below to join the meeting.' : 'A Meet link is not on this session yet.',
|
||||
|
|
@ -136,11 +144,11 @@ export async function notifySessionReminder({ prt, session, cohort }) {
|
|||
export async function notifySessionPushed({ prt, admins = [], cohort, fromDate, toDate, reason }) {
|
||||
const subject = `Session moved: ${cohort?.name || 'Cohort'}`;
|
||||
const content = {
|
||||
intro: `The ${fromDate} session for ${cohort?.name || 'a cohort'} was moved.`,
|
||||
intro: `The ${toDmy(fromDate)} session for ${cohort?.name || 'a cohort'} was moved.`,
|
||||
details: [
|
||||
{ label: 'Cohort', value: cohort?.name || '' },
|
||||
{ label: 'Original date', value: fromDate },
|
||||
{ label: 'New date', value: toDate },
|
||||
{ label: 'Original date', value: toDmy(fromDate) },
|
||||
{ label: 'New date', value: toDmy(toDate) },
|
||||
{ label: 'Reason', value: reason || 'Rescheduled' },
|
||||
],
|
||||
note: 'The replacement session keeps the same slot. Please update anyone who was expecting the original date.',
|
||||
|
|
@ -171,15 +179,15 @@ export async function notifySessionPushed({ prt, admins = [], cohort, fromDate,
|
|||
export async function notifyLeaveDecision({ prt, status, startDate, endDate }) {
|
||||
if (!prt?.email) return;
|
||||
const approved = status === 'approved';
|
||||
const subject = `Leave ${approved ? 'approved' : status}: ${startDate} to ${endDate}`;
|
||||
const subject = `Leave ${approved ? 'approved' : status}: ${toDmy(startDate)} to ${toDmy(endDate)}`;
|
||||
const { text, html } = brandedEmail({
|
||||
greeting: staffGreeting(prt),
|
||||
intro: approved
|
||||
? 'Your leave request has been approved.'
|
||||
: `Your leave request was ${status}.`,
|
||||
details: [
|
||||
{ label: 'From', value: startDate },
|
||||
{ label: 'To', value: endDate },
|
||||
{ label: 'From', value: toDmy(startDate) },
|
||||
{ label: 'To', value: toDmy(endDate) },
|
||||
{ label: 'Decision', value: approved ? 'Approved' : status },
|
||||
],
|
||||
note: approved
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ 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 { writeAudit } from './audit.js';
|
||||
import { notifySessionPushed, notifySessionReminder } from './notify.js';
|
||||
import {
|
||||
addDays,
|
||||
|
|
@ -380,6 +381,7 @@ export async function appendTodaySessions(date, { cohortId } = {}) {
|
|||
htmlLink: link.htmlLink || '',
|
||||
records: [],
|
||||
});
|
||||
await writeAudit(null, { action: 'session.created', resourceType: 'cohort', resourceId: cohort._id });
|
||||
await ensureSessionRecords(cohort);
|
||||
await syncExistingMeetSeries(cohort, await CohortSession.find({ cohort: cohort._id }));
|
||||
added += 1;
|
||||
|
|
@ -528,17 +530,25 @@ async function applyMeetToSessions(sessions, event, slot) {
|
|||
}
|
||||
}
|
||||
|
||||
// Writes one cohort row when its Meet link is first saved or replaced.
|
||||
async function auditMeetLink(cohort, previousUrl, nextUrl) {
|
||||
if (!nextUrl || nextUrl === previousUrl) return;
|
||||
await writeAudit(null, { action: 'meet.saved', resourceType: 'cohort', resourceId: cohort._id });
|
||||
}
|
||||
|
||||
// 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 previousUrl = String(cohort.meetUrl || '');
|
||||
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 } });
|
||||
await auditMeetLink(cohort, previousUrl, legacy.meetUrl);
|
||||
}
|
||||
}
|
||||
if (cohort.meetUrl) {
|
||||
|
|
@ -584,6 +594,7 @@ export async function ensureMeetForCohort(cohort) {
|
|||
const link = { googleEventId: event.id || '', meetUrl: event.meetUrl || '', htmlLink: event.htmlLink || '' };
|
||||
Object.assign(cohort, link);
|
||||
await Cohort.updateOne({ _id: cohort._id }, { $set: link });
|
||||
await auditMeetLink(cohort, previousUrl, link.meetUrl);
|
||||
await applyMeetToSessions(sessions, event, cohort.slot);
|
||||
if (event.meetUrl) {
|
||||
const { notifyGroupMeetLink } = await import('./whatsapp.js');
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { readOnboardedPii } from './cryptoPii.js';
|
|||
import { groupDescription, groupSubject, inviteMessage, toWhatsappDigits } from './whatsappFormat.js';
|
||||
import { toYmd } from './schedule.js';
|
||||
import { getAppSettings } from './settings.js';
|
||||
import { createGroup, fetchInvite, sendCta, sendText, updateGroup } from './wastra.js';
|
||||
import { createGroup, fetchInvite, sendCta, sendText, updateGroup, updateParticipants } from './wastra.js';
|
||||
|
||||
const LIVE = new Set(['active', 'confirmed']);
|
||||
const MAX_ATTEMPTS = 3;
|
||||
|
|
@ -143,6 +143,79 @@ function inviteSteps(cohortId, people) {
|
|||
return people.filter((person) => person.phone).map((person) => inviteStep(cohortId, person));
|
||||
}
|
||||
|
||||
const PRT_ADMIN_MISSING_PHONE = 'Assigned therapist needs a mobile number before they can be a WhatsApp group admin';
|
||||
|
||||
// True for old patient add/remove tasks. Therapist admin steps and leave steps still run.
|
||||
export function isRetiredMembershipTask(task) {
|
||||
if (task?.flag === 'prt' && (task.kind === 'add_member' || task.kind === 'promote_member')) return false;
|
||||
if (task?.flag === 'leave' && task.kind === 'remove_member') return false;
|
||||
return ['ensure_contact', 'add_member', 'promote_member', 'remove_member'].includes(task?.kind);
|
||||
}
|
||||
|
||||
// Removes one phone from the cohort group.
|
||||
function leaveStep(cohortId, person) {
|
||||
return {
|
||||
kind: 'remove_member',
|
||||
phone: person.phone,
|
||||
name: person.name || '',
|
||||
patient: person.patient || null,
|
||||
user: person.user || null,
|
||||
flag: 'leave',
|
||||
dedupeKey: `${cohortId}:leave:${person.phone}`,
|
||||
};
|
||||
}
|
||||
|
||||
// True when this phone is still the therapist or a ticked staff admin.
|
||||
async function phoneKeptInGroup(cohort, phone) {
|
||||
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
|
||||
const prt = cohort.virtualPrt?.phone != null
|
||||
? cohort.virtualPrt
|
||||
: prtId ? await User.findById(prtId).select('phone') : null;
|
||||
if (toWhatsappDigits(prt?.phone) === phone) return true;
|
||||
const settings = await getAppSettings();
|
||||
const admins = await User.find({ _id: { $in: settings.whatsappAdminIds || [] }, isActive: true }).select('phone');
|
||||
return admins.some((user) => toWhatsappDigits(user.phone) === phone);
|
||||
}
|
||||
|
||||
// Add then promote the conducting therapist when this cohort does not already record them as admin.
|
||||
async function prtAdminSteps(cohort) {
|
||||
const prtId = cohort.virtualPrt?._id || cohort.virtualPrt;
|
||||
if (!prtId || String(cohort.whatsappAdminUser || '') === String(prtId)) return [];
|
||||
const user = cohort.virtualPrt?.phone != null
|
||||
? cohort.virtualPrt
|
||||
: await User.findById(prtId).select('firstName lastName phone');
|
||||
const phone = toWhatsappDigits(user?.phone);
|
||||
if (!phone) {
|
||||
if (cohort.whatsappError !== PRT_ADMIN_MISSING_PHONE) {
|
||||
cohort.whatsappError = PRT_ADMIN_MISSING_PHONE;
|
||||
await cohort.save();
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (cohort.whatsappError === PRT_ADMIN_MISSING_PHONE) {
|
||||
cohort.whatsappError = '';
|
||||
await cohort.save();
|
||||
}
|
||||
return [
|
||||
{
|
||||
kind: 'add_member',
|
||||
phone,
|
||||
name: personName(user),
|
||||
user: prtId,
|
||||
flag: 'prt',
|
||||
dedupeKey: `${cohort._id}:prt_add:${prtId}:${phone}`,
|
||||
},
|
||||
{
|
||||
kind: 'promote_member',
|
||||
phone,
|
||||
name: personName(user),
|
||||
user: prtId,
|
||||
flag: 'prt',
|
||||
dedupeKey: `${cohort._id}:prt_promote:${prtId}:${phone}`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export async function enqueueCohortGroup(cohortId) {
|
||||
const cohort = await Cohort.findById(cohortId).populate('virtualPrt', 'firstName lastName phone');
|
||||
if (!cohort || !LIVE.has(cohort.status)) return cohort;
|
||||
|
|
@ -169,6 +242,7 @@ export async function enqueueCohortGroup(cohortId) {
|
|||
if (!step.phone) continue;
|
||||
steps.push(inviteStep(cohort._id, step));
|
||||
}
|
||||
steps.push(...await prtAdminSteps(cohort));
|
||||
await enqueueMany(cohort._id, steps);
|
||||
return cohort;
|
||||
}
|
||||
|
|
@ -209,6 +283,10 @@ export async function enqueuePatientRemove(cohortId, patientId) {
|
|||
},
|
||||
{ $set: { status: 'cancelled', lastError: 'Cancelled because this person left the cohort' } },
|
||||
);
|
||||
const cohort = await Cohort.findById(cohortId).select('whatsappGroupJid virtualPrt');
|
||||
if (!cohort?.whatsappGroupJid || await phoneKeptInGroup(cohort, phone)) return;
|
||||
const pii = readOnboardedPii(patient);
|
||||
await enqueueMany(cohortId, [leaveStep(cohortId, { phone, name: pii.name || 'Patient', patient: patientId })]);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -222,6 +300,17 @@ export async function enqueuePrtSwap(cohortOrId, previousPrtId) {
|
|||
: await User.findById(cohort.virtualPrt).select('firstName lastName phone');
|
||||
const nextPhone = toWhatsappDigits(next?.phone);
|
||||
const steps = [];
|
||||
const previous = previousPrtId
|
||||
? await User.findById(previousPrtId).select('firstName lastName phone')
|
||||
: null;
|
||||
const previousPhone = toWhatsappDigits(previous?.phone);
|
||||
if (previousPhone && previousPhone !== nextPhone && !await phoneKeptInGroup(cohort, previousPhone)) {
|
||||
steps.push(leaveStep(cohort._id, {
|
||||
phone: previousPhone,
|
||||
name: personName(previous),
|
||||
user: previousPrtId,
|
||||
}));
|
||||
}
|
||||
if (nextPhone) {
|
||||
steps.push(inviteStep(cohort._id, { id: String(next._id), phone: nextPhone, name: personName(next) }));
|
||||
const text = `Your therapist for this group is now ${personName(next)}.`;
|
||||
|
|
@ -288,14 +377,91 @@ async function clearCohortError(cohortId) {
|
|||
await Cohort.updateOne({ _id: cohortId }, { $set: { whatsappError: '' } });
|
||||
}
|
||||
|
||||
function participantAlreadyUpdated(action, err) {
|
||||
const message = String(err?.message || '').toLowerCase();
|
||||
if (!message.includes('already') && !message.includes('409')) return false;
|
||||
return action === 'add' || action === 'promote';
|
||||
}
|
||||
|
||||
function participantAlreadyGone(err) {
|
||||
const message = String(err?.message || '').toLowerCase();
|
||||
return message.includes('not a participant') || message.includes('not in') || message.includes('404') || message.includes('already');
|
||||
}
|
||||
|
||||
// Removes the therapist or patient from the WhatsApp group.
|
||||
async function runLeaveStep(task) {
|
||||
const cohort = await Cohort.findById(task.cohort);
|
||||
if (!cohort?.whatsappGroupJid) {
|
||||
const waiting = await WhatsAppTask.exists({
|
||||
cohort: task.cohort,
|
||||
kind: 'create_group',
|
||||
status: { $in: OPEN },
|
||||
});
|
||||
if (waiting) {
|
||||
const error = new Error('Waiting for the WhatsApp group');
|
||||
error.defer = true;
|
||||
throw error;
|
||||
}
|
||||
throw new Error('This cohort has no WhatsApp group');
|
||||
}
|
||||
if (!task.phone) throw new Error('Missing phone number');
|
||||
try {
|
||||
await updateParticipants(cohort.whatsappGroupJid, 'remove', [task.phone]);
|
||||
} catch (err) {
|
||||
if (!participantAlreadyGone(err)) throw err;
|
||||
}
|
||||
if (task.patient) {
|
||||
upsertMember(cohort, task.patient, 'removed', '');
|
||||
await cohort.save();
|
||||
}
|
||||
}
|
||||
|
||||
// Adds the conducting therapist to the group, or promotes them once they are a member.
|
||||
async function runPrtAdminStep(task) {
|
||||
const cohort = await Cohort.findById(task.cohort);
|
||||
if (!cohort?.whatsappGroupJid) {
|
||||
const waiting = await WhatsAppTask.exists({
|
||||
cohort: task.cohort,
|
||||
kind: 'create_group',
|
||||
status: { $in: OPEN },
|
||||
});
|
||||
if (waiting) {
|
||||
const error = new Error('Waiting for the WhatsApp group');
|
||||
error.defer = true;
|
||||
throw error;
|
||||
}
|
||||
throw new Error('This cohort has no WhatsApp group');
|
||||
}
|
||||
if (!task.phone) throw new Error(PRT_ADMIN_MISSING_PHONE);
|
||||
const action = task.kind === 'promote_member' ? 'promote' : 'add';
|
||||
try {
|
||||
await updateParticipants(cohort.whatsappGroupJid, action, [task.phone]);
|
||||
} catch (err) {
|
||||
if (!participantAlreadyUpdated(action, err)) throw err;
|
||||
}
|
||||
if (action === 'promote' && task.user) {
|
||||
cohort.whatsappAdminUser = task.user;
|
||||
if (cohort.whatsappError === PRT_ADMIN_MISSING_PHONE) cohort.whatsappError = '';
|
||||
await cohort.save();
|
||||
}
|
||||
}
|
||||
|
||||
async function execute(task) {
|
||||
if (task.kind === 'ensure_contact' || task.kind === 'add_member' || task.kind === 'promote_member' || task.kind === 'remove_member') {
|
||||
if (isRetiredMembershipTask(task)) {
|
||||
task.status = 'cancelled';
|
||||
task.lastError = 'Membership updates are no longer sent to WhatsApp';
|
||||
task.lockedAt = null;
|
||||
await task.save();
|
||||
return;
|
||||
}
|
||||
if (task.flag === 'prt' && (task.kind === 'add_member' || task.kind === 'promote_member')) {
|
||||
await runPrtAdminStep(task);
|
||||
return;
|
||||
}
|
||||
if (task.flag === 'leave' && task.kind === 'remove_member') {
|
||||
await runLeaveStep(task);
|
||||
return;
|
||||
}
|
||||
if (task.kind === 'create_group') {
|
||||
const cohort = await Cohort.findById(task.cohort);
|
||||
if (!cohort) return;
|
||||
|
|
@ -490,11 +656,16 @@ async function runOne() {
|
|||
}
|
||||
}
|
||||
|
||||
const MEMBERSHIP_KINDS = ['ensure_contact', 'add_member', 'promote_member', 'remove_member'];
|
||||
|
||||
function cancelMembershipTasks() {
|
||||
return WhatsAppTask.updateMany(
|
||||
{ status: { $in: ['pending', 'running'] }, kind: { $in: MEMBERSHIP_KINDS } },
|
||||
{
|
||||
status: { $in: ['pending', 'running'] },
|
||||
$or: [
|
||||
{ kind: 'ensure_contact' },
|
||||
{ kind: 'remove_member', flag: { $ne: 'leave' } },
|
||||
{ kind: { $in: ['add_member', 'promote_member'] }, flag: { $ne: 'prt' } },
|
||||
],
|
||||
},
|
||||
{ $set: { status: 'cancelled', lockedAt: null, lastError: 'Membership updates are no longer sent to WhatsApp' } },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { dedupeStatusesForStep, randomGapMs } from './whatsappQueue.js';
|
||||
import { dedupeStatusesForStep, isRetiredMembershipTask, randomGapMs } from './whatsappQueue.js';
|
||||
|
||||
test('draws each WhatsApp gap from 15 to 40 seconds', () => {
|
||||
const settings = { whatsappTaskGapMinMs: 15000, whatsappTaskGapMaxMs: 40000 };
|
||||
|
|
@ -10,6 +10,15 @@ test('draws each WhatsApp gap from 15 to 40 seconds', () => {
|
|||
}
|
||||
});
|
||||
|
||||
test('keeps the conducting therapist admin steps and drops old membership tasks', () => {
|
||||
assert.equal(isRetiredMembershipTask({ kind: 'promote_member', flag: 'prt' }), false);
|
||||
assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'prt' }), false);
|
||||
assert.equal(isRetiredMembershipTask({ kind: 'promote_member', flag: '' }), true);
|
||||
assert.equal(isRetiredMembershipTask({ kind: 'remove_member', flag: 'leave' }), false);
|
||||
assert.equal(isRetiredMembershipTask({ kind: 'remove_member' }), true);
|
||||
assert.equal(isRetiredMembershipTask({ kind: 'send_text', flag: 'invite' }), false);
|
||||
});
|
||||
|
||||
test('invite steps treat a done send as already delivered', () => {
|
||||
assert.deepEqual(dedupeStatusesForStep({ flag: 'invite' }), ['pending', 'running', 'done']);
|
||||
assert.deepEqual(dedupeStatusesForStep({ flag: 'reminder' }), ['pending', 'running']);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,42 @@
|
|||
function pad(n) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
function fromDate(date) {
|
||||
return { y: String(date.getFullYear()), m: pad(date.getMonth() + 1), d: pad(date.getDate()) };
|
||||
}
|
||||
|
||||
// Reads a stored yyyy-mm-dd, or the local calendar day of a timestamp.
|
||||
function dayParts(value) {
|
||||
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : fromDate(value);
|
||||
const text = String(value ?? '').trim();
|
||||
const dayOnly = text.match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
||||
if (dayOnly) return { y: dayOnly[1], m: dayOnly[2], d: dayOnly[3] };
|
||||
if (!text) return null;
|
||||
const date = new Date(text);
|
||||
return Number.isNaN(date.getTime()) ? null : fromDate(date);
|
||||
}
|
||||
|
||||
// Shows a stored date as dd-mm-yyyy. The saved value stays yyyy-mm-dd.
|
||||
export function showDate(value) {
|
||||
if (value == null || value === '') return '';
|
||||
const text = String(value).trim();
|
||||
const match = text.slice(0, 10).match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
||||
return match ? `${match[3]}-${match[2]}-${match[1]}` : text;
|
||||
}
|
||||
|
||||
// Shows a date that was already written with slashes as dd/mm/yyyy.
|
||||
export function showSlashDate(value) {
|
||||
const parts = dayParts(value);
|
||||
return parts ? `${parts.d}/${parts.m}/${parts.y}` : '';
|
||||
}
|
||||
|
||||
// Shows a date and time that was already written with slashes as dd/mm/yyyy.
|
||||
export function showSlashDateTime(value) {
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
if (!value || Number.isNaN(date.getTime())) return '';
|
||||
const hours = date.getHours();
|
||||
const h12 = hours % 12 || 12;
|
||||
const ampm = hours >= 12 ? 'pm' : 'am';
|
||||
return `${pad(date.getDate())}/${pad(date.getMonth() + 1)}/${date.getFullYear()}, ${h12}:${pad(date.getMinutes())} ${ampm}`;
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
|
|||
import { Card, CardBody, Container, Table } from 'react-bootstrap';
|
||||
import PageBreadcrumb from '@/components/PageBreadcrumb';
|
||||
import { api } from '@/lib/api';
|
||||
import { showSlashDateTime } from '@/lib/dates';
|
||||
|
||||
export default function AuditPage() {
|
||||
const [items, setItems] = useState([]);
|
||||
|
|
@ -39,7 +40,7 @@ export default function AuditPage() {
|
|||
<tbody>
|
||||
{items.map((item) => (
|
||||
<tr key={item.id}>
|
||||
<td className="small">{item.at ? new Date(item.at).toLocaleString() : ''}</td>
|
||||
<td className="small">{showSlashDateTime(item.at)}</td>
|
||||
<td>{item.actor ? `${item.actor.firstName} ${item.actor.lastName}` : '—'}</td>
|
||||
<td>{item.action}</td>
|
||||
<td className="small">{[item.resourceType, item.resourceId].filter(Boolean).join(' ')}</td>
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { Card, CardBody, Col, Container, Row, Table } from 'react-bootstrap';
|
|||
import PageBreadcrumb from '@/components/PageBreadcrumb';
|
||||
import { WEEKDAY_LABELS } from '@/hooks/useSettings';
|
||||
import { api } from '@/lib/api';
|
||||
import { showDate } from '@/lib/dates';
|
||||
|
||||
function addDays(ymd, days) {
|
||||
const [year, month, day] = ymd.split('-').map(Number);
|
||||
|
|
@ -58,7 +59,7 @@ export default function CalendarPage() {
|
|||
<Card>
|
||||
<CardBody>
|
||||
<h6>{WEEKDAY_LABELS[new Date(`${day}T00:00:00`).getDay()]}</h6>
|
||||
<div className="text-muted small mb-2">{day}</div>
|
||||
<div className="text-muted small mb-2">{showDate(day)}</div>
|
||||
{sessions.map((session) => (
|
||||
<div key={session.id} className="border rounded p-2 mb-2 small">
|
||||
<div className="fw-semibold">{session.slot}</div>
|
||||
|
|
@ -80,7 +81,7 @@ export default function CalendarPage() {
|
|||
<tbody>
|
||||
{items.map((session) => (
|
||||
<tr key={session.id}>
|
||||
<td>{session.date}</td>
|
||||
<td>{showDate(session.date)}</td>
|
||||
<td>{session.slot}</td>
|
||||
<td>{session.cohort?.name}</td>
|
||||
<td className="text-capitalize">{session.status}</td>
|
||||
|
|
|
|||
|
|
@ -11,10 +11,10 @@ import DeleteConfirmationModal from '@/components/table/DeleteConfirmationModal'
|
|||
import TablePagination from '@/components/table/TablePagination';
|
||||
import { useAuth } from '@/context/useAuthContext';
|
||||
import { api } from '@/lib/api';
|
||||
import { showDate } from '@/lib/dates';
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return '';
|
||||
return String(value).slice(0, 10);
|
||||
return showDate(value);
|
||||
}
|
||||
|
||||
export default function CohortsPage() {
|
||||
|
|
|
|||
|
|
@ -9,10 +9,10 @@ import DeleteConfirmationModal from '@/components/table/DeleteConfirmationModal'
|
|||
import { useAuth } from '@/context/useAuthContext';
|
||||
import { useSettings } from '@/hooks/useSettings';
|
||||
import { api } from '@/lib/api';
|
||||
import { showDate } from '@/lib/dates';
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return '';
|
||||
return String(value).slice(0, 10);
|
||||
return showDate(value);
|
||||
}
|
||||
|
||||
export default function HolidaysPage() {
|
||||
|
|
|
|||
|
|
@ -8,10 +8,10 @@ import DataTable from '@/components/table/DataTable';
|
|||
import DeleteConfirmationModal from '@/components/table/DeleteConfirmationModal';
|
||||
import { useAuth } from '@/context/useAuthContext';
|
||||
import { api } from '@/lib/api';
|
||||
import { showDate } from '@/lib/dates';
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return '';
|
||||
return String(value).slice(0, 10);
|
||||
return showDate(value);
|
||||
}
|
||||
|
||||
const empty = { user: '', startDate: '', endDate: '', reason: '' };
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import PageBreadcrumb from '@/components/PageBreadcrumb';
|
|||
import SlotSelect from '@/components/SlotSelect';
|
||||
import { WEEKDAY_LABELS, useSettings } from '@/hooks/useSettings';
|
||||
import { api } from '@/lib/api';
|
||||
import { showDate } from '@/lib/dates';
|
||||
import { isMobileNumber, mobileDigits } from '@/lib/mobile';
|
||||
|
||||
const empty = {
|
||||
|
|
@ -23,8 +24,7 @@ const empty = {
|
|||
};
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return '';
|
||||
return String(value).slice(0, 10);
|
||||
return showDate(value);
|
||||
}
|
||||
|
||||
function cohortLabel(cohort) {
|
||||
|
|
|
|||
|
|
@ -12,10 +12,10 @@ import TablePagination from '@/components/table/TablePagination';
|
|||
import { useAuth } from '@/context/useAuthContext';
|
||||
import { useSettings } from '@/hooks/useSettings';
|
||||
import { api } from '@/lib/api';
|
||||
import { showDate } from '@/lib/dates';
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return '';
|
||||
return String(value).slice(0, 10);
|
||||
return showDate(value);
|
||||
}
|
||||
|
||||
function reviewBadge(status) {
|
||||
|
|
|
|||
|
|
@ -8,11 +8,10 @@ import DataTable from '@/components/table/DataTable';
|
|||
import DeleteConfirmationModal from '@/components/table/DeleteConfirmationModal';
|
||||
import { useAuth } from '@/context/useAuthContext';
|
||||
import { api } from '@/lib/api';
|
||||
import { showSlashDate } from '@/lib/dates';
|
||||
|
||||
function fmtDate(value) {
|
||||
if (!value) return '—';
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? '—' : d.toLocaleDateString();
|
||||
return showSlashDate(value) || '—';
|
||||
}
|
||||
|
||||
export default function PatientDetail() {
|
||||
|
|
|
|||
|
|
@ -6,12 +6,11 @@ import PageBreadcrumb from '@/components/PageBreadcrumb';
|
|||
import DeleteConfirmationModal from '@/components/table/DeleteConfirmationModal';
|
||||
import { useAuth } from '@/context/useAuthContext';
|
||||
import { api } from '@/lib/api';
|
||||
import { showSlashDate } from '@/lib/dates';
|
||||
import { displayValue } from './session-fields';
|
||||
|
||||
function fmtDate(value) {
|
||||
if (!value) return '—';
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? '—' : d.toLocaleDateString();
|
||||
return showSlashDate(value) || '—';
|
||||
}
|
||||
|
||||
function Field({ label, value }) {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { Button, Card, CardBody, Container, FormControl, FormLabel, Modal, Modal
|
|||
import PageBreadcrumb from '@/components/PageBreadcrumb';
|
||||
import SessionVitalsModal, { rosterFromSession } from '@/components/SessionVitalsModal';
|
||||
import { api } from '@/lib/api';
|
||||
import { showDate } from '@/lib/dates';
|
||||
|
||||
export default function ProgramSessionsPage() {
|
||||
const [items, setItems] = useState([]);
|
||||
|
|
@ -50,7 +51,7 @@ export default function ProgramSessionsPage() {
|
|||
<tbody>
|
||||
{items.map((session) => (
|
||||
<tr key={session.id}>
|
||||
<td>{session.date} #{session.index}</td>
|
||||
<td>{showDate(session.date)} #{session.index}</td>
|
||||
<td>{session.cohort?.name || '—'}</td>
|
||||
<td>{session.slot}</td>
|
||||
<td className="text-capitalize">{session.status}</td>
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
|
|||
import { Button, Card, CardBody, Col, Container, Row, Table } from 'react-bootstrap';
|
||||
import PageBreadcrumb from '@/components/PageBreadcrumb';
|
||||
import { api } from '@/lib/api';
|
||||
import { showDate } from '@/lib/dates';
|
||||
|
||||
export default function ReportsPage() {
|
||||
const [patients, setPatients] = useState([]);
|
||||
|
|
@ -57,7 +58,7 @@ export default function ReportsPage() {
|
|||
<td>{item.name}<div className="small text-muted">{item.diseaseType}</div></td>
|
||||
<td>{item.cohort?.name || '—'}</td>
|
||||
<td>{item.prt ? `${item.prt.firstName} ${item.prt.lastName}` : '—'}</td>
|
||||
<td>{item.firstSession || '—'}</td>
|
||||
<td>{showDate(item.firstSession) || '—'}</td>
|
||||
<td>{item.completed}</td>
|
||||
{/* <td>{item.assigned}</td> */}
|
||||
{/* <td>{item.completion}</td> */}
|
||||
|
|
@ -97,7 +98,7 @@ export default function ReportsPage() {
|
|||
{(productivity.reassignments || []).length ? (
|
||||
<ul className="mb-0">
|
||||
{productivity.reassignments.map((item) => (
|
||||
<li key={item.id}>{item.date}: {item.cohort} {item.from} → {item.to || 'open'} ({item.reason})</li>
|
||||
<li key={item.id}>{showDate(item.date)}: {item.cohort} {item.from} → {item.to || 'open'} ({item.reason})</li>
|
||||
))}
|
||||
</ul>
|
||||
) : <p className="text-muted mb-0">None yet.</p>}
|
||||
|
|
|
|||
Loading…
Reference in New Issue