@peopl-health/nexus 6.5.0-dev.20074 → 6.5.0-dev.20126
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.
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +23 -8
- package/lib/clinical/tools/reportMedicalEscalationTool.js +2 -2
- package/lib/services/characterizationOutcomeService.js +22 -11
- package/lib/services/doctorDigestService.js +27 -9
- package/lib/services/escalationReviewService.js +5 -3
- package/package.json +1 -1
|
@@ -201,7 +201,7 @@ const briefDrugs = (draft) => (draft?.symptoms ?? []).flatMap((entry) => entry.p
|
|
|
201
201
|
|
|
202
202
|
const namedFlags = (list) => (Array.isArray(list) ? list.map(oneLineOf).filter(Boolean) : []);
|
|
203
203
|
|
|
204
|
-
function briefKeyLine(draft, entry) {
|
|
204
|
+
function briefKeyLine(draft, entry, lead = null) {
|
|
205
205
|
const grave = namedFlags(draft?.urgentPresentRedFlags);
|
|
206
206
|
const present = namedFlags(entry?.presentRedFlags).filter((flag) => !grave.includes(flag));
|
|
207
207
|
const unknown = (namedFlags(draft?.urgentUnassessedRedFlags).length ? namedFlags(draft.urgentUnassessedRedFlags) : namedFlags(entry?.unassessedRedFlags))
|
|
@@ -209,6 +209,7 @@ function briefKeyLine(draft, entry) {
|
|
|
209
209
|
const absent = namedFlags(entry?.absentRedFlags);
|
|
210
210
|
const drugs = briefDrugs(draft);
|
|
211
211
|
const parts = [
|
|
212
|
+
lead,
|
|
212
213
|
grave.length && `⚠️ ${capitalized(grave.join(', '))}`,
|
|
213
214
|
present.length && `Presente: ${present.join(', ')}`,
|
|
214
215
|
unknown.length && `Sin dato aún: ${unknown.join(', ')}`,
|
|
@@ -218,24 +219,36 @@ function briefKeyLine(draft, entry) {
|
|
|
218
219
|
return cutOnWord(parts.join(' · '), MAX_BRIEF_KEY);
|
|
219
220
|
}
|
|
220
221
|
|
|
222
|
+
function briefCaseLine(identity, entry, alarmSymptom) {
|
|
223
|
+
const label = cutOnWord(entry?.symptom || alarmSymptom || 'Síntoma no especificado', MAX_BRIEF_SYMPTOM);
|
|
224
|
+
const graded = [1, 2, 3, 4, 5].includes(entry?.grade) && !/\bG[1-5]\b/i.test(label) ? `${label} G${entry.grade}` : label;
|
|
225
|
+
const patient = identity.age ? `${titleCased(oneLineOf(identity.patientName))}, ${identity.age}` : titleCased(oneLineOf(identity.patientName));
|
|
226
|
+
const doctor = titleCased(oneLineOf(identity.treatingDoctor));
|
|
227
|
+
return doctor ? `${patient} · ${graded} (${withTitle(doctor)})` : `${patient} · ${graded}`;
|
|
228
|
+
}
|
|
229
|
+
|
|
221
230
|
// The four lines of the doctor's alert; each is a template variable, so none may be empty.
|
|
222
|
-
function doctorBrief({ kind, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
|
|
231
|
+
function doctorBrief({ kind, change = null, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
|
|
223
232
|
const entry = briefSymptomOf(draft, alarmSymptom);
|
|
224
233
|
// A grave flag present asks for an assessment whoever sends the case, not only the bot's act_now.
|
|
225
234
|
const actNow = kind === 'act_now' || namedFlags(draft?.urgentPresentRedFlags).length > 0;
|
|
226
235
|
const verb = actNow ? BRIEF_VERBS.act_now : (briefDrugs(draft).length ? BRIEF_VERBS.proposal : BRIEF_VERBS.indication);
|
|
227
236
|
const mark = actNow ? '🔴' : BRIEF_MARKS[level];
|
|
228
|
-
const label = cutOnWord(entry?.symptom || alarmSymptom || 'Síntoma no especificado', MAX_BRIEF_SYMPTOM);
|
|
229
|
-
const graded = [1, 2, 3, 4, 5].includes(entry?.grade) && !/\bG[1-5]\b/i.test(label) ? `${label} G${entry.grade}` : label;
|
|
230
|
-
const patient = identity.age ? `${titleCased(oneLineOf(identity.patientName))}, ${identity.age}` : titleCased(oneLineOf(identity.patientName));
|
|
231
237
|
return [
|
|
232
|
-
[[mark, verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
|
|
233
|
-
|
|
234
|
-
briefKeyLine(draft, entry),
|
|
238
|
+
[[mark, change ? `Cambió: ${verb}` : verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
|
|
239
|
+
briefCaseLine(identity, entry, alarmSymptom),
|
|
240
|
+
briefKeyLine(draft, entry, change === 'level' ? `Subió a ${URGENCY_LABELS[level]}` : null),
|
|
235
241
|
link,
|
|
236
242
|
];
|
|
237
243
|
}
|
|
238
244
|
|
|
245
|
+
const doctorDigestTitle = (count) => `${LEVEL_MARKS.urgent} ${BRIEF_VERBS.indication}: ${count} ${count === 1 ? 'caso urgente' : 'casos urgentes'}`;
|
|
246
|
+
|
|
247
|
+
function doctorDigestLine({ identity, draft, alarmSymptom, deadline, now, timeZone, link }) {
|
|
248
|
+
const head = [briefCaseLine(identity, briefSymptomOf(draft, alarmSymptom), alarmSymptom), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · ');
|
|
249
|
+
return `${head}: ${link}`;
|
|
250
|
+
}
|
|
251
|
+
|
|
239
252
|
module.exports = {
|
|
240
253
|
REQUESTED_ACTION,
|
|
241
254
|
ASSESSMENT_ACTION,
|
|
@@ -248,4 +261,6 @@ module.exports = {
|
|
|
248
261
|
doctorAlertHeadline,
|
|
249
262
|
doctorAlertOpener,
|
|
250
263
|
doctorBrief,
|
|
264
|
+
doctorDigestLine,
|
|
265
|
+
doctorDigestTitle,
|
|
251
266
|
};
|
|
@@ -161,11 +161,11 @@ const FEVER_SIGNS_TIMER = 'Outside a must-go `stat`, no warning signs';
|
|
|
161
161
|
const FEVER_URGENCIAS = '(two exceptions: the fever rule, and chest pain';
|
|
162
162
|
const FEVER_URGENCIAS_TIMER = '(one exception: chest pain';
|
|
163
163
|
|
|
164
|
-
const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, malaise while on an antipyretic or steroid
|
|
164
|
+
const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, or malaise while on an antipyretic or steroid — is `asap` with `category: febrile_neutropenia`. A low reading means below 36.0 °C only; 36.0 °C is normal. A low reading is not fever and is never called fever, neither to the patient nor in `details`: before escalating, ask for a re-measure and how they feel right now. Still below 36.0 °C with current malaise, chills or shivering, or a confirmed ≤35.0 °C, is `asap`; still below 36.0 °C with no other symptom is `urgent`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
|
|
165
165
|
|
|
166
166
|
const FEVER_RUBRIC_STAT_TIMER = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
|
|
167
167
|
|
|
168
|
-
const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C, o
|
|
168
|
+
const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C, o temperatura baja (menos de 36.0 °C) confirmada al volver a medir con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
|
|
169
169
|
|
|
170
170
|
const CLINICAL_ASSESSMENT_PROPERTY = nullable({
|
|
171
171
|
'type': 'object',
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const { cutOnWord, normalizedKeyOf } = require('../utils/coercionUtils');
|
|
2
2
|
const { logger } = require('../utils/logger');
|
|
3
3
|
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
4
|
-
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
4
|
+
const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
5
5
|
const { INTERNAL_ORIGINS } = require('../models/messageModel');
|
|
6
6
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
7
7
|
const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
|
|
@@ -9,9 +9,9 @@ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableSer
|
|
|
9
9
|
const { countMessages, getMessages } = require('./messageService');
|
|
10
10
|
const { logPatientChange } = require('./patientService');
|
|
11
11
|
const { getThreadInfo } = require('./threadService');
|
|
12
|
-
const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
|
|
12
|
+
const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
|
|
13
13
|
const { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented } = require('./gravePendingService');
|
|
14
|
-
const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
14
|
+
const { BUSINESS_HOURS_LEVELS, levelsOf, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
15
15
|
const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
|
|
16
16
|
const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
|
|
17
17
|
|
|
@@ -39,7 +39,6 @@ const blockingAskText = (question) => `La revisión de esta escalación necesita
|
|
|
39
39
|
const graveAskText = (flags) => `La revisión de esta escalación necesita saber si la paciente tiene: ${flags.join('; ')}. Pregúntale, en un solo mensaje breve y con palabras sencillas, por lo que ella pueda notar o medir, sin nombrar diagnósticos. ${ASK_RULES}`;
|
|
40
40
|
|
|
41
41
|
const noteOf = (text) => cutOnWord(text, MAX_NOTE_LENGTH);
|
|
42
|
-
const flagKey = (flag) => String(flag ?? '').trim().toLowerCase();
|
|
43
42
|
const timeOf = (value) => new Date(value).getTime();
|
|
44
43
|
const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
|
|
45
44
|
// When the team's alert for this grave datum first fell due, which a failed send's retry does not move; one not recorded yet has not.
|
|
@@ -61,6 +60,13 @@ function teamGraveOf(review, clock, grave, now) {
|
|
|
61
60
|
return { due: [], waiting: asked };
|
|
62
61
|
}
|
|
63
62
|
|
|
63
|
+
function handedRankOf(review, handoff) {
|
|
64
|
+
const by = (date) => timeOf(date) <= timeOf(handoff.createdAt);
|
|
65
|
+
const alarms = currentAlarms(review).filter((alarm) => !alarm.isHeldInFollowUp && by(alarm.raisedAt));
|
|
66
|
+
const levels = levelsOf(alarms, (review.urgencyReclassifications ?? []).filter((change) => by(change.at)), appliedLevelOf);
|
|
67
|
+
return Math.max(0, ...levels.map(({ level }) => URGENCY_RANK[level]));
|
|
68
|
+
}
|
|
69
|
+
|
|
64
70
|
// Whether the bot's latest draft goes to the doctor now, and with which note; null while the patient still has time to answer.
|
|
65
71
|
function outcomeOf(review, clock, now) {
|
|
66
72
|
const wait = pendingWaitMinutes(clock?.level);
|
|
@@ -80,13 +86,18 @@ function outcomeOf(review, clock, now) {
|
|
|
80
86
|
const graveFlags = graveMissingOf(review, clock, now);
|
|
81
87
|
const { due: grave, waiting } = teamGraveOf(review, clock, graveFlags, now);
|
|
82
88
|
const present = latest.urgentPresentRedFlags ?? [];
|
|
83
|
-
//
|
|
84
|
-
|
|
89
|
+
// The model rewords a flag on every redraft, so the flags' text cannot tell a new one; the panel always shows the latest draft.
|
|
90
|
+
// Only a handoff that rang told the doctor's phone about its grave flag.
|
|
91
|
+
const handedGrave = handoffs.some((handoff) => handoff.transport && (review.drafts[handoff.draftNumber - 1]?.urgentPresentRedFlags ?? []).length > 0);
|
|
92
|
+
const handedRank = update ? handedRankOf(review, last) : 0;
|
|
93
|
+
const rose = handedRank > 0 && URGENCY_RANK[clock.level] > handedRank;
|
|
85
94
|
// Airtable's alert reaches the team, not the doctor's phone.
|
|
86
95
|
const raisedSince = (level) => (review.alarms ?? []).some((alarm) => alarm.urgencyLevel === level && timeOf(alarm.raisedAt) > timeOf(last.createdAt));
|
|
87
96
|
const rangSince = update && (review.doctorAlerts ?? []).some((sent) => sent.kind === 'initial' && !sent.error
|
|
88
97
|
&& sent.transport && sent.transport !== 'airtable' && timeOf(sent.sentAt) > timeOf(last.createdAt) && raisedSince(sent.urgencyLevel));
|
|
89
|
-
const
|
|
98
|
+
const firstGrave = present.length > 0 && !handedGrave;
|
|
99
|
+
const notify = !update || (!rangSince && (firstGrave || rose));
|
|
100
|
+
const change = update && notify ? (firstGrave ? 'grave' : 'level') : null;
|
|
90
101
|
// A missing grave datum is the team's to get: a first handoff waits the level's wait after the team's alert falls due, unless a grave flag is present.
|
|
91
102
|
const teamFirst = !update && !present.length && grave.length + waiting.length > 0;
|
|
92
103
|
const held = teamFirst && (waiting.length > 0 || grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000));
|
|
@@ -95,11 +106,11 @@ function outcomeOf(review, clock, now) {
|
|
|
95
106
|
// A grave datum still inside its wait goes in the note too, so the doctor knows it is still open.
|
|
96
107
|
const pending = pendingFlagsOf(review, clock.since).flags.map(({ flag }) => flag).filter((flag) => !graveFlags.some((entry) => entry.flag === flag));
|
|
97
108
|
const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, lacking, pending.length && `Pendiente: ${pending.join(', ')}`];
|
|
98
|
-
return { grave, update, notify, held, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
|
|
109
|
+
return { grave, update, notify, ...(change && { change }), held, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
|
|
99
110
|
}
|
|
100
111
|
// A grave question still inside its wait holds the case even when the rest is enough.
|
|
101
112
|
if (pendingFlagsOf(review, clock.since).flags.length) return null;
|
|
102
|
-
if (latest.sufficientForDoctor === true) return { grave: [], update, notify, note: withUpdate(null) };
|
|
113
|
+
if (latest.sufficientForDoctor === true) return { grave: [], update, notify, ...(change && { change }), note: withUpdate(null) };
|
|
103
114
|
if (latest.sufficientForDoctor !== false) return null;
|
|
104
115
|
// The wait runs from the bot's question to the patient, so «no contestó» is said only of a question she was asked.
|
|
105
116
|
const ask = (review.blockingAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
|
|
@@ -109,7 +120,7 @@ function outcomeOf(review, clock, now) {
|
|
|
109
120
|
if (minutesSince(sent ? ask.sentAt : latest.createdAt, now) < wait) return null;
|
|
110
121
|
const missing = latest.blockingQuestion ? `Falta: ${latest.blockingQuestion}` : 'Falta información';
|
|
111
122
|
// An update's draft is never asked about, so it says only what is missing.
|
|
112
|
-
if (update) return { grave: [], update, notify, note: withUpdate(noteOf(missing)) };
|
|
123
|
+
if (update) return { grave: [], update, notify, ...(change && { change }), note: withUpdate(noteOf(missing)) };
|
|
113
124
|
const asked = (sent && ASKED_OUTCOMES.includes(ask.outcome)) || ask?.skippedReason === 'question_open';
|
|
114
125
|
return { grave: [], update, notify, note: noteOf(`${missing} (${asked ? 'no contestó' : 'no se le preguntó'})`) };
|
|
115
126
|
}
|
|
@@ -163,7 +174,7 @@ async function handOff(review, clock, outcome, now) {
|
|
|
163
174
|
try {
|
|
164
175
|
if (digest) await getEscalationReview().updateOne({ _id: review._id }, { $set: { digestQueuedAt: now, digestClaimedAt: null, digestSentAt: null } }, BOOKKEEPING);
|
|
165
176
|
const kind = review.drafts.at(-1)?.urgentPresentRedFlags?.length ? 'act_now' : 'ready';
|
|
166
|
-
await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, handoffs: (review.doctorHandoffs ?? []).length, note: outcome.note, notify: outcome.notify && !digest, kind, level: clock.level, symptom: clock.symptom });
|
|
177
|
+
await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, handoffs: (review.doctorHandoffs ?? []).length, note: outcome.note, notify: outcome.notify && !digest, kind, change: outcome.change, level: clock.level, symptom: clock.symptom });
|
|
167
178
|
} catch (error) {
|
|
168
179
|
// Someone handed the case off since the sweep read it: nothing failed, and the next sweep reads the new handoff.
|
|
169
180
|
const next = `doctorHandoffs.${(review.doctorHandoffs ?? []).length}`;
|
|
@@ -5,13 +5,16 @@ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUti
|
|
|
5
5
|
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
6
6
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
7
7
|
const { whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
|
|
8
|
+
const { doctorDigestLine, doctorDigestTitle } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
8
9
|
|
|
9
10
|
const { logPatientChange } = require('./patientService');
|
|
10
11
|
const { listEscalationApprovers } = require('./physicianService');
|
|
11
|
-
const { responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
12
|
+
const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
12
13
|
const { BOOKKEEPING, doctorLink, teamAlertIdentity } = require('./escalationReviewService');
|
|
13
14
|
|
|
14
15
|
const DIGEST_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_CONTENT_SID';
|
|
16
|
+
// Until Meta approves this template the earlier digest keeps going out.
|
|
17
|
+
const DIGEST_BRIEF_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_BRIEF_CONTENT_SID';
|
|
15
18
|
const DEFAULT_WINDOW_MINUTES = 60;
|
|
16
19
|
const DEFAULT_LEAD_MINUTES = 120;
|
|
17
20
|
const MAX_CASES_PER_MESSAGE = 5;
|
|
@@ -29,7 +32,7 @@ const minutesOf = (key, fallback) => {
|
|
|
29
32
|
const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
|
|
30
33
|
|
|
31
34
|
// Urgent cases ready for the doctor go in a digest only once its template exists.
|
|
32
|
-
const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_TEMPLATE_KEY));
|
|
35
|
+
const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DIGEST_TEMPLATE_KEY));
|
|
33
36
|
|
|
34
37
|
// The approving doctor's WhatsApp, or null when there is none to send the digest to.
|
|
35
38
|
async function digestRecipient() {
|
|
@@ -56,10 +59,23 @@ function digestDueAt(reviews, policy) {
|
|
|
56
59
|
return teamOpenAt(new Date(Math.min(...times)), policy);
|
|
57
60
|
}
|
|
58
61
|
|
|
59
|
-
async function digestLines(reviews) {
|
|
62
|
+
async function digestLines(reviews, now, policy) {
|
|
63
|
+
const brief = Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY));
|
|
60
64
|
const lines = [];
|
|
61
65
|
for (const review of reviews) {
|
|
62
|
-
const { patient } = await teamAlertIdentity(review);
|
|
66
|
+
const { patient, identity } = await teamAlertIdentity(review);
|
|
67
|
+
if (brief) {
|
|
68
|
+
lines.push(doctorDigestLine({
|
|
69
|
+
identity: { ...identity, patientName: identity.patientName || patient },
|
|
70
|
+
draft: review.drafts?.at(-1),
|
|
71
|
+
alarmSymptom: effectiveUrgencyOf(review)?.symptom,
|
|
72
|
+
deadline: responseDeadlineOf(review, policy)?.dueAt,
|
|
73
|
+
now,
|
|
74
|
+
timeZone: policy.teamHours.timeZone,
|
|
75
|
+
link: doctorLink(review),
|
|
76
|
+
}));
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
63
79
|
const label = [patient, review.alarms?.at(-1)?.symptom].map((text) => oneLineOf(text).slice(0, MAX_FIELD_LENGTH).trim()).filter(Boolean).join(' · ');
|
|
64
80
|
lines.push(`${label}: ${doctorLink(review)}`);
|
|
65
81
|
}
|
|
@@ -80,10 +96,12 @@ function chunksOf(entries) {
|
|
|
80
96
|
|
|
81
97
|
async function sendDigest(code, entries) {
|
|
82
98
|
const lines = entries.map(({ line }) => line);
|
|
83
|
-
const
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
99
|
+
const briefSid = runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY);
|
|
100
|
+
const title = briefSid ? doctorDigestTitle(entries.length) : String(entries.length);
|
|
101
|
+
const inWindow = await isWithin24HourWindow(code);
|
|
102
|
+
const outgoing = inWindow
|
|
103
|
+
? { code, body: (briefSid ? [title, ...lines] : [`🟡 Casos urgentes listos para decidir: ${title}`, '', ...lines]).join('\n'), triggeredBy: OPERATOR }
|
|
104
|
+
: { code, contentSid: briefSid || runtimeConfig.get(DIGEST_TEMPLATE_KEY), variables: { 1: title, 2: lines.join(' | ') }, triggeredBy: OPERATOR };
|
|
87
105
|
const result = await getMessaging().sendMessage(outgoing);
|
|
88
106
|
if (!result?.success && !result?.completed) throw new Error('The doctor digest could not be sent');
|
|
89
107
|
if (result?.deferred) throw new Error('The doctor digest was queued for template approval, not sent');
|
|
@@ -117,7 +135,7 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
|
|
|
117
135
|
logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the digest waits');
|
|
118
136
|
return 0;
|
|
119
137
|
}
|
|
120
|
-
const lines = await digestLines(queued);
|
|
138
|
+
const lines = await digestLines(queued, now, policy);
|
|
121
139
|
let sent = 0;
|
|
122
140
|
// Each message claims its own cases just before it goes, so a crash in between leaves the rest for the next sweep.
|
|
123
141
|
for (const chunk of chunksOf(queued.map((review, index) => ({ review, line: lines[index] })))) {
|
|
@@ -1377,6 +1377,7 @@ async function teamAlertIdentity(review) {
|
|
|
1377
1377
|
return {
|
|
1378
1378
|
patient: oneLineOf(identity.patientName) || 'sin nombre registrado',
|
|
1379
1379
|
doctor: oneLineOf(identity.treatingDoctor) || 'sin médico registrado',
|
|
1380
|
+
identity,
|
|
1380
1381
|
link: conversationLink(review.patientCode) || 'abrir el chat en la plataforma',
|
|
1381
1382
|
};
|
|
1382
1383
|
}
|
|
@@ -1793,7 +1794,7 @@ async function soleApprover() {
|
|
|
1793
1794
|
return approvers[0];
|
|
1794
1795
|
}
|
|
1795
1796
|
|
|
1796
|
-
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom }) {
|
|
1797
|
+
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change }) {
|
|
1797
1798
|
const briefSid = runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
|
|
1798
1799
|
// A navigator's draft is free text with no symptoms or flags to summarize, so it keeps the full alert.
|
|
1799
1800
|
if (briefSid && draft.symptoms?.length) {
|
|
@@ -1801,6 +1802,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
|
|
|
1801
1802
|
const lead = effectiveUrgencyOf(review);
|
|
1802
1803
|
const lines = doctorBrief({
|
|
1803
1804
|
kind,
|
|
1805
|
+
change,
|
|
1804
1806
|
level: level ?? lead?.urgency,
|
|
1805
1807
|
identity,
|
|
1806
1808
|
draft,
|
|
@@ -1823,7 +1825,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
|
|
|
1823
1825
|
}
|
|
1824
1826
|
|
|
1825
1827
|
// With notify false the case is handed over in the platform without a WhatsApp to the doctor; `kind` (act_now, ready) picks the alert the doctor gets.
|
|
1826
|
-
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
|
|
1828
|
+
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, change = null, level = null, symptom = null, requestId = null } = {}) {
|
|
1827
1829
|
const reviewId = reviewIdOf(id);
|
|
1828
1830
|
const operator = requiredText(sentBy, 'sentBy');
|
|
1829
1831
|
if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
|
|
@@ -1849,7 +1851,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
1849
1851
|
const identity = await readDoctorIdentity(review);
|
|
1850
1852
|
if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
1851
1853
|
const link = doctorLink(review);
|
|
1852
|
-
const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom });
|
|
1854
|
+
const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change });
|
|
1853
1855
|
|
|
1854
1856
|
const patientCaseRecordIds = await reviewCaseIds(review);
|
|
1855
1857
|
|