@peopl-health/nexus 6.4.9 → 6.4.11

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.
@@ -36,6 +36,10 @@ function escalationWatchExpiryLive() {
36
36
  return flagNotOff('ESCALATION_WATCH_EXPIRY_LIVE');
37
37
  }
38
38
 
39
+ function escalationWatchTeamNoticeLive() {
40
+ return flagOn('ESCALATION_WATCH_TEAM_NOTICE_LIVE');
41
+ }
42
+
39
43
  module.exports = {
40
44
  escalationApproverAlertLive,
41
45
  escalationAssessmentLive,
@@ -44,5 +48,6 @@ module.exports = {
44
48
  escalationUntakenAlertsLive,
45
49
  escalationUpdateModeLive,
46
50
  escalationWatchExpiryLive,
51
+ escalationWatchTeamNoticeLive,
47
52
  feverPatientTimerLive,
48
53
  };
@@ -291,6 +291,10 @@ const supersedeForStat = ({ patientCode, trace, isLive }) => retireNets({
291
291
  patientCode, trace, isLive, select: (active) => active.filter((net) => isCeilingNet(net) || net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'for a stat escalation',
292
292
  });
293
293
 
294
+ const retireSilenceNets = ({ patientCode, trace = null }) => retireNets({
295
+ patientCode, trace, isLive: null, select: (active) => active.filter((net) => net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'after the doctor decided',
296
+ });
297
+
294
298
  function escalationUrgencyOf(net) {
295
299
  if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
296
300
  const silence = net?.patientReminder?.firesAfterSilenceMinutes;
@@ -493,4 +497,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
493
497
  return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
494
498
  }
495
499
 
496
- module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
500
+ module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, retireSilenceNets, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
@@ -35,6 +35,7 @@ const { generateKeyQuestions } = require('../clinical/services/escalationQuestio
35
35
  const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
36
36
  const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
37
37
  const { getPlanTexts } = require('../clinical/config/planTextsConfig');
38
+ const { retireSilenceNets } = require('../clinical/services/contingencyDispatchService');
38
39
  const { DEFAULT_FOLLOW_UP_HOURS, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
39
40
  const { approvedInstructions, planOf, replyIssues } = require('../clinical/services/doctorPlanService');
40
41
  const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
@@ -1948,6 +1949,7 @@ async function recordDoctorDecision({
1948
1949
  await audit(updated, operator, requestId, {
1949
1950
  action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
1950
1951
  });
1952
+ if (decision !== 'returned' || returnReason === 'no_requiere') await retireSilenceNetsAfter(updated);
1951
1953
  if (returnReason === 'no_requiere') {
1952
1954
  await audit(updated, operator, requestId, { action: 'cancelled', reason: updated.cancellationReason });
1953
1955
  const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
@@ -1960,6 +1962,16 @@ const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
1960
1962
  ? { patientCaseRecordIds: review.patientCaseRecordIds }
1961
1963
  : { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
1962
1964
 
1965
+ async function retireSilenceNetsAfter(review) {
1966
+ try {
1967
+ await retireSilenceNets({ patientCode: review.patientCode });
1968
+ } catch (error) {
1969
+ logger.warn('[EscalationReview] The escalation check-in was not retired after the decision or cancel', {
1970
+ escalationReviewId: String(review._id), error: redactedError(error),
1971
+ });
1972
+ }
1973
+ }
1974
+
1963
1975
  async function recordDirectIndication({ code, triggeredBy, body, messageId = null, status = null, deferred = false } = {}) {
1964
1976
  try {
1965
1977
  const text = String(body ?? '').trim();
@@ -2005,6 +2017,7 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
2005
2017
  ).lean();
2006
2018
  if (updated) {
2007
2019
  await audit(updated, operator, null, { action: 'direct_chat_resolved', decisionNumber, statusFrom: review.status });
2020
+ await retireSilenceNetsAfter(updated);
2008
2021
  const { review: synced } = await syncCase(updated, operator, null);
2009
2022
  return synced;
2010
2023
  }
@@ -2413,6 +2426,7 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, closingC
2413
2426
  }
2414
2427
 
2415
2428
  await audit(review, operator, requestId, { action: 'cancelled', reason: notes });
2429
+ await retireSilenceNetsAfter(review);
2416
2430
  return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
2417
2431
  }
2418
2432
 
@@ -2,7 +2,7 @@ const { logger } = require('../utils/logger');
2
2
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
3
  const { getEscalationReview } = require('../models/escalationReviewModel');
4
4
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
5
- const { escalationWatchExpiryLive } = require('../clinical/flags/escalationFlags');
5
+ const { escalationWatchExpiryLive, escalationWatchTeamNoticeLive } = require('../clinical/flags/escalationFlags');
6
6
 
7
7
  const { countMessages } = require('./messageService');
8
8
  const { logPatientChange } = require('./patientService');
@@ -24,6 +24,7 @@ const TEAM_WAIT_MS = 2 * 60 * 60 * 1000;
24
24
  // A reminder this late (an outage, a deploy) is not sent; the team notice still goes.
25
25
  const STALE_MS = 30 * 60 * 1000;
26
26
  const getMessaging = () => require('../core/NexusMessaging');
27
+ const REMINDED_UNTILS = { $map: { input: { $filter: { input: { $ifNull: ['$watchNotices', []] }, cond: { $eq: ['$$this.kind', 'reminder'] } } }, in: '$$this.until' } };
27
28
 
28
29
  const timeOf = (value) => new Date(value).getTime();
29
30
 
@@ -128,12 +129,16 @@ async function noticeTeam(review, reminder, now) {
128
129
  return true;
129
130
  }
130
131
 
131
- // A watch that ran out is never closed silently: the patient gets one reminder, then the team is told.
132
+ // A watch that ran out is never closed silently: the patient gets one reminder, then the team is told while its flag is on.
132
133
  async function sweepExpiredWatches({ now = new Date() } = {}) {
133
134
  if (!escalationWatchExpiryLive()) return 0;
135
+ const teamNotice = escalationWatchTeamNoticeLive();
136
+ const query = { closedAt: null, status: 'monitoring', monitoringUntil: { $lte: now } };
137
+ // With no team notice a reminded watch has nothing left to send, so it must not hold a sweep slot.
138
+ if (!teamNotice) query.$expr = { $not: [{ $in: ['$monitoringUntil', REMINDED_UNTILS] }] };
134
139
  const reviews = await getEscalationReview()
135
140
  .find(
136
- { closedAt: null, status: 'monitoring', monitoringUntil: { $lte: now } },
141
+ query,
137
142
  { patientCode: 1, status: 1, monitoringUntil: 1, watchNotices: 1, 'alarms.emergencyRecordId': 1 },
138
143
  )
139
144
  .sort({ monitoringUntil: 1 })
@@ -144,6 +149,7 @@ async function sweepExpiredWatches({ now = new Date() } = {}) {
144
149
  try {
145
150
  if (noticesOf(review, 'team').some((entry) => !failed(entry))) continue;
146
151
  const [reminder] = noticesOf(review, 'reminder');
152
+ if (reminder && !teamNotice) continue;
147
153
  if (await (reminder ? noticeTeam(review, reminder, now) : remindPatient(review, now))) sent += 1;
148
154
  } catch (error) {
149
155
  logger.error('[WatchExpiry] Could not check an expired watch', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.9",
3
+ "version": "6.4.11",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",