@peopl-health/nexus 6.0.24 → 6.0.26
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 +21 -4
- package/lib/clinical/services/escalationDraftService.js +1 -0
- package/lib/models/escalationReviewModel.js +3 -1
- package/lib/services/characterizationOutcomeService.js +31 -14
- package/lib/services/escalationReviewService.js +15 -6
- package/lib/services/gravePendingService.js +7 -5
- package/lib/services/untakenAlertService.js +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
2
|
-
const { inlineOf } = require('../../utils/coercionUtils');
|
|
2
|
+
const { inlineOf, oneLineOf } = require('../../utils/coercionUtils');
|
|
3
3
|
const { mexicoStamp } = require('../../utils/dateUtils');
|
|
4
4
|
|
|
5
5
|
const URGENCY_LABELS = {
|
|
@@ -134,12 +134,27 @@ function renderDoctorMessage({ identity, review, doctorText, link }) {
|
|
|
134
134
|
return [withIdentity({ identity, review, doctorText }), '', link].join('\n');
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
-
|
|
137
|
+
const MAX_SYMPTOM_LENGTH = 60;
|
|
138
|
+
|
|
139
|
+
// The symptom and level a template variable carries: the case's own (its clock's) when the caller knows them, else the latest alarm's.
|
|
140
|
+
function templateSummary(review, { level = null, symptom = null } = {}) {
|
|
138
141
|
const alarm = latestAlarm(review);
|
|
139
|
-
if (!alarm) return 'sin alarma registrada';
|
|
140
|
-
|
|
142
|
+
if (!alarm && !level) return 'sin alarma registrada';
|
|
143
|
+
const urgency = level ?? alarm.urgencyLevel;
|
|
144
|
+
return [oneLineOf(symptom ?? alarm?.symptom).slice(0, MAX_SYMPTOM_LENGTH).trim(), URGENCY_LABELS[urgency] ?? inlineOf(urgency)].filter(Boolean).join(' · ');
|
|
141
145
|
}
|
|
142
146
|
|
|
147
|
+
const LEVEL_MARKS = { asap: '🟠', urgent: '🟡' };
|
|
148
|
+
const ALERT_OPENERS = { act_now: '🔴 Entra ya', ready: 'Caso listo para decidir' };
|
|
149
|
+
|
|
150
|
+
// What the doctor's phone shows first: an «act now» alert or a case ready to decide, with its level, symptom and note.
|
|
151
|
+
function doctorAlertHeadline({ review, kind, note = null, level = null, symptom = null }) {
|
|
152
|
+
const mark = kind === 'ready' ? LEVEL_MARKS[level ?? latestAlarm(review)?.urgencyLevel] : null;
|
|
153
|
+
return oneLineOf([[mark, templateSummary(review, { level, symptom })].filter(Boolean).join(' '), note].filter(Boolean).join(' · '));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const doctorAlertOpener = (kind, headline) => `${ALERT_OPENERS[kind]}: ${headline}`;
|
|
157
|
+
|
|
143
158
|
module.exports = {
|
|
144
159
|
REQUESTED_ACTION,
|
|
145
160
|
ASSESSMENT_ACTION,
|
|
@@ -149,4 +164,6 @@ module.exports = {
|
|
|
149
164
|
renderDoctorMessage,
|
|
150
165
|
withIdentity,
|
|
151
166
|
templateSummary,
|
|
167
|
+
doctorAlertHeadline,
|
|
168
|
+
doctorAlertOpener,
|
|
152
169
|
};
|
|
@@ -228,6 +228,7 @@ async function generateEscalationDraft({
|
|
|
228
228
|
missingCharacterization: textList(parsed?.missingCharacterization),
|
|
229
229
|
sufficientForDoctor,
|
|
230
230
|
blockingQuestion: sufficientForDoctor === false ? trimmed(parsed?.blockingQuestion) || null : null,
|
|
231
|
+
blockingFlag: sufficientForDoctor === false ? trimmed(parsed?.blockingFlag) || null : null,
|
|
231
232
|
suggestCall: suggestCallOf(parsed?.suggestCall),
|
|
232
233
|
sectionsUnavailable: context.degradedSections ?? [],
|
|
233
234
|
};
|
|
@@ -73,7 +73,7 @@ const graveAlertSchema = new mongoose.Schema({
|
|
|
73
73
|
level: { type: String, enum: URGENCY_LEVELS, required: true },
|
|
74
74
|
since: { type: Date, required: true },
|
|
75
75
|
firstSeenAt: { type: Date, required: true },
|
|
76
|
-
reason: { type: String, enum: ['unobtainable', 'unanswered'], required: true },
|
|
76
|
+
reason: { type: String, enum: ['unobtainable', 'unanswered', 'not_said'], required: true },
|
|
77
77
|
takenReason: { type: String, default: null },
|
|
78
78
|
audience: { type: String, enum: ['all', 'group_doctor'], default: null },
|
|
79
79
|
dueAt: { type: Date, required: true },
|
|
@@ -93,6 +93,7 @@ const quietReminderSchema = new mongoose.Schema({
|
|
|
93
93
|
const blockingAskSchema = new mongoose.Schema({
|
|
94
94
|
draftAt: { type: Date, required: true },
|
|
95
95
|
question: { type: String, default: null },
|
|
96
|
+
flags: { type: [String], default: undefined },
|
|
96
97
|
sentAt: { type: Date, required: true },
|
|
97
98
|
skippedReason: { type: String, default: null },
|
|
98
99
|
outcome: { type: String, default: null },
|
|
@@ -144,6 +145,7 @@ const draftSchema = new mongoose.Schema({
|
|
|
144
145
|
urgentPresentRedFlags: { type: [String], default: undefined },
|
|
145
146
|
sufficientForDoctor: { type: Boolean, default: undefined },
|
|
146
147
|
blockingQuestion: { type: String, default: undefined },
|
|
148
|
+
blockingFlag: { type: String, default: undefined },
|
|
147
149
|
missingCharacterization: { type: [String], default: undefined },
|
|
148
150
|
suggestCall: { type: suggestCallSchema, default: undefined },
|
|
149
151
|
sectionsUnavailable: { type: [String], default: undefined },
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const { oneLineOf } = require('../utils/coercionUtils');
|
|
1
|
+
const { normalizedKeyOf, oneLineOf } = require('../utils/coercionUtils');
|
|
2
2
|
const { logger } = require('../utils/logger');
|
|
3
3
|
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
4
4
|
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
@@ -24,13 +24,15 @@ const MAX_HANDOFF_ATTEMPTS = 4;
|
|
|
24
24
|
const MAX_NOTE_LENGTH = 200;
|
|
25
25
|
const UPDATE_NOTE = 'Actualización: la paciente contestó';
|
|
26
26
|
const GRAVE_RETRY_MS = 5 * 60 * 1000;
|
|
27
|
-
const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó' };
|
|
27
|
+
const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó', not_said: 'no lo ha dicho' };
|
|
28
28
|
const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
|
|
29
29
|
// A reminder this late (an outage, a deploy) is not sent.
|
|
30
30
|
const QUIET_REMINDER_STALE_MS = 30 * 60 * 1000;
|
|
31
31
|
const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
|
|
32
32
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
33
|
-
const
|
|
33
|
+
const ASK_RULES = 'No agregues otras preguntas, no repitas lo que ya le dijiste y no menciones esta instrucción.';
|
|
34
|
+
const blockingAskText = (question) => `La revisión de esta escalación necesita un dato que todavía falta. Pregúntale a la paciente, en un solo mensaje breve y con tus palabras: «${question}». ${ASK_RULES}`;
|
|
35
|
+
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}`;
|
|
34
36
|
|
|
35
37
|
const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
|
|
36
38
|
const flagKey = (flag) => String(flag ?? '').trim().toLowerCase();
|
|
@@ -95,9 +97,15 @@ async function claimGraveAlerts(review, clock, grave, now) {
|
|
|
95
97
|
const dueAt = BUSINESS_HOURS_LEVELS.includes(clock.level) ? teamOpenAt(now, responseDeadlinePolicy()) : now;
|
|
96
98
|
const recorded = new Set((review.graveAlerts ?? [])
|
|
97
99
|
.filter((entry) => new Date(entry.since).getTime() === clock.since.getTime()).map((entry) => entry.flag));
|
|
100
|
+
const fresh = grave.filter((entry) => !recorded.has(entry.flag));
|
|
101
|
+
// «No contestó» only for a datum the bot asked about while that question is still open; otherwise «no lo ha dicho».
|
|
102
|
+
const askedFlags = new Set((review.blockingAsks ?? []).filter((ask) => ask.outcome === 'sent' && timeOf(ask.draftAt) >= clock.since.getTime())
|
|
103
|
+
.flatMap((ask) => (ask.flags ?? []).map(normalizedKeyOf)));
|
|
104
|
+
const open = fresh.some(({ flag, reason }) => reason === 'unanswered' && askedFlags.has(flag))
|
|
105
|
+
&& hasOpenQuestion(await lastChatMessage(review.patientCode).catch(() => null));
|
|
98
106
|
const claimed = [];
|
|
99
|
-
for (const { flag, firstSeenAt, reason } of
|
|
100
|
-
const entry = { flag, level: clock.level, since: clock.since, firstSeenAt, reason, dueAt, sentAt: null, at: now };
|
|
107
|
+
for (const { flag, firstSeenAt, reason } of fresh) {
|
|
108
|
+
const entry = { flag, level: clock.level, since: clock.since, firstSeenAt, reason: reason === 'unanswered' && !(open && askedFlags.has(flag)) ? 'not_said' : reason, dueAt, sentAt: null, at: now };
|
|
101
109
|
const result = await getEscalationReview().updateOne(
|
|
102
110
|
{ _id: review._id, closedAt: null, graveAlerts: { $not: { $elemMatch: { flag, since: clock.since } } } },
|
|
103
111
|
{ $push: { graveAlerts: entry } },
|
|
@@ -122,7 +130,8 @@ async function handOff(review, clock, outcome, now) {
|
|
|
122
130
|
&& Boolean(await digestRecipient().catch(() => null));
|
|
123
131
|
try {
|
|
124
132
|
if (digest) await getEscalationReview().updateOne({ _id: review._id }, { $set: { digestQueuedAt: now, digestClaimedAt: null, digestSentAt: null } }, BOOKKEEPING);
|
|
125
|
-
|
|
133
|
+
const kind = review.drafts.at(-1)?.urgentPresentRedFlags?.length ? 'act_now' : 'ready';
|
|
134
|
+
await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note, notify: outcome.notify && !digest, kind, level: clock.level, symptom: clock.symptom });
|
|
126
135
|
} catch (error) {
|
|
127
136
|
if (digest) await getEscalationReview().updateOne({ _id: review._id, status: { $ne: 'awaiting_doctor' } }, { $set: { digestQueuedAt: null } }, BOOKKEEPING).catch(() => {});
|
|
128
137
|
const attempt = attemptsOf(review, clock) + 1;
|
|
@@ -220,7 +229,7 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
|
|
|
220
229
|
const { latest, flags } = pendingFlagsOf(review, clock.since);
|
|
221
230
|
const stillPending = new Set(flags.map(({ flag }) => flag));
|
|
222
231
|
const redrafted = latest && isDraftCurrent(review, latest);
|
|
223
|
-
const answered = (entry) => entry.reason
|
|
232
|
+
const answered = (entry) => entry.reason !== 'unobtainable' && redrafted && timeOf(latest.createdAt) > timeOf(entry.at) && !stillPending.has(entry.flag);
|
|
224
233
|
for (const entry of due.filter(answered)) await setOn(review, entry, { sentAt: now, skippedReason: 'answered' }, { sentAt: null });
|
|
225
234
|
const pending = due.filter((entry) => !answered(entry));
|
|
226
235
|
if (!pending.length) return 0;
|
|
@@ -267,6 +276,8 @@ async function lastChatMessage(code) {
|
|
|
267
276
|
return last;
|
|
268
277
|
}
|
|
269
278
|
|
|
279
|
+
const hasOpenQuestion = (last) => Boolean(last?.from_me && String(last.body ?? '').includes('?'));
|
|
280
|
+
|
|
270
281
|
// In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
|
|
271
282
|
async function remindQuietPatient(review, clock, now) {
|
|
272
283
|
if (clock.level !== 'urgent' || !PRE_DECISION_STATUSES.includes(review.status) || review.closedAt) return;
|
|
@@ -283,7 +294,7 @@ async function remindQuietPatient(review, clock, now) {
|
|
|
283
294
|
const last = await lastChatMessage(review.patientCode);
|
|
284
295
|
let skippedReason = null;
|
|
285
296
|
if (now.getTime() - dueAt.getTime() > QUIET_REMINDER_STALE_MS) skippedReason = 'stale';
|
|
286
|
-
else if (!
|
|
297
|
+
else if (!hasOpenQuestion(last)) skippedReason = 'no_open_question';
|
|
287
298
|
else skippedReason = await takenOf(review, clock);
|
|
288
299
|
if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
|
|
289
300
|
const entry = { draftAt: latest.createdAt, sentAt: now, skippedReason, delivered: null };
|
|
@@ -314,22 +325,27 @@ async function remindQuietPatient(review, clock, now) {
|
|
|
314
325
|
await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
|
|
315
326
|
}
|
|
316
327
|
|
|
317
|
-
//
|
|
328
|
+
// Once per draft the bot asks its blocking question or the pending grave data, unless a question is open; after a patient message, once the bot replied.
|
|
318
329
|
async function askBlockingQuestion(review, clock, now) {
|
|
319
330
|
if (!OUTCOME_LEVELS.includes(clock.level) || review.status !== 'draft_ready' || review.closedAt) return;
|
|
320
331
|
const latest = (review.drafts ?? []).at(-1);
|
|
321
|
-
if (latest?.writtenBy !== DRAFT_OPERATOR ||
|
|
332
|
+
if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
|
|
333
|
+
const graveFlags = latest.blockingQuestion || latest.urgentPresentRedFlags?.length ? []
|
|
334
|
+
: pendingFlagsOf(review, clock.since).flags.filter(({ unobtainable }) => !unobtainable).map(({ flag }) => flag);
|
|
335
|
+
const question = latest.blockingQuestion || graveFlags.join('; ') || null;
|
|
336
|
+
const flags = latest.blockingQuestion ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
|
|
337
|
+
if (!question) return;
|
|
322
338
|
const asks = review.blockingAsks ?? [];
|
|
323
339
|
if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
|
|
324
340
|
const last = await lastChatMessage(review.patientCode);
|
|
341
|
+
if (!last?.from_me) return;
|
|
325
342
|
|
|
326
343
|
let skippedReason = await takenOf(review, clock);
|
|
327
|
-
if (!skippedReason &&
|
|
328
|
-
if (!skippedReason && String(last.body ?? '').includes('?')) skippedReason = 'question_open';
|
|
344
|
+
if (!skippedReason && hasOpenQuestion(last)) skippedReason = 'question_open';
|
|
329
345
|
if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
|
|
330
346
|
const claimed = await getEscalationReview().updateOne(
|
|
331
347
|
{ _id: review._id, closedAt: null, blockingAsks: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
|
|
332
|
-
{ $push: { blockingAsks: { draftAt: latest.createdAt, question
|
|
348
|
+
{ $push: { blockingAsks: { draftAt: latest.createdAt, question, flags, sentAt: now, skippedReason, outcome: null } } },
|
|
333
349
|
BOOKKEEPING,
|
|
334
350
|
);
|
|
335
351
|
if (!claimed.modifiedCount || skippedReason) return;
|
|
@@ -340,7 +356,8 @@ async function askBlockingQuestion(review, clock, now) {
|
|
|
340
356
|
if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
|
|
341
357
|
return takenOf(fresh, clock);
|
|
342
358
|
};
|
|
343
|
-
|
|
359
|
+
const instruction = latest.blockingQuestion ? blockingAskText(latest.blockingQuestion) : graveAskText(graveFlags);
|
|
360
|
+
getMessaging().processInstruction(review.patientCode, instruction, 'developer', { triggeredBy: OPERATOR, beforeRun })
|
|
344
361
|
.then((result) => result?.outcome ?? null, (error) => {
|
|
345
362
|
logger.error('[CharacterizationOutcome] The blocking question was not asked', {
|
|
346
363
|
escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
|
|
@@ -28,7 +28,7 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
|
28
28
|
const { DrainingError } = require('../core/BatchingManager');
|
|
29
29
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
30
30
|
const { conversationLink, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
31
|
-
const { renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
31
|
+
const { doctorAlertHeadline, doctorAlertOpener, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
32
32
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
33
33
|
const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
|
|
34
34
|
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
@@ -130,6 +130,9 @@ const reviewIdOf = (id) => {
|
|
|
130
130
|
return id;
|
|
131
131
|
};
|
|
132
132
|
|
|
133
|
+
// The template per kind of doctor alert; one not configured yet falls back to the identified alert.
|
|
134
|
+
const DOCTOR_ALERT_TEMPLATE_KEYS = { act_now: 'ESCALATION_REVIEW_DOCTOR_ACT_NOW_CONTENT_SID', ready: 'ESCALATION_REVIEW_DOCTOR_READY_CONTENT_SID' };
|
|
135
|
+
|
|
133
136
|
const configured = (key) => {
|
|
134
137
|
const value = runtimeConfig.get(key);
|
|
135
138
|
if (!value) throw httpError(503, `${key} is not configured`);
|
|
@@ -389,7 +392,7 @@ async function sendDoctorAlert({ message, approver, operator }) {
|
|
|
389
392
|
const inWindow = await isWithin24HourWindow(doctorCode);
|
|
390
393
|
const outgoing = inWindow
|
|
391
394
|
? { code: doctorCode, body: message.body, triggeredBy: operator }
|
|
392
|
-
: { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID'), variables: message.template, triggeredBy: operator };
|
|
395
|
+
: { code: doctorCode, contentSid: message.contentSid || configured('ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID'), variables: message.template, triggeredBy: operator };
|
|
393
396
|
const result = await getMessaging().sendMessage(outgoing);
|
|
394
397
|
if (!result?.success && !result?.completed) {
|
|
395
398
|
throw httpError(502, 'The WhatsApp message to the physician could not be sent');
|
|
@@ -1456,6 +1459,7 @@ async function generateBotDraft({ id, lease = null } = {}) {
|
|
|
1456
1459
|
urgentPresentRedFlags: draft.urgentPresentRedFlags,
|
|
1457
1460
|
sufficientForDoctor: draft.sufficientForDoctor,
|
|
1458
1461
|
blockingQuestion: draft.blockingQuestion,
|
|
1462
|
+
blockingFlag: draft.blockingFlag,
|
|
1459
1463
|
missingCharacterization: draft.missingCharacterization,
|
|
1460
1464
|
...(draft.suggestCall && { suggestCall: draft.suggestCall }),
|
|
1461
1465
|
...(draft.sectionsUnavailable?.length && { sectionsUnavailable: draft.sectionsUnavailable }),
|
|
@@ -1676,8 +1680,8 @@ async function soleApprover() {
|
|
|
1676
1680
|
return approvers[0];
|
|
1677
1681
|
}
|
|
1678
1682
|
|
|
1679
|
-
// With notify false the case is handed over in the platform without a WhatsApp to the doctor.
|
|
1680
|
-
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, notify = true, requestId = null } = {}) {
|
|
1683
|
+
// 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.
|
|
1684
|
+
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
|
|
1681
1685
|
const reviewId = reviewIdOf(id);
|
|
1682
1686
|
const operator = requiredText(sentBy, 'sentBy');
|
|
1683
1687
|
if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
|
|
@@ -1703,9 +1707,14 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note =
|
|
|
1703
1707
|
const identity = await readDoctorIdentity(review);
|
|
1704
1708
|
if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
1705
1709
|
const link = doctorLink(review);
|
|
1710
|
+
const headline = kind && doctorAlertHeadline({ review, kind, note, level, symptom });
|
|
1711
|
+
const kindSid = kind ? runtimeConfig.get(DOCTOR_ALERT_TEMPLATE_KEYS[kind]) : null;
|
|
1706
1712
|
const message = {
|
|
1707
|
-
body: [note, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
|
|
1708
|
-
template:
|
|
1713
|
+
body: [headline ? doctorAlertOpener(kind, headline) : note, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
|
|
1714
|
+
template: kindSid
|
|
1715
|
+
? { 1: headline, 2: oneLineOf(identity.patientName), 3: oneLineOf(identity.treatingDoctor), 4: link }
|
|
1716
|
+
: { 1: oneLineOf(identity.patientName), 2: oneLineOf(identity.treatingDoctor), 3: oneLineOf([templateSummary(review, { level, symptom }), note].filter(Boolean).join(' · ')), 4: link },
|
|
1717
|
+
...(kindSid && { contentSid: kindSid }),
|
|
1709
1718
|
};
|
|
1710
1719
|
|
|
1711
1720
|
const patientCaseRecordIds = await reviewCaseIds(review);
|
|
@@ -24,7 +24,7 @@ function pendingFlagsOf(review, since) {
|
|
|
24
24
|
const isDraftCurrent = (review, latest) => !review.draftDueAt
|
|
25
25
|
&& !(review.updates ?? []).some((update) => new Date(update.at).getTime() > new Date(latest.createdAt).getTime());
|
|
26
26
|
|
|
27
|
-
// A grave datum is missing at once when
|
|
27
|
+
// A grave datum is missing at once when it cannot be given, or past the level's wait; the others still pending go with it in one alert.
|
|
28
28
|
function graveMissingOf(review, clock, now) {
|
|
29
29
|
const limit = pendingWaitMinutes(clock?.level);
|
|
30
30
|
if (!limit) return [];
|
|
@@ -32,10 +32,12 @@ function graveMissingOf(review, clock, now) {
|
|
|
32
32
|
if (!latest || !isDraftCurrent(review, latest)) return [];
|
|
33
33
|
// Once the case left documenting (with the doctor) no new draft comes, so the wait no longer means unanswered.
|
|
34
34
|
const waiting = DOCUMENTING_STATUSES.includes(review.status);
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
35
|
+
const isDue = ({ firstSeenAt, unobtainable }) => unobtainable || (waiting && now.getTime() - firstSeenAt.getTime() >= limit * 60 * 1000);
|
|
36
|
+
if (!flags.some(isDue)) return [];
|
|
37
|
+
// Only the first alert gathers the data still waiting; one that appears after it waits its own time.
|
|
38
|
+
const recorded = new Set((review.graveAlerts ?? []).filter((entry) => new Date(entry.since).getTime() === clock.since.getTime()).map((entry) => entry.flag));
|
|
39
|
+
return flags.filter((entry) => isDue(entry) || recorded.has(entry.flag) || (waiting && !recorded.size))
|
|
40
|
+
.map(({ flag, firstSeenAt, unobtainable }) => ({ flag, firstSeenAt, reason: unobtainable ? 'unobtainable' : 'unanswered' }));
|
|
39
41
|
}
|
|
40
42
|
|
|
41
43
|
module.exports = { graveMissingOf, isDraftCurrent, pendingFlagsOf };
|
|
@@ -174,7 +174,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
174
174
|
alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
|
|
175
175
|
}, { 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, quietReminders: 1, blockingAsks: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
176
176
|
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
177
|
-
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
|
|
177
|
+
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
178
178
|
})
|
|
179
179
|
.sort({ _id: -1 })
|
|
180
180
|
.limit(SWEEP_LIMIT)
|