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'],
|
||||
default: 'Unpaid',
|
||||
},
|
||||
sessionsPaid: { type: Number, default: 30 }, // sessions covered by payment; default 30 when blank
|
||||
patientStatus: {
|
||||
type: String,
|
||||
enum: ['active', 'deactivated'],
|
||||
default: 'active',
|
||||
},
|
||||
paymentScreenshot: {
|
||||
filename: { type: String, default: '' },
|
||||
originalName: { type: String, default: '' },
|
||||
|
|
@ -74,6 +80,11 @@ const onboardedPatientSchema = new mongoose.Schema(
|
|||
{ 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({ mobileHash: 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 { releaseCohortPatients, syncCohortPatients, applyCohortToPatients, applyPatientEdits, createManualCohortPatients } from '../services/cohorts.js';
|
||||
import { activateManualCohort, cancelCohort, startCohortMeetings } from '../services/matching.js';
|
||||
import { ensureSessionRecords, persistCohortSessions, rescheduleOpenSessions } from '../services/programSessions.js';
|
||||
import { attachCohortPatientProgress, ensureSessionRecords, meetingWeekdays, 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';
|
||||
|
|
@ -57,6 +57,8 @@ const cohortPayload = Joi.object({
|
|||
whatsappOptOut: Joi.boolean().optional(),
|
||||
offlineSessions: Joi.number().integer().min(0).required(), // sessions already done offline before joining
|
||||
offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null).optional(), // first offline session, if known
|
||||
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([]),
|
||||
/* Replaced by patientEdits, which also carries name, mobile, age, and gender.
|
||||
patientOffline: Joi.array().items(Joi.object({
|
||||
|
|
@ -73,6 +75,8 @@ const cohortPayload = Joi.object({
|
|||
gender: Joi.string().trim().allow('').optional(),
|
||||
offlineSessions: Joi.number().integer().min(0).required(),
|
||||
offlineStartDate: Joi.string().pattern(/^\d{4}-\d{2}-\d{2}$/).allow('', null),
|
||||
sessionsPaid: Joi.alternatives().try(Joi.number().integer().min(0), Joi.string().allow('')).optional(),
|
||||
patientStatus: Joi.string().valid('active', 'deactivated').optional(),
|
||||
})).default([]),
|
||||
});
|
||||
|
||||
|
|
@ -135,7 +139,7 @@ async function findCohort(request) {
|
|||
.populate('virtualPrt', 'firstName lastName email')
|
||||
// .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
|
||||
// .populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut 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');
|
||||
return cohort;
|
||||
}
|
||||
|
|
@ -257,7 +261,10 @@ export function cohortRoutes(server) {
|
|||
pre: [{ method: requireAnyPermission(['cohorts', 'prt_cohorts'], 'view') }],
|
||||
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({
|
||||
|
|
@ -275,7 +282,7 @@ export function cohortRoutes(server) {
|
|||
const stored = await CohortSession.find({ cohort: cohort._id }).sort({ index: 1 });
|
||||
if (stored.length) return { items: stored.map(toCohortSessionDto) };
|
||||
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' })) };
|
||||
},
|
||||
});
|
||||
|
|
@ -413,8 +420,8 @@ export function cohortRoutes(server) {
|
|||
const { ensureCohortGroup } = await import('../services/whatsapp.js');
|
||||
const updated = await ensureCohortGroup(cohort._id);
|
||||
await updated?.populate?.('virtualPrt', 'firstName lastName email');
|
||||
await updated?.populate?.({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
|
||||
return toCohortDto(updated || cohort);
|
||||
await updated?.populate?.({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate sessionsPaid patientStatus' });
|
||||
return attachCohortPatientProgress(toCohortDto(updated || cohort));
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -437,8 +444,8 @@ export function cohortRoutes(server) {
|
|||
console.error(`[whatsapp] closing notice failed: ${err?.message || err}`);
|
||||
});
|
||||
await cohort.populate('virtualPrt', 'firstName lastName email');
|
||||
await cohort.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile whatsappOptOut' });
|
||||
return toCohortDto(cohort);
|
||||
await cohort.populate({ path: 'patients', match: { reviewStatus: 'confirmed' }, select: 'name mobile age gender whatsappOptOut offlineSessions offlineStartDate sessionsPaid patientStatus' });
|
||||
return attachCohortPatientProgress(toCohortDto(cohort));
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { Patient } from '../models/Patient.js';
|
|||
import { Session } from '../models/Session.js';
|
||||
import { Cohort } from '../models/Cohort.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 { applyOnboardedPii, hashMobile, hashName, isMobileNumber, readOnboardedPii } from '../services/cryptoPii.js';
|
||||
import { deleteScreenshot, presignGet, s3Enabled } from '../services/s3.js';
|
||||
|
|
@ -157,6 +157,8 @@ function parseOnboardingFields(payload, settings, { requirePlacement = true, req
|
|||
diseaseType,
|
||||
preferredWeekday,
|
||||
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()),
|
||||
};
|
||||
if (hasPayloadKey(payload, 'lungCondition')) fields.lungCondition = textField(payload, 'lungCondition');
|
||||
|
|
@ -398,6 +400,8 @@ export function onboardingRoutes(server) {
|
|||
slot: cohort?.slot || fields.slot || '',
|
||||
matchingStatus: cohort ? 'unassigned' : 'unassigned',
|
||||
paymentStatus: fields.paymentStatus,
|
||||
sessionsPaid: fields.sessionsPaid,
|
||||
patientStatus: fields.patientStatus,
|
||||
paymentScreenshot,
|
||||
sourcePatientId: fields.sourcePatientId || '',
|
||||
onboardedBy: creds.user._id,
|
||||
|
|
@ -491,10 +495,22 @@ export function onboardingRoutes(server) {
|
|||
}
|
||||
applyOnboardedPii(item, fields);
|
||||
item.paymentStatus = fields.paymentStatus;
|
||||
item.sessionsPaid = fields.sessionsPaid;
|
||||
const previousPatientStatus = normalizePatientStatus(item.patientStatus);
|
||||
item.patientStatus = fields.patientStatus;
|
||||
item.whatsappOptOut = fields.whatsappOptOut;
|
||||
if (confirmed) {
|
||||
await item.save();
|
||||
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('reviewedBy', 'firstName lastName');
|
||||
await item.populate('cohort', 'name startDate slot language');
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { AuditEvent } from '../models/AuditEvent.js';
|
||||
|
||||
export function clientIp(request) {
|
||||
return request.headers['x-forwarded-for']?.split(',')[0]?.trim()
|
||||
|| request.info?.remoteAddress
|
||||
return request?.headers?.['x-forwarded-for']?.split(',')[0]?.trim()
|
||||
|| request?.info?.remoteAddress
|
||||
|| '';
|
||||
}
|
||||
|
||||
|
|
@ -19,11 +19,11 @@ export function reminderAuditText(rules = []) {
|
|||
export async function writeAudit(request, { action, resourceType = '', resourceId = '', actor } = {}) {
|
||||
try {
|
||||
await AuditEvent.create({
|
||||
actor: actor || request.auth?.credentials?.user?._id || null,
|
||||
actor: actor || request?.auth?.credentials?.user?._id || null,
|
||||
action,
|
||||
resourceType,
|
||||
resourceId: resourceId ? String(resourceId) : '',
|
||||
ip: request ? clientIp(request) : '',
|
||||
ip: clientIp(request),
|
||||
at: new Date(),
|
||||
});
|
||||
} catch (err) {
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ 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';
|
||||
import { normalizePatientStatus, normalizeSessionsPaid } from '../utils/serialize.js';
|
||||
import Boom from '@hapi/boom';
|
||||
|
||||
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 = []) {
|
||||
const nextIds = (cohort.patients || []).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) {
|
||||
await OnboardedPatient.updateMany(
|
||||
{ _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) {
|
||||
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 current = (cohort.patients || []).map((item) => String(item._id || item));
|
||||
const joined = !current.includes(id);
|
||||
const existing = await OnboardedPatient.findById(patientId).select('cohort patientStatus');
|
||||
if (existing) assertCanPlacePatient(existing, cohort);
|
||||
if (joined) {
|
||||
cohort.patients.push(patientId);
|
||||
await cohort.save();
|
||||
|
|
@ -74,7 +94,7 @@ export async function addPatientToCohort(cohort, patientId, actorId = null) {
|
|||
{ $set: {
|
||||
assignedEducator: cohort.virtualPrt,
|
||||
cohort: cohort._id,
|
||||
matchingStatus: 'assigned',
|
||||
matchingStatus: placedMatchingStatus(cohort),
|
||||
...(joined ? { cohortJoinedOn: todayYmd(env.APP_TIMEZONE) } : {}),
|
||||
} },
|
||||
);
|
||||
|
|
@ -146,13 +166,26 @@ export async function applyPatientEdits(cohort, rows = []) {
|
|||
if (age !== current.age) fields.age = age;
|
||||
const gender = String(row.gender || '');
|
||||
if (gender !== current.gender) fields.gender = gender;
|
||||
ready.push({ patient, fields, offlineSessions: row.offlineSessions, offlineStartDate: row.offlineStartDate || '' });
|
||||
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);
|
||||
patient.offlineSessions = offlineSessions;
|
||||
patient.offlineStartDate = offlineStartDate;
|
||||
patient.sessionsPaid = sessionsPaid;
|
||||
patient.patientStatus = patientStatus;
|
||||
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),
|
||||
offlineSessions: Math.max(0, Number(row?.offlineSessions) || 0),
|
||||
offlineStartDate: String(row?.offlineStartDate || '').trim(),
|
||||
sessionsPaid: normalizeSessionsPaid(row?.sessionsPaid),
|
||||
patientStatus: normalizePatientStatus(row?.patientStatus),
|
||||
})).filter((row) => row.name || row.mobile);
|
||||
if (!list.length) return [];
|
||||
if (list.some((row) => !row.name || !isMobileNumber(row.mobile))) throw Boom.badRequest('Each patient needs a name and a 10 digit mobile.');
|
||||
|
|
@ -189,6 +224,8 @@ export async function createManualCohortPatients(cohort, rows, userId) {
|
|||
whatsappOptOut: row.whatsappOptOut,
|
||||
offlineSessions: row.offlineSessions,
|
||||
offlineStartDate: row.offlineStartDate,
|
||||
sessionsPaid: row.sessionsPaid,
|
||||
patientStatus: row.patientStatus,
|
||||
});
|
||||
created.push(doc._id);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { OnboardedPatient } from '../models/OnboardedPatient.js';
|
|||
import { ReassignmentEvent } from '../models/ReassignmentEvent.js';
|
||||
import { Role } from '../models/Role.js';
|
||||
import { User } from '../models/User.js';
|
||||
import { addPatientToCohort, releaseCohortPatients, removePatientFromCohort, syncCohortPatients } from './cohorts.js';
|
||||
import { addPatientToCohort, assertCanPlacePatient, releaseCohortPatients, removePatientFromCohort, syncCohortPatients } from './cohorts.js';
|
||||
import { writeAudit } from './audit.js';
|
||||
import { CohortSession } from '../models/CohortSession.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.');
|
||||
}
|
||||
const previous = patient.cohort;
|
||||
assertCanPlacePatient(patient, target);
|
||||
if (previous) await removePatientFromCohort(previous, patient._id);
|
||||
await addPatientToCohort(target, patient._id);
|
||||
patient.matchingStatus = 'proposed';
|
||||
|
|
@ -629,6 +630,7 @@ export async function migratePatient(patient, { cohortId, slot, preferredWeekday
|
|||
throw err;
|
||||
}
|
||||
const previous = patient.cohort;
|
||||
assertCanPlacePatient(patient, target);
|
||||
if (previous && String(previous) !== String(target._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.diseaseType = target.diseaseType || patient.diseaseType;
|
||||
patient.preferredWeekday = weekdayOf(toYmd(target.startDate));
|
||||
patient.matchingStatus = 'assigned';
|
||||
patient.matchingStatus = target.status === 'proposed' ? 'proposed' : 'assigned';
|
||||
await persistCohortSessions(target);
|
||||
const { ensureSessionRecords } = await import('./programSessions.js');
|
||||
await ensureSessionRecords(target);
|
||||
|
|
|
|||
|
|
@ -181,7 +181,7 @@ async function syncExistingMeetSeries(cohort, sessions) {
|
|||
const host = await sessionHost(linked, cohort);
|
||||
if (!host?.google?.refreshToken && !host?.google?.accessToken) return;
|
||||
const settings = await getAppSettings();
|
||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
||||
const weekdays = await meetingWeekdays(cohort);
|
||||
const first = active[0];
|
||||
const last = active[active.length - 1];
|
||||
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();
|
||||
}
|
||||
|
||||
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.
|
||||
async function nextWeekdayAppendDate(cohort, weekdays) {
|
||||
const settings = await getAppSettings();
|
||||
|
|
@ -316,9 +326,9 @@ async function nextWeekdayAppendDate(cohort, weekdays) {
|
|||
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) {
|
||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
||||
const weekdays = await meetingWeekdays(cohort);
|
||||
if (weekdays) return nextWeekdayAppendDate(cohort, weekdays);
|
||||
const settings = await getAppSettings();
|
||||
const interval = Math.max(1, Number(settings.repeatIntervalDays) || 2);
|
||||
|
|
@ -339,10 +349,10 @@ export async function nextAppendDate(cohort) {
|
|||
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) {
|
||||
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;
|
||||
const settings = await getAppSettings();
|
||||
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;
|
||||
const tail = sessions.filter((session) => session.status === 'scheduled' && session.date >= hit.date);
|
||||
if (!tail.length) continue;
|
||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
||||
const weekdays = await meetingWeekdays(cohort);
|
||||
const blocked = new Set(
|
||||
sessions.filter((session) => session.status === 'completed').map((session) => session.date),
|
||||
);
|
||||
|
|
@ -569,7 +579,7 @@ export async function ensureMeetForCohort(cohort) {
|
|||
}
|
||||
|
||||
const settings = await getAppSettings();
|
||||
const weekdays = await scheduleWeekdays(cohort.scheduleId);
|
||||
const weekdays = await meetingWeekdays(cohort);
|
||||
const firstDate = sessions[0]?.date || toYmd(cohort.startDate);
|
||||
const times = slotDateTimes(firstDate, cohort.slot, cohort.durationMinutes || settings.defaultDurationMinutes || 60);
|
||||
try {
|
||||
|
|
@ -888,6 +898,19 @@ export async function moveSessionEvent(session, nextDate) {
|
|||
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) {
|
||||
const ids = patientIds.map((id) => String(id));
|
||||
const sessions = await CohortSession.find({ 'records.patient': { $in: ids }, status: { $in: ['scheduled', 'completed'] } });
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import {
|
|||
toDmy,
|
||||
toWhatsappDigits,
|
||||
} from './whatsappFormat.js';
|
||||
import { isPatientMessagingActive } from '../utils/serialize.js';
|
||||
|
||||
const LIVE = new Set(['active', 'confirmed']);
|
||||
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);
|
||||
if (!ids.length) return [];
|
||||
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 } = {}) {
|
||||
|
|
@ -172,7 +173,7 @@ export async function sendSessionReminder(session, { rule, manual = false } = {}
|
|||
const patients = await cohortPatientsForReminder(cohort);
|
||||
let queued = 0;
|
||||
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 phone = toWhatsappDigits(pii.mobile);
|
||||
if (!phone) continue;
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import { readOnboardedPii } from './cryptoPii.js';
|
|||
import { groupDescription, groupSubject, inviteMessage, toWhatsappDigits } from './whatsappFormat.js';
|
||||
import { toYmd } from './schedule.js';
|
||||
import { getAppSettings, isWhatsappEnabled } from './settings.js';
|
||||
import { isPatientMessagingActive } from '../utils/serialize.js';
|
||||
import { createGroup, fetchInvite, sendCta, sendText, updateGroup, updateParticipants } from './wastra.js';
|
||||
|
||||
const LIVE = new Set(['active', 'confirmed']);
|
||||
|
|
@ -16,9 +17,12 @@ const STALE_LOCK_MS = 2 * 60 * 1000;
|
|||
const POLL_MS = 5000;
|
||||
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) {
|
||||
if (step?.flag === 'invite') return ['pending', 'running', 'done'];
|
||||
if (step?.kind === 'add_member' && ADD_FLAGS.has(step?.flag)) return ['pending', 'running', 'done'];
|
||||
return OPEN;
|
||||
}
|
||||
|
||||
|
|
@ -65,7 +69,7 @@ async function staffContacts(cohort) {
|
|||
async function confirmedPatients(cohort) {
|
||||
const ids = (cohort.patients || []).map((item) => item._id || item);
|
||||
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) {
|
||||
|
|
@ -147,15 +151,30 @@ function inviteStep(cohortId, person) {
|
|||
};
|
||||
}
|
||||
|
||||
function inviteSteps(cohortId, people) {
|
||||
return people.filter((person) => person.phone).map((person) => inviteStep(cohortId, person));
|
||||
// Adds the person to the cohort WhatsApp group without sending an invite message.
|
||||
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';
|
||||
|
||||
// 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) {
|
||||
// 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;
|
||||
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`,
|
||||
});
|
||||
}
|
||||
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) {
|
||||
if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut) continue;
|
||||
if (patient.reviewStatus !== 'confirmed' || patient.whatsappOptOut || !isPatientMessagingActive(patient)) continue;
|
||||
const step = patientStep(patient);
|
||||
if (!step.phone) continue;
|
||||
steps.push(inviteStep(cohort._id, step));
|
||||
steps.push(addMemberStep(cohort._id, { ...step, flag: 'patient' }));
|
||||
}
|
||||
// steps.push(...await prtAdminSteps(cohort));
|
||||
await enqueueMany(cohort._id, steps);
|
||||
|
|
@ -262,15 +285,16 @@ export async function enqueuePatientAdd(cohort, patientId) {
|
|||
await enqueueCohortGroup(cohort._id);
|
||||
}
|
||||
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;
|
||||
const step = patientStep(patient);
|
||||
if (patient.whatsappOptOut) {
|
||||
await enqueuePatientRemove(fresh._id, patientId);
|
||||
return;
|
||||
}
|
||||
if (!isPatientMessagingActive(patient)) 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) {
|
||||
|
|
@ -320,7 +344,12 @@ export async function enqueuePrtSwap(cohortOrId, previousPrtId) {
|
|||
}));
|
||||
}
|
||||
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)}.`;
|
||||
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;
|
||||
cohort.whatsappError = message || task.lastError || 'WhatsApp task 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();
|
||||
}
|
||||
|
||||
|
|
@ -385,11 +416,11 @@ 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 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();
|
||||
|
|
@ -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) {
|
||||
if (isRetiredMembershipTask(task)) {
|
||||
task.status = 'cancelled';
|
||||
|
|
@ -466,6 +526,10 @@ async function execute(task) {
|
|||
// await runPrtAdminStep(task);
|
||||
// return;
|
||||
// }
|
||||
if (task.kind === 'add_member' && ADD_FLAGS.has(task.flag)) {
|
||||
await runAddMemberStep(task);
|
||||
return;
|
||||
}
|
||||
if (task.flag === 'leave' && task.kind === 'remove_member') {
|
||||
await runLeaveStep(task);
|
||||
return;
|
||||
|
|
@ -675,7 +739,8 @@ function cancelMembershipTasks() {
|
|||
$or: [
|
||||
{ kind: 'ensure_contact' },
|
||||
{ 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' } },
|
||||
|
|
|
|||
|
|
@ -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', () => {
|
||||
// assert.equal(isRetiredMembershipTask({ kind: 'promote_member', flag: 'prt' }), false);
|
||||
// assert.equal(isRetiredMembershipTask({ kind: 'add_member', flag: 'prt' }), false);
|
||||
test('keeps direct add and leave steps and drops old membership tasks', () => {
|
||||
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: 'staff' }), false);
|
||||
assert.equal(isRetiredMembershipTask({ kind: 'add_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' }), true);
|
||||
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({ kind: 'add_member', flag: 'patient' }), ['pending', 'running', 'done']);
|
||||
assert.deepEqual(dedupeStatusesForStep({ flag: 'reminder' }), ['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) {
|
||||
if (!item) return null;
|
||||
const pii = readOnboardedPii(item);
|
||||
|
|
@ -191,6 +211,8 @@ export function toOnboardedPatientDto(item) {
|
|||
matchingStatus: item.matchingStatus || 'unassigned',
|
||||
rejectReason: item.rejectReason || '',
|
||||
paymentStatus: item.paymentStatus || 'Unpaid',
|
||||
sessionsPaid: normalizeSessionsPaid(item.sessionsPaid),
|
||||
patientStatus: normalizePatientStatus(item.patientStatus),
|
||||
hasScreenshot: Boolean(item.paymentScreenshot?.filename),
|
||||
onboardedBy: by
|
||||
? {
|
||||
|
|
@ -268,7 +290,18 @@ export function toCohortDto(cohort) {
|
|||
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), 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) }
|
||||
)),
|
||||
patientCount: patients.length,
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ const DataTable = ({
|
|||
</tr>)}
|
||||
</thead>}
|
||||
<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>)}
|
||||
</tr>) : <tr>
|
||||
<td colSpan={columns.length} className="text-center py-3 text-muted">
|
||||
|
|
|
|||
|
|
@ -98,7 +98,20 @@ export default function CohortsPage() {
|
|||
id: 'whatsapp',
|
||||
header: 'WhatsApp',
|
||||
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() || '—'}
|
||||
</Button>
|
||||
),
|
||||
|
|
@ -228,9 +241,15 @@ export default function CohortsPage() {
|
|||
<ul className="mb-0">
|
||||
{(waCohort?.patients || []).map((patient) => {
|
||||
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 (
|
||||
<li key={patient.id} className="mb-2">
|
||||
{patient.name} · {patient.whatsappOptOut ? 'opted out' : (member?.status || 'not synced')}
|
||||
<li key={patient.id} className={`mb-2${exhausted ? ' text-danger fw-semibold' : ''}`}>
|
||||
{patient.name}
|
||||
{exhausted ? ` · ${done}/${paid} sessions` : ''}
|
||||
{' · '}
|
||||
{patient.whatsappOptOut ? 'opted out' : (member?.status || 'not synced')}
|
||||
{member?.error ? ` · ${member.error}` : ''}
|
||||
{can('onboarding', 'edit') ? (
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ function prtLanguages(user) {
|
|||
}
|
||||
|
||||
// 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() {
|
||||
return { key: `${Date.now()}-${Math.random()}`, id: '', existing: false, ...emptyPatient };
|
||||
|
|
@ -124,6 +124,9 @@ export default function PrtCohortForm() {
|
|||
originalMobile: patient.mobile || '',
|
||||
offlineSessions: patient.offlineSessions ?? 0,
|
||||
offlineStartDate: patient.offlineStartDate || '',
|
||||
sessionsPaid: patient.sessionsPaid ?? 30,
|
||||
patientStatus: patient.patientStatus || 'active',
|
||||
sessionsCompleted: patient.sessionsCompleted ?? 0,
|
||||
})));
|
||||
}).catch((err) => {
|
||||
if (active) setError(err.message);
|
||||
|
|
@ -191,6 +194,8 @@ export default function PrtCohortForm() {
|
|||
whatsappOptOut: false,
|
||||
offlineSessions: Number(row.offlineSessions),
|
||||
offlineStartDate: row.offlineStartDate || '',
|
||||
sessionsPaid: row.sessionsPaid === '' || row.sessionsPaid == null ? 30 : Number(row.sessionsPaid),
|
||||
patientStatus: row.patientStatus || 'active',
|
||||
}));
|
||||
const statusProblem = cohortStatusError(statusValue);
|
||||
if (statusProblem) {
|
||||
|
|
@ -231,6 +236,8 @@ export default function PrtCohortForm() {
|
|||
gender: row.gender || '',
|
||||
offlineSessions: Number(row.offlineSessions) || 0,
|
||||
offlineStartDate: row.offlineStartDate || '',
|
||||
sessionsPaid: row.sessionsPaid === '' || row.sessionsPaid == null ? 30 : Number(row.sessionsPaid),
|
||||
patientStatus: row.patientStatus || 'active',
|
||||
})),
|
||||
scheduleId: '',
|
||||
createdAs: 'manual_cohorts',
|
||||
|
|
@ -366,12 +373,18 @@ export default function PrtCohortForm() {
|
|||
{/* <th style={{ width: 140 }}>Sessions completed</th> */}
|
||||
<th style={{ width: 140 }}>Offline completed</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 }} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.key}>
|
||||
{rows.map((row) => {
|
||||
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>
|
||||
<FormControl
|
||||
value={row.name}
|
||||
|
|
@ -426,6 +439,25 @@ export default function PrtCohortForm() {
|
|||
onChange={(e) => updateRow(row.key, { offlineStartDate: e.target.value })}
|
||||
/>
|
||||
</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>
|
||||
<Button
|
||||
type="button"
|
||||
|
|
@ -438,7 +470,8 @@ export default function PrtCohortForm() {
|
|||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@ const empty = {
|
|||
preferredWeekday: '',
|
||||
diseaseType: '',
|
||||
paymentStatus: 'Unpaid',
|
||||
sessionsPaid: 30,
|
||||
patientStatus: 'active',
|
||||
whatsappOptOut: false,
|
||||
};
|
||||
|
||||
|
|
@ -126,6 +128,8 @@ export default function OnboardingForm() {
|
|||
preferredWeekday: item.preferredWeekday ?? '',
|
||||
diseaseType: item.diseaseType || '',
|
||||
paymentStatus: item.paymentStatus || 'Unpaid',
|
||||
sessionsPaid: item.sessionsPaid ?? 30,
|
||||
patientStatus: item.patientStatus || 'active',
|
||||
whatsappOptOut: Boolean(item.whatsappOptOut),
|
||||
});
|
||||
}).catch((err) => setError(err.message));
|
||||
|
|
@ -222,6 +226,25 @@ export default function OnboardingForm() {
|
|||
<FormLabel>Payment status</FormLabel>
|
||||
<OptionsSelect value={form.paymentStatus} onChange={(value) => setField('paymentStatus', value)} options={settings?.paymentStatuses} required />
|
||||
</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 ? (
|
||||
<>
|
||||
{showSlot ? (
|
||||
|
|
|
|||
|
|
@ -24,6 +24,17 @@ function reviewBadge(status) {
|
|||
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) {
|
||||
const res = await fetch(`/api/onboarding/${id}/screenshot`, { credentials: 'include' });
|
||||
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.completed}` : '—', { id: 'progress', header: 'Attended / held' }),
|
||||
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', {
|
||||
id: 'reviewStatus',
|
||||
header: 'Status',
|
||||
header: 'Review',
|
||||
cell: ({ row }) => reviewBadge(row.original.reviewStatus),
|
||||
}),
|
||||
columnHelper.accessor((r) => (r.onboardedBy ? `${r.onboardedBy.firstName} ${r.onboardedBy.lastName}` : ''), {
|
||||
|
|
@ -231,6 +256,9 @@ export default function OnboardingPage() {
|
|||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
meta: {
|
||||
getRowClassName: (row) => (sessionsExhausted(row.original) ? 'table-danger' : ''),
|
||||
},
|
||||
});
|
||||
|
||||
const start = total === 0 ? 0 : page * pageSize + 1;
|
||||
|
|
|
|||
Loading…
Reference in New Issue