change of seesion paid and daily run
This commit is contained in:
parent
be209e7b76
commit
f7b45acb96
|
|
@ -48,6 +48,12 @@ const onboardedPatientSchema = new mongoose.Schema(
|
||||||
enum: ['Unpaid', 'Paid', 'Partial'],
|
enum: ['Unpaid', 'Paid', 'Partial'],
|
||||||
default: 'Unpaid',
|
default: 'Unpaid',
|
||||||
},
|
},
|
||||||
|
sessionsPaid: { type: Number, default: 30 }, // sessions covered by payment; default 30 when blank
|
||||||
|
patientStatus: {
|
||||||
|
type: String,
|
||||||
|
enum: ['active', 'deactivated'],
|
||||||
|
default: 'active',
|
||||||
|
},
|
||||||
paymentScreenshot: {
|
paymentScreenshot: {
|
||||||
filename: { type: String, default: '' },
|
filename: { type: String, default: '' },
|
||||||
originalName: { type: String, default: '' },
|
originalName: { type: String, default: '' },
|
||||||
|
|
@ -74,6 +80,11 @@ const onboardedPatientSchema = new mongoose.Schema(
|
||||||
{ timestamps: true },
|
{ timestamps: true },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Turns a stored return_pool value into deactivated before the record is saved.
|
||||||
|
onboardedPatientSchema.pre('validate', function convertOldPatientStatus() {
|
||||||
|
if (this.patientStatus === 'return_pool') this.patientStatus = 'deactivated';
|
||||||
|
});
|
||||||
|
|
||||||
onboardedPatientSchema.index({ onboardedBy: 1, createdAt: -1 });
|
onboardedPatientSchema.index({ onboardedBy: 1, createdAt: -1 });
|
||||||
onboardedPatientSchema.index({ mobileHash: 1 });
|
onboardedPatientSchema.index({ mobileHash: 1 });
|
||||||
onboardedPatientSchema.index({ assignedEducator: 1 });
|
onboardedPatientSchema.index({ assignedEducator: 1 });
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import { toCohortDto, userLanguages } from '../utils/serialize.js';
|
||||||
import { assertCohortStartDate, buildCohortName, scheduleSessionCount, scheduleWeekdays, toYmd, upcomingSessionDates, ymdToDate } from '../services/schedule.js';
|
import { assertCohortStartDate, buildCohortName, scheduleSessionCount, scheduleWeekdays, toYmd, upcomingSessionDates, ymdToDate } from '../services/schedule.js';
|
||||||
import { releaseCohortPatients, syncCohortPatients, applyCohortToPatients, applyPatientEdits, createManualCohortPatients } from '../services/cohorts.js';
|
import { releaseCohortPatients, syncCohortPatients, applyCohortToPatients, applyPatientEdits, createManualCohortPatients } from '../services/cohorts.js';
|
||||||
import { activateManualCohort, cancelCohort, startCohortMeetings } from '../services/matching.js';
|
import { activateManualCohort, cancelCohort, startCohortMeetings } from '../services/matching.js';
|
||||||
import { ensureSessionRecords, persistCohortSessions, rescheduleOpenSessions } from '../services/programSessions.js';
|
import { attachCohortPatientProgress, ensureSessionRecords, meetingWeekdays, persistCohortSessions, rescheduleOpenSessions } from '../services/programSessions.js';
|
||||||
import { CohortSession } from '../models/CohortSession.js';
|
import { CohortSession } from '../models/CohortSession.js';
|
||||||
import { assertConfiguredSlot, getAppSettings } from '../services/settings.js';
|
import { assertConfiguredSlot, getAppSettings } from '../services/settings.js';
|
||||||
import { reminderAuditText, writeAudit } from '../services/audit.js';
|
import { reminderAuditText, writeAudit } from '../services/audit.js';
|
||||||
|
|
@ -57,6 +57,8 @@ const cohortPayload = Joi.object({
|
||||||
whatsappOptOut: Joi.boolean().optional(),
|
whatsappOptOut: Joi.boolean().optional(),
|
||||||
offlineSessions: Joi.number().integer().min(0).required(), // sessions already done offline before joining
|
offlineSessions: Joi.number().integer().min(0).required(), // sessions already done offline before joining
|
||||||
offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null).optional(), // first offline session, if known
|
offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null).optional(), // first offline session, if known
|
||||||
|
sessionsPaid: Joi.alternatives().try(Joi.number().integer().min(0), Joi.string().allow('')).optional(), // sessions covered by payment
|
||||||
|
patientStatus: Joi.string().valid('active', 'deactivated').optional(),
|
||||||
})).default([]),
|
})).default([]),
|
||||||
/* Replaced by patientEdits, which also carries name, mobile, age, and gender.
|
/* Replaced by patientEdits, which also carries name, mobile, age, and gender.
|
||||||
patientOffline: Joi.array().items(Joi.object({
|
patientOffline: Joi.array().items(Joi.object({
|
||||||
|
|
@ -73,6 +75,8 @@ const cohortPayload = Joi.object({
|
||||||
gender: Joi.string().trim().allow('').optional(),
|
gender: Joi.string().trim().allow('').optional(),
|
||||||
offlineSessions: Joi.number().integer().min(0).required(),
|
offlineSessions: Joi.number().integer().min(0).required(),
|
||||||
offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null),
|
offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null),
|
||||||
|
sessionsPaid: Joi.alternatives().try(Joi.number().integer().min(0), Joi.string().allow('')).optional(),
|
||||||
|
patientStatus: Joi.string().valid('active', 'deactivated').optional(),
|
||||||
})).default([]),
|
})).default([]),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -135,7 +139,7 @@ async function findCohort(request) {
|
||||||
.populate('virtualPrt', 'firstName lastName email')
|
.populate('virtualPrt', 'firstName lastName email')
|
||||||
// .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
|
// .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
|
||||||
// .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut offlineSessions offlineStartDate' });
|
// .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut offlineSessions offlineStartDate' });
|
||||||
.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate' });
|
.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate sessionsPaid patientStatus' });
|
||||||
if (!cohort) throw Boom.notFound('Cohort not found');
|
if (!cohort) throw Boom.notFound('Cohort not found');
|
||||||
return cohort;
|
return cohort;
|
||||||
}
|
}
|
||||||
|
|
@ -257,7 +261,10 @@ export function cohortRoutes(server) {
|
||||||
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'view') }],
|
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'view') }],
|
||||||
validate: { params: Joi.object({ id: objectId.required() }) },
|
validate: { params: Joi.object({ id: objectId.required() }) },
|
||||||
},
|
},
|
||||||
handler: async (request) => (await withSessionCounts(await findCohort(request)))[0],
|
handler: async (request) => {
|
||||||
|
const [dto] = await withSessionCounts(await findCohort(request));
|
||||||
|
return attachCohortPatientProgress(dto);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
server.route({
|
server.route({
|
||||||
|
|
@ -275,7 +282,7 @@ export function cohortRoutes(server) {
|
||||||
const stored = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1 });
|
const stored = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1 });
|
||||||
if (stored.length) return { items: stored.map(toCohortSessionDto) };
|
if (stored.length) return { items: stored.map(toCohortSessionDto) };
|
||||||
const ownCount = await scheduleSessionCount(cohort.scheduleId);
|
const ownCount = await scheduleSessionCount(cohort.scheduleId);
|
||||||
const dates = await upcomingSessionDates(toYmd(cohort.startDate), cohort.virtualPrt?._id || cohort.virtualPrt, ownCount || request.query.count, cohort.language, await scheduleWeekdays(cohort.scheduleId));
|
const dates = await upcomingSessionDates(toYmd(cohort.startDate), cohort.virtualPrt?._id || cohort.virtualPrt, ownCount || request.query.count, cohort.language, await meetingWeekdays(cohort));
|
||||||
return { items: dates.map((date) => ({ date, slot: cohort.slot, status: 'scheduled' })) };
|
return { items: dates.map((date) => ({ date, slot: cohort.slot, status: 'scheduled' })) };
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
@ -413,8 +420,8 @@ export function cohortRoutes(server) {
|
||||||
const { ensureCohortGroup } = await import('../services/whatsapp.js');
|
const { ensureCohortGroup } = await import('../services/whatsapp.js');
|
||||||
const updated = await ensureCohortGroup(cohort._id);
|
const updated = await ensureCohortGroup(cohort._id);
|
||||||
await updated?.populate?.('virtualPrt', 'firstName lastName email');
|
await updated?.populate?.('virtualPrt', 'firstName lastName email');
|
||||||
await updated?.populate?.({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
|
await updated?.populate?.({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate sessionsPaid patientStatus' });
|
||||||
return toCohortDto(updated || cohort);
|
return attachCohortPatientProgress(toCohortDto(updated || cohort));
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -437,8 +444,8 @@ export function cohortRoutes(server) {
|
||||||
console.error(`[whatsapp] closing notice failed: ${err?.message || err}`);
|
console.error(`[whatsapp] closing notice failed: ${err?.message || err}`);
|
||||||
});
|
});
|
||||||
await cohort.populate('virtualPrt', 'firstName lastName email');
|
await cohort.populate('virtualPrt', 'firstName lastName email');
|
||||||
await cohort.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
|
await cohort.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate sessionsPaid patientStatus' });
|
||||||
return toCohortDto(cohort);
|
return attachCohortPatientProgress(toCohortDto(cohort));
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import { Patient } from '../models/Patient.js';
|
||||||
import { Session } from '../models/Session.js';
|
import { Session } from '../models/Session.js';
|
||||||
import { Cohort } from '../models/Cohort.js';
|
import { Cohort } from '../models/Cohort.js';
|
||||||
import { User } from '../models/User.js';
|
import { User } from '../models/User.js';
|
||||||
import { toOnboardedPatientDto, toCohortDto } from '../utils/serialize.js';
|
import { normalizePatientStatus, normalizeSessionsPaid, toOnboardedPatientDto, toCohortDto } from '../utils/serialize.js';
|
||||||
import { saveOnboardingScreenshot, screenshotPath, safeDownloadName } from '../services/onboardingUpload.js';
|
import { saveOnboardingScreenshot, screenshotPath, safeDownloadName } from '../services/onboardingUpload.js';
|
||||||
import { applyOnboardedPii, hashMobile, hashName, isMobileNumber, readOnboardedPii } from '../services/cryptoPii.js';
|
import { applyOnboardedPii, hashMobile, hashName, isMobileNumber, readOnboardedPii } from '../services/cryptoPii.js';
|
||||||
import { deleteScreenshot, presignGet, s3Enabled } from '../services/s3.js';
|
import { deleteScreenshot, presignGet, s3Enabled } from '../services/s3.js';
|
||||||
|
|
@ -157,6 +157,8 @@ function parseOnboardingFields(payload, settings, { requirePlacement = true, req
|
||||||
diseaseType,
|
diseaseType,
|
||||||
preferredWeekday,
|
preferredWeekday,
|
||||||
paymentStatus,
|
paymentStatus,
|
||||||
|
sessionsPaid: normalizeSessionsPaid(hasPayloadKey(payload, 'sessionsPaid') ? textField(payload, 'sessionsPaid') : 30),
|
||||||
|
patientStatus: normalizePatientStatus(hasPayloadKey(payload, 'patientStatus') ? textField(payload, 'patientStatus') : 'active'),
|
||||||
whatsappOptOut: ['true', '1', 'on', 'yes'].includes(textField(payload, 'whatsappOptOut').toLowerCase()),
|
whatsappOptOut: ['true', '1', 'on', 'yes'].includes(textField(payload, 'whatsappOptOut').toLowerCase()),
|
||||||
};
|
};
|
||||||
if (hasPayloadKey(payload, 'lungCondition')) fields.lungCondition = textField(payload, 'lungCondition');
|
if (hasPayloadKey(payload, 'lungCondition')) fields.lungCondition = textField(payload, 'lungCondition');
|
||||||
|
|
@ -398,6 +400,8 @@ export function onboardingRoutes(server) {
|
||||||
slot: cohort?.slot || fields.slot || '',
|
slot: cohort?.slot || fields.slot || '',
|
||||||
matchingStatus: cohort ? 'unassigned' : 'unassigned',
|
matchingStatus: cohort ? 'unassigned' : 'unassigned',
|
||||||
paymentStatus: fields.paymentStatus,
|
paymentStatus: fields.paymentStatus,
|
||||||
|
sessionsPaid: fields.sessionsPaid,
|
||||||
|
patientStatus: fields.patientStatus,
|
||||||
paymentScreenshot,
|
paymentScreenshot,
|
||||||
sourcePatientId: fields.sourcePatientId || '',
|
sourcePatientId: fields.sourcePatientId || '',
|
||||||
onboardedBy: creds.user._id,
|
onboardedBy: creds.user._id,
|
||||||
|
|
@ -491,10 +495,22 @@ export function onboardingRoutes(server) {
|
||||||
}
|
}
|
||||||
applyOnboardedPii(item, fields);
|
applyOnboardedPii(item, fields);
|
||||||
item.paymentStatus = fields.paymentStatus;
|
item.paymentStatus = fields.paymentStatus;
|
||||||
|
item.sessionsPaid = fields.sessionsPaid;
|
||||||
|
const previousPatientStatus = normalizePatientStatus(item.patientStatus);
|
||||||
|
item.patientStatus = fields.patientStatus;
|
||||||
item.whatsappOptOut = fields.whatsappOptOut;
|
item.whatsappOptOut = fields.whatsappOptOut;
|
||||||
if (confirmed) {
|
if (confirmed) {
|
||||||
await item.save();
|
await item.save();
|
||||||
await writeAudit(request, { action: 'patient.updated', resourceType: 'onboarding', resourceId: item._id });
|
await writeAudit(request, { action: 'patient.updated', resourceType: 'onboarding', resourceId: item._id });
|
||||||
|
if (previousPatientStatus !== 'active' && fields.patientStatus === 'active' && item.cohort) {
|
||||||
|
const { addPatientToWhatsapp } = await import('../services/whatsapp.js');
|
||||||
|
const cohort = await Cohort.findById(item.cohort);
|
||||||
|
if (cohort) {
|
||||||
|
await addPatientToWhatsapp(cohort, item._id).catch((err) => {
|
||||||
|
console.error(`[whatsapp] reactivate sync failed: ${err?.message || err}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
await item.populate('onboardedBy', 'firstName lastName email');
|
await item.populate('onboardedBy', 'firstName lastName email');
|
||||||
await item.populate('reviewedBy', 'firstName lastName');
|
await item.populate('reviewedBy', 'firstName lastName');
|
||||||
await item.populate('cohort', 'name startDate slot language');
|
await item.populate('cohort', 'name startDate slot language');
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import { AuditEvent } from '../models/AuditEvent.js';
|
import { AuditEvent } from '../models/AuditEvent.js';
|
||||||
|
|
||||||
export function clientIp(request) {
|
export function clientIp(request) {
|
||||||
return request.headers['x-forwarded-for']?.split(',')[0]?.trim()
|
return request?.headers?.['x-forwarded-for']?.split(',')[0]?.trim()
|
||||||
|| request.info?.remoteAddress
|
|| request?.info?.remoteAddress
|
||||||
|| '';
|
|| '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -19,11 +19,11 @@ export function reminderAuditText(rules = []) {
|
||||||
export async function writeAudit(request, { action, resourceType = '', resourceId = '', actor } = {}) {
|
export async function writeAudit(request, { action, resourceType = '', resourceId = '', actor } = {}) {
|
||||||
try {
|
try {
|
||||||
await AuditEvent.create({
|
await AuditEvent.create({
|
||||||
actor: actor || request.auth?.credentials?.user?._id || null,
|
actor: actor || request?.auth?.credentials?.user?._id || null,
|
||||||
action,
|
action,
|
||||||
resourceType,
|
resourceType,
|
||||||
resourceId: resourceId ? String(resourceId) : '',
|
resourceId: resourceId ? String(resourceId) : '',
|
||||||
ip: request ? clientIp(request) : '',
|
ip: clientIp(request),
|
||||||
at: new Date(),
|
at: new Date(),
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import { writeAudit } from './audit.js';
|
||||||
import { applyOnboardedPii, hashMobile, isMobileNumber, readOnboardedPii } from './cryptoPii.js';
|
import { applyOnboardedPii, hashMobile, isMobileNumber, readOnboardedPii } from './cryptoPii.js';
|
||||||
import { env } from '../config/env.js';
|
import { env } from '../config/env.js';
|
||||||
import { toYmd, todayYmd, weekdayOf } from './schedule.js';
|
import { toYmd, todayYmd, weekdayOf } from './schedule.js';
|
||||||
|
import { normalizePatientStatus, normalizeSessionsPaid } from '../utils/serialize.js';
|
||||||
import Boom from '@hapi/boom';
|
import Boom from '@hapi/boom';
|
||||||
|
|
||||||
async function safeWhatsapp(label, fn) {
|
async function safeWhatsapp(label, fn) {
|
||||||
|
|
@ -16,17 +17,34 @@ async function safeWhatsapp(label, fn) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Matching status for a patient placed on this cohort.
|
||||||
|
function placedMatchingStatus(cohort) {
|
||||||
|
return cohort.status === 'proposed' ? 'proposed' : 'assigned';
|
||||||
|
}
|
||||||
|
|
||||||
|
// A patient can join a cohort only while active. Someone already on it keeps their status.
|
||||||
|
export function assertCanPlacePatient(patient, cohort) {
|
||||||
|
const current = patient?.cohort ? String(patient.cohort._id || patient.cohort) : '';
|
||||||
|
if (current && current === String(cohort._id)) return;
|
||||||
|
if (normalizePatientStatus(patient?.patientStatus) === 'active') return;
|
||||||
|
throw Boom.badRequest('Only an active patient can be moved or added to a cohort.');
|
||||||
|
}
|
||||||
|
|
||||||
export async function syncCohortPatients(cohort, previousPatientIds = []) {
|
export async function syncCohortPatients(cohort, previousPatientIds = []) {
|
||||||
const nextIds = (cohort.patients || []).map((id) => String(id));
|
const nextIds = (cohort.patients || []).map((id) => String(id));
|
||||||
const prevIds = (previousPatientIds || []).map((id) => String(id));
|
const prevIds = (previousPatientIds || []).map((id) => String(id));
|
||||||
|
const added = nextIds.filter((id) => !prevIds.includes(id));
|
||||||
|
const joining = added.length
|
||||||
|
? await OnboardedPatient.find({ _id: { $in: added } }).select('cohort patientStatus')
|
||||||
|
: [];
|
||||||
|
for (const patient of joining) assertCanPlacePatient(patient, cohort);
|
||||||
|
|
||||||
if (nextIds.length) {
|
if (nextIds.length) {
|
||||||
await OnboardedPatient.updateMany(
|
await OnboardedPatient.updateMany(
|
||||||
{ _id: { $in: nextIds } },
|
{ _id: { $in: nextIds } },
|
||||||
{ $set: { assignedEducator: cohort.virtualPrt, cohort: cohort._id, matchingStatus: 'assigned' } },
|
{ $set: { assignedEducator: cohort.virtualPrt, cohort: cohort._id, matchingStatus: placedMatchingStatus(cohort) } },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const added = nextIds.filter((id) => !prevIds.includes(id));
|
|
||||||
if (added.length) {
|
if (added.length) {
|
||||||
await OnboardedPatient.updateMany({ _id: { $in: added } }, { $set: { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } });
|
await OnboardedPatient.updateMany({ _id: { $in: added } }, { $set: { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } });
|
||||||
}
|
}
|
||||||
|
|
@ -64,6 +82,8 @@ export async function addPatientToCohort(cohort, patientId, actorId = null) {
|
||||||
const id = String(patientId);
|
const id = String(patientId);
|
||||||
const current = (cohort.patients || []).map((item) => String(item._id || item));
|
const current = (cohort.patients || []).map((item) => String(item._id || item));
|
||||||
const joined = !current.includes(id);
|
const joined = !current.includes(id);
|
||||||
|
const existing = await OnboardedPatient.findById(patientId).select('cohort patientStatus');
|
||||||
|
if (existing) assertCanPlacePatient(existing, cohort);
|
||||||
if (joined) {
|
if (joined) {
|
||||||
cohort.patients.push(patientId);
|
cohort.patients.push(patientId);
|
||||||
await cohort.save();
|
await cohort.save();
|
||||||
|
|
@ -74,7 +94,7 @@ export async function addPatientToCohort(cohort, patientId, actorId = null) {
|
||||||
{ $set: {
|
{ $set: {
|
||||||
assignedEducator: cohort.virtualPrt,
|
assignedEducator: cohort.virtualPrt,
|
||||||
cohort: cohort._id,
|
cohort: cohort._id,
|
||||||
matchingStatus: 'assigned',
|
matchingStatus: placedMatchingStatus(cohort),
|
||||||
...(joined ? { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } : {}),
|
...(joined ? { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } : {}),
|
||||||
} },
|
} },
|
||||||
);
|
);
|
||||||
|
|
@ -146,13 +166,26 @@ export async function applyPatientEdits(cohort, rows = []) {
|
||||||
if (age !== current.age) fields.age = age;
|
if (age !== current.age) fields.age = age;
|
||||||
const gender = String(row.gender || '');
|
const gender = String(row.gender || '');
|
||||||
if (gender !== current.gender) fields.gender = gender;
|
if (gender !== current.gender) fields.gender = gender;
|
||||||
ready.push({ patient, fields, offlineSessions: row.offlineSessions, offlineStartDate: row.offlineStartDate || '' });
|
ready.push({
|
||||||
|
patient,
|
||||||
|
fields,
|
||||||
|
offlineSessions: row.offlineSessions,
|
||||||
|
offlineStartDate: row.offlineStartDate || '',
|
||||||
|
sessionsPaid: normalizeSessionsPaid(row.sessionsPaid),
|
||||||
|
patientStatus: normalizePatientStatus(row.patientStatus),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
for (const { patient, fields, offlineSessions, offlineStartDate } of ready) {
|
for (const { patient, fields, offlineSessions, offlineStartDate, sessionsPaid, patientStatus } of ready) {
|
||||||
|
const previousStatus = normalizePatientStatus(patient.patientStatus);
|
||||||
applyOnboardedPii(patient, fields);
|
applyOnboardedPii(patient, fields);
|
||||||
patient.offlineSessions = offlineSessions;
|
patient.offlineSessions = offlineSessions;
|
||||||
patient.offlineStartDate = offlineStartDate;
|
patient.offlineStartDate = offlineStartDate;
|
||||||
|
patient.sessionsPaid = sessionsPaid;
|
||||||
|
patient.patientStatus = patientStatus;
|
||||||
await patient.save();
|
await patient.save();
|
||||||
|
if (previousStatus !== 'active' && patientStatus === 'active' && cohort?._id) {
|
||||||
|
await safeWhatsapp('reactivate patient', () => addPatientToWhatsapp(cohort, patient._id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -166,6 +199,8 @@ export async function createManualCohortPatients(cohort, rows, userId) {
|
||||||
whatsappOptOut: Boolean(row?.whatsappOptOut),
|
whatsappOptOut: Boolean(row?.whatsappOptOut),
|
||||||
offlineSessions: Math.max(0, Number(row?.offlineSessions) || 0),
|
offlineSessions: Math.max(0, Number(row?.offlineSessions) || 0),
|
||||||
offlineStartDate: String(row?.offlineStartDate || '').trim(),
|
offlineStartDate: String(row?.offlineStartDate || '').trim(),
|
||||||
|
sessionsPaid: normalizeSessionsPaid(row?.sessionsPaid),
|
||||||
|
patientStatus: normalizePatientStatus(row?.patientStatus),
|
||||||
})).filter((row) => row.name || row.mobile);
|
})).filter((row) => row.name || row.mobile);
|
||||||
if (!list.length) return [];
|
if (!list.length) return [];
|
||||||
if (list.some((row) => !row.name || !isMobileNumber(row.mobile))) throw Boom.badRequest('Each patient needs a name and a 10 digit mobile.');
|
if (list.some((row) => !row.name || !isMobileNumber(row.mobile))) throw Boom.badRequest('Each patient needs a name and a 10 digit mobile.');
|
||||||
|
|
@ -189,6 +224,8 @@ export async function createManualCohortPatients(cohort, rows, userId) {
|
||||||
whatsappOptOut: row.whatsappOptOut,
|
whatsappOptOut: row.whatsappOptOut,
|
||||||
offlineSessions: row.offlineSessions,
|
offlineSessions: row.offlineSessions,
|
||||||
offlineStartDate: row.offlineStartDate,
|
offlineStartDate: row.offlineStartDate,
|
||||||
|
sessionsPaid: row.sessionsPaid,
|
||||||
|
patientStatus: row.patientStatus,
|
||||||
});
|
});
|
||||||
created.push(doc._id);
|
created.push(doc._id);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { OnboardedPatient } from '../models/OnboardedPatient.js';
|
||||||
import { ReassignmentEvent } from '../models/ReassignmentEvent.js';
|
import { ReassignmentEvent } from '../models/ReassignmentEvent.js';
|
||||||
import { Role } from '../models/Role.js';
|
import { Role } from '../models/Role.js';
|
||||||
import { User } from '../models/User.js';
|
import { User } from '../models/User.js';
|
||||||
import { addPatientToCohort, releaseCohortPatients, removePatientFromCohort, syncCohortPatients } from './cohorts.js';
|
import { addPatientToCohort, assertCanPlacePatient, releaseCohortPatients, removePatientFromCohort, syncCohortPatients } from './cohorts.js';
|
||||||
import { writeAudit } from './audit.js';
|
import { writeAudit } from './audit.js';
|
||||||
import { CohortSession } from '../models/CohortSession.js';
|
import { CohortSession } from '../models/CohortSession.js';
|
||||||
import { notifyCohortConfirmed, notifyReassignment } from './notify.js';
|
import { notifyCohortConfirmed, notifyReassignment } from './notify.js';
|
||||||
|
|
@ -398,6 +398,7 @@ export async function movePatient(patientId, toCohortId) {
|
||||||
throw Boom.badRequest('That proposed cohort is full.');
|
throw Boom.badRequest('That proposed cohort is full.');
|
||||||
}
|
}
|
||||||
const previous = patient.cohort;
|
const previous = patient.cohort;
|
||||||
|
assertCanPlacePatient(patient, target);
|
||||||
if (previous) await removePatientFromCohort(previous, patient._id);
|
if (previous) await removePatientFromCohort(previous, patient._id);
|
||||||
await addPatientToCohort(target, patient._id);
|
await addPatientToCohort(target, patient._id);
|
||||||
patient.matchingStatus = 'proposed';
|
patient.matchingStatus = 'proposed';
|
||||||
|
|
@ -629,6 +630,7 @@ export async function migratePatient(patient, { cohortId, slot, preferredWeekday
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
const previous = patient.cohort;
|
const previous = patient.cohort;
|
||||||
|
assertCanPlacePatient(patient, target);
|
||||||
if (previous && String(previous) !== String(target._id)) {
|
if (previous && String(previous) !== String(target._id)) {
|
||||||
await removePatientFromCohort(previous, patient._id);
|
await removePatientFromCohort(previous, patient._id);
|
||||||
}
|
}
|
||||||
|
|
@ -640,7 +642,7 @@ export async function migratePatient(patient, { cohortId, slot, preferredWeekday
|
||||||
patient.sessionLanguage = target.language || patient.sessionLanguage;
|
patient.sessionLanguage = target.language || patient.sessionLanguage;
|
||||||
patient.diseaseType = target.diseaseType || patient.diseaseType;
|
patient.diseaseType = target.diseaseType || patient.diseaseType;
|
||||||
patient.preferredWeekday = weekdayOf(toYmd(target.startDate));
|
patient.preferredWeekday = weekdayOf(toYmd(target.startDate));
|
||||||
patient.matchingStatus = 'assigned';
|
patient.matchingStatus = target.status === 'proposed' ? 'proposed' : 'assigned';
|
||||||
await persistCohortSessions(target);
|
await persistCohortSessions(target);
|
||||||
const { ensureSessionRecords } = await import('./programSessions.js');
|
const { ensureSessionRecords } = await import('./programSessions.js');
|
||||||
await ensureSessionRecords(target);
|
await ensureSessionRecords(target);
|
||||||
|
|
|
||||||
|
|
@ -181,7 +181,7 @@ async function syncExistingMeetSeries(cohort, sessions) {
|
||||||
const host = await sessionHost(linked, cohort);
|
const host = await sessionHost(linked, cohort);
|
||||||
if (!host?.google?.refreshToken && !host?.google?.accessToken) return;
|
if (!host?.google?.refreshToken && !host?.google?.accessToken) return;
|
||||||
const settings = await getAppSettings();
|
const settings = await getAppSettings();
|
||||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
const weekdays = await meetingWeekdays(cohort);
|
||||||
const first = active[0];
|
const first = active[0];
|
||||||
const last = active[active.length - 1];
|
const last = active[active.length - 1];
|
||||||
const times = slotDateTimes(first.date, first.slot || cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
|
const times = slotDateTimes(first.date, first.slot || cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
|
||||||
|
|
@ -294,6 +294,16 @@ export async function ensureSessionRecords(cohort) {
|
||||||
for (const session of dirty) await session.save();
|
for (const session of dirty) await session.save();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ALL_WEEKDAYS = [1, 2, 3, 4, 5, 6];
|
||||||
|
|
||||||
|
// Days this cohort meets. An extra schedule wins. All weekdays is Monday–Saturday. Otherwise the repeat interval.
|
||||||
|
export async function meetingWeekdays(cohort) {
|
||||||
|
const scheduled = await scheduleWeekdays(cohort?.scheduleId);
|
||||||
|
if (scheduled) return scheduled;
|
||||||
|
if (cohort?.sixDayWeek) return ALL_WEEKDAYS;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
// Next date for an extra schedule, skipping unticked days, Sunday, holiday, and leave.
|
// Next date for an extra schedule, skipping unticked days, Sunday, holiday, and leave.
|
||||||
async function nextWeekdayAppendDate(cohort, weekdays) {
|
async function nextWeekdayAppendDate(cohort, weekdays) {
|
||||||
const settings = await getAppSettings();
|
const settings = await getAppSettings();
|
||||||
|
|
@ -316,9 +326,9 @@ async function nextWeekdayAppendDate(cohort, weekdays) {
|
||||||
return cursor;
|
return cursor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Next date after the last session. Extra schedules use weekdays. Normal uses the interval.
|
// Next date after the last session. A schedule or all-weekdays uses those days. Otherwise the repeat interval.
|
||||||
export async function nextAppendDate(cohort) {
|
export async function nextAppendDate(cohort) {
|
||||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
const weekdays = await meetingWeekdays(cohort);
|
||||||
if (weekdays) return nextWeekdayAppendDate(cohort, weekdays);
|
if (weekdays) return nextWeekdayAppendDate(cohort, weekdays);
|
||||||
const settings = await getAppSettings();
|
const settings = await getAppSettings();
|
||||||
const interval = Math.max(1, Number(settings.repeatIntervalDays) || 2);
|
const interval = Math.max(1, Number(settings.repeatIntervalDays) || 2);
|
||||||
|
|
@ -339,10 +349,10 @@ export async function nextAppendDate(cohort) {
|
||||||
return cursor;
|
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.
|
// True when the cohort may meet on this date: its meeting days if set, never Sunday, and not a holiday or PRT leave.
|
||||||
async function canMeetOn(cohort, date) {
|
async function canMeetOn(cohort, date) {
|
||||||
if (weekdayOf(date) === 0) return false;
|
if (weekdayOf(date) === 0) return false;
|
||||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
const weekdays = await meetingWeekdays(cohort);
|
||||||
if (weekdays && !weekdays.map(Number).includes(weekdayOf(date))) return false;
|
if (weekdays && !weekdays.map(Number).includes(weekdayOf(date))) return false;
|
||||||
const settings = await getAppSettings();
|
const settings = await getAppSettings();
|
||||||
if (settings.skipHolidays !== false && (await holidayDatesBetween(date, date, cohort.language)).has(date)) return false;
|
if (settings.skipHolidays !== false && (await holidayDatesBetween(date, date, cohort.language)).has(date)) return false;
|
||||||
|
|
@ -481,7 +491,7 @@ export async function shiftApprovedLeaveSessions(prtId, startYmd, endYmd) {
|
||||||
if (!hit) continue;
|
if (!hit) continue;
|
||||||
const tail = sessions.filter((session) => session.status === 'scheduled' && session.date >= hit.date);
|
const tail = sessions.filter((session) => session.status === 'scheduled' && session.date >= hit.date);
|
||||||
if (!tail.length) continue;
|
if (!tail.length) continue;
|
||||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
const weekdays = await meetingWeekdays(cohort);
|
||||||
const blocked = new Set(
|
const blocked = new Set(
|
||||||
sessions.filter((session) => session.status === 'completed').map((session) => session.date),
|
sessions.filter((session) => session.status === 'completed').map((session) => session.date),
|
||||||
);
|
);
|
||||||
|
|
@ -569,7 +579,7 @@ export async function ensureMeetForCohort(cohort) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const settings = await getAppSettings();
|
const settings = await getAppSettings();
|
||||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
const weekdays = await meetingWeekdays(cohort);
|
||||||
const firstDate = sessions[0]?.date || toYmd(cohort.startDate);
|
const firstDate = sessions[0]?.date || toYmd(cohort.startDate);
|
||||||
const times = slotDateTimes(firstDate, cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
|
const times = slotDateTimes(firstDate, cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
|
||||||
try {
|
try {
|
||||||
|
|
@ -888,6 +898,19 @@ export async function moveSessionEvent(session, nextDate) {
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Adds sessionsCompleted onto each patient in a cohort DTO for paid-session red checks.
|
||||||
|
export async function attachCohortPatientProgress(dto) {
|
||||||
|
if (!dto?.patients?.length) return dto;
|
||||||
|
const stats = await patientProgramStats(dto.patients.map((patient) => patient.id).filter(Boolean));
|
||||||
|
return {
|
||||||
|
...dto,
|
||||||
|
patients: dto.patients.map((patient) => ({
|
||||||
|
...patient,
|
||||||
|
sessionsCompleted: stats.get(String(patient.id))?.completed || 0,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function patientProgramStats(patientIds) {
|
export async function patientProgramStats(patientIds) {
|
||||||
const ids = patientIds.map((id) => String(id));
|
const ids = patientIds.map((id) => String(id));
|
||||||
const sessions = await CohortSession.find({ 'records.patient': { $in: ids }, status: { $in: ['scheduled', 'completed'] } });
|
const sessions = await CohortSession.find({ 'records.patient': { $in: ids }, status: { $in: ['scheduled', 'completed'] } });
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,7 @@ import {
|
||||||
toDmy,
|
toDmy,
|
||||||
toWhatsappDigits,
|
toWhatsappDigits,
|
||||||
} from './whatsappFormat.js';
|
} from './whatsappFormat.js';
|
||||||
|
import { isPatientMessagingActive } from '../utils/serialize.js';
|
||||||
|
|
||||||
const LIVE = new Set(['active', 'confirmed']);
|
const LIVE = new Set(['active', 'confirmed']);
|
||||||
const DEFAULT_REMINDER = 'Reminder: {{cohort}} on {{date}} at {{time}}.\nTap Join Meet when you are ready.';
|
const DEFAULT_REMINDER = 'Reminder: {{cohort}} on {{date}} at {{time}}.\nTap Join Meet when you are ready.';
|
||||||
|
|
@ -146,7 +147,7 @@ async function cohortPatientsForReminder(cohort) {
|
||||||
const ids = (cohort.patients || []).map((item) => item._id || item);
|
const ids = (cohort.patients || []).map((item) => item._id || item);
|
||||||
if (!ids.length) return [];
|
if (!ids.length) return [];
|
||||||
return OnboardedPatient.find({ _id: { $in: ids } })
|
return OnboardedPatient.find({ _id: { $in: ids } })
|
||||||
.select('name mobile reviewStatus whatsappOptOut sessionLanguage');
|
.select('name mobile reviewStatus whatsappOptOut sessionLanguage patientStatus');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendSessionReminder(session, { rule, manual = false } = {}) {
|
export async function sendSessionReminder(session, { rule, manual = false } = {}) {
|
||||||
|
|
@ -172,7 +173,7 @@ export async function sendSessionReminder(session, { rule, manual = false } = {}
|
||||||
const patients = await cohortPatientsForReminder(cohort);
|
const patients = await cohortPatientsForReminder(cohort);
|
||||||
let queued = 0;
|
let queued = 0;
|
||||||
for (const patient of patients) {
|
for (const patient of patients) {
|
||||||
if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut) continue;
|
if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut || !isPatientMessagingActive(patient)) continue;
|
||||||
const pii = readOnboardedPii(patient);
|
const pii = readOnboardedPii(patient);
|
||||||
const phone = toWhatsappDigits(pii.mobile);
|
const phone = toWhatsappDigits(pii.mobile);
|
||||||
if (!phone) continue;
|
if (!phone) continue;
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { readOnboardedPii } from './cryptoPii.js';
|
||||||
import { groupDescription, groupSubject, inviteMessage, toWhatsappDigits } from './whatsappFormat.js';
|
import { groupDescription, groupSubject, inviteMessage, toWhatsappDigits } from './whatsappFormat.js';
|
||||||
import { toYmd } from './schedule.js';
|
import { toYmd } from './schedule.js';
|
||||||
import { getAppSettings, isWhatsappEnabled } from './settings.js';
|
import { getAppSettings, isWhatsappEnabled } from './settings.js';
|
||||||
|
import { isPatientMessagingActive } from '../utils/serialize.js';
|
||||||
import { createGroup, fetchInvite, sendCta, sendText, updateGroup, updateParticipants } from './wastra.js';
|
import { createGroup, fetchInvite, sendCta, sendText, updateGroup, updateParticipants } from './wastra.js';
|
||||||
|
|
||||||
const LIVE = new Set(['active', 'confirmed']);
|
const LIVE = new Set(['active', 'confirmed']);
|
||||||
|
|
@ -16,9 +17,12 @@ const STALE_LOCK_MS = 2 * 60 * 1000;
|
||||||
const POLL_MS = 5000;
|
const POLL_MS = 5000;
|
||||||
const OPEN = ['pending', 'running'];
|
const OPEN = ['pending', 'running'];
|
||||||
|
|
||||||
/** Invites stay unique after a successful send; failed/cancelled can retry. */
|
const ADD_FLAGS = new Set(['patient', 'prt', 'staff']);
|
||||||
|
|
||||||
|
/** Invites and direct adds stay unique after success; failed/cancelled can retry. */
|
||||||
export function dedupeStatusesForStep(step) {
|
export function dedupeStatusesForStep(step) {
|
||||||
if (step?.flag === 'invite') return ['pending', 'running', 'done'];
|
if (step?.flag === 'invite') return ['pending', 'running', 'done'];
|
||||||
|
if (step?.kind === 'add_member' && ADD_FLAGS.has(step?.flag)) return ['pending', 'running', 'done'];
|
||||||
return OPEN;
|
return OPEN;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -65,7 +69,7 @@ async function staffContacts(cohort) {
|
||||||
async function confirmedPatients(cohort) {
|
async function confirmedPatients(cohort) {
|
||||||
const ids = (cohort.patients || []).map((item) => item._id || item);
|
const ids = (cohort.patients || []).map((item) => item._id || item);
|
||||||
if (!ids.length) return [];
|
if (!ids.length) return [];
|
||||||
return OnboardedPatient.find({ _id: { $in: ids } }).select('name mobile reviewStatus whatsappOptOut');
|
return OnboardedPatient.find({ _id: { $in: ids } }).select('name mobile reviewStatus whatsappOptOut patientStatus');
|
||||||
}
|
}
|
||||||
|
|
||||||
function patientStep(patient) {
|
function patientStep(patient) {
|
||||||
|
|
@ -147,15 +151,30 @@ function inviteStep(cohortId, person) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function inviteSteps(cohortId, people) {
|
// Adds the person to the cohort WhatsApp group without sending an invite message.
|
||||||
return people.filter((person) => person.phone).map((person) => inviteStep(cohortId, person));
|
function addMemberStep(cohortId, person) {
|
||||||
|
const flag = person.flag || (person.patient ? 'patient' : 'staff');
|
||||||
|
return {
|
||||||
|
kind: 'add_member',
|
||||||
|
phone: person.phone,
|
||||||
|
name: person.name || '',
|
||||||
|
user: person.id || person.user || null,
|
||||||
|
patient: person.patient || null,
|
||||||
|
flag,
|
||||||
|
dedupeKey: `${cohortId}:add:${flag}:${person.phone}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function addMemberSteps(cohortId, people) {
|
||||||
|
return people.filter((person) => person.phone).map((person) => addMemberStep(cohortId, person));
|
||||||
}
|
}
|
||||||
|
|
||||||
// const PRT_ADMIN_MISSING_PHONE = 'Assigned therapist needs a mobile number before they can be a WhatsApp group admin';
|
// 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. Leave steps still run.
|
// True for old membership tasks. Direct patient/PRT/staff adds and leave steps still run.
|
||||||
export function isRetiredMembershipTask(task) {
|
export function isRetiredMembershipTask(task) {
|
||||||
// if (task?.flag === 'prt' && (task.kind === 'add_member' || task.kind === 'promote_member')) return false;
|
// if (task?.flag === 'prt' && (task.kind === 'add_member' || task.kind === 'promote_member')) return false;
|
||||||
|
if (task?.kind === 'add_member' && ADD_FLAGS.has(task?.flag)) return false;
|
||||||
if (task?.flag === 'leave' && task.kind === 'remove_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);
|
return ['ensure_contact', 'add_member', 'promote_member', 'remove_member'].includes(task?.kind);
|
||||||
}
|
}
|
||||||
|
|
@ -243,12 +262,16 @@ export async function enqueueCohortGroup(cohortId) {
|
||||||
dedupeKey: `${cohort._id}:create_group`,
|
dedupeKey: `${cohort._id}:create_group`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
steps.push(...inviteSteps(cohort._id, staff));
|
const prtId = String(cohort.virtualPrt?._id || cohort.virtualPrt || '');
|
||||||
|
steps.push(...addMemberSteps(cohort._id, staff.map((person) => ({
|
||||||
|
...person,
|
||||||
|
flag: String(person.id) === prtId ? 'prt' : 'staff',
|
||||||
|
}))));
|
||||||
for (const patient of patients) {
|
for (const patient of patients) {
|
||||||
if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut) continue;
|
if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut || !isPatientMessagingActive(patient)) continue;
|
||||||
const step = patientStep(patient);
|
const step = patientStep(patient);
|
||||||
if (!step.phone) continue;
|
if (!step.phone) continue;
|
||||||
steps.push(inviteStep(cohort._id, step));
|
steps.push(addMemberStep(cohort._id, { ...step, flag: 'patient' }));
|
||||||
}
|
}
|
||||||
// steps.push(...await prtAdminSteps(cohort));
|
// steps.push(...await prtAdminSteps(cohort));
|
||||||
await enqueueMany(cohort._id, steps);
|
await enqueueMany(cohort._id, steps);
|
||||||
|
|
@ -262,15 +285,16 @@ export async function enqueuePatientAdd(cohort, patientId) {
|
||||||
await enqueueCohortGroup(cohort._id);
|
await enqueueCohortGroup(cohort._id);
|
||||||
}
|
}
|
||||||
if (!fresh?.whatsappGroupJid) return;
|
if (!fresh?.whatsappGroupJid) return;
|
||||||
const patient = await OnboardedPatient.findById(patientId).select('name mobile reviewStatus whatsappOptOut');
|
const patient = await OnboardedPatient.findById(patientId).select('name mobile reviewStatus whatsappOptOut patientStatus');
|
||||||
if (!patient || patient.reviewStatus !== 'confirmed') return;
|
if (!patient || patient.reviewStatus !== 'confirmed') return;
|
||||||
const step = patientStep(patient);
|
const step = patientStep(patient);
|
||||||
if (patient.whatsappOptOut) {
|
if (patient.whatsappOptOut) {
|
||||||
await enqueuePatientRemove(fresh._id, patientId);
|
await enqueuePatientRemove(fresh._id, patientId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!isPatientMessagingActive(patient)) return;
|
||||||
if (!step.phone) return;
|
if (!step.phone) return;
|
||||||
await enqueueMany(fresh._id, [inviteStep(fresh._id, { ...step, patient: patient._id })]);
|
await enqueueMany(fresh._id, [addMemberStep(fresh._id, { ...step, patient: patient._id, flag: 'patient' })]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function enqueuePatientRemove(cohortId, patientId) {
|
export async function enqueuePatientRemove(cohortId, patientId) {
|
||||||
|
|
@ -320,7 +344,12 @@ export async function enqueuePrtSwap(cohortOrId, previousPrtId) {
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
if (nextPhone) {
|
if (nextPhone) {
|
||||||
steps.push(inviteStep(cohort._id, { id: String(next._id), phone: nextPhone, name: personName(next) }));
|
steps.push(addMemberStep(cohort._id, {
|
||||||
|
id: String(next._id),
|
||||||
|
phone: nextPhone,
|
||||||
|
name: personName(next),
|
||||||
|
flag: 'prt',
|
||||||
|
}));
|
||||||
const text = `Your therapist for this group is now ${personName(next)}.`;
|
const text = `Your therapist for this group is now ${personName(next)}.`;
|
||||||
steps.push({ kind: 'send_text', text, flag: 'prt', dedupeKey: textKey(cohort._id, text) });
|
steps.push({ kind: 'send_text', text, flag: 'prt', dedupeKey: textKey(cohort._id, text) });
|
||||||
}
|
}
|
||||||
|
|
@ -375,7 +404,9 @@ async function noteCohortError(task, message) {
|
||||||
if (!cohort) return;
|
if (!cohort) return;
|
||||||
cohort.whatsappError = message || task.lastError || 'WhatsApp task failed';
|
cohort.whatsappError = message || task.lastError || 'WhatsApp task failed';
|
||||||
if (task.kind === 'create_group') cohort.whatsappStatus = 'failed';
|
if (task.kind === 'create_group') cohort.whatsappStatus = 'failed';
|
||||||
if (task.patient && task.flag === 'invite') upsertMember(cohort, task.patient, 'failed', cohort.whatsappError);
|
if (task.patient && (task.flag === 'invite' || task.flag === 'patient')) {
|
||||||
|
upsertMember(cohort, task.patient, 'failed', cohort.whatsappError);
|
||||||
|
}
|
||||||
await cohort.save();
|
await cohort.save();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -385,11 +416,11 @@ async function clearCohortError(cohortId) {
|
||||||
await Cohort.updateOne({ _id: cohortId }, { $set: { whatsappError: '' } });
|
await Cohort.updateOne({ _id: cohortId }, { $set: { whatsappError: '' } });
|
||||||
}
|
}
|
||||||
|
|
||||||
// function participantAlreadyUpdated(action, err) {
|
function participantAlreadyUpdated(action, err) {
|
||||||
// const message = String(err?.message || '').toLowerCase();
|
const message = String(err?.message || '').toLowerCase();
|
||||||
// if (!message.includes('already') && !message.includes('409')) return false;
|
if (!message.includes('already') && !message.includes('409')) return false;
|
||||||
// return action === 'add' || action === 'promote';
|
return action === 'add' || action === 'promote';
|
||||||
// }
|
}
|
||||||
|
|
||||||
function participantAlreadyGone(err) {
|
function participantAlreadyGone(err) {
|
||||||
const message = String(err?.message || '').toLowerCase();
|
const message = String(err?.message || '').toLowerCase();
|
||||||
|
|
@ -454,6 +485,35 @@ async function runLeaveStep(task) {
|
||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
// Adds a patient, PRT, or staff number to the cohort WhatsApp group.
|
||||||
|
async function runAddMemberStep(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, 'add', [task.phone]);
|
||||||
|
} catch (err) {
|
||||||
|
if (!participantAlreadyUpdated('add', err)) throw err;
|
||||||
|
}
|
||||||
|
if (task.patient) {
|
||||||
|
upsertMember(cohort, task.patient, 'added', '');
|
||||||
|
await cohort.save();
|
||||||
|
}
|
||||||
|
await clearCohortError(cohort._id);
|
||||||
|
}
|
||||||
|
|
||||||
async function execute(task) {
|
async function execute(task) {
|
||||||
if (isRetiredMembershipTask(task)) {
|
if (isRetiredMembershipTask(task)) {
|
||||||
task.status = 'cancelled';
|
task.status = 'cancelled';
|
||||||
|
|
@ -466,6 +526,10 @@ async function execute(task) {
|
||||||
// await runPrtAdminStep(task);
|
// await runPrtAdminStep(task);
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
|
if (task.kind === 'add_member' && ADD_FLAGS.has(task.flag)) {
|
||||||
|
await runAddMemberStep(task);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (task.flag === 'leave' && task.kind === 'remove_member') {
|
if (task.flag === 'leave' && task.kind === 'remove_member') {
|
||||||
await runLeaveStep(task);
|
await runLeaveStep(task);
|
||||||
return;
|
return;
|
||||||
|
|
@ -675,7 +739,8 @@ function cancelMembershipTasks() {
|
||||||
$or: [
|
$or: [
|
||||||
{ kind: 'ensure_contact' },
|
{ kind: 'ensure_contact' },
|
||||||
{ kind: 'remove_member', flag: { $ne: 'leave' } },
|
{ kind: 'remove_member', flag: { $ne: 'leave' } },
|
||||||
{ kind: { $in: ['add_member', 'promote_member'] } },
|
{ kind: 'promote_member' },
|
||||||
|
{ kind: 'add_member', flag: { $nin: [...ADD_FLAGS] } },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{ $set: { status: 'cancelled', lockedAt: null, lastError: 'Membership updates are no longer sent to WhatsApp' } },
|
{ $set: { status: 'cancelled', lockedAt: null, lastError: 'Membership updates are no longer sent to WhatsApp' } },
|
||||||
|
|
|
||||||
|
|
@ -10,17 +10,20 @@ test('draws each WhatsApp gap from 15 to 40 seconds', () => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('keeps the conducting therapist admin steps and drops old membership tasks', () => {
|
test('keeps direct add and leave steps and drops old membership tasks', () => {
|
||||||
// assert.equal(isRetiredMembershipTask({ kind: 'promote_member', flag: 'prt' }), false);
|
assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'patient' }), false);
|
||||||
// assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'prt' }), false);
|
assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'prt' }), false);
|
||||||
|
assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'staff' }), false);
|
||||||
|
assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: '' }), true);
|
||||||
assert.equal(isRetiredMembershipTask({ kind: 'promote_member', flag: '' }), true);
|
assert.equal(isRetiredMembershipTask({ kind: 'promote_member', flag: '' }), true);
|
||||||
assert.equal(isRetiredMembershipTask({ kind: 'remove_member', flag: 'leave' }), false);
|
assert.equal(isRetiredMembershipTask({ kind: 'remove_member', flag: 'leave' }), false);
|
||||||
assert.equal(isRetiredMembershipTask({ kind: 'remove_member' }), true);
|
assert.equal(isRetiredMembershipTask({ kind: 'remove_member' }), true);
|
||||||
assert.equal(isRetiredMembershipTask({ kind: 'send_text', flag: 'invite' }), false);
|
assert.equal(isRetiredMembershipTask({ kind: 'send_text', flag: 'invite' }), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('invite steps treat a done send as already delivered', () => {
|
test('invite and direct add steps treat a done send as already delivered', () => {
|
||||||
assert.deepEqual(dedupeStatusesForStep({ flag: 'invite' }), ['pending', 'running', 'done']);
|
assert.deepEqual(dedupeStatusesForStep({ flag: 'invite' }), ['pending', 'running', 'done']);
|
||||||
|
assert.deepEqual(dedupeStatusesForStep({ kind: 'add_member', flag: 'patient' }), ['pending', 'running', 'done']);
|
||||||
assert.deepEqual(dedupeStatusesForStep({ flag: 'reminder' }), ['pending', 'running']);
|
assert.deepEqual(dedupeStatusesForStep({ flag: 'reminder' }), ['pending', 'running']);
|
||||||
assert.deepEqual(dedupeStatusesForStep({ kind: 'send_text' }), ['pending', 'running']);
|
assert.deepEqual(dedupeStatusesForStep({ kind: 'send_text' }), ['pending', 'running']);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -165,6 +165,26 @@ export function toSessionDto(session) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Blank or invalid paid-session counts become 30.
|
||||||
|
export function normalizeSessionsPaid(value) {
|
||||||
|
if (value === '' || value == null) return 30;
|
||||||
|
const n = Number(value);
|
||||||
|
if (Number.isNaN(n)) return 30;
|
||||||
|
return Math.max(0, Math.floor(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Patient status is active or deactivated. Old return_pool values count as deactivated.
|
||||||
|
export function normalizePatientStatus(value) {
|
||||||
|
const next = String(value || 'active');
|
||||||
|
if (next === 'deactivated' || next === 'return_pool') return 'deactivated';
|
||||||
|
return 'active';
|
||||||
|
}
|
||||||
|
|
||||||
|
// True when the patient can receive WhatsApp reminders and membership updates.
|
||||||
|
export function isPatientMessagingActive(patient) {
|
||||||
|
return normalizePatientStatus(patient?.patientStatus) === 'active';
|
||||||
|
}
|
||||||
|
|
||||||
export function toOnboardedPatientDto(item) {
|
export function toOnboardedPatientDto(item) {
|
||||||
if (!item) return null;
|
if (!item) return null;
|
||||||
const pii = readOnboardedPii(item);
|
const pii = readOnboardedPii(item);
|
||||||
|
|
@ -191,6 +211,8 @@ export function toOnboardedPatientDto(item) {
|
||||||
matchingStatus: item.matchingStatus || 'unassigned',
|
matchingStatus: item.matchingStatus || 'unassigned',
|
||||||
rejectReason: item.rejectReason || '',
|
rejectReason: item.rejectReason || '',
|
||||||
paymentStatus: item.paymentStatus || 'Unpaid',
|
paymentStatus: item.paymentStatus || 'Unpaid',
|
||||||
|
sessionsPaid: normalizeSessionsPaid(item.sessionsPaid),
|
||||||
|
patientStatus: normalizePatientStatus(item.patientStatus),
|
||||||
hasScreenshot: Boolean(item.paymentScreenshot?.filename),
|
hasScreenshot: Boolean(item.paymentScreenshot?.filename),
|
||||||
onboardedBy: by
|
onboardedBy: by
|
||||||
? {
|
? {
|
||||||
|
|
@ -268,7 +290,18 @@ export function toCohortDto(cohort) {
|
||||||
p && typeof p === 'object'
|
p && typeof p === 'object'
|
||||||
// ? { id: String(p._id), name: readOnboardedPii(p).name, mobile: readOnboardedPii(p).mobile, whatsappOptOut: Boolean(p.whatsappOptOut) }
|
// ? { id: String(p._id), name: readOnboardedPii(p).name, mobile: readOnboardedPii(p).mobile, whatsappOptOut: Boolean(p.whatsappOptOut) }
|
||||||
// ? { id: String(p._id), name: readOnboardedPii(p).name, mobile: readOnboardedPii(p).mobile, whatsappOptOut: Boolean(p.whatsappOptOut), offlineSessions: p.offlineSessions || 0, offlineStartDate: p.offlineStartDate || '' }
|
// ? { id: String(p._id), name: readOnboardedPii(p).name, mobile: readOnboardedPii(p).mobile, whatsappOptOut: Boolean(p.whatsappOptOut), offlineSessions: p.offlineSessions || 0, offlineStartDate: p.offlineStartDate || '' }
|
||||||
? { id: String(p._id), name: readOnboardedPii(p).name, mobile: readOnboardedPii(p).mobile, age: readOnboardedPii(p).age ?? '', gender: readOnboardedPii(p).gender, whatsappOptOut: Boolean(p.whatsappOptOut), offlineSessions: p.offlineSessions || 0, offlineStartDate: p.offlineStartDate || '' }
|
? {
|
||||||
|
id: String(p._id),
|
||||||
|
name: readOnboardedPii(p).name,
|
||||||
|
mobile: readOnboardedPii(p).mobile,
|
||||||
|
age: readOnboardedPii(p).age ?? '',
|
||||||
|
gender: readOnboardedPii(p).gender,
|
||||||
|
whatsappOptOut: Boolean(p.whatsappOptOut),
|
||||||
|
offlineSessions: p.offlineSessions || 0,
|
||||||
|
offlineStartDate: p.offlineStartDate || '',
|
||||||
|
sessionsPaid: normalizeSessionsPaid(p.sessionsPaid),
|
||||||
|
patientStatus: normalizePatientStatus(p.patientStatus),
|
||||||
|
}
|
||||||
: { id: String(p) }
|
: { id: String(p) }
|
||||||
)),
|
)),
|
||||||
patientCount: patients.length,
|
patientCount: patients.length,
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,7 @@ const DataTable = ({
|
||||||
</tr>)}
|
</tr>)}
|
||||||
</thead>}
|
</thead>}
|
||||||
<tbody>
|
<tbody>
|
||||||
{table.getRowModel().rows?.length ? table.getRowModel().rows.map(row => <tr key={row.id}>
|
{table.getRowModel().rows?.length ? table.getRowModel().rows.map(row => <tr key={row.id} className={table.options.meta?.getRowClassName?.(row) || ''}>
|
||||||
{row.getVisibleCells().map(cell => <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>)}
|
{row.getVisibleCells().map(cell => <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>)}
|
||||||
</tr>) : <tr>
|
</tr>) : <tr>
|
||||||
<td colSpan={columns.length} className="text-center py-3 text-muted">
|
<td colSpan={columns.length} className="text-center py-3 text-muted">
|
||||||
|
|
|
||||||
|
|
@ -98,7 +98,20 @@ export default function CohortsPage() {
|
||||||
id: 'whatsapp',
|
id: 'whatsapp',
|
||||||
header: 'WhatsApp',
|
header: 'WhatsApp',
|
||||||
cell: ({ row, getValue }) => (
|
cell: ({ row, getValue }) => (
|
||||||
<Button variant="link" className="p-0 text-capitalize" onClick={() => { setWaError(''); setWaCohort(row.original); }}>
|
<Button
|
||||||
|
variant="link"
|
||||||
|
className="p-0 text-capitalize"
|
||||||
|
onClick={async () => {
|
||||||
|
setWaError('');
|
||||||
|
try {
|
||||||
|
const detail = await api(`/api/cohorts/${row.original.id}`);
|
||||||
|
setWaCohort(detail);
|
||||||
|
} catch (err) {
|
||||||
|
setWaError(err.message);
|
||||||
|
setWaCohort(row.original);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
{getValue() || '—'}
|
{getValue() || '—'}
|
||||||
</Button>
|
</Button>
|
||||||
),
|
),
|
||||||
|
|
@ -228,9 +241,15 @@ export default function CohortsPage() {
|
||||||
<ul className="mb-0">
|
<ul className="mb-0">
|
||||||
{(waCohort?.patients || []).map((patient) => {
|
{(waCohort?.patients || []).map((patient) => {
|
||||||
const member = (waCohort.whatsapp?.members || []).find((item) => item.patientId === patient.id);
|
const member = (waCohort.whatsapp?.members || []).find((item) => item.patientId === patient.id);
|
||||||
|
const paid = Number(patient.sessionsPaid ?? 30);
|
||||||
|
const done = Number(patient.sessionsCompleted ?? 0);
|
||||||
|
const exhausted = done >= paid;
|
||||||
return (
|
return (
|
||||||
<li key={patient.id} className="mb-2">
|
<li key={patient.id} className={`mb-2${exhausted ? ' text-danger fw-semibold' : ''}`}>
|
||||||
{patient.name} · {patient.whatsappOptOut ? 'opted out' : (member?.status || 'not synced')}
|
{patient.name}
|
||||||
|
{exhausted ? ` · ${done}/${paid} sessions` : ''}
|
||||||
|
{' · '}
|
||||||
|
{patient.whatsappOptOut ? 'opted out' : (member?.status || 'not synced')}
|
||||||
{member?.error ? ` · ${member.error}` : ''}
|
{member?.error ? ` · ${member.error}` : ''}
|
||||||
{can('onboarding', 'edit') ? (
|
{can('onboarding', 'edit') ? (
|
||||||
<Button
|
<Button
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@ function prtLanguages(user) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// const emptyPatient = { name: '', mobile: '', age: '', gender: '' };
|
// const emptyPatient = { name: '', mobile: '', age: '', gender: '' };
|
||||||
const emptyPatient = { name: '', mobile: '', age: '', gender: '', offlineSessions: '', offlineStartDate: '' };
|
const emptyPatient = { name: '', mobile: '', age: '', gender: '', offlineSessions: '', offlineStartDate: '', sessionsPaid: 30, patientStatus: 'active' };
|
||||||
|
|
||||||
function blankRow() {
|
function blankRow() {
|
||||||
return { key: `${Date.now()}-${Math.random()}`, id: '', existing: false, ...emptyPatient };
|
return { key: `${Date.now()}-${Math.random()}`, id: '', existing: false, ...emptyPatient };
|
||||||
|
|
@ -124,6 +124,9 @@ export default function PrtCohortForm() {
|
||||||
originalMobile: patient.mobile || '',
|
originalMobile: patient.mobile || '',
|
||||||
offlineSessions: patient.offlineSessions ?? 0,
|
offlineSessions: patient.offlineSessions ?? 0,
|
||||||
offlineStartDate: patient.offlineStartDate || '',
|
offlineStartDate: patient.offlineStartDate || '',
|
||||||
|
sessionsPaid: patient.sessionsPaid ?? 30,
|
||||||
|
patientStatus: patient.patientStatus || 'active',
|
||||||
|
sessionsCompleted: patient.sessionsCompleted ?? 0,
|
||||||
})));
|
})));
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
if (active) setError(err.message);
|
if (active) setError(err.message);
|
||||||
|
|
@ -191,6 +194,8 @@ export default function PrtCohortForm() {
|
||||||
whatsappOptOut: false,
|
whatsappOptOut: false,
|
||||||
offlineSessions: Number(row.offlineSessions),
|
offlineSessions: Number(row.offlineSessions),
|
||||||
offlineStartDate: row.offlineStartDate || '',
|
offlineStartDate: row.offlineStartDate || '',
|
||||||
|
sessionsPaid: row.sessionsPaid === '' || row.sessionsPaid == null ? 30 : Number(row.sessionsPaid),
|
||||||
|
patientStatus: row.patientStatus || 'active',
|
||||||
}));
|
}));
|
||||||
const statusProblem = cohortStatusError(statusValue);
|
const statusProblem = cohortStatusError(statusValue);
|
||||||
if (statusProblem) {
|
if (statusProblem) {
|
||||||
|
|
@ -231,6 +236,8 @@ export default function PrtCohortForm() {
|
||||||
gender: row.gender || '',
|
gender: row.gender || '',
|
||||||
offlineSessions: Number(row.offlineSessions) || 0,
|
offlineSessions: Number(row.offlineSessions) || 0,
|
||||||
offlineStartDate: row.offlineStartDate || '',
|
offlineStartDate: row.offlineStartDate || '',
|
||||||
|
sessionsPaid: row.sessionsPaid === '' || row.sessionsPaid == null ? 30 : Number(row.sessionsPaid),
|
||||||
|
patientStatus: row.patientStatus || 'active',
|
||||||
})),
|
})),
|
||||||
scheduleId: '',
|
scheduleId: '',
|
||||||
createdAs: 'manual_cohorts',
|
createdAs: 'manual_cohorts',
|
||||||
|
|
@ -366,12 +373,18 @@ export default function PrtCohortForm() {
|
||||||
{/* <th style={{ width: 140 }}>Sessions completed</th> */}
|
{/* <th style={{ width: 140 }}>Sessions completed</th> */}
|
||||||
<th style={{ width: 140 }}>Offline completed</th>
|
<th style={{ width: 140 }}>Offline completed</th>
|
||||||
<th style={{ width: 170 }}>Start date</th>
|
<th style={{ width: 170 }}>Start date</th>
|
||||||
|
<th style={{ width: 120 }}>Sessions paid</th>
|
||||||
|
<th style={{ width: 150 }}>Patient status</th>
|
||||||
<th style={{ width: 48 }} />
|
<th style={{ width: 48 }} />
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{rows.map((row) => (
|
{rows.map((row) => {
|
||||||
<tr key={row.key}>
|
const paid = Number(row.sessionsPaid === '' || row.sessionsPaid == null ? 30 : row.sessionsPaid);
|
||||||
|
const done = Number(row.sessionsCompleted ?? 0);
|
||||||
|
const exhausted = row.existing && done >= paid;
|
||||||
|
return (
|
||||||
|
<tr key={row.key} className={exhausted ? 'table-danger' : ''}>
|
||||||
<td>
|
<td>
|
||||||
<FormControl
|
<FormControl
|
||||||
value={row.name}
|
value={row.name}
|
||||||
|
|
@ -426,6 +439,25 @@ export default function PrtCohortForm() {
|
||||||
onChange={(e) => updateRow(row.key, { offlineStartDate: e.target.value })}
|
onChange={(e) => updateRow(row.key, { offlineStartDate: e.target.value })}
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
|
<td>
|
||||||
|
<FormControl
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
value={row.sessionsPaid}
|
||||||
|
placeholder="30"
|
||||||
|
onChange={(e) => updateRow(row.key, { sessionsPaid: e.target.value })}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<select
|
||||||
|
className="form-select form-select-sm"
|
||||||
|
value={row.patientStatus || 'active'}
|
||||||
|
onChange={(e) => updateRow(row.key, { patientStatus: e.target.value })}
|
||||||
|
>
|
||||||
|
<option value="active">Active</option>
|
||||||
|
<option value="deactivated">Deactivated</option>
|
||||||
|
</select>
|
||||||
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
|
|
@ -438,7 +470,8 @@ export default function PrtCohortForm() {
|
||||||
</Button>
|
</Button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,8 @@ const empty = {
|
||||||
preferredWeekday: '',
|
preferredWeekday: '',
|
||||||
diseaseType: '',
|
diseaseType: '',
|
||||||
paymentStatus: 'Unpaid',
|
paymentStatus: 'Unpaid',
|
||||||
|
sessionsPaid: 30,
|
||||||
|
patientStatus: 'active',
|
||||||
whatsappOptOut: false,
|
whatsappOptOut: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -126,6 +128,8 @@ export default function OnboardingForm() {
|
||||||
preferredWeekday: item.preferredWeekday ?? '',
|
preferredWeekday: item.preferredWeekday ?? '',
|
||||||
diseaseType: item.diseaseType || '',
|
diseaseType: item.diseaseType || '',
|
||||||
paymentStatus: item.paymentStatus || 'Unpaid',
|
paymentStatus: item.paymentStatus || 'Unpaid',
|
||||||
|
sessionsPaid: item.sessionsPaid ?? 30,
|
||||||
|
patientStatus: item.patientStatus || 'active',
|
||||||
whatsappOptOut: Boolean(item.whatsappOptOut),
|
whatsappOptOut: Boolean(item.whatsappOptOut),
|
||||||
});
|
});
|
||||||
}).catch((err) => setError(err.message));
|
}).catch((err) => setError(err.message));
|
||||||
|
|
@ -222,6 +226,25 @@ export default function OnboardingForm() {
|
||||||
<FormLabel>Payment status</FormLabel>
|
<FormLabel>Payment status</FormLabel>
|
||||||
<OptionsSelect value={form.paymentStatus} onChange={(value) => setField('paymentStatus', value)} options={settings?.paymentStatuses} required />
|
<OptionsSelect value={form.paymentStatus} onChange={(value) => setField('paymentStatus', value)} options={settings?.paymentStatuses} required />
|
||||||
</Col>
|
</Col>
|
||||||
|
<Col md={4}>
|
||||||
|
<FormLabel>Sessions paid</FormLabel>
|
||||||
|
<FormControl
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
value={form.sessionsPaid}
|
||||||
|
onChange={(e) => setField('sessionsPaid', e.target.value === '' ? '' : Number(e.target.value))}
|
||||||
|
placeholder="30"
|
||||||
|
/>
|
||||||
|
<div className="form-text">Defaults to 30 if left blank. Raise this after more payment to clear the red limit.</div>
|
||||||
|
</Col>
|
||||||
|
<Col md={4}>
|
||||||
|
<FormLabel>Patient status</FormLabel>
|
||||||
|
<select className="form-select" value={form.patientStatus} onChange={(e) => setField('patientStatus', e.target.value)}>
|
||||||
|
<option value="active">Active</option>
|
||||||
|
<option value="deactivated">Deactivated</option>
|
||||||
|
</select>
|
||||||
|
<div className="form-text">Deactivated keeps the patient on the cohort. Only an active patient can be moved.</div>
|
||||||
|
</Col>
|
||||||
{poolMode ? (
|
{poolMode ? (
|
||||||
<>
|
<>
|
||||||
{showSlot ? (
|
{showSlot ? (
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,17 @@ function reviewBadge(status) {
|
||||||
return <span className="badge bg-warning-subtle text-warning">Pending</span>;
|
return <span className="badge bg-warning-subtle text-warning">Pending</span>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function patientStatusBadge(status) {
|
||||||
|
if (status === 'deactivated') return <span className="badge bg-secondary-subtle text-secondary">Deactivated</span>;
|
||||||
|
return <span className="badge bg-success-subtle text-success">Active</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionsExhausted(item) {
|
||||||
|
const paid = Number(item.sessionsPaid ?? 30);
|
||||||
|
const done = Number(item.progress?.completed ?? 0);
|
||||||
|
return done >= paid;
|
||||||
|
}
|
||||||
|
|
||||||
async function loadScreenshot(id) {
|
async function loadScreenshot(id) {
|
||||||
const res = await fetch(`/api/onboarding/${id}/screenshot`, { credentials: 'include' });
|
const res = await fetch(`/api/onboarding/${id}/screenshot`, { credentials: 'include' });
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
|
|
@ -152,9 +163,23 @@ export default function OnboardingPage() {
|
||||||
// columnHelper.accessor((r) => r.progress ? `${r.progress.attended}/${r.progress.total}` : '—', { id: 'progress', header: 'Sessions' }),
|
// columnHelper.accessor((r) => r.progress ? `${r.progress.attended}/${r.progress.total}` : '—', { id: 'progress', header: 'Sessions' }),
|
||||||
// columnHelper.accessor((r) => r.progress ? `${r.progress.attended}/${r.progress.completed}` : '—', { id: 'progress', header: 'Attended / held' }),
|
// columnHelper.accessor((r) => r.progress ? `${r.progress.attended}/${r.progress.completed}` : '—', { id: 'progress', header: 'Attended / held' }),
|
||||||
columnHelper.accessor((r) => r.progress?.completed ?? 0, { id: 'progress', header: 'Sessions completed' }),
|
columnHelper.accessor((r) => r.progress?.completed ?? 0, { id: 'progress', header: 'Sessions completed' }),
|
||||||
|
columnHelper.accessor((r) => r.sessionsPaid ?? 30, {
|
||||||
|
id: 'sessionsPaid',
|
||||||
|
header: 'Sessions paid',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const paid = row.original.sessionsPaid ?? 30;
|
||||||
|
const done = row.original.progress?.completed ?? 0;
|
||||||
|
return sessionsExhausted(row.original) ? `${done}/${paid}` : `${paid}`;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
columnHelper.accessor((r) => r.patientStatus || 'active', {
|
||||||
|
id: 'patientStatus',
|
||||||
|
header: 'Patient status',
|
||||||
|
cell: ({ row }) => patientStatusBadge(row.original.patientStatus),
|
||||||
|
}),
|
||||||
columnHelper.accessor((r) => r.reviewStatus || 'pending', {
|
columnHelper.accessor((r) => r.reviewStatus || 'pending', {
|
||||||
id: 'reviewStatus',
|
id: 'reviewStatus',
|
||||||
header: 'Status',
|
header: 'Review',
|
||||||
cell: ({ row }) => reviewBadge(row.original.reviewStatus),
|
cell: ({ row }) => reviewBadge(row.original.reviewStatus),
|
||||||
}),
|
}),
|
||||||
columnHelper.accessor((r) => (r.onboardedBy ? `${r.onboardedBy.firstName} ${r.onboardedBy.lastName}` : ''), {
|
columnHelper.accessor((r) => (r.onboardedBy ? `${r.onboardedBy.firstName} ${r.onboardedBy.lastName}` : ''), {
|
||||||
|
|
@ -231,6 +256,9 @@ export default function OnboardingPage() {
|
||||||
columns,
|
columns,
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
getSortedRowModel: getSortedRowModel(),
|
getSortedRowModel: getSortedRowModel(),
|
||||||
|
meta: {
|
||||||
|
getRowClassName: (row) => (sessionsExhausted(row.original) ? 'table-danger' : ''),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const start = total === 0 ? 0 : page * pageSize + 1;
|
const start = total === 0 ? 0 : page * pageSize + 1;
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue