@peopl-health/nexus 6.8.0-dev.21713 → 6.8.0-dev.21714
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -188,6 +188,8 @@ function deadlineLabel(deadline, now, timeZone) {
|
|
|
188
188
|
return `antes del ${new Date(deadline).toLocaleDateString('es-MX', { timeZone, day: '2-digit', month: '2-digit' })} ${time}`;
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
+
const patientPromptNotice = (promptAt, timeZone) => `⏰ Si nadie lo toma, a las ${new Date(promptAt).toLocaleTimeString('es-MX', { timeZone, ...HOUR_FORMAT })} la paciente recibe los números para llamar`;
|
|
192
|
+
|
|
191
193
|
function briefSymptomOf(draft, symptom) {
|
|
192
194
|
const symptoms = Array.isArray(draft?.symptoms) ? draft.symptoms : [];
|
|
193
195
|
const wanted = oneLineOf(symptom).toLowerCase();
|
|
@@ -229,14 +231,14 @@ function briefCaseLine(identity, entry, alarmSymptom) {
|
|
|
229
231
|
}
|
|
230
232
|
|
|
231
233
|
// The four lines of the doctor's alert; each is a template variable, so none may be empty.
|
|
232
|
-
function doctorBrief({ kind, change = null, reminder = null, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
|
|
234
|
+
function doctorBrief({ kind, change = null, reminder = null, timer = null, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
|
|
233
235
|
const entry = briefSymptomOf(draft, alarmSymptom);
|
|
234
236
|
// A grave flag present asks for an assessment whoever sends the case, not only the bot's act_now.
|
|
235
237
|
const actNow = kind === 'act_now' || namedFlags(draft?.urgentPresentRedFlags).length > 0;
|
|
236
238
|
const verb = actNow ? BRIEF_VERBS.act_now : (briefDrugs(draft).length ? BRIEF_VERBS.proposal : BRIEF_VERBS.indication);
|
|
237
239
|
const mark = actNow ? '🔴' : BRIEF_MARKS[level];
|
|
238
240
|
return [
|
|
239
|
-
[reminder, [mark, change ? `Cambió: ${verb}` : verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
|
|
241
|
+
[reminder, [mark, change ? `Cambió: ${verb}` : verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone), timer].filter(Boolean).join(' · '),
|
|
240
242
|
briefCaseLine(identity, entry, alarmSymptom),
|
|
241
243
|
briefKeyLine(draft, entry, change === 'level' ? `Subió a ${URGENCY_LABELS[level]}` : null),
|
|
242
244
|
link,
|
|
@@ -263,6 +265,7 @@ module.exports = {
|
|
|
263
265
|
doctorAlertHeadline,
|
|
264
266
|
doctorAlertOpener,
|
|
265
267
|
doctorBrief,
|
|
268
|
+
patientPromptNotice,
|
|
266
269
|
doctorDigestLine,
|
|
267
270
|
doctorDigestTitle,
|
|
268
271
|
};
|
|
@@ -230,6 +230,7 @@ const doctorHandoffSchema = new mongoose.Schema({
|
|
|
230
230
|
messageId: { type: String, default: null },
|
|
231
231
|
message: { type: String, default: null },
|
|
232
232
|
alarmCount: { type: Number, default: null },
|
|
233
|
+
promptAt: { type: Date, default: null },
|
|
233
234
|
sentBy: { type: String, required: true },
|
|
234
235
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
235
236
|
|
|
@@ -31,7 +31,7 @@ const { ensureWhatsAppFormat, whatsAppCodeFromPhone } = require('../helpers/twil
|
|
|
31
31
|
const { DrainingError } = require('../core/BatchingManager');
|
|
32
32
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
33
33
|
const { conversationLink, readGroupMessageId, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
34
|
-
const { doctorAlertHeadline, doctorAlertOpener, doctorBrief, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
34
|
+
const { doctorAlertHeadline, doctorAlertOpener, doctorBrief, patientPromptNotice, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
35
35
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
36
36
|
const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
|
|
37
37
|
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
@@ -1294,6 +1294,13 @@ const currentAlarms = (review) => {
|
|
|
1294
1294
|
return decidedAt ? alarms.filter((alarm) => new Date(alarm.raisedAt) > new Date(decidedAt)) : alarms;
|
|
1295
1295
|
};
|
|
1296
1296
|
|
|
1297
|
+
const patientTimerLiveFor = (review) => (currentAlarms(review).some(isLiveFeverOf(review)) ? feverTimerLive() : escalationTimerLive());
|
|
1298
|
+
|
|
1299
|
+
// While a send holds the slot (attempts above 0, or a lease) its due time is not the prompt's, so only an untouched slot gives the time.
|
|
1300
|
+
const armedPromptAt = (review) => (review.doctorAlertKind === 'patient_prompt' && !review.doctorAlertAttempts ? review.doctorAlertDueAt ?? null : null);
|
|
1301
|
+
|
|
1302
|
+
const patientPromptAt = (review) => (patientTimerLiveFor(review) ? armedPromptAt(review) : null);
|
|
1303
|
+
|
|
1297
1304
|
const topUrgencyOf = (review) => {
|
|
1298
1305
|
const open = currentAlarms(review);
|
|
1299
1306
|
return (open.length ? open : review.alarms ?? [])
|
|
@@ -1984,7 +1991,7 @@ async function notifiedApprover() {
|
|
|
1984
1991
|
throw httpError(409, `More than one physician approves escalation reviews; name one of: ${approvers.map((approver) => approver.email).join(', ')}, or tick aprobador_principal on exactly one`);
|
|
1985
1992
|
}
|
|
1986
1993
|
|
|
1987
|
-
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, now = new Date() }) {
|
|
1994
|
+
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, timer = null, now = new Date() }) {
|
|
1988
1995
|
const briefSid = runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
|
|
1989
1996
|
// A navigator's draft is free text with no symptoms or flags to summarize, so it keeps the full alert.
|
|
1990
1997
|
if (briefSid && draft.symptoms?.length) {
|
|
@@ -1994,6 +2001,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
|
|
|
1994
2001
|
kind,
|
|
1995
2002
|
change,
|
|
1996
2003
|
reminder,
|
|
2004
|
+
timer,
|
|
1997
2005
|
level: level ?? lead?.urgency,
|
|
1998
2006
|
identity,
|
|
1999
2007
|
draft,
|
|
@@ -2005,7 +2013,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
|
|
|
2005
2013
|
});
|
|
2006
2014
|
return { body: lines.join('\n'), template: Object.fromEntries(lines.map((line, index) => [index + 1, line])), contentSid: briefSid };
|
|
2007
2015
|
}
|
|
2008
|
-
const opener = [reminder, note].filter(Boolean).join(' · ') || null;
|
|
2016
|
+
const opener = [reminder, note, timer].filter(Boolean).join(' · ') || null;
|
|
2009
2017
|
const headline = kind && doctorAlertHeadline({ review, kind, note: opener, level, symptom });
|
|
2010
2018
|
const kindSid = kind ? runtimeConfig.get(DOCTOR_ALERT_TEMPLATE_KEYS[kind]) : null;
|
|
2011
2019
|
return {
|
|
@@ -2056,7 +2064,10 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
2056
2064
|
const identity = await readDoctorIdentity(review);
|
|
2057
2065
|
if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
2058
2066
|
const link = doctorLink(review);
|
|
2059
|
-
const
|
|
2067
|
+
const armedAt = mode === 'sent_whatsapp' ? patientPromptAt(review) : null;
|
|
2068
|
+
const promptAt = armedAt && new Date(armedAt) > new Date() ? new Date(armedAt) : null;
|
|
2069
|
+
const timer = promptAt && patientPromptNotice(promptAt, responseDeadlinePolicy().teamHours.timeZone);
|
|
2070
|
+
const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, timer });
|
|
2060
2071
|
|
|
2061
2072
|
const patientCaseRecordIds = await reviewCaseIds(review);
|
|
2062
2073
|
|
|
@@ -2075,7 +2086,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
2075
2086
|
if (approver) delivery = { physicianEmail: approver.email, ...(rings ? await sendDoctorAlert({ message, approver, operator }) : {}) };
|
|
2076
2087
|
const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : (rings ? message.body : null);
|
|
2077
2088
|
const handoff = {
|
|
2078
|
-
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, sentBy: operator } },
|
|
2089
|
+
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, ...(sent && promptAt && { promptAt }), sentBy: operator } },
|
|
2079
2090
|
$addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
|
|
2080
2091
|
$unset: { identityBlock: '' },
|
|
2081
2092
|
};
|
|
@@ -2755,6 +2766,8 @@ module.exports = {
|
|
|
2755
2766
|
caseTakenReason,
|
|
2756
2767
|
promptedSince,
|
|
2757
2768
|
currentAlarms,
|
|
2769
|
+
armedPromptAt,
|
|
2770
|
+
patientPromptAt,
|
|
2758
2771
|
DOCTOR_BRIEF_TEMPLATE_KEY,
|
|
2759
2772
|
doctorAlertMessage,
|
|
2760
2773
|
doctorLink,
|
|
@@ -10,7 +10,6 @@ const TEAM_TIMEZONE = 'America/Mexico_City';
|
|
|
10
10
|
const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5, 6, 7], startHour: 9, endHour: 22 };
|
|
11
11
|
const UNTAKEN_STAGES = { stat: ['early', 'deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
|
|
12
12
|
const PATIENT_PROMPT_LEAD_MINUTES = 5;
|
|
13
|
-
const URGENT_REMINDER_LEAD_MINUTES = 60;
|
|
14
13
|
const DEFAULT_PATIENT_TIMER_MINUTES = { stat: 15, asap: 20, fever: 15 };
|
|
15
14
|
const PATIENT_TIMER_KEYS = { stat: 'ESCALATION_PATIENT_TIMER_MINUTES', asap: 'ESCALATION_ASAP_PATIENT_TIMER_MINUTES', fever: 'FEVER_PATIENT_TIMER_MINUTES' };
|
|
16
15
|
const DEFAULT_UNTAKEN_EARLY_MINUTES = 15;
|
|
@@ -101,8 +100,6 @@ function untakenStagesOf(level, since, policy, { fever = false } = {}) {
|
|
|
101
100
|
|
|
102
101
|
function doctorReminderAt(level, since, policy, promptAt = null) {
|
|
103
102
|
if (promptAt) return new Date(timeOf(promptAt) - PATIENT_PROMPT_LEAD_MINUTES * 60 * 1000);
|
|
104
|
-
// addWorkingMinutes can land on the closing minute itself, which the team counts as closed.
|
|
105
|
-
if (level === 'urgent') return teamOpenAt(dueAtFor(since, level, policy, policy.responseMinutes.urgent - URGENT_REMINDER_LEAD_MINUTES), policy);
|
|
106
103
|
return untakenStagesOf(level, since, policy).find((stage) => stage.stage === 'early')?.dueAt ?? null;
|
|
107
104
|
}
|
|
108
105
|
|
|
@@ -5,11 +5,11 @@ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
|
5
5
|
const { withTimeout } = require('../utils/timeoutUtils');
|
|
6
6
|
const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
7
7
|
const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
|
|
8
|
-
const { escalationAutoHandoffLive,
|
|
8
|
+
const { escalationAutoHandoffLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
|
|
9
9
|
|
|
10
10
|
const { logPatientChange } = require('./patientService');
|
|
11
11
|
const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
|
|
12
|
-
const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, PRE_DECISION_STATUSES, appliedLevelOf, isLiveFeverOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
|
|
12
|
+
const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, PRE_DECISION_STATUSES, appliedLevelOf, armedPromptAt, isLiveFeverOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, patientPromptAt, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
|
|
13
13
|
const { settleCharacterization } = require('./characterizationOutcomeService');
|
|
14
14
|
const { sendTeamAlert } = require('./teamAlertService');
|
|
15
15
|
const { digestAtSetTimes, digestDueAt, digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
|
|
@@ -37,7 +37,7 @@ const REMINDER_RETRY_MS = 3 * 60 * 1000;
|
|
|
37
37
|
const REMINDER_SEND_TIMEOUT_MS = 60 * 1000;
|
|
38
38
|
const MAX_REMINDER_ATTEMPTS = 3;
|
|
39
39
|
// Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
|
|
40
|
-
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, 'doctorHandoffs.mode': 1, 'doctorHandoffs.physicianEmail': 1, feverPromptStartedAt: 1, digestQueuedAt: 1, quietReminders: 1, blockingAsks: 1, inTurnAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1, digestSentAt: 1,
|
|
40
|
+
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, 'doctorHandoffs.mode': 1, 'doctorHandoffs.physicianEmail': 1, 'doctorHandoffs.promptAt': 1, feverPromptStartedAt: 1, digestQueuedAt: 1, quietReminders: 1, blockingAsks: 1, inTurnAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1, digestSentAt: 1,
|
|
41
41
|
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
42
42
|
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
43
43
|
};
|
|
@@ -110,16 +110,6 @@ function pendingQuestionOf(review, clock) {
|
|
|
110
110
|
return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
-
function patientTimerLiveFor(review) {
|
|
114
|
-
const fever = currentAlarms(review).some(isLiveFeverOf(review));
|
|
115
|
-
return fever ? feverPatientTimerLive() : escalationPatientTimerLive();
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// While a send holds the slot (attempts above 0, or a lease) its due time is not the prompt's, so only an untouched slot gives the time.
|
|
119
|
-
const armedPromptAt = (review) => (review.doctorAlertKind === 'patient_prompt' && !review.doctorAlertAttempts ? review.doctorAlertDueAt ?? null : null);
|
|
120
|
-
|
|
121
|
-
const patientPromptAt = (review) => (patientTimerLiveFor(review) ? armedPromptAt(review) : null);
|
|
122
|
-
|
|
123
113
|
function patientPromptNote(review, stage, now) {
|
|
124
114
|
const promptAt = stage.stage === 'early' ? patientPromptAt(review) : null;
|
|
125
115
|
if (!promptAt) return null;
|
|
@@ -236,8 +226,9 @@ const remindersSince = (review, since) => (review.doctorAlerts ?? [])
|
|
|
236
226
|
async function remindDoctorIfDue(review, clock, now, policy) {
|
|
237
227
|
if (review.status !== 'awaiting_doctor') return false;
|
|
238
228
|
const promptAt = armedPromptAt(review);
|
|
239
|
-
if (!promptAt && clock.level === 'urgent' && escalationUnopenedReminderLive() && ringAtOf(review)) return false;
|
|
240
229
|
if (review.doctorAlertKind === 'patient_prompt' && review.doctorAlertAttempts > 0) return false;
|
|
230
|
+
const announcedAt = review.doctorHandoffs?.at(-1)?.promptAt;
|
|
231
|
+
if (promptAt && announcedAt && new Date(announcedAt).getTime() === new Date(promptAt).getTime()) return false;
|
|
241
232
|
const dueAt = doctorReminderAt(clock.level, clock.stagesFrom, policy, promptAt);
|
|
242
233
|
const deadline = clock.stages.find((stage) => stage.stage === 'deadline').dueAt;
|
|
243
234
|
if (!dueAt || now < dueAt || now.getTime() - dueAt.getTime() > STALE_MS || now >= deadline) return false;
|