@peopl-health/nexus 6.5.0-dev.19149 → 6.5.0-dev.20074
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 +3 -1
- package/lib/clinical/config/planTextsConfig.js +41 -0
- package/lib/clinical/flags/escalationFlags.js +15 -0
- package/lib/clinical/helpers/doctorPlanHelper.js +32 -23
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +72 -2
- package/lib/clinical/helpers/legacyContextHelper.js +6 -2
- package/lib/clinical/helpers/planTextHelper.js +9 -2
- package/lib/clinical/protocols/treatmentFormulary.js +3 -3
- package/lib/clinical/services/bridgeService.js +2 -2
- package/lib/clinical/services/checkInDueService.js +3 -2
- package/lib/clinical/services/clinicalAirtableService.js +3 -2
- package/lib/clinical/services/clinicalExtractionService.js +9 -2
- package/lib/clinical/services/contingencyDispatchService.js +8 -4
- package/lib/clinical/services/doctorPlanService.js +27 -11
- package/lib/clinical/tools/deliverPatientMessageTool.js +1 -1
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
- package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
- package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +10 -1
- package/lib/config/awsConfig.js +1 -1
- package/lib/controllers/assistantController.js +5 -2
- package/lib/controllers/escalationReviewController.js +16 -3
- package/lib/controllers/messageController.js +5 -6
- package/lib/core/NexusMessaging.js +16 -18
- package/lib/fhir/constants/escalationCaseStatus.js +1 -1
- package/lib/helpers/caregiverHelper.js +8 -0
- package/lib/helpers/templateFlowControllerHelper.js +9 -48
- package/lib/index.d.ts +3 -3
- package/lib/models/escalationReviewModel.js +32 -2
- package/lib/services/assistantMessageService.js +11 -6
- package/lib/services/caseFollowUpService.js +226 -0
- package/lib/services/caseFollowUpSweepService.js +89 -0
- package/lib/services/characterizationOutcomeService.js +27 -15
- package/lib/services/escalationCaseStateService.js +68 -0
- package/lib/services/escalationReviewService.js +123 -37
- package/lib/services/flowDataExchangeService.js +6 -35
- package/lib/services/reviewAlertSweepService.js +19 -1
- package/lib/services/reviewBoardService.js +24 -6
- package/lib/services/reviewDeadlineService.js +1 -1
- package/lib/services/untakenAlertService.js +9 -7
- package/lib/services/watchExpiryService.js +162 -0
- package/lib/utils/coercionUtils.js +5 -1
- package/lib/utils/textMatchUtils.js +52 -18
- package/package.json +1 -1
|
@@ -30,11 +30,13 @@ const { ensureWhatsAppFormat, whatsAppCodeFromPhone } = require('../helpers/twil
|
|
|
30
30
|
const { DrainingError } = require('../core/BatchingManager');
|
|
31
31
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
32
32
|
const { conversationLink, readGroupMessageId, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
33
|
-
const { doctorAlertHeadline, doctorAlertOpener, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
33
|
+
const { doctorAlertHeadline, doctorAlertOpener, doctorBrief, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
34
34
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
35
35
|
const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
|
|
36
36
|
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
37
|
-
const {
|
|
37
|
+
const { getPlanTexts } = require('../clinical/config/planTextsConfig');
|
|
38
|
+
const { retireSilenceNets } = require('../clinical/services/contingencyDispatchService');
|
|
39
|
+
const { DEFAULT_FOLLOW_UP_HOURS, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
|
|
38
40
|
const { approvedInstructions, planOf, replyIssues } = require('../clinical/services/doctorPlanService');
|
|
39
41
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
40
42
|
const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
|
|
@@ -50,6 +52,7 @@ const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper
|
|
|
50
52
|
const { composePrompt } = require('../clinical/services/promptComposerService');
|
|
51
53
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
52
54
|
const { ageFrom, birthDateFrom } = require('../fhir/resources/Patient');
|
|
55
|
+
const { armCaseFollowUp, cancelCaseFollowUp } = require('./caseFollowUpService');
|
|
53
56
|
|
|
54
57
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
55
58
|
const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
|
|
@@ -106,6 +109,7 @@ const AIRTABLE_TRANSPORT = 'airtable';
|
|
|
106
109
|
const NOT_RECORDED = 'no se registró en Airtable';
|
|
107
110
|
const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
|
|
108
111
|
const SAME_URGENCY = 'The review is already at that urgency';
|
|
112
|
+
const STAT_WATCH = 'A stat case is not watched at home; lower its urgency with a reason first';
|
|
109
113
|
const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
|
|
110
114
|
const DIRECT_CHAT_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor', 'approved', 'needs_intervention'];
|
|
111
115
|
const APPROVALS = ['approved', 'edited_approved', 'plan_approved'];
|
|
@@ -145,6 +149,8 @@ const reviewIdOf = (id) => {
|
|
|
145
149
|
|
|
146
150
|
// The template per kind of doctor alert; one not configured yet falls back to the identified alert.
|
|
147
151
|
const DOCTOR_ALERT_TEMPLATE_KEYS = { act_now: 'ESCALATION_REVIEW_DOCTOR_ACT_NOW_CONTENT_SID', ready: 'ESCALATION_REVIEW_DOCTOR_READY_CONTENT_SID' };
|
|
152
|
+
// Until Meta approves this template the earlier alerts keep going out.
|
|
153
|
+
const DOCTOR_BRIEF_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_BRIEF_CONTENT_SID';
|
|
148
154
|
|
|
149
155
|
const configured = (key) => {
|
|
150
156
|
const value = runtimeConfig.get(key);
|
|
@@ -521,7 +527,8 @@ async function recordReviewUpdate({ code, update, now = new Date(), settleInBack
|
|
|
521
527
|
|
|
522
528
|
if (FOLLOWUP_STATUSES.includes(pushed.status)) {
|
|
523
529
|
await audit(pushed, AGENT_OPERATOR, null, { action: 'case_updated', turnId: update.turnId, tools: update.tools });
|
|
524
|
-
|
|
530
|
+
const canClose = !(pushed.alarms ?? []).some((alarm) => alarm.isHeldInFollowUp && alarm.turnId === update.turnId);
|
|
531
|
+
return await settleFollowUp(pushed, { background: settleInBackground, canClose });
|
|
525
532
|
}
|
|
526
533
|
|
|
527
534
|
const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
|
|
@@ -567,7 +574,26 @@ async function closeStaleInterruption(EscalationReview, patientCode, now) {
|
|
|
567
574
|
}
|
|
568
575
|
}
|
|
569
576
|
|
|
570
|
-
|
|
577
|
+
function shouldHoldInFollowUp(review, alarm, mode) {
|
|
578
|
+
if (mode !== 'update' || ALERTED_URGENCIES.includes(alarm.urgencyLevel)) return false;
|
|
579
|
+
const decided = effectiveUrgencyOf({ ...review, alarms: (review.alarms ?? []).filter((entry) => entry.alarmId !== alarm.alarmId) })?.urgency;
|
|
580
|
+
return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
async function holdInFollowUp(review, alarm) {
|
|
584
|
+
const held = await getEscalationReview()
|
|
585
|
+
.findOneAndUpdate(
|
|
586
|
+
{ _id: review._id, status: review.status, 'alarms.alarmId': alarm.alarmId },
|
|
587
|
+
{ $set: { 'alarms.$.isHeldInFollowUp': true, updatedSinceSeen: true } },
|
|
588
|
+
{ new: true },
|
|
589
|
+
)
|
|
590
|
+
.lean();
|
|
591
|
+
if (!held) return review;
|
|
592
|
+
await audit(held, AGENT_OPERATOR, null, { action: 'followup_result', result: 'update_held', statusFrom: review.status });
|
|
593
|
+
return held;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date() } = {}) {
|
|
571
597
|
try {
|
|
572
598
|
const patientCode = patientCodeOf(code);
|
|
573
599
|
const entry = { ...alarm, raisedAt: alarm?.raisedAt ?? now };
|
|
@@ -583,7 +609,9 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
|
583
609
|
if (joined) {
|
|
584
610
|
await scheduleDoctorAlert(joined, entry, now);
|
|
585
611
|
await armPatientTimerOnJoin(joined, entry, now);
|
|
586
|
-
if (FOLLOWUP_STATUSES.includes(joined.status))
|
|
612
|
+
if (FOLLOWUP_STATUSES.includes(joined.status)) {
|
|
613
|
+
return shouldHoldInFollowUp(joined, entry, mode) ? await holdInFollowUp(joined, entry) : await reopenFromFollowUp(joined, 'new_alarm');
|
|
614
|
+
}
|
|
587
615
|
if (!DOCUMENTING_STATUSES.includes(joined.status)) {
|
|
588
616
|
logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
|
|
589
617
|
escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
|
|
@@ -615,7 +643,7 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
|
615
643
|
}
|
|
616
644
|
|
|
617
645
|
function escalationAnchorOf(review, alarmId) {
|
|
618
|
-
const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId);
|
|
646
|
+
const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId && !alarm.isHeldInFollowUp);
|
|
619
647
|
if (!prior.length) return null;
|
|
620
648
|
const levelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
|
|
621
649
|
const rankOf = (alarm) => URGENCY_RANK[levelOf(alarm)] || 0;
|
|
@@ -792,9 +820,9 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
|
|
|
792
820
|
};
|
|
793
821
|
}
|
|
794
822
|
|
|
795
|
-
function previewPlanInstructions({ id, plan } = {}) {
|
|
823
|
+
async function previewPlanInstructions({ id, plan } = {}) {
|
|
796
824
|
reviewIdOf(id);
|
|
797
|
-
return planInstructions(planOf(plan));
|
|
825
|
+
return planInstructions(planOf(plan), await getPlanTexts());
|
|
798
826
|
}
|
|
799
827
|
|
|
800
828
|
async function getReviewTimeline({ id } = {}) {
|
|
@@ -1406,12 +1434,21 @@ async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel
|
|
|
1406
1434
|
}
|
|
1407
1435
|
}
|
|
1408
1436
|
|
|
1409
|
-
async function reopenFromFollowUp(review, reason) {
|
|
1437
|
+
async function reopenFromFollowUp(review, reason, { background = false } = {}) {
|
|
1410
1438
|
const reopened = await getEscalationReview()
|
|
1411
1439
|
.findOneAndUpdate({ _id: review._id, status: review.status }, { $set: { status: 'documenting', updatedSinceSeen: true } }, { new: true })
|
|
1412
1440
|
.lean();
|
|
1413
1441
|
if (!reopened) return review;
|
|
1414
1442
|
await audit(reopened, AGENT_OPERATOR, null, { action: 'followup_result', result: reason, statusFrom: review.status });
|
|
1443
|
+
await cancelCaseFollowUp(reopened, 'case_reopened');
|
|
1444
|
+
// A new alarm already reaches the group through its emergency row.
|
|
1445
|
+
if (reason === 'worsening') {
|
|
1446
|
+
const notice = noticeCaseThread(reopened, {
|
|
1447
|
+
header: '📈 La paciente va peor después de la decisión del médico', kind: 'worsening',
|
|
1448
|
+
action: 'Qué hacer: llamar a la paciente y, si hace falta, pedirle al médico una nueva indicación',
|
|
1449
|
+
});
|
|
1450
|
+
if (!background) await notice;
|
|
1451
|
+
}
|
|
1415
1452
|
return reopened;
|
|
1416
1453
|
}
|
|
1417
1454
|
|
|
@@ -1455,7 +1492,7 @@ async function closeSettled(review) {
|
|
|
1455
1492
|
}
|
|
1456
1493
|
}
|
|
1457
1494
|
|
|
1458
|
-
async function settleFollowUp(snapshot, { background = true } = {}) {
|
|
1495
|
+
async function settleFollowUp(snapshot, { background = true, canClose = true } = {}) {
|
|
1459
1496
|
const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
|
|
1460
1497
|
if (!since) return snapshot;
|
|
1461
1498
|
const sinceMs = new Date(since).getTime();
|
|
@@ -1469,9 +1506,9 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
|
|
|
1469
1506
|
.filter((impression) => known.has(impression.caseId) && readingOf(impression))
|
|
1470
1507
|
.forEach((impression) => latest.set(impression.caseId, readingOf(impression))));
|
|
1471
1508
|
|
|
1472
|
-
if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
|
|
1509
|
+
if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening', { background });
|
|
1473
1510
|
const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
|
|
1474
|
-
if (!settled || !SETTLEABLE_STATUSES.includes(review.status)) {
|
|
1511
|
+
if (!settled || !canClose || !SETTLEABLE_STATUSES.includes(review.status)) {
|
|
1475
1512
|
await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
|
|
1476
1513
|
return review;
|
|
1477
1514
|
}
|
|
@@ -1756,6 +1793,35 @@ async function soleApprover() {
|
|
|
1756
1793
|
return approvers[0];
|
|
1757
1794
|
}
|
|
1758
1795
|
|
|
1796
|
+
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom }) {
|
|
1797
|
+
const briefSid = runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
|
|
1798
|
+
// A navigator's draft is free text with no symptoms or flags to summarize, so it keeps the full alert.
|
|
1799
|
+
if (briefSid && draft.symptoms?.length) {
|
|
1800
|
+
const policy = responseDeadlinePolicy();
|
|
1801
|
+
const lead = effectiveUrgencyOf(review);
|
|
1802
|
+
const lines = doctorBrief({
|
|
1803
|
+
kind,
|
|
1804
|
+
level: level ?? lead?.urgency,
|
|
1805
|
+
identity,
|
|
1806
|
+
draft,
|
|
1807
|
+
alarmSymptom: symptom ?? lead?.symptom,
|
|
1808
|
+
deadline: responseDeadlineOf(review, policy)?.dueAt,
|
|
1809
|
+
timeZone: policy.teamHours.timeZone,
|
|
1810
|
+
link,
|
|
1811
|
+
});
|
|
1812
|
+
return { body: lines.join('\n'), template: Object.fromEntries(lines.map((line, index) => [index + 1, line])), contentSid: briefSid };
|
|
1813
|
+
}
|
|
1814
|
+
const headline = kind && doctorAlertHeadline({ review, kind, note, level, symptom });
|
|
1815
|
+
const kindSid = kind ? runtimeConfig.get(DOCTOR_ALERT_TEMPLATE_KEYS[kind]) : null;
|
|
1816
|
+
return {
|
|
1817
|
+
body: [headline ? doctorAlertOpener(kind, headline) : note, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
|
|
1818
|
+
template: kindSid
|
|
1819
|
+
? { 1: headline, 2: oneLineOf(identity.patientName), 3: oneLineOf(identity.treatingDoctor), 4: link }
|
|
1820
|
+
: { 1: oneLineOf(identity.patientName), 2: oneLineOf(identity.treatingDoctor), 3: oneLineOf([templateSummary(review, { level, symptom }), note].filter(Boolean).join(' · ')), 4: link },
|
|
1821
|
+
...(kindSid && { contentSid: kindSid }),
|
|
1822
|
+
};
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1759
1825
|
// 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.
|
|
1760
1826
|
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
|
|
1761
1827
|
const reviewId = reviewIdOf(id);
|
|
@@ -1783,15 +1849,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
1783
1849
|
const identity = await readDoctorIdentity(review);
|
|
1784
1850
|
if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
1785
1851
|
const link = doctorLink(review);
|
|
1786
|
-
const
|
|
1787
|
-
const kindSid = kind ? runtimeConfig.get(DOCTOR_ALERT_TEMPLATE_KEYS[kind]) : null;
|
|
1788
|
-
const message = {
|
|
1789
|
-
body: [headline ? doctorAlertOpener(kind, headline) : note, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
|
|
1790
|
-
template: kindSid
|
|
1791
|
-
? { 1: headline, 2: oneLineOf(identity.patientName), 3: oneLineOf(identity.treatingDoctor), 4: link }
|
|
1792
|
-
: { 1: oneLineOf(identity.patientName), 2: oneLineOf(identity.treatingDoctor), 3: oneLineOf([templateSummary(review, { level, symptom }), note].filter(Boolean).join(' · ')), 4: link },
|
|
1793
|
-
...(kindSid && { contentSid: kindSid }),
|
|
1794
|
-
};
|
|
1852
|
+
const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom });
|
|
1795
1853
|
|
|
1796
1854
|
const patientCaseRecordIds = await reviewCaseIds(review);
|
|
1797
1855
|
|
|
@@ -1870,7 +1928,7 @@ async function recordDoctorDecision({
|
|
|
1870
1928
|
// The plan names the draft it started from, so a newer draft is refused instead of decided unseen.
|
|
1871
1929
|
if (seenDraftNumber === null) throw httpError(400, 'draftNumber is required for a plan');
|
|
1872
1930
|
plan = planOf(requestedPlan);
|
|
1873
|
-
plan = { ...plan, ...approvedInstructions(plan, instructions) };
|
|
1931
|
+
plan = { ...plan, ...approvedInstructions(plan, instructions, await getPlanTexts()) };
|
|
1874
1932
|
// Anyone may record a plan, often beside the doctor; one with a drug, study, note or edit names the doctor who gave it.
|
|
1875
1933
|
const namesDrug = drugsNamedIn(plan.homeCare.join(' ')).length > 0;
|
|
1876
1934
|
if (needsPrescriber(plan) || plan.note || plan.instructionsEdited || namesDrug) {
|
|
@@ -1883,6 +1941,15 @@ async function recordDoctorDecision({
|
|
|
1883
1941
|
const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
|
|
1884
1942
|
const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
|
|
1885
1943
|
if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
|
|
1944
|
+
let monitoringUntil = null;
|
|
1945
|
+
if (decision === 'monitor') {
|
|
1946
|
+
// Team rule (2026-10-31): stat goes to the ER; watching one at home first takes a lowering with its reason.
|
|
1947
|
+
const open = currentAlarms(review);
|
|
1948
|
+
if (effectiveUrgencyOf({ ...review, alarms: open.length ? open : review.alarms })?.urgency === 'stat') throw httpError(409, STAT_WATCH);
|
|
1949
|
+
// A watch recorded by someone who is not an approver names the doctor who ordered it.
|
|
1950
|
+
if (source === 'platform' && !await isEscalationApprover(operator)) decidedBy = requiredText(doctorName, 'doctorName');
|
|
1951
|
+
monitoringUntil = new Date(Date.now() + DEFAULT_FOLLOW_UP_HOURS.vigilancia * 60 * 60 * 1000);
|
|
1952
|
+
}
|
|
1886
1953
|
const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
|
|
1887
1954
|
// The panel shows the latest draft, so a doctor deciding on a bot update not sent yet decides on that one.
|
|
1888
1955
|
const onUnsentUpdate = handoff?.sentBy === AUTO_HANDOFF_OPERATOR && Number(seenDraftNumber) === review.drafts.length
|
|
@@ -1932,11 +1999,13 @@ async function recordDoctorDecision({
|
|
|
1932
1999
|
},
|
|
1933
2000
|
$set: returnReason === 'no_requiere'
|
|
1934
2001
|
? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}`, ...(closingIds && { closingCaseIds: closingIds }) }
|
|
1935
|
-
: { status: statusAfter(decision) },
|
|
2002
|
+
: { status: statusAfter(decision), ...(monitoringUntil && { monitoringUntil }) },
|
|
1936
2003
|
}, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
|
|
1937
2004
|
await audit(updated, operator, requestId, {
|
|
1938
2005
|
action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
|
|
1939
2006
|
});
|
|
2007
|
+
if (decision !== 'returned' || returnReason === 'no_requiere') await retireSilenceNetsAfter(updated);
|
|
2008
|
+
if (decision === 'monitor') await armCaseFollowUp(updated);
|
|
1940
2009
|
if (returnReason === 'no_requiere') {
|
|
1941
2010
|
await audit(updated, operator, requestId, { action: 'cancelled', reason: updated.cancellationReason });
|
|
1942
2011
|
const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
|
|
@@ -1949,6 +2018,16 @@ const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
|
|
|
1949
2018
|
? { patientCaseRecordIds: review.patientCaseRecordIds }
|
|
1950
2019
|
: { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
|
|
1951
2020
|
|
|
2021
|
+
async function retireSilenceNetsAfter(review) {
|
|
2022
|
+
try {
|
|
2023
|
+
await retireSilenceNets({ patientCode: review.patientCode });
|
|
2024
|
+
} catch (error) {
|
|
2025
|
+
logger.warn('[EscalationReview] The escalation check-in was not retired after the decision or cancel', {
|
|
2026
|
+
escalationReviewId: String(review._id), error: redactedError(error),
|
|
2027
|
+
});
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
|
|
1952
2031
|
async function recordDirectIndication({ code, triggeredBy, body, messageId = null, status = null, deferred = false } = {}) {
|
|
1953
2032
|
try {
|
|
1954
2033
|
const text = String(body ?? '').trim();
|
|
@@ -1994,6 +2073,8 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
|
|
|
1994
2073
|
).lean();
|
|
1995
2074
|
if (updated) {
|
|
1996
2075
|
await audit(updated, operator, null, { action: 'direct_chat_resolved', decisionNumber, statusFrom: review.status });
|
|
2076
|
+
await retireSilenceNetsAfter(updated);
|
|
2077
|
+
if (!deferred) await armCaseFollowUp(updated);
|
|
1997
2078
|
const { review: synced } = await syncCase(updated, operator, null);
|
|
1998
2079
|
return synced;
|
|
1999
2080
|
}
|
|
@@ -2131,6 +2212,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2131
2212
|
}, { recommendation: finalText });
|
|
2132
2213
|
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status).catch((error) => { throw withSendCode(error, SEND_UNCONFIRMED); });
|
|
2133
2214
|
await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
|
|
2215
|
+
if (!deferred) await armCaseFollowUp(review);
|
|
2134
2216
|
return syncCase(review, operator, requestId);
|
|
2135
2217
|
}
|
|
2136
2218
|
|
|
@@ -2157,20 +2239,17 @@ function replyOutcome(delivery, sendThrew) {
|
|
|
2157
2239
|
return 'unknown';
|
|
2158
2240
|
}
|
|
2159
2241
|
|
|
2160
|
-
// A notice that fails is logged and never undoes
|
|
2161
|
-
async function
|
|
2242
|
+
// A notice that fails is logged and never undoes what it reports.
|
|
2243
|
+
async function noticeCaseThread(review, { header, action, kind }) {
|
|
2162
2244
|
try {
|
|
2163
2245
|
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
2164
|
-
|
|
2165
|
-
const lines = issues.map((issue) => `- ${issue}`);
|
|
2166
|
-
const action = 'Qué hacer: revisar el chat; corregir con la paciente o volver a mandar la receta si hace falta';
|
|
2167
|
-
// Every alarm, not only those since the decision: the plan is always sent after it, so the case's alarm came before.
|
|
2246
|
+
// Every alarm, not only those since the decision: the case's alarm always came before it.
|
|
2168
2247
|
const recordId = [...(review.alarms ?? [])].reverse().find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId;
|
|
2169
2248
|
const quoted = await readGroupMessageId(recordId, review.patientCode);
|
|
2170
|
-
const sent = await sendGroupNotice([header, `${patient} (${doctor})`,
|
|
2171
|
-
if (!sent.delivered) logger.error(
|
|
2249
|
+
const sent = await sendGroupNotice([header, `${patient} (${doctor})`, action, link].join('\n'), quoted, [header, action].join('\n'));
|
|
2250
|
+
if (!sent.delivered) logger.error(`[EscalationReview] The ${kind} notice did not reach the group`, { escalationReviewId: String(review._id), error: sent.error });
|
|
2172
2251
|
} catch (error) {
|
|
2173
|
-
logger.error(
|
|
2252
|
+
logger.error(`[EscalationReview] The ${kind} notice failed`, { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
2174
2253
|
}
|
|
2175
2254
|
}
|
|
2176
2255
|
|
|
@@ -2189,7 +2268,7 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
|
|
|
2189
2268
|
try {
|
|
2190
2269
|
if (needsPrescriber(plan) && !prescriberEmail) throw httpError(409, 'This plan names no doctor to sign the receta; record the plan again');
|
|
2191
2270
|
({ delivery = null, sendThrew = false, reply = null } = await getMessaging().processSystemMessage(
|
|
2192
|
-
claimed.patientCode, [
|
|
2271
|
+
claimed.patientCode, [plan.instructions], 'system', { reply: true, triggeredBy: operator },
|
|
2193
2272
|
) ?? {});
|
|
2194
2273
|
} catch (error) {
|
|
2195
2274
|
// A turn refused by a deploy's drain never ran; any other failure after the instructions were stored may have answered.
|
|
@@ -2211,7 +2290,6 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
|
|
|
2211
2290
|
}
|
|
2212
2291
|
if (outcome === 'unknown') {
|
|
2213
2292
|
logger.error('[EscalationReview] The assistant reply could not be confirmed; leaving the review in sending', { escalationReviewId: String(reviewId) });
|
|
2214
|
-
await notifyPlanIssues(claimed, ['no se pudo confirmar que el mensaje salió; el caso sigue en «enviando»']);
|
|
2215
2293
|
throw httpError(502, 'The assistant reply could not be confirmed; check the chat before sending again', SEND_UNCONFIRMED);
|
|
2216
2294
|
}
|
|
2217
2295
|
|
|
@@ -2231,9 +2309,14 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
|
|
|
2231
2309
|
await audit(review, operator, requestId, {
|
|
2232
2310
|
action: status, decisionNumber, transport: 'assistant', checks: issues.length, ...(prescriberEmail && { prescription: prescriptionFailed ? 'failed' : 'created' }),
|
|
2233
2311
|
});
|
|
2234
|
-
if (
|
|
2235
|
-
|
|
2236
|
-
|
|
2312
|
+
if (prescriptionFailed) {
|
|
2313
|
+
await noticeCaseThread(review, {
|
|
2314
|
+
header: '⚠️ No se pudo crear la receta', kind: 'prescription',
|
|
2315
|
+
action: 'Qué hacer: revisar el chat y volver a mandar la receta',
|
|
2316
|
+
});
|
|
2317
|
+
}
|
|
2318
|
+
if (!queued) await armCaseFollowUp(review);
|
|
2319
|
+
if (plan.followUp.kind === 'none' && !queued && !prescriptionFailed) {
|
|
2237
2320
|
try {
|
|
2238
2321
|
return await closeEscalationReview({ id: reviewId, closedBy: operator, requestId });
|
|
2239
2322
|
} catch (error) {
|
|
@@ -2347,6 +2430,7 @@ async function closeEscalationReview({
|
|
|
2347
2430
|
escalationReviewId: String(review._id), error: redactedError(error), stack: redactedStack(error),
|
|
2348
2431
|
});
|
|
2349
2432
|
}
|
|
2433
|
+
await cancelCaseFollowUp(review, 'case_closed');
|
|
2350
2434
|
await recordEpisode(review);
|
|
2351
2435
|
return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
|
|
2352
2436
|
}
|
|
@@ -2402,6 +2486,8 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, closingC
|
|
|
2402
2486
|
}
|
|
2403
2487
|
|
|
2404
2488
|
await audit(review, operator, requestId, { action: 'cancelled', reason: notes });
|
|
2489
|
+
await retireSilenceNetsAfter(review);
|
|
2490
|
+
await cancelCaseFollowUp(review, 'case_cancelled');
|
|
2405
2491
|
return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
|
|
2406
2492
|
}
|
|
2407
2493
|
|
|
@@ -15,47 +15,23 @@ const {
|
|
|
15
15
|
} = require('../helpers/flowDataExchangeHelper');
|
|
16
16
|
const {
|
|
17
17
|
getFlowConditionalRules,
|
|
18
|
-
|
|
19
|
-
attachFlowToken,
|
|
20
|
-
getAnyFlowConditionalRules,
|
|
18
|
+
flowIdFromToken,
|
|
21
19
|
getFlowRulesCacheSize
|
|
22
20
|
} = require('../helpers/templateFlowControllerHelper');
|
|
23
21
|
|
|
24
|
-
const flowTokenRuleCache = new Map();
|
|
25
|
-
|
|
26
22
|
async function resolveFlowRules(flow_id, flow_token, initialScreen) {
|
|
27
23
|
let flowRules = null;
|
|
28
24
|
let ruleSource = 'none';
|
|
29
25
|
if (flow_id) {
|
|
30
26
|
flowRules = await getFlowConditionalRules(flow_id);
|
|
31
|
-
if (flowRules && flow_token) flowTokenRuleCache.set(flow_token, flowRules);
|
|
32
27
|
if (flowRules) ruleSource = 'flow_id';
|
|
33
28
|
}
|
|
34
|
-
if (!flowRules && flow_token) {
|
|
35
|
-
if (flowTokenRuleCache.has(flow_token)) {
|
|
36
|
-
flowRules = flowTokenRuleCache.get(flow_token);
|
|
37
|
-
if (flowRules) ruleSource = 'flow_token_cache';
|
|
38
|
-
} else {
|
|
39
|
-
flowRules = await getFlowConditionalRulesByToken(flow_token);
|
|
40
|
-
if (flowRules) {
|
|
41
|
-
flowTokenRuleCache.set(flow_token, flowRules);
|
|
42
|
-
ruleSource = 'flow_token_db';
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
if (!flowRules && flow_token) {
|
|
47
|
-
const latest = await getAnyFlowConditionalRules();
|
|
48
|
-
if (latest) {
|
|
49
|
-
flowRules = latest;
|
|
50
|
-
await attachFlowToken(latest.flowId, flow_token);
|
|
51
|
-
flowTokenRuleCache.set(flow_token, flowRules);
|
|
52
|
-
ruleSource = 'bound_latest_to_token';
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
29
|
if (!flowRules) {
|
|
56
|
-
|
|
57
|
-
if (
|
|
58
|
-
|
|
30
|
+
const tokenFlowId = flowIdFromToken(flow_token);
|
|
31
|
+
if (tokenFlowId) {
|
|
32
|
+
flowRules = await getFlowConditionalRules(tokenFlowId);
|
|
33
|
+
if (flowRules) ruleSource = 'flow_token';
|
|
34
|
+
}
|
|
59
35
|
}
|
|
60
36
|
const defaultScreen = initialScreen || flowRules?.flowFirstPageId;
|
|
61
37
|
return { flowRules, defaultScreen, ruleSource };
|
|
@@ -95,11 +71,6 @@ async function processDataExchange(req) {
|
|
|
95
71
|
const { formResponses, responses } = extractResponses(sourceData);
|
|
96
72
|
const conditionalVisibility = flowRules ? getConditionalVisibilityFromRules(screen, responses, safeRules) : {};
|
|
97
73
|
|
|
98
|
-
if (flowRules && flow_token && flowRules.flowToken !== flow_token) {
|
|
99
|
-
await attachFlowToken(flowRules.flowId || flow_id, flow_token);
|
|
100
|
-
flowRules.flowToken = flow_token;
|
|
101
|
-
flowTokenRuleCache.set(flow_token, flowRules);
|
|
102
|
-
}
|
|
103
74
|
if (flowRules) logger.debug('[DataExchange] Using stored conditional rules', { screen, rulesCount: safeRules.length, ruleSource });
|
|
104
75
|
else logger.debug('[DataExchange] No conditional rules found for flow', { flow_id, flow_token, cacheSize: getFlowRulesCacheSize(), dbCount: await FlowRouting.countDocuments().catch(() => null) });
|
|
105
76
|
|
|
@@ -5,9 +5,12 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
|
5
5
|
|
|
6
6
|
const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
|
|
7
7
|
const { sweepUntakenAlerts } = require('./untakenAlertService');
|
|
8
|
+
const { sweepExpiredWatches } = require('./watchExpiryService');
|
|
9
|
+
const { sweepCaseFollowUps } = require('./caseFollowUpSweepService');
|
|
8
10
|
|
|
9
11
|
const SWEEP_LIMIT = 10;
|
|
10
12
|
const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
|
|
13
|
+
const WATCH_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
|
11
14
|
const LEASE_MS = 5 * 60 * 1000;
|
|
12
15
|
const SEND_TIMEOUT_MS = 2 * 60 * 1000;
|
|
13
16
|
const SELF_HEAL_WINDOW_MS = 60 * 60 * 1000;
|
|
@@ -90,10 +93,25 @@ const untakenSweeper = createIntervalSweeper({
|
|
|
90
93
|
defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
|
|
91
94
|
});
|
|
92
95
|
|
|
96
|
+
const watchSweeper = createIntervalSweeper({
|
|
97
|
+
label: '[WatchExpirySweep]',
|
|
98
|
+
sweep: () => sweepExpiredWatches(),
|
|
99
|
+
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const caseFollowUpSweeper = createIntervalSweeper({
|
|
103
|
+
label: '[CaseFollowUpSweep]',
|
|
104
|
+
sweep: () => sweepCaseFollowUps(),
|
|
105
|
+
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
106
|
+
});
|
|
107
|
+
|
|
93
108
|
const startReviewAlertSweep = (options) => {
|
|
94
109
|
untakenSweeper.start(options);
|
|
110
|
+
// A watch runs out in hours, so it keeps its own slower interval.
|
|
111
|
+
watchSweeper.start();
|
|
112
|
+
caseFollowUpSweeper.start();
|
|
95
113
|
return sweeper.start(options);
|
|
96
114
|
};
|
|
97
|
-
const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop()]);
|
|
115
|
+
const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop()]);
|
|
98
116
|
|
|
99
117
|
module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
|
|
@@ -1,12 +1,18 @@
|
|
|
1
|
+
const { mapConcurrent } = require('../utils/concurrencyUtils');
|
|
1
2
|
const { httpError } = require('../utils/httpErrorUtils');
|
|
3
|
+
const { logger } = require('../utils/logger');
|
|
4
|
+
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
2
5
|
const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
3
6
|
|
|
4
7
|
const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
|
|
5
8
|
const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
9
|
+
const { caseStateOf } = require('./escalationCaseStateService');
|
|
10
|
+
const { UNTAKEN_PROJECTION } = require('./untakenAlertService');
|
|
6
11
|
|
|
7
12
|
const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
8
13
|
const DONE_STATUSES = ['closed', 'cancelled'];
|
|
9
14
|
const BOARD_BUCKETS = ['pending', 'followup', 'done'];
|
|
15
|
+
const STATE_CONCURRENCY = 10;
|
|
10
16
|
const BOARD_FILTER_PREFIX = 'clinical-review-';
|
|
11
17
|
|
|
12
18
|
const bucketQuery = (bucket, now) => {
|
|
@@ -22,7 +28,7 @@ const bucketQuery = (bucket, now) => {
|
|
|
22
28
|
}
|
|
23
29
|
};
|
|
24
30
|
|
|
25
|
-
const boardRowOf = (review, bucket, deadlinePolicy) => {
|
|
31
|
+
const boardRowOf = (review, bucket, deadlinePolicy, state) => {
|
|
26
32
|
const alarms = review.alarms || [];
|
|
27
33
|
const lead = effectiveUrgencyOf(review);
|
|
28
34
|
const raised = alarms.map((alarm) => alarm.raisedAt).filter(Boolean);
|
|
@@ -40,9 +46,21 @@ const boardRowOf = (review, bucket, deadlinePolicy) => {
|
|
|
40
46
|
closedAt: review.closedAt || null,
|
|
41
47
|
updatedSinceSeen: review.updatedSinceSeen === true,
|
|
42
48
|
responseDeadline: responseDeadlineOf(review, deadlinePolicy),
|
|
49
|
+
caseState: state,
|
|
43
50
|
};
|
|
44
51
|
};
|
|
45
52
|
|
|
53
|
+
const ROW_PROJECTION = {
|
|
54
|
+
patientCode: 1, status: 1, 'alarms.urgencyLevel': 1, 'alarms.symptom': 1, 'alarms.raisedAt': 1, createdAt: 1, closedAt: 1, updatedSinceSeen: 1,
|
|
55
|
+
'decisions.createdAt': 1, urgencyReclassifications: 1,
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// A row whose state cannot be read still shows, with its case status.
|
|
59
|
+
const stateOf = (review, now, policy) => caseStateOf(review, { now, policy }).catch((error) => {
|
|
60
|
+
logger.warn('[ReviewBoard] Could not read the case state of a row', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
|
|
61
|
+
return null;
|
|
62
|
+
});
|
|
63
|
+
|
|
46
64
|
const byUrgencyThenAge = (a, b) => (URGENCY_RANK[b.urgency] || 0) - (URGENCY_RANK[a.urgency] || 0)
|
|
47
65
|
|| new Date(a.since) - new Date(b.since);
|
|
48
66
|
|
|
@@ -50,13 +68,13 @@ const byMostRecentlyClosed = (a, b) => new Date(b.closedAt) - new Date(a.closedA
|
|
|
50
68
|
|
|
51
69
|
async function listReviewBoard({ bucket, now = new Date() } = {}) {
|
|
52
70
|
const reviews = await getEscalationReview()
|
|
53
|
-
.find(bucketQuery(bucket, now), {
|
|
54
|
-
patientCode: 1, status: 1, 'alarms.urgencyLevel': 1, 'alarms.symptom': 1, 'alarms.raisedAt': 1, createdAt: 1, closedAt: 1, updatedSinceSeen: 1,
|
|
55
|
-
'decisions.createdAt': 1, urgencyReclassifications: 1,
|
|
56
|
-
})
|
|
71
|
+
.find(bucketQuery(bucket, now), bucket === 'pending' ? { ...UNTAKEN_PROJECTION, createdAt: 1, updatedSinceSeen: 1 } : ROW_PROJECTION)
|
|
57
72
|
.lean();
|
|
58
73
|
const deadlinePolicy = responseDeadlinePolicy();
|
|
59
|
-
|
|
74
|
+
// Each open case reads its thread and messages, so a long board must not open hundreds of queries at once.
|
|
75
|
+
const states = [];
|
|
76
|
+
await mapConcurrent(reviews, STATE_CONCURRENCY, async (review, index) => { states[index] = await stateOf(review, now, deadlinePolicy); });
|
|
77
|
+
const rows = reviews.map((review, index) => boardRowOf(review, bucket, deadlinePolicy, states[index]))
|
|
60
78
|
.sort(bucket === 'done' ? byMostRecentlyClosed : byUrgencyThenAge);
|
|
61
79
|
const seen = new Set();
|
|
62
80
|
return rows.filter((row) => !seen.has(row.patientCode) && seen.add(row.patientCode));
|
|
@@ -98,7 +98,7 @@ function responseDeadlineOf(review, policy) {
|
|
|
98
98
|
if (review.closedAt || FOLLOWUP_STATUSES.includes(review.status)) return null;
|
|
99
99
|
const decidedAt = timeOf((review.decisions ?? []).at(-1)?.createdAt);
|
|
100
100
|
const waiting = alarmLevelsOf(review)
|
|
101
|
-
.filter(({ alarm }) => Number.isNaN(decidedAt) || timeOf(alarm.raisedAt) > decidedAt)
|
|
101
|
+
.filter(({ alarm }) => !alarm.isHeldInFollowUp && (Number.isNaN(decidedAt) || timeOf(alarm.raisedAt) > decidedAt))
|
|
102
102
|
.map(({ level, clockFrom }) => ({ urgency: level, dueAt: dueAtFor(clockFrom, level, policy) }))
|
|
103
103
|
.filter(({ dueAt }) => dueAt);
|
|
104
104
|
if (!waiting.length) return null;
|
|
@@ -26,6 +26,11 @@ const ACTIONS = {
|
|
|
26
26
|
urgent: 'Tomar el caso: escribir o llamar y registrar la llamada',
|
|
27
27
|
};
|
|
28
28
|
const MAX_QUESTION_LENGTH = 200;
|
|
29
|
+
// Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
|
|
30
|
+
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
|
|
31
|
+
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
32
|
+
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
33
|
+
};
|
|
29
34
|
|
|
30
35
|
const duration = (minutes) => {
|
|
31
36
|
const hours = Math.floor(minutes / 60);
|
|
@@ -41,7 +46,7 @@ function episodeStartOf(alarms) {
|
|
|
41
46
|
}
|
|
42
47
|
|
|
43
48
|
function untakenClockOf(review, policy) {
|
|
44
|
-
const entries = levelsOf(currentAlarms(review), review.urgencyReclassifications, appliedLevelOf).filter((entry) => UNTAKEN_LEVELS.includes(entry.level));
|
|
49
|
+
const entries = levelsOf(currentAlarms(review).filter((alarm) => !alarm.isHeldInFollowUp), review.urgencyReclassifications, appliedLevelOf).filter((entry) => UNTAKEN_LEVELS.includes(entry.level));
|
|
45
50
|
const level = entries.reduce((top, entry) => (URGENCY_RANK[entry.level] > (URGENCY_RANK[top] || 0) ? entry.level : top), null);
|
|
46
51
|
if (!level) return null;
|
|
47
52
|
const atLevel = entries.filter((entry) => entry.level === level);
|
|
@@ -148,7 +153,7 @@ async function alertIfUntaken(review, clock, stage, now) {
|
|
|
148
153
|
// Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
|
|
149
154
|
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
150
155
|
if (!await claimStage(review, clock, stage, now)) return false;
|
|
151
|
-
const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted });
|
|
156
|
+
const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors: clock.level === 'stat' });
|
|
152
157
|
const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
|
|
153
158
|
await getEscalationReview().updateOne(
|
|
154
159
|
{ _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
|
|
@@ -177,10 +182,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
177
182
|
closedAt: null,
|
|
178
183
|
status: { $in: PRE_DECISION_STATUSES },
|
|
179
184
|
alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
|
|
180
|
-
},
|
|
181
|
-
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
182
|
-
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
183
|
-
})
|
|
185
|
+
}, UNTAKEN_PROJECTION)
|
|
184
186
|
.sort({ _id: -1 })
|
|
185
187
|
.limit(SWEEP_LIMIT)
|
|
186
188
|
.lean();
|
|
@@ -217,4 +219,4 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
217
219
|
return sent;
|
|
218
220
|
}
|
|
219
221
|
|
|
220
|
-
module.exports = { sweepUntakenAlerts };
|
|
222
|
+
module.exports = { UNTAKEN_PROJECTION, dueStageOf, sweepUntakenAlerts, untakenClockOf };
|