@peopl-health/nexus 6.5.0-dev.19149 → 6.5.0-dev.20073

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.
Files changed (42) hide show
  1. package/lib/clinical/AssistantProcessor.js +3 -1
  2. package/lib/clinical/config/planTextsConfig.js +41 -0
  3. package/lib/clinical/flags/escalationFlags.js +15 -0
  4. package/lib/clinical/helpers/doctorPlanHelper.js +32 -23
  5. package/lib/clinical/helpers/legacyContextHelper.js +6 -2
  6. package/lib/clinical/helpers/planTextHelper.js +9 -2
  7. package/lib/clinical/protocols/treatmentFormulary.js +3 -3
  8. package/lib/clinical/services/bridgeService.js +2 -2
  9. package/lib/clinical/services/checkInDueService.js +3 -2
  10. package/lib/clinical/services/clinicalAirtableService.js +3 -2
  11. package/lib/clinical/services/clinicalExtractionService.js +9 -2
  12. package/lib/clinical/services/contingencyDispatchService.js +8 -4
  13. package/lib/clinical/services/doctorPlanService.js +27 -11
  14. package/lib/clinical/tools/deliverPatientMessageTool.js +1 -1
  15. package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
  16. package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
  17. package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -0
  18. package/lib/clinical/tools/schedulePatientReminderTool.js +10 -1
  19. package/lib/config/awsConfig.js +1 -1
  20. package/lib/controllers/assistantController.js +5 -2
  21. package/lib/controllers/escalationReviewController.js +16 -3
  22. package/lib/controllers/messageController.js +5 -6
  23. package/lib/core/NexusMessaging.js +16 -18
  24. package/lib/fhir/constants/escalationCaseStatus.js +1 -1
  25. package/lib/helpers/caregiverHelper.js +8 -0
  26. package/lib/helpers/templateFlowControllerHelper.js +9 -48
  27. package/lib/index.d.ts +3 -3
  28. package/lib/models/escalationReviewModel.js +32 -2
  29. package/lib/services/assistantMessageService.js +11 -6
  30. package/lib/services/caseFollowUpService.js +226 -0
  31. package/lib/services/caseFollowUpSweepService.js +89 -0
  32. package/lib/services/characterizationOutcomeService.js +25 -9
  33. package/lib/services/escalationCaseStateService.js +68 -0
  34. package/lib/services/escalationReviewService.js +90 -27
  35. package/lib/services/flowDataExchangeService.js +6 -35
  36. package/lib/services/reviewAlertSweepService.js +19 -1
  37. package/lib/services/reviewBoardService.js +24 -6
  38. package/lib/services/reviewDeadlineService.js +1 -1
  39. package/lib/services/untakenAlertService.js +9 -7
  40. package/lib/services/watchExpiryService.js +162 -0
  41. package/lib/utils/textMatchUtils.js +52 -18
  42. package/package.json +1 -1
@@ -34,7 +34,9 @@ const { doctorAlertHeadline, doctorAlertOpener, renderDoctorMessage, templateSum
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 { assistantInstructionsOf, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
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'];
@@ -521,7 +525,8 @@ async function recordReviewUpdate({ code, update, now = new Date(), settleInBack
521
525
 
522
526
  if (FOLLOWUP_STATUSES.includes(pushed.status)) {
523
527
  await audit(pushed, AGENT_OPERATOR, null, { action: 'case_updated', turnId: update.turnId, tools: update.tools });
524
- return await settleFollowUp(pushed, { background: settleInBackground });
528
+ const canClose = !(pushed.alarms ?? []).some((alarm) => alarm.isHeldInFollowUp && alarm.turnId === update.turnId);
529
+ return await settleFollowUp(pushed, { background: settleInBackground, canClose });
525
530
  }
526
531
 
527
532
  const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
@@ -567,7 +572,26 @@ async function closeStaleInterruption(EscalationReview, patientCode, now) {
567
572
  }
568
573
  }
569
574
 
570
- async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
575
+ function shouldHoldInFollowUp(review, alarm, mode) {
576
+ if (mode !== 'update' || ALERTED_URGENCIES.includes(alarm.urgencyLevel)) return false;
577
+ const decided = effectiveUrgencyOf({ ...review, alarms: (review.alarms ?? []).filter((entry) => entry.alarmId !== alarm.alarmId) })?.urgency;
578
+ return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
579
+ }
580
+
581
+ async function holdInFollowUp(review, alarm) {
582
+ const held = await getEscalationReview()
583
+ .findOneAndUpdate(
584
+ { _id: review._id, status: review.status, 'alarms.alarmId': alarm.alarmId },
585
+ { $set: { 'alarms.$.isHeldInFollowUp': true, updatedSinceSeen: true } },
586
+ { new: true },
587
+ )
588
+ .lean();
589
+ if (!held) return review;
590
+ await audit(held, AGENT_OPERATOR, null, { action: 'followup_result', result: 'update_held', statusFrom: review.status });
591
+ return held;
592
+ }
593
+
594
+ async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date() } = {}) {
571
595
  try {
572
596
  const patientCode = patientCodeOf(code);
573
597
  const entry = { ...alarm, raisedAt: alarm?.raisedAt ?? now };
@@ -583,7 +607,9 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
583
607
  if (joined) {
584
608
  await scheduleDoctorAlert(joined, entry, now);
585
609
  await armPatientTimerOnJoin(joined, entry, now);
586
- if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
610
+ if (FOLLOWUP_STATUSES.includes(joined.status)) {
611
+ return shouldHoldInFollowUp(joined, entry, mode) ? await holdInFollowUp(joined, entry) : await reopenFromFollowUp(joined, 'new_alarm');
612
+ }
587
613
  if (!DOCUMENTING_STATUSES.includes(joined.status)) {
588
614
  logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
589
615
  escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
@@ -615,7 +641,7 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
615
641
  }
616
642
 
617
643
  function escalationAnchorOf(review, alarmId) {
618
- const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId);
644
+ const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId && !alarm.isHeldInFollowUp);
619
645
  if (!prior.length) return null;
620
646
  const levelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
621
647
  const rankOf = (alarm) => URGENCY_RANK[levelOf(alarm)] || 0;
@@ -792,9 +818,9 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
792
818
  };
793
819
  }
794
820
 
795
- function previewPlanInstructions({ id, plan } = {}) {
821
+ async function previewPlanInstructions({ id, plan } = {}) {
796
822
  reviewIdOf(id);
797
- return planInstructions(planOf(plan));
823
+ return planInstructions(planOf(plan), await getPlanTexts());
798
824
  }
799
825
 
800
826
  async function getReviewTimeline({ id } = {}) {
@@ -1406,12 +1432,21 @@ async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel
1406
1432
  }
1407
1433
  }
1408
1434
 
1409
- async function reopenFromFollowUp(review, reason) {
1435
+ async function reopenFromFollowUp(review, reason, { background = false } = {}) {
1410
1436
  const reopened = await getEscalationReview()
1411
1437
  .findOneAndUpdate({ _id: review._id, status: review.status }, { $set: { status: 'documenting', updatedSinceSeen: true } }, { new: true })
1412
1438
  .lean();
1413
1439
  if (!reopened) return review;
1414
1440
  await audit(reopened, AGENT_OPERATOR, null, { action: 'followup_result', result: reason, statusFrom: review.status });
1441
+ await cancelCaseFollowUp(reopened, 'case_reopened');
1442
+ // A new alarm already reaches the group through its emergency row.
1443
+ if (reason === 'worsening') {
1444
+ const notice = noticeCaseThread(reopened, {
1445
+ header: '📈 La paciente va peor después de la decisión del médico', kind: 'worsening',
1446
+ action: 'Qué hacer: llamar a la paciente y, si hace falta, pedirle al médico una nueva indicación',
1447
+ });
1448
+ if (!background) await notice;
1449
+ }
1415
1450
  return reopened;
1416
1451
  }
1417
1452
 
@@ -1455,7 +1490,7 @@ async function closeSettled(review) {
1455
1490
  }
1456
1491
  }
1457
1492
 
1458
- async function settleFollowUp(snapshot, { background = true } = {}) {
1493
+ async function settleFollowUp(snapshot, { background = true, canClose = true } = {}) {
1459
1494
  const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
1460
1495
  if (!since) return snapshot;
1461
1496
  const sinceMs = new Date(since).getTime();
@@ -1469,9 +1504,9 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
1469
1504
  .filter((impression) => known.has(impression.caseId) && readingOf(impression))
1470
1505
  .forEach((impression) => latest.set(impression.caseId, readingOf(impression))));
1471
1506
 
1472
- if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
1507
+ if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening', { background });
1473
1508
  const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
1474
- if (!settled || !SETTLEABLE_STATUSES.includes(review.status)) {
1509
+ if (!settled || !canClose || !SETTLEABLE_STATUSES.includes(review.status)) {
1475
1510
  await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
1476
1511
  return review;
1477
1512
  }
@@ -1870,7 +1905,7 @@ async function recordDoctorDecision({
1870
1905
  // The plan names the draft it started from, so a newer draft is refused instead of decided unseen.
1871
1906
  if (seenDraftNumber === null) throw httpError(400, 'draftNumber is required for a plan');
1872
1907
  plan = planOf(requestedPlan);
1873
- plan = { ...plan, ...approvedInstructions(plan, instructions) };
1908
+ plan = { ...plan, ...approvedInstructions(plan, instructions, await getPlanTexts()) };
1874
1909
  // Anyone may record a plan, often beside the doctor; one with a drug, study, note or edit names the doctor who gave it.
1875
1910
  const namesDrug = drugsNamedIn(plan.homeCare.join(' ')).length > 0;
1876
1911
  if (needsPrescriber(plan) || plan.note || plan.instructionsEdited || namesDrug) {
@@ -1883,6 +1918,15 @@ async function recordDoctorDecision({
1883
1918
  const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
1884
1919
  const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
1885
1920
  if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1921
+ let monitoringUntil = null;
1922
+ if (decision === 'monitor') {
1923
+ // Team rule (2026-10-31): stat goes to the ER; watching one at home first takes a lowering with its reason.
1924
+ const open = currentAlarms(review);
1925
+ if (effectiveUrgencyOf({ ...review, alarms: open.length ? open : review.alarms })?.urgency === 'stat') throw httpError(409, STAT_WATCH);
1926
+ // A watch recorded by someone who is not an approver names the doctor who ordered it.
1927
+ if (source === 'platform' && !await isEscalationApprover(operator)) decidedBy = requiredText(doctorName, 'doctorName');
1928
+ monitoringUntil = new Date(Date.now() + DEFAULT_FOLLOW_UP_HOURS.vigilancia * 60 * 60 * 1000);
1929
+ }
1886
1930
  const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
1887
1931
  // The panel shows the latest draft, so a doctor deciding on a bot update not sent yet decides on that one.
1888
1932
  const onUnsentUpdate = handoff?.sentBy === AUTO_HANDOFF_OPERATOR && Number(seenDraftNumber) === review.drafts.length
@@ -1932,11 +1976,13 @@ async function recordDoctorDecision({
1932
1976
  },
1933
1977
  $set: returnReason === 'no_requiere'
1934
1978
  ? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}`, ...(closingIds && { closingCaseIds: closingIds }) }
1935
- : { status: statusAfter(decision) },
1979
+ : { status: statusAfter(decision), ...(monitoringUntil && { monitoringUntil }) },
1936
1980
  }, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
1937
1981
  await audit(updated, operator, requestId, {
1938
1982
  action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
1939
1983
  });
1984
+ if (decision !== 'returned' || returnReason === 'no_requiere') await retireSilenceNetsAfter(updated);
1985
+ if (decision === 'monitor') await armCaseFollowUp(updated);
1940
1986
  if (returnReason === 'no_requiere') {
1941
1987
  await audit(updated, operator, requestId, { action: 'cancelled', reason: updated.cancellationReason });
1942
1988
  const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
@@ -1949,6 +1995,16 @@ const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
1949
1995
  ? { patientCaseRecordIds: review.patientCaseRecordIds }
1950
1996
  : { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
1951
1997
 
1998
+ async function retireSilenceNetsAfter(review) {
1999
+ try {
2000
+ await retireSilenceNets({ patientCode: review.patientCode });
2001
+ } catch (error) {
2002
+ logger.warn('[EscalationReview] The escalation check-in was not retired after the decision or cancel', {
2003
+ escalationReviewId: String(review._id), error: redactedError(error),
2004
+ });
2005
+ }
2006
+ }
2007
+
1952
2008
  async function recordDirectIndication({ code, triggeredBy, body, messageId = null, status = null, deferred = false } = {}) {
1953
2009
  try {
1954
2010
  const text = String(body ?? '').trim();
@@ -1994,6 +2050,8 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1994
2050
  ).lean();
1995
2051
  if (updated) {
1996
2052
  await audit(updated, operator, null, { action: 'direct_chat_resolved', decisionNumber, statusFrom: review.status });
2053
+ await retireSilenceNetsAfter(updated);
2054
+ if (!deferred) await armCaseFollowUp(updated);
1997
2055
  const { review: synced } = await syncCase(updated, operator, null);
1998
2056
  return synced;
1999
2057
  }
@@ -2131,6 +2189,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
2131
2189
  }, { recommendation: finalText });
2132
2190
  const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status).catch((error) => { throw withSendCode(error, SEND_UNCONFIRMED); });
2133
2191
  await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
2192
+ if (!deferred) await armCaseFollowUp(review);
2134
2193
  return syncCase(review, operator, requestId);
2135
2194
  }
2136
2195
 
@@ -2157,20 +2216,17 @@ function replyOutcome(delivery, sendThrew) {
2157
2216
  return 'unknown';
2158
2217
  }
2159
2218
 
2160
- // A notice that fails is logged and never undoes the send.
2161
- async function notifyPlanIssues(review, issues) {
2219
+ // A notice that fails is logged and never undoes what it reports.
2220
+ async function noticeCaseThread(review, { header, action, kind }) {
2162
2221
  try {
2163
2222
  const { patient, doctor, link } = await teamAlertIdentity(review);
2164
- const header = '⚠️ Revisar el envío del plan';
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.
2223
+ // Every alarm, not only those since the decision: the case's alarm always came before it.
2168
2224
  const recordId = [...(review.alarms ?? [])].reverse().find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId;
2169
2225
  const quoted = await readGroupMessageId(recordId, review.patientCode);
2170
- const sent = await sendGroupNotice([header, `${patient} (${doctor})`, ...lines, action, link].join('\n'), quoted, [header, ...lines, action].join('\n'));
2171
- if (!sent.delivered) logger.error('[EscalationReview] The plan check notice did not reach the group', { escalationReviewId: String(review._id), error: sent.error });
2226
+ const sent = await sendGroupNotice([header, `${patient} (${doctor})`, action, link].join('\n'), quoted, [header, action].join('\n'));
2227
+ if (!sent.delivered) logger.error(`[EscalationReview] The ${kind} notice did not reach the group`, { escalationReviewId: String(review._id), error: sent.error });
2172
2228
  } catch (error) {
2173
- logger.error('[EscalationReview] The plan check notice failed', { escalationReviewId: String(review._id), error: redactedError(error) });
2229
+ logger.error(`[EscalationReview] The ${kind} notice failed`, { escalationReviewId: String(review._id), error: redactedError(error) });
2174
2230
  }
2175
2231
  }
2176
2232
 
@@ -2189,7 +2245,7 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
2189
2245
  try {
2190
2246
  if (needsPrescriber(plan) && !prescriberEmail) throw httpError(409, 'This plan names no doctor to sign the receta; record the plan again');
2191
2247
  ({ delivery = null, sendThrew = false, reply = null } = await getMessaging().processSystemMessage(
2192
- claimed.patientCode, [assistantInstructionsOf(plan)], 'system', { reply: true, triggeredBy: operator },
2248
+ claimed.patientCode, [plan.instructions], 'system', { reply: true, triggeredBy: operator },
2193
2249
  ) ?? {});
2194
2250
  } catch (error) {
2195
2251
  // A turn refused by a deploy's drain never ran; any other failure after the instructions were stored may have answered.
@@ -2211,7 +2267,6 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
2211
2267
  }
2212
2268
  if (outcome === 'unknown') {
2213
2269
  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
2270
  throw httpError(502, 'The assistant reply could not be confirmed; check the chat before sending again', SEND_UNCONFIRMED);
2216
2271
  }
2217
2272
 
@@ -2231,9 +2286,14 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
2231
2286
  await audit(review, operator, requestId, {
2232
2287
  action: status, decisionNumber, transport: 'assistant', checks: issues.length, ...(prescriberEmail && { prescription: prescriptionFailed ? 'failed' : 'created' }),
2233
2288
  });
2234
- if (issues.length) await notifyPlanIssues(review, issues);
2235
- // Closing waits for a sent reply that kept to the plan and the receta it promised; otherwise the team still has something to do.
2236
- if (plan.followUp.kind === 'none' && !queued && !issues.length) {
2289
+ if (prescriptionFailed) {
2290
+ await noticeCaseThread(review, {
2291
+ header: '⚠️ No se pudo crear la receta', kind: 'prescription',
2292
+ action: 'Qué hacer: revisar el chat y volver a mandar la receta',
2293
+ });
2294
+ }
2295
+ if (!queued) await armCaseFollowUp(review);
2296
+ if (plan.followUp.kind === 'none' && !queued && !prescriptionFailed) {
2237
2297
  try {
2238
2298
  return await closeEscalationReview({ id: reviewId, closedBy: operator, requestId });
2239
2299
  } catch (error) {
@@ -2347,6 +2407,7 @@ async function closeEscalationReview({
2347
2407
  escalationReviewId: String(review._id), error: redactedError(error), stack: redactedStack(error),
2348
2408
  });
2349
2409
  }
2410
+ await cancelCaseFollowUp(review, 'case_closed');
2350
2411
  await recordEpisode(review);
2351
2412
  return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
2352
2413
  }
@@ -2402,6 +2463,8 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, closingC
2402
2463
  }
2403
2464
 
2404
2465
  await audit(review, operator, requestId, { action: 'cancelled', reason: notes });
2466
+ await retireSilenceNetsAfter(review);
2467
+ await cancelCaseFollowUp(review, 'case_cancelled');
2405
2468
  return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
2406
2469
  }
2407
2470
 
@@ -15,47 +15,23 @@ const {
15
15
  } = require('../helpers/flowDataExchangeHelper');
16
16
  const {
17
17
  getFlowConditionalRules,
18
- getFlowConditionalRulesByToken,
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
- flowRules = await getAnyFlowConditionalRules();
57
- if (flowRules && flow_token) flowTokenRuleCache.set(flow_token, flowRules);
58
- if (flowRules && ruleSource === 'none') ruleSource = 'latest_db';
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
- const rows = reviews.map((review) => boardRowOf(review, bucket, deadlinePolicy))
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
- }, { 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,
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 };