@peopl-health/nexus 6.1.0-dev.18134 → 6.1.0-dev.18138
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 -9
- package/lib/fhir/resources/Patient.js +1 -1
- package/lib/services/characterizationOutcomeService.js +29 -13
- package/lib/services/escalationReviewService.js +32 -8
- package/lib/services/gravePendingService.js +8 -4
- package/package.json +1 -1
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
2
2
|
const { inlineOf, oneLineOf } = require('../../utils/coercionUtils');
|
|
3
|
-
const { mexicoStamp } = require('../../utils/dateUtils');
|
|
4
3
|
|
|
5
4
|
const URGENCY_LABELS = {
|
|
6
5
|
stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
|
|
@@ -82,16 +81,25 @@ function proposalLine({ proposal, conduct, sections }) {
|
|
|
82
81
|
].filter(Boolean).join(' ');
|
|
83
82
|
}
|
|
84
83
|
|
|
84
|
+
const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
85
|
+
// The part as a whole phrase of the text, so «no» is not found inside «ibuprofeno».
|
|
86
|
+
const includesText = (text, part) => Boolean(text && part) && new RegExp(`(^|[^\\p{L}\\d/])${escaped(part)}($|[^\\p{L}\\d/])`, 'iu').test(text);
|
|
87
|
+
|
|
85
88
|
function symptomParagraph(entry, fallbackSymptom) {
|
|
86
89
|
const sections = entry.sections ?? {};
|
|
87
|
-
const
|
|
88
|
-
const
|
|
90
|
+
const label = inlineOf(sections.symptom) || fallbackSymptom || 'Síntoma no especificado';
|
|
91
|
+
const graded = [1, 2, 3, 4, 5].includes(sections.grade);
|
|
92
|
+
const grade = graded ? `G${sections.grade}` : 'grado no establecido';
|
|
93
|
+
const { present, absent, unassessed, urgent } = flagsByStatus(sections);
|
|
89
94
|
const summary = inlineOf(sections.characterizationSummary);
|
|
90
95
|
return [
|
|
91
|
-
|
|
96
|
+
// An ungraded symptom whose label already names a grade is not called ungraded.
|
|
97
|
+
!graded && /\bG[1-5]\b/.test(label) ? `${label}:` : `${label} (${grade}):`,
|
|
92
98
|
summary && sentence(summary),
|
|
93
99
|
present.length && `${present.length > 1 ? 'Banderas rojas presentes' : 'Bandera roja presente'}: ${sentence(present.join(', '))}`,
|
|
94
100
|
!present.length && !unassessed.length && absent.length && 'Sin banderas rojas.',
|
|
101
|
+
// A proposal names its own pending grave flags; without one they would go unsaid.
|
|
102
|
+
!proposedDrugs(entry).length && urgent.length && `Falta descartar: ${sentence(urgent.join(', '))}`,
|
|
95
103
|
proposalLine(entry),
|
|
96
104
|
].filter(Boolean).join(' ');
|
|
97
105
|
}
|
|
@@ -102,12 +110,15 @@ function composeDoctorBody({ alarm, shared, symptoms }) {
|
|
|
102
110
|
const lastDose = inlineOf(context?.lastDose);
|
|
103
111
|
const priorManagement = inlineOf(context?.priorManagement);
|
|
104
112
|
const response = inlineOf(context?.response);
|
|
105
|
-
const urgency = [URGENCY_LABELS[alarm?.urgencyLevel] ?? inlineOf(alarm?.urgencyLevel), alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null].filter(Boolean);
|
|
106
113
|
const priorities = inlineOf(shared?.doctorPriorities);
|
|
114
|
+
// The last dose is said once, so not again when the treatment text already gives it.
|
|
115
|
+
const dose = includesText(treatment, lastDose) ? null : `última dosis: ${lastDose || 'no disponible'}`;
|
|
116
|
+
// A response that already reads as one («sin respuesta», «respuesta parcial») is not prefixed again; «no aplica» says nothing.
|
|
117
|
+
const answer = response && !/^no aplica\b/i.test(response) && !includesText(priorManagement, response)
|
|
118
|
+
&& (/^(respuesta\b|(sin|no)\s)/i.test(response) ? response : `respuesta ${response}`);
|
|
107
119
|
return [
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
priorManagement || response ? `Manejo previo: ${sentence([priorManagement, response && `respuesta ${response}`].filter(Boolean).join('; '))}` : null,
|
|
120
|
+
treatment || lastDose ? `Tratamiento: ${[treatment || 'no disponible', dose].filter(Boolean).join('; ')}.` : 'Tratamiento y última dosis: no disponibles.',
|
|
121
|
+
priorManagement || answer ? `Manejo previo: ${sentence([priorManagement, answer].filter(Boolean).join('; '))}` : null,
|
|
111
122
|
vitalsLine(shared?.vitals),
|
|
112
123
|
inlineOf(shared?.objectiveData) ? `Datos objetivos: ${sentence(inlineOf(shared.objectiveData))}` : null,
|
|
113
124
|
'',
|
|
@@ -120,7 +131,8 @@ function composeDoctorBody({ alarm, shared, symptoms }) {
|
|
|
120
131
|
|
|
121
132
|
function identityLines({ identity, review }) {
|
|
122
133
|
const phone = String(review?.patientCode ?? '').replace(/^whatsapp:/, '');
|
|
123
|
-
|
|
134
|
+
const patient = identity.age ? `${identity.patientName}, ${identity.age} años` : identity.patientName;
|
|
135
|
+
return [`Paciente: ${patient} · ${phone}`, `Médico tratante: ${withTitle(identity.treatingDoctor)}`];
|
|
124
136
|
}
|
|
125
137
|
|
|
126
138
|
function withIdentity({ identity, review, doctorText }) {
|
|
@@ -10,7 +10,7 @@ const { countMessages, getMessages } = require('./messageService');
|
|
|
10
10
|
const { logPatientChange } = require('./patientService');
|
|
11
11
|
const { getThreadInfo } = require('./threadService');
|
|
12
12
|
const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
|
|
13
|
-
const { graveMissingOf, isDraftCurrent, pendingFlagsOf } = require('./gravePendingService');
|
|
13
|
+
const { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented } = require('./gravePendingService');
|
|
14
14
|
const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
15
15
|
const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
|
|
16
16
|
const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
|
|
@@ -75,7 +75,9 @@ function outcomeOf(review, clock, now) {
|
|
|
75
75
|
const held = teamFirst && grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000);
|
|
76
76
|
if (grave.length || present.length) {
|
|
77
77
|
const missing = grave.length && `Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
|
|
78
|
-
|
|
78
|
+
// A grave datum still inside its wait goes in the note too, so the doctor knows it is being asked.
|
|
79
|
+
const asking = pendingFlagsOf(review, clock.since).flags.map(({ flag }) => flag).filter((flag) => !grave.some((entry) => entry.flag === flag));
|
|
80
|
+
const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, missing, asking.length && `Preguntando: ${asking.join(', ')}`];
|
|
79
81
|
return { grave, update, notify, held, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
|
|
80
82
|
}
|
|
81
83
|
// A grave question still inside its wait holds the case even when the rest is enough.
|
|
@@ -144,9 +146,18 @@ async function handOff(review, clock, outcome, now) {
|
|
|
144
146
|
try {
|
|
145
147
|
if (digest) await getEscalationReview().updateOne({ _id: review._id }, { $set: { digestQueuedAt: now, digestClaimedAt: null, digestSentAt: null } }, BOOKKEEPING);
|
|
146
148
|
const kind = review.drafts.at(-1)?.urgentPresentRedFlags?.length ? 'act_now' : 'ready';
|
|
147
|
-
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 });
|
|
149
|
+
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 });
|
|
148
150
|
} catch (error) {
|
|
149
|
-
|
|
151
|
+
// Someone handed the case off since the sweep read it: nothing failed, and the next sweep reads the new handoff.
|
|
152
|
+
const next = `doctorHandoffs.${(review.doctorHandoffs ?? []).length}`;
|
|
153
|
+
const overtaken = error?.statusCode === 409
|
|
154
|
+
&& Boolean(await getEscalationReview().exists({ _id: review._id, [next]: { $exists: true } }).catch(() => null));
|
|
155
|
+
// The digest stays queued for a handoff still being sent or one that did not ring the doctor, as another sweep's may rely on it.
|
|
156
|
+
const unqueue = overtaken
|
|
157
|
+
? { [`${next}.transport`]: { $exists: true, $ne: null } }
|
|
158
|
+
: { status: { $nin: ['awaiting_doctor', 'handing_off'] } };
|
|
159
|
+
if (digest) await getEscalationReview().updateOne({ _id: review._id, ...unqueue }, { $set: { digestQueuedAt: null } }, BOOKKEEPING).catch(() => {});
|
|
160
|
+
if (overtaken) return false;
|
|
150
161
|
const attempt = attemptsOf(review, clock) + 1;
|
|
151
162
|
await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
|
|
152
163
|
// A 409 is mostly another sweep or a person who moved the case first.
|
|
@@ -229,8 +240,8 @@ async function graveMessage(review, clock, entries) {
|
|
|
229
240
|
}
|
|
230
241
|
|
|
231
242
|
const sameEntry = (entry) => ({ flag: entry.flag, since: entry.since });
|
|
232
|
-
const setOn = (review, entry, fields, filter = {}) => getEscalationReview().updateOne(
|
|
233
|
-
{ _id: review._id, graveAlerts: { $elemMatch: { ...sameEntry(entry), ...filter } } },
|
|
243
|
+
const setOn = (review, entry, fields, filter = {}, guard = {}) => getEscalationReview().updateOne(
|
|
244
|
+
{ _id: review._id, ...guard, graveAlerts: { $elemMatch: { ...sameEntry(entry), ...filter } } },
|
|
234
245
|
{ $set: Object.fromEntries(Object.entries(fields).map(([key, value]) => [`graveAlerts.$.${key}`, value])) },
|
|
235
246
|
BOOKKEEPING,
|
|
236
247
|
);
|
|
@@ -251,7 +262,9 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
|
|
|
251
262
|
const message = await graveMessage(review, clock, pending);
|
|
252
263
|
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
253
264
|
const sending = [];
|
|
254
|
-
|
|
265
|
+
// A decision or a closing since the sweep read the case means the alert is no longer due.
|
|
266
|
+
const undecided = { closedAt: null, status: { $in: PRE_DECISION_STATUSES }, decisions: { $size: (review.decisions ?? []).length } };
|
|
267
|
+
for (const entry of pending) if ((await setOn(review, entry, { sentAt: now }, { sentAt: null }, undecided)).modifiedCount) sending.push(entry);
|
|
255
268
|
if (!sending.length) return 0;
|
|
256
269
|
let delivered = 0;
|
|
257
270
|
try {
|
|
@@ -340,13 +353,16 @@ async function remindQuietPatient(review, clock, now) {
|
|
|
340
353
|
|
|
341
354
|
// 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.
|
|
342
355
|
async function askBlockingQuestion(review, clock, now) {
|
|
343
|
-
|
|
356
|
+
// With the doctor, only a case the bot handed over is still asked, and only its grave data.
|
|
357
|
+
const withDoctor = review.status === 'awaiting_doctor';
|
|
358
|
+
if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return;
|
|
344
359
|
const latest = (review.drafts ?? []).at(-1);
|
|
345
360
|
if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
|
|
346
|
-
const
|
|
361
|
+
const blocking = withDoctor ? null : latest.blockingQuestion;
|
|
362
|
+
const graveFlags = blocking || latest.urgentPresentRedFlags?.length ? []
|
|
347
363
|
: pendingFlagsOf(review, clock.since).flags.filter(({ unobtainable }) => !unobtainable).map(({ flag }) => flag);
|
|
348
|
-
const question =
|
|
349
|
-
const flags =
|
|
364
|
+
const question = blocking || graveFlags.join('; ') || null;
|
|
365
|
+
const flags = blocking ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
|
|
350
366
|
if (!question) return;
|
|
351
367
|
const asks = review.blockingAsks ?? [];
|
|
352
368
|
if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
|
|
@@ -366,11 +382,11 @@ async function askBlockingQuestion(review, clock, now) {
|
|
|
366
382
|
// The turn runs in the background so the sweep does not wait on it; while it waits for the chat lock the case can be handed over, redrafted or taken.
|
|
367
383
|
const beforeRun = async () => {
|
|
368
384
|
const fresh = await getEscalationReview().findById(review._id).lean();
|
|
369
|
-
if (!fresh || fresh.closedAt || fresh.status !==
|
|
385
|
+
if (!fresh || fresh.closedAt || fresh.status !== review.status || (withDoctor && !stillDocumented(fresh))) return 'moved';
|
|
370
386
|
if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
|
|
371
387
|
return takenOf(fresh, clock);
|
|
372
388
|
};
|
|
373
|
-
const instruction =
|
|
389
|
+
const instruction = blocking ? blockingAskText(blocking) : graveAskText(graveFlags);
|
|
374
390
|
getMessaging().processInstruction(review.patientCode, instruction, 'developer', { triggeredBy: OPERATOR, beforeRun })
|
|
375
391
|
.then((result) => result?.outcome ?? null, (error) => {
|
|
376
392
|
logger.error('[CharacterizationOutcome] The blocking question was not asked', {
|
|
@@ -5,7 +5,8 @@ const { httpError, requiredText } = require('../utils/httpErrorUtils');
|
|
|
5
5
|
const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
|
|
6
6
|
const { logger } = require('../utils/logger');
|
|
7
7
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
8
|
-
const { isoDay, mexicoDay } = require('../utils/dateUtils');
|
|
8
|
+
const { ageInYears, isoDay, mexicoDay } = require('../utils/dateUtils');
|
|
9
|
+
const { safeParse } = require('../utils/jsonUtils');
|
|
9
10
|
const {
|
|
10
11
|
CALL_OUTCOMES,
|
|
11
12
|
CANCELLABLE_AFTER_HANDOFF_STATUSES,
|
|
@@ -45,6 +46,7 @@ const { cytotoxicWindowDays, daysSinceLastCytotoxic } = require('../clinical/hel
|
|
|
45
46
|
const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
|
|
46
47
|
const { composePrompt } = require('../clinical/services/promptComposerService');
|
|
47
48
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
49
|
+
const { ageFrom, birthDateFrom } = require('../fhir/resources/Patient');
|
|
48
50
|
|
|
49
51
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
50
52
|
const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
|
|
@@ -72,6 +74,7 @@ const MAX_ALERT_ATTEMPTS = 3;
|
|
|
72
74
|
const BOOKKEEPING = { timestamps: false };
|
|
73
75
|
const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
74
76
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
77
|
+
const HANDING_OFF_WAIT_MS = 3000;
|
|
75
78
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
76
79
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
77
80
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
@@ -348,7 +351,10 @@ function doctorIdentity(patient) {
|
|
|
348
351
|
const missing = [];
|
|
349
352
|
if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
|
|
350
353
|
if (!treatingDoctor) missing.push('médico tratante');
|
|
351
|
-
|
|
354
|
+
const demografia = safeParse(patient?.['clinical-context-json'], null)?.demografia;
|
|
355
|
+
const born = ageInYears(birthDateFrom(demografia?.fecha_nacimiento));
|
|
356
|
+
const age = born > 0 && born < 130 ? born : ageFrom(demografia?.edad);
|
|
357
|
+
return { patientName, treatingDoctor, age, missing };
|
|
352
358
|
}
|
|
353
359
|
|
|
354
360
|
async function readDoctorIdentity(review) {
|
|
@@ -792,6 +798,21 @@ async function appendKeepingDraft(id, entry) {
|
|
|
792
798
|
throw httpError(409, STATUS_CONFLICT);
|
|
793
799
|
}
|
|
794
800
|
|
|
801
|
+
// With the doctor the case keeps its status; a bot handoff redrafts it as an update, so the call reaches the draft the doctor reads.
|
|
802
|
+
async function appendWithDoctor(id, entry) {
|
|
803
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
804
|
+
const review = await loadReview(id);
|
|
805
|
+
// The bot's own update passes through handing_off while it sends; the call waits for it once.
|
|
806
|
+
if (review.status === 'handing_off' && attempt === 0) {
|
|
807
|
+
await new Promise((resolve) => { setTimeout(resolve, HANDING_OFF_WAIT_MS); });
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (review.status !== 'awaiting_doctor') break;
|
|
811
|
+
return updateReview(id, ['awaiting_doctor'], { $push: { callLogs: entry }, ...(updatesDoctor(review) && { $set: redraftAfterCall() }) });
|
|
812
|
+
}
|
|
813
|
+
throw httpError(409, STATUS_CONFLICT);
|
|
814
|
+
}
|
|
815
|
+
|
|
795
816
|
async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId = null } = {}) {
|
|
796
817
|
const reviewId = reviewIdOf(id);
|
|
797
818
|
const operator = requiredText(updatedBy, 'updatedBy');
|
|
@@ -844,11 +865,13 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
|
|
|
844
865
|
if (Number.isNaN(callTime.getTime())) throw httpError(400, 'calledAt must be a valid date');
|
|
845
866
|
|
|
846
867
|
const entry = { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator };
|
|
847
|
-
const review = outcome === 'contacted'
|
|
848
|
-
?
|
|
849
|
-
:
|
|
868
|
+
const review = await (outcome === 'contacted'
|
|
869
|
+
? updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } })
|
|
870
|
+
: appendKeepingDraft(reviewId, entry))
|
|
871
|
+
.catch((error) => (error.statusCode === 409 ? appendWithDoctor(reviewId, entry) : Promise.reject(error)));
|
|
850
872
|
await audit(review, operator, requestId, { action: 'call_logged', outcome });
|
|
851
|
-
|
|
873
|
+
// Note facts are confirmed only while the case is documented, so none are proposed while it is with the doctor.
|
|
874
|
+
if (outcome !== 'contacted' || review.status === 'awaiting_doctor') return review;
|
|
852
875
|
return proposeNoteFacts(review, operator, requestId);
|
|
853
876
|
}
|
|
854
877
|
|
|
@@ -1681,7 +1704,7 @@ async function soleApprover() {
|
|
|
1681
1704
|
}
|
|
1682
1705
|
|
|
1683
1706
|
// 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 } = {}) {
|
|
1707
|
+
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
|
|
1685
1708
|
const reviewId = reviewIdOf(id);
|
|
1686
1709
|
const operator = requiredText(sentBy, 'sentBy');
|
|
1687
1710
|
if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
|
|
@@ -1724,7 +1747,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note =
|
|
|
1724
1747
|
reviewId,
|
|
1725
1748
|
[review.status],
|
|
1726
1749
|
{ $set: { status: 'handing_off', operationClaim: claim } },
|
|
1727
|
-
|
|
1750
|
+
// A caller that read the case earlier passes how many handoffs it saw, so one made since is not repeated.
|
|
1751
|
+
{ drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt, ...(handoffs != null && { doctorHandoffs: { $size: handoffs } }) },
|
|
1728
1752
|
);
|
|
1729
1753
|
let delivery = {};
|
|
1730
1754
|
let updated;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const { normalizedKeyOf } = require('../utils/coercionUtils');
|
|
2
2
|
|
|
3
|
-
const { DOCUMENTING_STATUSES } = require('./escalationReviewService');
|
|
3
|
+
const { AUTO_HANDOFF_OPERATOR, DOCUMENTING_STATUSES } = require('./escalationReviewService');
|
|
4
4
|
const { pendingWaitMinutes } = require('./reviewDeadlineService');
|
|
5
5
|
|
|
6
6
|
const keysOf = (flags) => [...new Set((flags ?? []).map(normalizedKeyOf).filter(Boolean))];
|
|
@@ -20,6 +20,10 @@ function pendingFlagsOf(review, since) {
|
|
|
20
20
|
return { latest: drafts.at(-1) ?? null, flags: [...firstSeen].map(([flag, firstSeenAt]) => ({ flag, firstSeenAt, unobtainable: unobtainable.includes(flag) })) };
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
// The bot keeps documenting a case it handed to the doctor itself, so its grave questions still wait for the patient there.
|
|
24
|
+
const stillDocumented = (review) => DOCUMENTING_STATUSES.includes(review.status)
|
|
25
|
+
|| (review.status === 'awaiting_doctor' && review.doctorHandoffs?.at(-1)?.sentBy === AUTO_HANDOFF_OPERATOR);
|
|
26
|
+
|
|
23
27
|
// The latest draft speaks for the case only while no newer patient turn or redraft is waiting to replace it.
|
|
24
28
|
const isDraftCurrent = (review, latest) => !review.draftDueAt
|
|
25
29
|
&& !(review.updates ?? []).some((update) => new Date(update.at).getTime() > new Date(latest.createdAt).getTime());
|
|
@@ -30,8 +34,8 @@ function graveMissingOf(review, clock, now) {
|
|
|
30
34
|
if (!limit) return [];
|
|
31
35
|
const { latest, flags } = pendingFlagsOf(review, clock.since);
|
|
32
36
|
if (!latest || !isDraftCurrent(review, latest)) return [];
|
|
33
|
-
// Once
|
|
34
|
-
const waiting =
|
|
37
|
+
// Once a person handed the case over no new draft comes, so the wait no longer means unanswered.
|
|
38
|
+
const waiting = stillDocumented(review);
|
|
35
39
|
const isDue = ({ firstSeenAt, unobtainable }) => unobtainable || (waiting && now.getTime() - firstSeenAt.getTime() >= limit * 60 * 1000);
|
|
36
40
|
if (!flags.some(isDue)) return [];
|
|
37
41
|
// Only the first alert gathers the data still waiting; one that appears after it waits its own time.
|
|
@@ -40,4 +44,4 @@ function graveMissingOf(review, clock, now) {
|
|
|
40
44
|
.map(({ flag, firstSeenAt, unobtainable }) => ({ flag, firstSeenAt, reason: unobtainable ? 'unobtainable' : 'unanswered' }));
|
|
41
45
|
}
|
|
42
46
|
|
|
43
|
-
module.exports = { graveMissingOf, isDraftCurrent, pendingFlagsOf };
|
|
47
|
+
module.exports = { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented };
|