@peopl-health/nexus 5.61.0-dev.11186 → 5.61.0-dev.11231
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/AssistantProcessor.js +0 -16
- package/lib/clinical/config/subAgentsConfig.js +7 -1
- package/lib/clinical/models/supportLightModel.js +19 -1
- package/lib/clinical/services/escalationDraftService.js +3 -17
- package/lib/clinical/services/gradeSourceService.js +33 -8
- package/lib/clinical/services/supportLightEvaluationService.js +159 -0
- package/lib/clinical/services/treatmentProposalService.js +2 -7
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +1 -1
- package/lib/clinical/tools/reportMedicalEscalationTool.js +0 -3
- package/lib/config/lifecycle.js +1 -4
- package/lib/controllers/escalationReviewController.js +0 -15
- package/lib/controllers/messageController.js +1 -21
- package/lib/index.d.ts +33 -14
- package/lib/index.js +2 -20
- package/lib/models/escalationReviewModel.js +2 -64
- package/lib/routes/index.js +0 -2
- package/lib/services/escalationReviewService.js +45 -614
- package/lib/services/patientTaskService.js +0 -1
- package/package.json +1 -1
- package/lib/clinical/helpers/reviewUpdateHelper.js +0 -74
- package/lib/services/reviewAlertSweepService.js +0 -88
- package/lib/services/reviewDraftSweepService.js +0 -79
|
@@ -14,55 +14,31 @@ const {
|
|
|
14
14
|
DOCTOR_DECISIONS,
|
|
15
15
|
HANDOFF_MODES,
|
|
16
16
|
INTERRUPTED_STATUSES,
|
|
17
|
-
RETURN_REASONS,
|
|
18
17
|
getEscalationReview,
|
|
19
18
|
} = require('../models/escalationReviewModel');
|
|
20
|
-
const { getPatientAuditLog } = require('../models/patientAuditLogModel');
|
|
21
19
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
22
20
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
23
21
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
24
22
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
25
|
-
const {
|
|
23
|
+
const { writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
26
24
|
const { renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
27
25
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
28
|
-
const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
|
|
29
|
-
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
30
26
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
31
27
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
32
28
|
|
|
33
29
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
34
|
-
const {
|
|
30
|
+
const { getPatientTasks, openCaseIds, updatePatientTask } = require('./patientTaskService');
|
|
35
31
|
const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
|
|
36
32
|
const { switchThreadStoppedStatus } = require('./threadService');
|
|
37
33
|
|
|
38
34
|
const AUDIT_SOURCE = 'escalation_review';
|
|
39
35
|
const RECENT_REVIEW_LIMIT = 20;
|
|
40
|
-
const TIMELINE_LIMIT = 500;
|
|
41
|
-
const MAX_REVIEW_UPDATES = 50;
|
|
42
|
-
const DRAFT_DEBOUNCE_MS = 60 * 1000;
|
|
43
|
-
const DRAFT_OPERATOR = 'bot:escalationDraft';
|
|
44
|
-
const DIRECT_CHAT_ATTEMPTS = 3;
|
|
45
|
-
const RECHECK_DELAY_MS = 60 * 1000;
|
|
46
|
-
const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
47
36
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
48
37
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
49
38
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
50
39
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
51
40
|
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'needs_intervention'];
|
|
52
41
|
const SENDABLE_STATUSES = ['approved', 'needs_intervention'];
|
|
53
|
-
const DECIDABLE_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
54
|
-
const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued'];
|
|
55
|
-
const SETTLED_TRAJECTORIES = ['improving', 'stable'];
|
|
56
|
-
const ALERTED_URGENCIES = ['stat', 'asap'];
|
|
57
|
-
const URGENCY_RANK = { routine: 1, urgent: 2, asap: 3, stat: 4 };
|
|
58
|
-
const DEFAULT_STAT_REALERT_MINUTES = 15;
|
|
59
|
-
const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
|
|
60
|
-
const ALERT_OPERATOR = 'bot:escalationAlert';
|
|
61
|
-
const DIRECT_CHAT_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor', 'approved', 'needs_intervention'];
|
|
62
|
-
const APPROVALS = ['approved', 'edited_approved'];
|
|
63
|
-
const STALE_DRAFT = 'New information reached the review after this draft; wait for the updated draft before approving';
|
|
64
|
-
const STALE_HANDOFF = 'New information reached the review after the draft the doctor received; it went back to documenting for a new draft';
|
|
65
|
-
const DRAFT_CHANGED = 'A newer draft was written after the one you saw; read it before deciding';
|
|
66
42
|
const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
|
|
67
43
|
const MAX_TEMPLATE_TEXT_LENGTH = 800;
|
|
68
44
|
const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
|
|
@@ -436,83 +412,19 @@ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseR
|
|
|
436
412
|
}
|
|
437
413
|
|
|
438
414
|
const BOT_OPERATOR = 'bot:reportMedicalEscalation';
|
|
439
|
-
const AGENT_OPERATOR = 'bot:clinicalAgent';
|
|
440
|
-
|
|
441
|
-
async function previousReviewIdOf(EscalationReview, patientCode, now) {
|
|
442
|
-
try {
|
|
443
|
-
const previous = await EscalationReview
|
|
444
|
-
.findOne({ patientCode, closedAt: { $gte: new Date(now.getTime() - PREVIOUS_REVIEW_WINDOW_MS) } }, { _id: 1 })
|
|
445
|
-
.sort({ closedAt: -1 })
|
|
446
|
-
.lean();
|
|
447
|
-
return previous ? String(previous._id) : null;
|
|
448
|
-
} catch (error) {
|
|
449
|
-
logger.warn('[EscalationReview] The previous review lookup failed; opening the review unlinked', { error: redactedError(error) });
|
|
450
|
-
return null;
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
// Files what the agent characterized after the escalation on the patient's open review, and sends a
|
|
455
|
-
// returned review back to the queue. Never opens a review: only an escalation does.
|
|
456
|
-
async function recordReviewUpdate({ code, update, now = new Date(), settleInBackground = true } = {}) {
|
|
457
|
-
if (!update) return null;
|
|
458
|
-
try {
|
|
459
|
-
const patientCode = patientCodeOf(code);
|
|
460
|
-
const EscalationReview = getEscalationReview();
|
|
461
|
-
const pushed = await EscalationReview.findOneAndUpdate(
|
|
462
|
-
{ patientCode, closedAt: null },
|
|
463
|
-
{
|
|
464
|
-
$push: { updates: { $each: [update], $slice: -MAX_REVIEW_UPDATES } },
|
|
465
|
-
$set: { draftDueAt: new Date(now.getTime() + DRAFT_DEBOUNCE_MS), draftAttempts: 0 },
|
|
466
|
-
},
|
|
467
|
-
{ new: true },
|
|
468
|
-
).lean();
|
|
469
|
-
if (!pushed) return null;
|
|
470
|
-
|
|
471
|
-
if (FOLLOWUP_STATUSES.includes(pushed.status)) {
|
|
472
|
-
await audit(pushed, AGENT_OPERATOR, null, { action: 'case_updated', turnId: update.turnId, tools: update.tools });
|
|
473
|
-
return await settleFollowUp(pushed, { background: settleInBackground });
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// The turn that opened the review seeds its draft, but it is not news to whoever opens it.
|
|
477
|
-
const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
|
|
478
|
-
const updated = openingTurn ? pushed : (await EscalationReview
|
|
479
|
-
.findOneAndUpdate({ _id: pushed._id }, { $set: { updatedSinceSeen: true } }, { new: true })
|
|
480
|
-
.lean()) ?? pushed;
|
|
481
|
-
const requeued = updated.status === 'returned'
|
|
482
|
-
? await EscalationReview
|
|
483
|
-
.findOneAndUpdate({ _id: updated._id, status: 'returned' }, { $set: { status: 'documenting' } }, { new: true })
|
|
484
|
-
.lean()
|
|
485
|
-
: null;
|
|
486
|
-
await audit(updated, AGENT_OPERATOR, null, {
|
|
487
|
-
action: 'case_updated',
|
|
488
|
-
turnId: update.turnId,
|
|
489
|
-
tools: update.tools,
|
|
490
|
-
...(requeued && { statusFrom: 'returned', statusTo: 'documenting' }),
|
|
491
|
-
});
|
|
492
|
-
return requeued || updated;
|
|
493
|
-
} catch (error) {
|
|
494
|
-
logger.error('[EscalationReview] The agent update was not recorded against the review', {
|
|
495
|
-
error: redactedError(error), stack: redactedStack(error),
|
|
496
|
-
});
|
|
497
|
-
return null;
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
415
|
|
|
501
416
|
async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
502
417
|
try {
|
|
503
418
|
const patientCode = patientCodeOf(code);
|
|
504
419
|
const entry = { ...alarm, raisedAt: alarm?.raisedAt ?? now };
|
|
505
420
|
const EscalationReview = getEscalationReview();
|
|
506
|
-
const draftDueAt = new Date(now.getTime() + DRAFT_DEBOUNCE_MS);
|
|
507
421
|
const join = () => EscalationReview
|
|
508
|
-
.findOneAndUpdate({ patientCode, closedAt: null }, { $push: { alarms: entry }
|
|
422
|
+
.findOneAndUpdate({ patientCode, closedAt: null }, { $push: { alarms: entry } }, { new: true })
|
|
509
423
|
.lean();
|
|
510
424
|
|
|
511
425
|
await ensureActiveReviewIndex(EscalationReview);
|
|
512
426
|
const joined = await join();
|
|
513
427
|
if (joined) {
|
|
514
|
-
await scheduleDoctorAlert(joined, entry, now);
|
|
515
|
-
if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
|
|
516
428
|
if (!DOCUMENTING_STATUSES.includes(joined.status)) {
|
|
517
429
|
logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
|
|
518
430
|
escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
|
|
@@ -521,16 +433,9 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
|
521
433
|
return joined;
|
|
522
434
|
}
|
|
523
435
|
try {
|
|
524
|
-
|
|
525
|
-
patientCode,
|
|
526
|
-
openedBy: BOT_OPERATOR,
|
|
527
|
-
alarms: [entry],
|
|
528
|
-
assistantPausedByReview: false,
|
|
529
|
-
previousReviewId: await previousReviewIdOf(EscalationReview, patientCode, now),
|
|
530
|
-
draftDueAt,
|
|
436
|
+
return (await EscalationReview.create({
|
|
437
|
+
patientCode, openedBy: BOT_OPERATOR, alarms: [entry], assistantPausedByReview: false,
|
|
531
438
|
})).toObject();
|
|
532
|
-
await scheduleDoctorAlert(created, entry, now);
|
|
533
|
-
return created;
|
|
534
439
|
} catch (error) {
|
|
535
440
|
if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
|
|
536
441
|
return await join();
|
|
@@ -608,50 +513,7 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
|
|
|
608
513
|
const reviewId = reviewIdOf(id);
|
|
609
514
|
const operator = requiredText(requestedBy, 'requestedBy');
|
|
610
515
|
const review = await loadReview(reviewId);
|
|
611
|
-
|
|
612
|
-
const readAt = new Date();
|
|
613
|
-
const isApprover = await isEscalationApprover(operator);
|
|
614
|
-
const EscalationReview = getEscalationReview();
|
|
615
|
-
const warnUnmarked = (error) => logger.warn('[EscalationReview] The review read was not marked', {
|
|
616
|
-
escalationReviewId: String(review._id), error: redactedError(error),
|
|
617
|
-
});
|
|
618
|
-
if (review.updatedSinceSeen) {
|
|
619
|
-
// Only clears what this read returned: an update that lands meanwhile changes updatedAt and stays unread.
|
|
620
|
-
// A read is not a change: neither mark touches updatedAt, so handoff claims and grace periods hold.
|
|
621
|
-
await EscalationReview
|
|
622
|
-
.updateOne({ _id: review._id, updatedAt: review.updatedAt }, { $set: { updatedSinceSeen: false } }, { timestamps: false })
|
|
623
|
-
.catch(warnUnmarked);
|
|
624
|
-
}
|
|
625
|
-
if (isApprover) {
|
|
626
|
-
await EscalationReview
|
|
627
|
-
// $max: a slow read finishing late never moves the last view back.
|
|
628
|
-
.updateOne({ _id: review._id }, { $max: { approverViewedAt: readAt } }, { timestamps: false })
|
|
629
|
-
.catch(warnUnmarked);
|
|
630
|
-
}
|
|
631
|
-
return { review, isApprover };
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
async function getReviewTimeline({ id } = {}) {
|
|
635
|
-
const review = await loadReview(reviewIdOf(id));
|
|
636
|
-
// Newest first, so a busy review keeps its latest steps under the limit.
|
|
637
|
-
const rows = await getPatientAuditLog()
|
|
638
|
-
.find({ code: review.patientCode, source: AUDIT_SOURCE, 'changes.escalationReviewId': String(review._id) })
|
|
639
|
-
.sort({ createdAt: -1 })
|
|
640
|
-
.limit(TIMELINE_LIMIT)
|
|
641
|
-
.lean();
|
|
642
|
-
const alarms = (review.alarms ?? []).map((alarm) => ({
|
|
643
|
-
at: alarm.raisedAt,
|
|
644
|
-
action: 'alarm',
|
|
645
|
-
by: BOT_OPERATOR,
|
|
646
|
-
details: { urgencyLevel: alarm.urgencyLevel, symptom: alarm.symptom ?? null },
|
|
647
|
-
}));
|
|
648
|
-
const steps = rows.map(({ createdAt, updatedBy, changes }) => {
|
|
649
|
-
const details = { ...changes };
|
|
650
|
-
delete details.escalationReviewId;
|
|
651
|
-
delete details.action;
|
|
652
|
-
return { at: createdAt, action: changes?.action ?? null, by: updatedBy, details };
|
|
653
|
-
});
|
|
654
|
-
return [...alarms, ...steps].sort((a, b) => new Date(a.at) - new Date(b.at)).slice(-TIMELINE_LIMIT);
|
|
516
|
+
return { review, isApprover: await isEscalationApprover(operator) };
|
|
655
517
|
}
|
|
656
518
|
|
|
657
519
|
async function listEscalationReviews({ code } = {}) {
|
|
@@ -659,22 +521,18 @@ async function listEscalationReviews({ code } = {}) {
|
|
|
659
521
|
return getEscalationReview().find({ patientCode }).sort({ createdAt: -1 }).limit(RECENT_REVIEW_LIMIT).lean();
|
|
660
522
|
}
|
|
661
523
|
|
|
662
|
-
// A call note is new material for the automatic draft: it re-arms it, and a draft generated without
|
|
663
|
-
// the note is no longer saved.
|
|
664
|
-
const redraftAfterCall = () => ({ draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS), draftAttempts: 0 });
|
|
665
|
-
|
|
666
524
|
async function appendKeepingDraft(id, entry) {
|
|
667
525
|
const EscalationReview = getEscalationReview();
|
|
668
526
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
669
527
|
const kept = await EscalationReview
|
|
670
|
-
.findOneAndUpdate({ _id: id, status: 'draft_ready' }, { $push: { callLogs: entry }
|
|
528
|
+
.findOneAndUpdate({ _id: id, status: 'draft_ready' }, { $push: { callLogs: entry } }, { new: true })
|
|
671
529
|
.lean();
|
|
672
530
|
if (kept) return kept;
|
|
673
531
|
|
|
674
532
|
const moved = await EscalationReview
|
|
675
533
|
.findOneAndUpdate(
|
|
676
534
|
{ _id: id, status: { $in: UNDRAFTED_STATUSES } },
|
|
677
|
-
{ $push: { callLogs: entry }, $set: { status: 'documenting'
|
|
535
|
+
{ $push: { callLogs: entry }, $set: { status: 'documenting' } },
|
|
678
536
|
{ new: true },
|
|
679
537
|
)
|
|
680
538
|
.lean();
|
|
@@ -742,7 +600,7 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
|
|
|
742
600
|
|
|
743
601
|
const entry = { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator };
|
|
744
602
|
const review = outcome === 'contacted'
|
|
745
|
-
? await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting'
|
|
603
|
+
? await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting' } })
|
|
746
604
|
: await appendKeepingDraft(reviewId, entry);
|
|
747
605
|
await audit(review, operator, requestId, { action: 'call_logged', outcome });
|
|
748
606
|
if (outcome !== 'contacted') return review;
|
|
@@ -792,287 +650,6 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
|
|
|
792
650
|
return { ...draft, doctorText: withIdentity({ identity, review, doctorText: draft.doctorText }) };
|
|
793
651
|
}
|
|
794
652
|
|
|
795
|
-
// The most urgent level the doctor was actually alerted about; a failed attempt told them nothing.
|
|
796
|
-
// Scheduling and sending gate on the same one.
|
|
797
|
-
const alertedRankOf = (review) => Math.max(0, ...(review.doctorAlerts ?? [])
|
|
798
|
-
.filter((sent) => sent.kind === 'initial' && !sent.error)
|
|
799
|
-
.map((sent) => URGENCY_RANK[sent.urgencyLevel] || 0));
|
|
800
|
-
|
|
801
|
-
// A stat or asap alarm more urgent than anything the doctor was already told about is due now.
|
|
802
|
-
async function scheduleDoctorAlert(review, alarm, now) {
|
|
803
|
-
try {
|
|
804
|
-
if (!ALERTED_URGENCIES.includes(alarm?.urgencyLevel)) return;
|
|
805
|
-
if (URGENCY_RANK[alarm.urgencyLevel] <= alertedRankOf(review)) return;
|
|
806
|
-
// An initial alert in flight holds its lease; its sender schedules this urgency once it is done.
|
|
807
|
-
const scheduled = await getEscalationReview().updateOne(
|
|
808
|
-
{ _id: review._id, $nor: [{ doctorAlertKind: 'initial', doctorAlertDueAt: { $gt: now } }] },
|
|
809
|
-
{ $set: { doctorAlertDueAt: now, doctorAlertKind: 'initial', doctorAlertAttempts: 0 } },
|
|
810
|
-
);
|
|
811
|
-
if (scheduled.matchedCount) Object.assign(review, { doctorAlertDueAt: now, doctorAlertKind: 'initial' });
|
|
812
|
-
} catch (error) {
|
|
813
|
-
logger.error('[EscalationReview] The doctor alert was not scheduled', { escalationReviewId: String(review?._id), error: redactedError(error) });
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
const statRealertMs = () => {
|
|
818
|
-
const minutes = Number(runtimeConfig.get('ESCALATION_REVIEW_STAT_REALERT_MINUTES', DEFAULT_STAT_REALERT_MINUTES));
|
|
819
|
-
return (Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_STAT_REALERT_MINUTES) * 60 * 1000;
|
|
820
|
-
};
|
|
821
|
-
|
|
822
|
-
// The doctor answered once they opened the review or anything was decided after the alert.
|
|
823
|
-
function answeredSince(review, since) {
|
|
824
|
-
const sinceMs = new Date(since).getTime();
|
|
825
|
-
if (!PRE_DECISION_STATUSES.includes(review.status)) return true;
|
|
826
|
-
if (review.approverViewedAt && new Date(review.approverViewedAt).getTime() >= sinceMs) return true;
|
|
827
|
-
return (review.decisions ?? []).some((decision) => decision.createdAt && new Date(decision.createdAt).getTime() >= sinceMs);
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
async function prepareDoctorAlert(review, kind, urgencyLevel) {
|
|
831
|
-
const identity = await readDoctorIdentity(review);
|
|
832
|
-
if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
|
|
833
|
-
const approver = await soleApprover();
|
|
834
|
-
const link = doctorLink(review);
|
|
835
|
-
const label = urgencyLevel === 'stat' ? 'STAT' : 'ASAP';
|
|
836
|
-
const lead = kind === 'realert' ? `Sigue pendiente · revisión clínica ${label}` : `Revisión clínica ${label}`;
|
|
837
|
-
const message = {
|
|
838
|
-
body: `${lead}: ${identity.patientName} (médico tratante: ${identity.treatingDoctor}). ${templateSummary(review)}.\n${link}`,
|
|
839
|
-
template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: templateSummary(review), 4: link },
|
|
840
|
-
};
|
|
841
|
-
return { approver, message };
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
const topUrgencyOf = (review) => (review.alarms ?? [])
|
|
845
|
-
.reduce((top, alarm) => (URGENCY_RANK[alarm.urgencyLevel] > (URGENCY_RANK[top] || 0) ? alarm.urgencyLevel : top), null);
|
|
846
|
-
|
|
847
|
-
const realertStillDue = (review, initial) => !review.closedAt && Boolean(initial) && !answeredSince(review, initial.sentAt);
|
|
848
|
-
|
|
849
|
-
// Sends the alert the sweep claimed under `lease`. A stat alert arms the re-alert; the re-alert goes
|
|
850
|
-
// out only if the doctor has not answered, checked again right before sending, and also files a new
|
|
851
|
-
// emergency row so the team is alerted. The schedule is only touched while the lease is still ours.
|
|
852
|
-
async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date() } = {}) {
|
|
853
|
-
const EscalationReview = getEscalationReview();
|
|
854
|
-
const ours = lease ? { doctorAlertDueAt: lease } : {};
|
|
855
|
-
const release = (set = { doctorAlertDueAt: null, doctorAlertKind: null, doctorAlertAttempts: 0 }) => EscalationReview
|
|
856
|
-
.updateOne({ _id: id, ...ours }, { $set: set });
|
|
857
|
-
|
|
858
|
-
const review = await loadReview(reviewIdOf(id));
|
|
859
|
-
// Once anything was decided, the doctor has nothing left to be alerted about.
|
|
860
|
-
if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) {
|
|
861
|
-
await release();
|
|
862
|
-
return null;
|
|
863
|
-
}
|
|
864
|
-
const initial = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial').at(-1);
|
|
865
|
-
if (kind === 'realert' && !realertStillDue(review, initial)) {
|
|
866
|
-
await release();
|
|
867
|
-
return null;
|
|
868
|
-
}
|
|
869
|
-
const urgencyLevel = kind === 'realert' ? initial.urgencyLevel : topUrgencyOf(review);
|
|
870
|
-
// The doctor already heard about this urgency (a recheck, or a retry whose record landed): nothing to send.
|
|
871
|
-
if (kind === 'initial' && (URGENCY_RANK[urgencyLevel] || 0) <= alertedRankOf(review)) {
|
|
872
|
-
await release();
|
|
873
|
-
return null;
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
let delivery;
|
|
877
|
-
try {
|
|
878
|
-
const { approver, message } = await prepareDoctorAlert(review, kind, urgencyLevel);
|
|
879
|
-
if (kind === 'realert' && !realertStillDue(await loadReview(review._id), initial)) {
|
|
880
|
-
await release();
|
|
881
|
-
return null;
|
|
882
|
-
}
|
|
883
|
-
delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
|
|
884
|
-
} catch (error) {
|
|
885
|
-
delivery = { error: redactedError(error) };
|
|
886
|
-
logger.error('[EscalationReview] The doctor alert was not sent', { escalationReviewId: String(review._id), kind, error: delivery.error });
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
let teamAlerted = false;
|
|
890
|
-
if (kind === 'realert') {
|
|
891
|
-
const lead = review.alarms?.findLast((alarm) => alarm.urgencyLevel === 'stat') ?? review.alarms?.at(-1);
|
|
892
|
-
teamAlerted = Boolean(await recordEmergency({
|
|
893
|
-
code: review.patientCode,
|
|
894
|
-
trace: null,
|
|
895
|
-
symptom: lead?.symptom || 'Revisión clínica STAT',
|
|
896
|
-
urgencyFhir: 'stat',
|
|
897
|
-
documentation: `Re-aviso: revisión clínica STAT sin respuesta del médico ${Math.round(statRealertMs() / 60000)} min después del aviso.`,
|
|
898
|
-
mergeWithRecent: false,
|
|
899
|
-
}).catch((error) => {
|
|
900
|
-
logger.error('[EscalationReview] The team alert for an unanswered stat review was not filed', { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
901
|
-
return false;
|
|
902
|
-
}));
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, teamAlerted, sentAt: now };
|
|
906
|
-
const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { new: true }).lean();
|
|
907
|
-
const armRealert = kind === 'initial' && urgencyLevel === 'stat';
|
|
908
|
-
await release(armRealert
|
|
909
|
-
? { doctorAlertDueAt: new Date(now.getTime() + statRealertMs()), doctorAlertKind: 'realert', doctorAlertAttempts: 0 }
|
|
910
|
-
: undefined);
|
|
911
|
-
// A more urgent alarm that landed while this alert was out could not take the lease. Read after the
|
|
912
|
-
// release, so one landing later finds no lease and schedules itself.
|
|
913
|
-
if (kind === 'initial' && urgencyLevel !== 'stat') {
|
|
914
|
-
try {
|
|
915
|
-
const latest = await loadReview(review._id);
|
|
916
|
-
const topNow = topUrgencyOf(latest);
|
|
917
|
-
if (URGENCY_RANK[topNow] > (URGENCY_RANK[urgencyLevel] || 0)) await scheduleDoctorAlert(latest, { urgencyLevel: topNow }, new Date());
|
|
918
|
-
} catch (error) {
|
|
919
|
-
// Unread, so not known to be clear: the sweep checks again shortly, and a covered urgency sends nothing.
|
|
920
|
-
logger.error('[EscalationReview] Could not check for a more urgent alarm after the alert', { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
921
|
-
await EscalationReview.updateOne(
|
|
922
|
-
{ _id: review._id, doctorAlertDueAt: null },
|
|
923
|
-
{ $set: { doctorAlertDueAt: new Date(Date.now() + RECHECK_DELAY_MS), doctorAlertKind: 'initial', doctorAlertAttempts: 0 } },
|
|
924
|
-
).catch(() => {});
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
await audit(updated ?? review, ALERT_OPERATOR, null, {
|
|
928
|
-
action: kind === 'realert' ? 'doctor_realerted' : 'doctor_alerted', urgencyLevel, delivered: !sent.error, teamAlerted,
|
|
929
|
-
});
|
|
930
|
-
return updated;
|
|
931
|
-
}
|
|
932
|
-
|
|
933
|
-
async function reopenFromFollowUp(review, reason) {
|
|
934
|
-
const reopened = await getEscalationReview()
|
|
935
|
-
.findOneAndUpdate({ _id: review._id, status: review.status }, { $set: { status: 'documenting', updatedSinceSeen: true } }, { new: true })
|
|
936
|
-
.lean();
|
|
937
|
-
if (!reopened) return review;
|
|
938
|
-
await audit(reopened, AGENT_OPERATOR, null, { action: 'followup_result', result: reason, statusFrom: review.status });
|
|
939
|
-
return reopened;
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
// The agent's own trajectory for the cases of the review, read after the indication went out:
|
|
943
|
-
// any of them worse sends the review back to the queue; all of them holding or better closes it.
|
|
944
|
-
// A closed or resolved case is a settled one, whether or not the call carried a trajectory.
|
|
945
|
-
const readingOf = (impression) => (['close', 'resolve_episode'].includes(impression.event) ? 'improving' : impression.trajectory);
|
|
946
|
-
|
|
947
|
-
async function followUpCasesOf(review, sinceMs) {
|
|
948
|
-
const decisionNumber = (review.decisions ?? []).length;
|
|
949
|
-
if (review.followUpCases && review.followUpDecision === decisionNumber) return { review, known: new Set(review.followUpCases) };
|
|
950
|
-
// Fixed once per indication, on its first follow-up reading, so later updates evicting old ones
|
|
951
|
-
// cannot shrink it; a later indication keeps the cases already followed and adds the newer ones.
|
|
952
|
-
const known = [...new Set([
|
|
953
|
-
...(review.followUpCases ?? []),
|
|
954
|
-
...(review.updates ?? [])
|
|
955
|
-
.filter((entry) => new Date(entry.at).getTime() <= sinceMs)
|
|
956
|
-
.flatMap((entry) => (entry.impressions ?? []).map((impression) => impression.caseId).filter(Boolean)),
|
|
957
|
-
])];
|
|
958
|
-
const stored = await getEscalationReview()
|
|
959
|
-
.findOneAndUpdate(
|
|
960
|
-
// A decision added meanwhile starts its own follow-up; this one must not settle on its readings.
|
|
961
|
-
{ _id: review._id, followUpDecision: review.followUpDecision ?? null, decisions: { $size: decisionNumber } },
|
|
962
|
-
{ $set: { followUpCases: known, followUpDecision: decisionNumber } },
|
|
963
|
-
{ new: true },
|
|
964
|
-
)
|
|
965
|
-
.lean();
|
|
966
|
-
// Lost to another writer: either a new decision, which starts its own follow-up, or a reply that
|
|
967
|
-
// already fixed this set and settles it.
|
|
968
|
-
if (!stored) return { review, known: new Set() };
|
|
969
|
-
// Settles on what the write returned: a reading that landed after the snapshot is in it, and its
|
|
970
|
-
// updatedAt is the one the close matches on.
|
|
971
|
-
return { review: stored, known: new Set(known) };
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
async function closeSettled(review) {
|
|
975
|
-
try {
|
|
976
|
-
// Closes only the review that was evaluated: a new alarm or reading since then keeps it open for that.
|
|
977
|
-
const { review: closed } = await closeEscalationReview({
|
|
978
|
-
id: String(review._id),
|
|
979
|
-
closedBy: AGENT_OPERATOR,
|
|
980
|
-
expectedAlarmCount: (review.alarms ?? []).length,
|
|
981
|
-
expectedUpdatedAt: review.updatedAt,
|
|
982
|
-
});
|
|
983
|
-
await audit(closed, AGENT_OPERATOR, null, { action: 'followup_result', result: 'settled' });
|
|
984
|
-
return closed;
|
|
985
|
-
} catch (error) {
|
|
986
|
-
logger.warn('[EscalationReview] The follow-up settled the case but the review did not close', {
|
|
987
|
-
escalationReviewId: String(review._id), error: redactedError(error),
|
|
988
|
-
});
|
|
989
|
-
return review;
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
async function settleFollowUp(snapshot, { background = true } = {}) {
|
|
994
|
-
const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
|
|
995
|
-
if (!since) return snapshot;
|
|
996
|
-
const sinceMs = new Date(since).getTime();
|
|
997
|
-
const { review, known } = await followUpCasesOf(snapshot, sinceMs);
|
|
998
|
-
if (!known.size) return review;
|
|
999
|
-
|
|
1000
|
-
const latest = new Map();
|
|
1001
|
-
// Clinical order is the turn time, not the order the writes landed in.
|
|
1002
|
-
(review.updates ?? []).filter((entry) => new Date(entry.at).getTime() > sinceMs)
|
|
1003
|
-
.sort((a, b) => new Date(a.at) - new Date(b.at))
|
|
1004
|
-
.forEach((entry) => (entry.impressions ?? [])
|
|
1005
|
-
.filter((impression) => known.has(impression.caseId) && readingOf(impression))
|
|
1006
|
-
.forEach((impression) => latest.set(impression.caseId, readingOf(impression))));
|
|
1007
|
-
|
|
1008
|
-
if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
|
|
1009
|
-
const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
|
|
1010
|
-
if (!settled || review.status !== 'indications_sent') {
|
|
1011
|
-
// Still waiting on readings: the news is flagged for whoever looks at the review.
|
|
1012
|
-
await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
|
|
1013
|
-
return review;
|
|
1014
|
-
}
|
|
1015
|
-
// The close writes the episode and syncs cases; the patient's reply does not wait on it.
|
|
1016
|
-
if (!background) return closeSettled(review);
|
|
1017
|
-
void closeSettled(review);
|
|
1018
|
-
return review;
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
// Writes the draft the doctor will see without anyone asking for it. Answers whether a failed
|
|
1022
|
-
// generation is worth retrying; a review that cannot take a draft is not.
|
|
1023
|
-
async function generateBotDraft({ id, lease = null } = {}) {
|
|
1024
|
-
const review = await loadReview(reviewIdOf(id));
|
|
1025
|
-
if (review.closedAt || !DOCUMENTING_STATUSES.includes(review.status)) return { review: null, retry: false };
|
|
1026
|
-
// A draft the navigator wrote is theirs to replace; the bot never writes over it.
|
|
1027
|
-
const latest = (review.drafts ?? []).at(-1);
|
|
1028
|
-
if (latest && latest.writtenBy !== DRAFT_OPERATOR) return { review: null, retry: false };
|
|
1029
|
-
|
|
1030
|
-
const identity = await readDoctorIdentity(review);
|
|
1031
|
-
if (identity.missing.length) {
|
|
1032
|
-
if (!review.identityBlock) await blockForMissingIdentity({ review, missing: identity.missing, operator: DRAFT_OPERATOR });
|
|
1033
|
-
return { review: null, retry: false };
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
const draft = await generateEscalationDraft({
|
|
1037
|
-
code: review.patientCode,
|
|
1038
|
-
callLogs: review.callLogs ?? [],
|
|
1039
|
-
alarms: review.alarms ?? [],
|
|
1040
|
-
agentCharacterization: characterizationSeedOf(review.updates),
|
|
1041
|
-
reviewId: String(review._id),
|
|
1042
|
-
});
|
|
1043
|
-
if (draft.attempted) {
|
|
1044
|
-
await audit(review, DRAFT_OPERATOR, null, draft.completed
|
|
1045
|
-
? { action: 'draft_generated', protocolVersion: draft.protocolVersion }
|
|
1046
|
-
: { action: 'draft_generation_failed', reason: redactedError({ message: draft.reason }) });
|
|
1047
|
-
}
|
|
1048
|
-
if (!draft.completed) {
|
|
1049
|
-
logger.warn('[EscalationReview] The automatic draft was not written', { escalationReviewId: String(review._id), reason: draft.reason });
|
|
1050
|
-
return { review: null, retry: draft.configured !== false };
|
|
1051
|
-
}
|
|
1052
|
-
|
|
1053
|
-
const entry = {
|
|
1054
|
-
doctorText: withIdentity({ identity, review, doctorText: draft.doctorText }),
|
|
1055
|
-
patientMessage: draft.patientMessage,
|
|
1056
|
-
writtenBy: DRAFT_OPERATOR,
|
|
1057
|
-
protocolVersion: draft.protocolVersion,
|
|
1058
|
-
keyQuestions: draft.keyQuestions,
|
|
1059
|
-
unassessedRedFlags: draft.unassessedRedFlags,
|
|
1060
|
-
missingCharacterization: draft.missingCharacterization,
|
|
1061
|
-
...(draft.suggestCall && { suggestCall: draft.suggestCall }),
|
|
1062
|
-
...(draft.sectionsUnavailable?.length && { sectionsUnavailable: draft.sectionsUnavailable }),
|
|
1063
|
-
};
|
|
1064
|
-
// Every alarm or agent update re-arms draftDueAt, so a draft is only kept while draftDueAt still
|
|
1065
|
-
// holds the sweep's lease: a draft that missed newer material is dropped, and the next sweep writes
|
|
1066
|
-
// one that has it. A draft saved by hand meanwhile also wins.
|
|
1067
|
-
const saved = await getEscalationReview().findOneAndUpdate(
|
|
1068
|
-
{ _id: review._id, status: { $in: DOCUMENTING_STATUSES }, draftDueAt: lease, drafts: { $size: (review.drafts ?? []).length } },
|
|
1069
|
-
{ $push: { drafts: entry }, $set: { status: 'draft_ready', draftDueAt: null }, $unset: { identityBlock: '' } },
|
|
1070
|
-
{ new: true },
|
|
1071
|
-
).lean();
|
|
1072
|
-
if (saved) await audit(saved, DRAFT_OPERATOR, null, { action: 'draft_saved', draftNumber: saved.drafts.length });
|
|
1073
|
-
return { review: saved, retry: false };
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
653
|
async function noteFactsContext(review) {
|
|
1077
654
|
try {
|
|
1078
655
|
return await readContextFacts({ patientId: review.patientCode });
|
|
@@ -1217,20 +794,6 @@ async function suggestKeyQuestions({ id, requestedBy, requestId = null } = {}) {
|
|
|
1217
794
|
const review = await loadReview(reviewId);
|
|
1218
795
|
if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
|
|
1219
796
|
|
|
1220
|
-
// The draft already asks what the agent left open; the separate generator is only the fallback
|
|
1221
|
-
// for drafts written before the preset emitted key questions.
|
|
1222
|
-
const latest = (review.drafts ?? []).at(-1);
|
|
1223
|
-
if (latest?.keyQuestions?.length) {
|
|
1224
|
-
return {
|
|
1225
|
-
completed: true,
|
|
1226
|
-
source: 'draft',
|
|
1227
|
-
questions: latest.keyQuestions,
|
|
1228
|
-
redFlags: latest.unassessedRedFlags ?? [],
|
|
1229
|
-
missingCharacterization: latest.missingCharacterization ?? [],
|
|
1230
|
-
suggestCall: latest.suggestCall ?? null,
|
|
1231
|
-
};
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
797
|
const generated = await generateKeyQuestions({
|
|
1235
798
|
code: review.patientCode,
|
|
1236
799
|
callLogs: review.callLogs ?? [],
|
|
@@ -1294,9 +857,6 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
1294
857
|
if (draftedAt && (review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > draftedAt)) {
|
|
1295
858
|
throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
|
|
1296
859
|
}
|
|
1297
|
-
if (draftedAt && (review.updates ?? []).some((entry) => new Date(entry.at).getTime() > draftedAt)) {
|
|
1298
|
-
throw httpError(409, 'The agent characterized the case after this draft was written; review it and save a new draft before sending it to the doctor');
|
|
1299
|
-
}
|
|
1300
860
|
const identity = await readDoctorIdentity(review);
|
|
1301
861
|
if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
1302
862
|
const link = doctorLink(review);
|
|
@@ -1312,8 +872,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
1312
872
|
reviewId,
|
|
1313
873
|
[review.status],
|
|
1314
874
|
{ $set: { status: 'handing_off', operationClaim: claim } },
|
|
1315
|
-
|
|
1316
|
-
{ drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt },
|
|
875
|
+
{ drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length } },
|
|
1317
876
|
);
|
|
1318
877
|
let delivery = {};
|
|
1319
878
|
let updated;
|
|
@@ -1347,66 +906,35 @@ async function recordDoctorDecision({
|
|
|
1347
906
|
comment = null,
|
|
1348
907
|
doctorName = null,
|
|
1349
908
|
doctorReply = null,
|
|
1350
|
-
reason = null,
|
|
1351
|
-
draftNumber: seenDraftNumber = null,
|
|
1352
909
|
recordedBy,
|
|
1353
910
|
requestId = null,
|
|
1354
911
|
} = {}) {
|
|
1355
912
|
const reviewId = reviewIdOf(id);
|
|
1356
913
|
const operator = requiredText(recordedBy, 'recordedBy');
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
if (!sources.includes(source)) throw httpError(400, `source must be one of: ${sources.join(', ')}`);
|
|
1360
|
-
if (!decisions.includes(decision)) throw httpError(400, `decision must be one of: ${decisions.join(', ')}`);
|
|
914
|
+
if (!DECISION_SOURCES.includes(source)) throw httpError(400, `source must be one of: ${DECISION_SOURCES.join(', ')}`);
|
|
915
|
+
if (!DOCTOR_DECISIONS.includes(decision)) throw httpError(400, `decision must be one of: ${DOCTOR_DECISIONS.join(', ')}`);
|
|
1361
916
|
|
|
1362
|
-
// Anyone on the team decides in the platform for now; the decision records who did.
|
|
1363
917
|
let decidedBy = operator;
|
|
1364
918
|
let reply = null;
|
|
1365
|
-
if (source === '
|
|
919
|
+
if (source === 'platform') {
|
|
920
|
+
const approver = await getEscalationApprover(operator);
|
|
921
|
+
if (!approver) throw httpError(403, 'Only an escalation review approver can decide in the platform');
|
|
922
|
+
} else {
|
|
1366
923
|
decidedBy = requiredText(doctorName, 'doctorName');
|
|
1367
924
|
reply = requiredText(doctorReply, 'doctorReply');
|
|
1368
925
|
}
|
|
1369
|
-
let returnReason = null;
|
|
1370
|
-
if (decision === 'returned') {
|
|
1371
|
-
if (!RETURN_REASONS.includes(reason)) throw httpError(400, `reason must be one of: ${RETURN_REASONS.join(', ')}`);
|
|
1372
|
-
returnReason = reason;
|
|
1373
|
-
}
|
|
1374
926
|
|
|
1375
927
|
const review = await loadReview(reviewId);
|
|
1376
|
-
if (
|
|
1377
|
-
|
|
1378
|
-
const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
|
|
1379
|
-
const draftNumber = handoff?.draftNumber ?? review.drafts.length;
|
|
928
|
+
if (review.status !== 'awaiting_doctor') throw httpError(409, STATUS_CONFLICT);
|
|
929
|
+
const { draftNumber } = review.doctorHandoffs[review.doctorHandoffs.length - 1];
|
|
1380
930
|
const draft = review.drafts[draftNumber - 1];
|
|
1381
|
-
if (!draft) throw httpError(409, STATUS_CONFLICT);
|
|
1382
|
-
// The caller says which draft it showed; a newer one written meanwhile was never read.
|
|
1383
|
-
if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
|
|
1384
|
-
|
|
1385
931
|
let approvedText = null;
|
|
1386
932
|
if (decision === 'approved') approvedText = draft.patientMessage;
|
|
1387
933
|
if (decision === 'edited_approved') approvedText = requiredText(finalText, 'finalText');
|
|
1388
934
|
// Truthiness, not != null: an empty textarea is a decline with nothing to say.
|
|
1389
935
|
if (decision === 'needs_intervention' && finalText) approvedText = requiredText(finalText, 'finalText');
|
|
1390
936
|
|
|
1391
|
-
|
|
1392
|
-
// A handed-off review cannot take a new draft where it is, so it goes back to be re-drafted:
|
|
1393
|
-
// by the bot when the overtaken draft was its own, by a person otherwise.
|
|
1394
|
-
if (review.status === 'awaiting_doctor') {
|
|
1395
|
-
const redraft = draft.writtenBy === DRAFT_OPERATOR ? { draftDueAt: new Date(), draftAttempts: 0 } : {};
|
|
1396
|
-
const returned = await updateReview(reviewId, ['awaiting_doctor'], { $set: { status: 'documenting', ...redraft } }, {
|
|
1397
|
-
doctorHandoffs: { $size: review.doctorHandoffs.length },
|
|
1398
|
-
drafts: { $size: review.drafts.length },
|
|
1399
|
-
});
|
|
1400
|
-
await audit(returned, operator, requestId, {
|
|
1401
|
-
action: 'handoff_overtaken', decision, source, draftNumber, ...(reply && { decidedBy, doctorReply: reply }),
|
|
1402
|
-
});
|
|
1403
|
-
throw httpError(409, STALE_HANDOFF);
|
|
1404
|
-
}
|
|
1405
|
-
throw httpError(409, STALE_DRAFT);
|
|
1406
|
-
}
|
|
1407
|
-
const warnings = decision === 'edited_approved' ? draftlessDrugWarnings(approvedText, draft) : [];
|
|
1408
|
-
|
|
1409
|
-
const updated = await updateReview(reviewId, DECIDABLE_STATUSES, {
|
|
937
|
+
const updated = await updateReview(reviewId, ['awaiting_doctor'], {
|
|
1410
938
|
$push: {
|
|
1411
939
|
decisions: {
|
|
1412
940
|
decision,
|
|
@@ -1415,110 +943,16 @@ async function recordDoctorDecision({
|
|
|
1415
943
|
finalText: approvedText,
|
|
1416
944
|
comment: optionalText(comment),
|
|
1417
945
|
doctorReply: reply,
|
|
1418
|
-
...(returnReason && { returnReason }),
|
|
1419
|
-
...(warnings.length && { warnings }),
|
|
1420
946
|
decidedBy,
|
|
1421
947
|
recordedBy: operator,
|
|
1422
948
|
},
|
|
1423
949
|
},
|
|
1424
|
-
|
|
1425
|
-
$set: returnReason === 'no_requiere'
|
|
1426
|
-
? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}` }
|
|
1427
|
-
: { status: statusAfter(decision) },
|
|
1428
|
-
}, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length } });
|
|
1429
|
-
await audit(updated, operator, requestId, {
|
|
1430
|
-
action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
|
|
950
|
+
$set: { status: statusAfter(decision) },
|
|
1431
951
|
});
|
|
1432
|
-
|
|
1433
|
-
await audit(updated, operator, requestId, { action: 'cancelled', reason: updated.cancellationReason });
|
|
1434
|
-
const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
|
|
1435
|
-
return cancelled;
|
|
1436
|
-
}
|
|
952
|
+
await audit(updated, operator, requestId, { action: 'doctor_decision', decision, source, draftNumber });
|
|
1437
953
|
return updated;
|
|
1438
954
|
}
|
|
1439
955
|
|
|
1440
|
-
// An approver writing to the patient in the chat delivers the indication themselves: the open
|
|
1441
|
-
// review is resolved with what they wrote and moves to follow-up. Anyone else's message is not.
|
|
1442
|
-
// The case selection a write was built from; a review from before the list holds a single case id.
|
|
1443
|
-
const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
1444
|
-
? { patientCaseRecordIds: review.patientCaseRecordIds }
|
|
1445
|
-
: { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
|
|
1446
|
-
|
|
1447
|
-
async function recordDirectIndication({ code, triggeredBy, body, messageId = null, status = null, deferred = false } = {}) {
|
|
1448
|
-
try {
|
|
1449
|
-
const text = String(body ?? '').trim();
|
|
1450
|
-
const operator = String(triggeredBy ?? '').trim();
|
|
1451
|
-
if (!text || !operator) return null;
|
|
1452
|
-
const patientCode = patientCodeOf(code);
|
|
1453
|
-
const EscalationReview = getEscalationReview();
|
|
1454
|
-
const openReview = (only = {}) => EscalationReview
|
|
1455
|
-
.findOne({ patientCode, closedAt: null, status: { $in: DIRECT_CHAT_STATUSES }, ...only })
|
|
1456
|
-
.lean();
|
|
1457
|
-
let review = await openReview();
|
|
1458
|
-
if (!review) return null;
|
|
1459
|
-
if (!await getEscalationApprover(operator)) return null;
|
|
1460
|
-
|
|
1461
|
-
// The write names the cases it mirrors to; a selection changed in between is read again.
|
|
1462
|
-
for (let attempt = 1; review && attempt <= DIRECT_CHAT_ATTEMPTS; attempt += 1) {
|
|
1463
|
-
const decisionNumber = (review.decisions ?? []).length + 1;
|
|
1464
|
-
// The doctor's own words become the cases' recommendation, as an approved send would.
|
|
1465
|
-
const updated = await EscalationReview.findOneAndUpdate(
|
|
1466
|
-
{ _id: review._id, status: review.status, closedAt: null, ...casesAsRead(review) },
|
|
1467
|
-
withCaseMirror(review, {
|
|
1468
|
-
$push: {
|
|
1469
|
-
decisions: {
|
|
1470
|
-
decision: 'direct_chat',
|
|
1471
|
-
source: 'chat',
|
|
1472
|
-
draftNumber: (review.drafts ?? []).length,
|
|
1473
|
-
finalText: text,
|
|
1474
|
-
decidedBy: operator,
|
|
1475
|
-
recordedBy: operator,
|
|
1476
|
-
},
|
|
1477
|
-
},
|
|
1478
|
-
// A send still waiting on the 24 h window is queued for template recovery, exactly as an approved send.
|
|
1479
|
-
$set: {
|
|
1480
|
-
status: deferred ? 'indications_queued' : 'indications_sent',
|
|
1481
|
-
patientDelivery: {
|
|
1482
|
-
decisionNumber,
|
|
1483
|
-
messageId,
|
|
1484
|
-
status: optionalText(status),
|
|
1485
|
-
transport: deferred ? 'template_recovery' : 'text',
|
|
1486
|
-
deferred: Boolean(deferred),
|
|
1487
|
-
sentBy: operator,
|
|
1488
|
-
},
|
|
1489
|
-
},
|
|
1490
|
-
}, { recommendation: text.slice(0, MAX_NOTE_LENGTH) }),
|
|
1491
|
-
{ new: true },
|
|
1492
|
-
).lean();
|
|
1493
|
-
if (updated) {
|
|
1494
|
-
await audit(updated, operator, null, { action: 'direct_chat_resolved', decisionNumber, statusFrom: review.status });
|
|
1495
|
-
const { review: synced } = await syncCase(updated, operator, null);
|
|
1496
|
-
return synced;
|
|
1497
|
-
}
|
|
1498
|
-
// Only the review this message was meant for: one opened since then never saw it.
|
|
1499
|
-
if (attempt < DIRECT_CHAT_ATTEMPTS) review = await openReview({ _id: review._id });
|
|
1500
|
-
}
|
|
1501
|
-
return null;
|
|
1502
|
-
} catch (error) {
|
|
1503
|
-
logger.error('[EscalationReview] An approver message could not resolve the open review', {
|
|
1504
|
-
error: redactedError(error), stack: redactedStack(error),
|
|
1505
|
-
});
|
|
1506
|
-
return null;
|
|
1507
|
-
}
|
|
1508
|
-
}
|
|
1509
|
-
|
|
1510
|
-
const arrivedAfter = (review, since) => Boolean(since) && [
|
|
1511
|
-
...(review.alarms ?? []).map((alarm) => alarm.raisedAt),
|
|
1512
|
-
...(review.updates ?? []).map((update) => update.at),
|
|
1513
|
-
].some((at) => at && new Date(at) > new Date(since));
|
|
1514
|
-
|
|
1515
|
-
// The edited text may name a drug the draft never proposed. The doctor decides; the warning only
|
|
1516
|
-
// leaves a trace of it next to the decision.
|
|
1517
|
-
const draftlessDrugWarnings = (text, draft) => {
|
|
1518
|
-
const drafted = new Set(drugsNamedIn(`${draft.doctorText} ${draft.patientMessage}`));
|
|
1519
|
-
return drugsNamedIn(text).filter((drug) => !drafted.has(drug)).map((drug) => `el texto editado menciona ${drug}, que no estaba en el borrador`);
|
|
1520
|
-
};
|
|
1521
|
-
|
|
1522
956
|
async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy, requestId = null } = {}) {
|
|
1523
957
|
const reviewId = reviewIdOf(id);
|
|
1524
958
|
const operator = requiredText(sentBy, 'sentBy');
|
|
@@ -1541,17 +975,6 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
1541
975
|
throw httpError(409, 'This decision carries no approved text to send to the patient');
|
|
1542
976
|
}
|
|
1543
977
|
|
|
1544
|
-
const decidedAt = claimed.decisions[decisionNumber - 1].createdAt;
|
|
1545
|
-
if (decidedAt && (claimed.updates ?? []).some((entry) => new Date(entry.at) > new Date(decidedAt))) {
|
|
1546
|
-
// Back to documenting: the decision is spent, and a new draft and decision have to follow.
|
|
1547
|
-
await releaseReview(reviewId, 'sending', 'documenting', claim).catch((releaseError) => {
|
|
1548
|
-
logger.error('[EscalationReview] The claim was not released after a decision new information overtook', {
|
|
1549
|
-
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
1550
|
-
});
|
|
1551
|
-
});
|
|
1552
|
-
throw httpError(409, 'The agent characterized the case after this decision; it went back to documenting for a new draft and decision');
|
|
1553
|
-
}
|
|
1554
|
-
|
|
1555
978
|
// Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
|
|
1556
979
|
let message;
|
|
1557
980
|
try {
|
|
@@ -1603,9 +1026,27 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
1603
1026
|
}, { recommendation: finalText });
|
|
1604
1027
|
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
|
|
1605
1028
|
await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1029
|
+
const sent = await syncCase(review, operator, requestId);
|
|
1030
|
+
if (review.status !== 'indications_sent' || decision === 'needs_intervention') return sent;
|
|
1031
|
+
const decidedDraft = review.decisions[decisionNumber - 1]?.draftNumber;
|
|
1032
|
+
const handoff = (review.doctorHandoffs ?? []).findLast((entry) => entry.draftNumber === decidedDraft);
|
|
1033
|
+
if (handoff?.alarmCount == null || (review.alarms ?? []).length > handoff.alarmCount) {
|
|
1034
|
+
logger.warn('[EscalationReview] The doctor did not see every alarm on this review; it stays open for them', {
|
|
1035
|
+
escalationReviewId: String(review._id),
|
|
1036
|
+
});
|
|
1037
|
+
return sent;
|
|
1038
|
+
}
|
|
1039
|
+
try {
|
|
1040
|
+
const closed = await closeEscalationReview({ id: reviewId, closedBy: operator, requestId, expectedAlarmCount: (review.alarms ?? []).length });
|
|
1041
|
+
return closed;
|
|
1042
|
+
} catch (error) {
|
|
1043
|
+
const stored = await loadReview(reviewId).catch(() => sent.review);
|
|
1044
|
+
let note = 'The indications were delivered but the review did not close; close it by hand';
|
|
1045
|
+
if (stored.status === 'closed') note = 'The review closed, but a step after closing failed';
|
|
1046
|
+
else if (error.statusCode === 409) note = 'An alarm joined while the review was closing; it stays open for it';
|
|
1047
|
+
logger.error(`[EscalationReview] ${note}`, { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
1048
|
+
return { ...sent, review: stored };
|
|
1049
|
+
}
|
|
1609
1050
|
}
|
|
1610
1051
|
|
|
1611
1052
|
const EPISODE_TRUST = 0.7;
|
|
@@ -1664,9 +1105,7 @@ async function recordEpisode(review, now = new Date()) {
|
|
|
1664
1105
|
}
|
|
1665
1106
|
}
|
|
1666
1107
|
|
|
1667
|
-
async function closeEscalationReview({
|
|
1668
|
-
id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null, expectedAlarmCount = null, expectedUpdatedAt = null,
|
|
1669
|
-
} = {}) {
|
|
1108
|
+
async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null, expectedAlarmCount = null } = {}) {
|
|
1670
1109
|
const reviewId = reviewIdOf(id);
|
|
1671
1110
|
const operator = requiredText(closedBy, 'closedBy');
|
|
1672
1111
|
|
|
@@ -1694,7 +1133,6 @@ async function closeEscalationReview({
|
|
|
1694
1133
|
{
|
|
1695
1134
|
...(interrupted ? { operationClaim: current.operationClaim ?? null } : {}),
|
|
1696
1135
|
...(expectedAlarmCount === null ? {} : { alarms: { $size: expectedAlarmCount } }),
|
|
1697
|
-
...(expectedUpdatedAt === null ? {} : { updatedAt: expectedUpdatedAt }),
|
|
1698
1136
|
},
|
|
1699
1137
|
);
|
|
1700
1138
|
const closeChanges = { action: interrupted ? 'closed_from_interruption' : 'closed' };
|
|
@@ -1723,15 +1161,13 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
|
|
|
1723
1161
|
|
|
1724
1162
|
let review;
|
|
1725
1163
|
try {
|
|
1726
|
-
// Once the doctor has seen or decided the review, cancelling it needs a reason whatever its status.
|
|
1727
1164
|
review = await updateReview(reviewId, allowed, {
|
|
1728
1165
|
$set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
|
|
1729
|
-
}
|
|
1166
|
+
});
|
|
1730
1167
|
} catch (error) {
|
|
1731
1168
|
if (error?.statusCode !== 409 || notes) throw error;
|
|
1732
1169
|
const current = await loadReview(reviewId);
|
|
1733
|
-
|
|
1734
|
-
if (doctorInvolved || CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
|
|
1170
|
+
if (CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
|
|
1735
1171
|
throw error;
|
|
1736
1172
|
}
|
|
1737
1173
|
|
|
@@ -1751,17 +1187,12 @@ module.exports = {
|
|
|
1751
1187
|
addDraft,
|
|
1752
1188
|
cancelEscalationReview,
|
|
1753
1189
|
closeEscalationReview,
|
|
1754
|
-
generateBotDraft,
|
|
1755
1190
|
getEscalationReviewById,
|
|
1756
|
-
getReviewTimeline,
|
|
1757
1191
|
handOffToDoctor,
|
|
1758
1192
|
listEscalationReviews,
|
|
1759
1193
|
openEscalationReview,
|
|
1760
1194
|
recordEscalationAlarm,
|
|
1761
|
-
recordDirectIndication,
|
|
1762
1195
|
recordDoctorDecision,
|
|
1763
|
-
sendScheduledDoctorAlert,
|
|
1764
|
-
recordReviewUpdate,
|
|
1765
1196
|
sendApprovedIndications,
|
|
1766
1197
|
setReviewCases,
|
|
1767
1198
|
suggestDraft,
|