@peopl-health/nexus 5.72.14 → 5.72.15

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.
@@ -22,7 +22,7 @@ const { getRecordByFilter } = require('../../services/airtableService');
22
22
  const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
23
23
  const { getMessages, countMessages } = require('../../services/messageService');
24
24
  const { hasInstructionInFlight } = require('../../services/instructionInFlightService');
25
- const { isStaffSend } = require('../../services/patientSendHoldService');
25
+ const { isStaffSend } = require('../../helpers/staffSendHelper');
26
26
  const { getTurnScopedToolNames, getReplayArgsByTool } = require('../../services/toolRegistryService');
27
27
  const { CURRENT_TURN } = require('../promptPlacement');
28
28
 
@@ -3,7 +3,6 @@ const crypto = require('crypto');
3
3
  const { logger } = require('../../utils/logger');
4
4
  const { clampToHourWindow } = require('../../utils/scheduleUtils');
5
5
  const { readContingencies, readSymptomCases, storeContingency } = require('../../fhir');
6
- const { patientIsHospitalized } = require('../../helpers/pausedThreadHelper');
7
6
  const { ContingencySafetyNet, ACTIVE_CARE_PLAN_STATUSES, RESOLVED_REASONS, RESOLVES_ON, ARMED_BY, isNetActive } = require('../../shared/dtos/ContingencySafetyNet');
8
7
  const { recordReminder, hasPendingContingencyRow, recordContingencyEscalation, cancelContingencyRows } = require('./clinicalAirtableService');
9
8
  const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
@@ -153,7 +152,6 @@ async function escalationNetTarget(patientCode, { stepsAside = () => false, touc
153
152
  async function commitMachineNet({ patientCode, contingency, caseId, trace, isLive, planId, stepsAside = () => false }) {
154
153
  if (isShadowRun()) return { armed: false, reason: 'shadow_run', planId };
155
154
  if (isLive && !isLive()) return { armed: false, reason: 'turn_superseded', planId };
156
- if (await patientIsHospitalized(patientCode)) return { armed: false, reason: 'patient_hospitalized', planId };
157
155
 
158
156
  await storeContingency({ patientId: patientCode, contingency });
159
157
  const raced = (await readActiveNets(patientCode, caseId))
@@ -5,7 +5,7 @@ const { Symptoms_ID } = require('../../config/airtableConfig');
5
5
  const { getMessages } = require('../../services/messageService');
6
6
  const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
7
7
  const { logger } = require('../../utils/logger');
8
- const { botIsPaused, patientIsHospitalized } = require('../../helpers/pausedThreadHelper');
8
+ const { botIsPaused } = require('../../helpers/pausedThreadHelper');
9
9
  const { isArchivedPatientCode } = require('../../helpers/twilioHelper');
10
10
  const { Thread } = require('../../models/threadModel');
11
11
  const { PATIENT_CONTACT_WINDOW } = require('./contingencyDispatchService');
@@ -298,7 +298,6 @@ async function rejectionReason(candidate, {
298
298
  if (opsReason) return opsReason;
299
299
  if (await Thread.exists({ code: candidate.code, outreachOptOut: true })) return 'outreach_opt_out';
300
300
  if (await botIsPaused(candidate.code, { label: '[outreachSweep]' })) return 'bot_paused';
301
- if (await patientIsHospitalized(candidate.code)) return 'patient_hospitalized';
302
301
  if (!includePreviouslySwept) {
303
302
  const sweptReason = candidate.source === SCOPE_SOURCE
304
303
  ? (await sweepClaims.has(sweepClaimKey(candidate, now)) ? 'already_swept_this_week' : null)
@@ -6,7 +6,6 @@ const { readSymptomCases, readClusters, readContingencies, storeContingency } =
6
6
  const { ContingencySafetyNet, ESCALATION_PRIORITIES, RESOLVED_REASONS, RESOLVES_ON, isAgentArmed, isNetActive, isExpired } = require('../../shared/dtos/ContingencySafetyNet');
7
7
  const { OPEN_STATUSES } = require('../../shared/dtos/ManagedSymptom');
8
8
  const { logger } = require('../../utils/logger');
9
- const { patientIsHospitalized } = require('../../helpers/pausedThreadHelper');
10
9
 
11
10
  const STEP_SHAPE = '{message, fires_after_silence_minutes, window_reasoning}';
12
11
  const MAX_PATIENT_SILENCE_MIN = 1380;
@@ -198,9 +197,6 @@ async function handler(args = {}, context = {}) {
198
197
  }
199
198
 
200
199
  const patientId = runtime.patientCode;
201
- if (await patientIsHospitalized(patientId)) {
202
- return fail('patient_hospitalized — no check-in is armed while the patient is in hospital; the team follows up there.');
203
- }
204
200
  if (relatedCaseId) {
205
201
  const targetCase = (await readSymptomCases({ patientId })).find((c) => c.condition.conditionId === relatedCaseId);
206
202
  if (!targetCase) return fail('case_not_found_or_wrong_patient', { related_case_id: relatedCaseId });
@@ -14,7 +14,6 @@ const { CAREGIVER_ROLE, resolveCaregiver } = require('../helpers/caregiverHelper
14
14
 
15
15
  const { getRecordByFilter } = require('../services/airtableService');
16
16
  const { getMessages } = require('../services/messageService');
17
- const { holdsAutomatedSend } = require('../services/patientSendHoldService');
18
17
  const { recordDirectIndication } = require('../services/escalationReviewService');
19
18
 
20
19
  const INDICATION_WAIT_MS = 5000;
@@ -61,8 +60,6 @@ const _sendBulkMessages = async (payloads, res, logMessage) => {
61
60
  res.status(200).json({ success: true, response: 'Messages sent', messageIds });
62
61
  };
63
62
 
64
- const HOSPITALIZED_SKIP = { success: false, status: 'patient_hospitalized' };
65
-
66
63
  const sendMessageController = async (req, res) => {
67
64
  if (!_validateMessagingDeps(res)) return;
68
65
 
@@ -87,7 +84,6 @@ const sendMessageController = async (req, res) => {
87
84
  }
88
85
 
89
86
  try {
90
- if (await holdsAutomatedSend({ code: formattedCode, triggeredBy })) return res.status(200).json(HOSPITALIZED_SKIP);
91
87
  let contact = {};
92
88
  if (contactCode) {
93
89
  if (sendTime) {
@@ -171,7 +167,6 @@ const sendBulkMessageController = async (req, res) => {
171
167
  let extraDelay = 0;
172
168
  const staggered = [];
173
169
  for (const recipient of codes) {
174
- if (await holdsAutomatedSend({ code: ensureWhatsAppFormat(recipient), triggeredBy })) continue;
175
170
  staggered.push({
176
171
  offset: extraDelay,
177
172
  payload: {
@@ -232,7 +227,6 @@ const sendBulkMessageAirtableController = async (req, res) => {
232
227
  code = ensureWhatsAppFormat(code);
233
228
  if (sentPhones.has(code)) continue;
234
229
  sentPhones.add(code);
235
- if (await holdsAutomatedSend({ code, triggeredBy })) continue;
236
230
 
237
231
  payloads.push({
238
232
  fileUrl, message: customMessage, fileType, contentSid, hidePreview,
@@ -22,13 +22,13 @@ const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper')
22
22
  const { prepareMessageMedia } = require('../helpers/mediaHelper');
23
23
  const { botIsPaused, patientIsDeceased } = require('../helpers/pausedThreadHelper');
24
24
  const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../helpers/sendClaimHelper');
25
+ const { isStaffSend } = require('../helpers/staffSendHelper');
25
26
 
26
27
  const { createMessagingProvider } = require('../adapters/registry');
27
28
  const { ensureThreadExists } = require('../services/threadService');
28
29
 
29
30
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
30
31
  const { getMessages, updateMessage } = require('../services/messageService');
31
- const { isStaffSend } = require('../services/patientSendHoldService');
32
32
  const { processAssistantSystemMessage } = require('../services/assistantMessageService');
33
33
  const { beginInstruction, endInstruction } = require('../services/instructionInFlightService');
34
34
  const { QueueReconciliationService } = require('../services/queueReconciliationService');
@@ -34,9 +34,4 @@ async function patientIsDeceased(code) {
34
34
  return Boolean(deceased);
35
35
  }
36
36
 
37
- async function patientIsHospitalized(code) {
38
- const hospitalized = await Thread.findOne({ code, hospitalizedAt: { $ne: null } }, { _id: 1 }).lean();
39
- return Boolean(hospitalized);
40
- }
41
-
42
- module.exports = { alertsMutedFor, botIsPaused, patientIsDeceased, patientIsHospitalized, pausedSince };
37
+ module.exports = { alertsMutedFor, botIsPaused, patientIsDeceased, pausedSince };
@@ -0,0 +1,4 @@
1
+ // Staff sign what they send with their email; automations sign with a name or not at all.
2
+ const isStaffSend = (triggeredBy) => /@/.test(triggeredBy || '');
3
+
4
+ module.exports = { isStaffSend };
@@ -1,7 +1,6 @@
1
1
  const { logger } = require('../utils/logger');
2
2
  const { isRetryableError } = require('../utils/retryUtils');
3
3
  const { ScheduledMessage } = require('../models/agendaMessageModel');
4
- const { holdsAutomatedSend } = require('../services/patientSendHoldService');
5
4
  const { BaseJob } = require('./BaseJob');
6
5
 
7
6
  const QUEUE_NAME = 'scheduled-messages';
@@ -94,14 +93,6 @@ class ScheduledMessageJob extends BaseJob {
94
93
  }
95
94
 
96
95
  try {
97
- if (await holdsAutomatedSend({ code: msg.code, triggeredBy: msg.triggeredBy })) {
98
- await ScheduledMessage.updateOne(
99
- { _id: scheduledMessageId },
100
- { $set: { status: 'cancelled', errorCode: 'patient_hospitalized', errorMessage: 'The patient is in hospital' } }
101
- );
102
- logger.info('[ScheduledMessageJob] Not sent to a hospitalized patient', { scheduledMessageId });
103
- return { success: false, reason: 'patient_hospitalized' };
104
- }
105
96
  const parentMessageId = msg.parentMessageId || null;
106
97
  if (!parentMessageId && msg.contentSid && !msg.message) {
107
98
  const provider = this.requireProvider?.();
@@ -7,7 +7,6 @@ const { WHATSAPP_PATIENT_CODE } = require('../utils/sanitizerUtils');
7
7
  const { Thread } = require('../models/threadModel');
8
8
  const { CANCELLABLE_STATUSES } = require('../models/escalationReviewModel');
9
9
  const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
10
- const { RESOLVED_REASONS } = require('../shared/dtos/ContingencySafetyNet');
11
10
 
12
11
  const { requirePatientIdentity } = require('../clinical/services/patientIdentityService');
13
12
  const { standDownAllPendingRows } = require('../clinical/services/clinicalAirtableService');
@@ -86,15 +85,6 @@ async function markThreadFields(code, fields) {
86
85
  if (!matchedCount) throw new Error('the patient has no thread');
87
86
  }
88
87
 
89
- // A net armed before the admission would never fire in hospital and would keep new nets from arming after the discharge.
90
- async function retireNets(code) {
91
- const { readContingencies } = require('../fhir');
92
- const { autoResolveNets } = require('../clinical/services/contingencyDispatchService');
93
- const nets = await readContingencies({ patientId: code });
94
- const { cascadeErrors } = await autoResolveNets({ patientCode: code, nets, resolvedReason: RESOLVED_REASONS.NO_LONGER_RELEVANT });
95
- if (cascadeErrors.length) throw new Error('some nets were not retired');
96
- }
97
-
98
88
  async function writeFhirHospitalization(code, stay) {
99
89
  if (!patientResourceWriteLive()) return;
100
90
  const { storeHospitalization } = require('../fhir');
@@ -132,8 +122,7 @@ async function markActive({ code }) {
132
122
  return { status: ACTIVE, failed };
133
123
  }
134
124
 
135
- // Routine messages, the 15-minute escalation prompt and silence check-ins stop while the patient is in hospital;
136
- // the bot still answers, and its seguimientos still ask how the patient is doing.
125
+ // Only the 15-minute urgencias prompt stops while the patient is in hospital; everything else still reaches them.
137
126
  async function markHospitalized({ code, admittedOn }) {
138
127
  const thread = await Thread.findOne({ code }, { hospitalizedAt: 1 }).lean();
139
128
  const current = thread?.hospitalizedAt?.toISOString().slice(0, 10);
@@ -141,7 +130,6 @@ async function markHospitalized({ code, admittedOn }) {
141
130
  await writeProgramStatus(code, { internado_desde: admittedOn });
142
131
  const failed = [];
143
132
  await attempt('mark_thread', failed, () => markThreadFields(code, { hospitalizedAt: dayStart(admittedOn) }));
144
- await attempt('retire_nets', failed, () => retireNets(code));
145
133
  await attempt('fhir_encounter', failed, () => writeFhirHospitalization(code, { admittedOn }));
146
134
  return { status: HOSPITALIZED, admittedOn, failed };
147
135
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.72.14",
3
+ "version": "5.72.15",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,14 +0,0 @@
1
- const { patientIsHospitalized } = require('../helpers/pausedThreadHelper');
2
-
3
- // Staff sign what they send with their email; automations sign with a name or not at all.
4
- const isStaffSend = (triggeredBy) => /@/.test(triggeredBy || '');
5
-
6
- // send_reminder carries the bot's seguimientos and the reminders a patient asked for; they still reach a hospitalized patient.
7
- const REMINDER_SENDER = 'send_reminder';
8
-
9
- // Automated sends wait while the patient is in hospital; staff and reminders still reach them.
10
- async function holdsAutomatedSend({ code, triggeredBy }) {
11
- return !isStaffSend(triggeredBy) && triggeredBy !== REMINDER_SENDER && patientIsHospitalized(code);
12
- }
13
-
14
- module.exports = { isStaffSend, holdsAutomatedSend };