@peopl-health/nexus 5.72.12 → 5.72.13

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.
@@ -601,6 +601,14 @@ async function standDownRow({ code, trace, table, filter, planId, standDownReaso
601
601
  });
602
602
  }
603
603
 
604
+ // Stands down every pending reminder and contingency row of a patient, whatever their type.
605
+ async function standDownAllPendingRows({ code, reason }) {
606
+ const filter = `AND(${fieldEquals('whatsapp_id', code)}, ${PENDING_ROW_FILTER})`;
607
+ const remindersOk = await standDownRow({ code, trace: null, planId: null, standDownReason: reason, table: 'reminder', filter });
608
+ const escalationsOk = await standDownRow({ code, trace: null, planId: null, table: 'contingency', filter });
609
+ return remindersOk && escalationsOk;
610
+ }
611
+
604
612
  async function cancelContingencyRows({ code, trace, planId, standDownReason = null }) {
605
613
  const remindersOk = await standDownRow({
606
614
  code, trace, planId, standDownReason, table: 'reminder', filter: `AND({schedule_id} = "${planId}-patient", ${PENDING_ROW_FILTER})`,
@@ -692,6 +700,7 @@ module.exports = {
692
700
  markReminderSent,
693
701
  recordContingencyEscalation,
694
702
  cancelContingencyRows,
703
+ standDownAllPendingRows,
695
704
  recordClusterRecommendationsMirror,
696
705
  _clearRecentIntakeCache,
697
706
  };
@@ -13,7 +13,7 @@ const {
13
13
  const { logger } = require('../../utils/logger');
14
14
  const { phoneDigits } = require('../../helpers/whatsappHelper');
15
15
 
16
- const { pausedSince } = require('../../helpers/pausedThreadHelper');
16
+ const { patientIsDeceased, pausedSince } = require('../../helpers/pausedThreadHelper');
17
17
  const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../../helpers/sendClaimHelper');
18
18
 
19
19
  const { normalizePayload: normalize, registerInteractiveRoute, unregisterInteractiveRoute } = require('../../core/interactiveRouteService');
@@ -112,6 +112,7 @@ function templateFor(reason) {
112
112
  async function offerSafetyNet({ code, reason = PAUSED }) {
113
113
  try {
114
114
  if (!code || !getSafetyNetContentSid() || !getSafetyNetPhone()) return { sent: false, reason: 'not_configured' };
115
+ if (await patientIsDeceased(code)) return { sent: false, reason: 'deceased' };
115
116
  if (await offerClaims().get(code)) return { sent: false, reason: 'recent_offer' };
116
117
  if (await pausedSince(code, new Date(Date.now() - getPauseQuietMs()))) return { sent: false, reason: 'just_paused' };
117
118
  if (await humanRepliedSince(code, new Date(Date.now() - getHumanQuietMs()))) return { sent: false, reason: 'human_active' };
@@ -8,6 +8,7 @@ const { getTriageHistory } = require('../services/triageHistoryService');
8
8
  const { getCarePlanHistory } = require('../services/carePlanHistoryService');
9
9
  const { getEscalationContext } = require('../services/escalationContextService');
10
10
  const { getPatientTasks, updatePatientTask } = require('../services/patientTaskService');
11
+ const { setPatientClinicalStatus } = require('../services/patientClinicalStatusService');
11
12
  const {
12
13
  getRecommendationCarousels,
13
14
  getRecommendationCarouselImage,
@@ -127,6 +128,18 @@ const updatePatientTaskController = async (req, res) => {
127
128
  }
128
129
  };
129
130
 
131
+ const setPatientClinicalStatusController = async (req, res) => {
132
+ try {
133
+ const { code } = req.params;
134
+ const { status, deceasedOn, updatedBy, source } = req.body || {};
135
+ const result = await setPatientClinicalStatus({ code, status, deceasedOn, updatedBy, source, requestId: req.requestId });
136
+ res.status(200).json({ success: true, ...result });
137
+ } catch (error) {
138
+ logger.error('Error setting patient clinical status:', { error: error.message, code: req.params?.code });
139
+ res.status(error.statusCode || 500).json({ success: false, error: error.message });
140
+ }
141
+ };
142
+
130
143
  const getPatientRecommendationCarouselsController = async (req, res) => {
131
144
  try {
132
145
  const code = String(req.params.code || '').trim();
@@ -301,5 +314,6 @@ module.exports = {
301
314
  getPatientRecommendationCarouselImageController,
302
315
  updatePatientController,
303
316
  updatePatientTaskController,
317
+ setPatientClinicalStatusController,
304
318
  logPatientChangeController,
305
319
  };
@@ -20,7 +20,7 @@ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
20
20
  const { maskCaregiverLabel, remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
21
21
  const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper');
22
22
  const { prepareMessageMedia } = require('../helpers/mediaHelper');
23
- const { botIsPaused } = require('../helpers/pausedThreadHelper');
23
+ const { botIsPaused, patientIsDeceased } = require('../helpers/pausedThreadHelper');
24
24
  const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../helpers/sendClaimHelper');
25
25
 
26
26
  const { createMessagingProvider } = require('../adapters/registry');
@@ -101,6 +101,8 @@ function createDefaultLlmMonitor(options, loader = loadDefaultLlmMonitor) {
101
101
  /**
102
102
  * Core messaging orchestrator for providers, storage, and assistant processing.
103
103
  */
104
+ const NOT_SENT_DECEASED = { success: false, messageId: null, status: 'patient_deceased', delivered: false, deferred: false };
105
+
104
106
  class NexusMessaging {
105
107
  constructor(config = {}) {
106
108
  this.config = config;
@@ -375,6 +377,9 @@ class NexusMessaging {
375
377
  */
376
378
 
377
379
  async sendMessage(messageData) {
380
+ // Only an operator writing now still reaches a deceased patient's phone; automations and scheduled sends do not.
381
+ const operatorNow = /@/.test(messageData.triggeredBy || '') && !String(messageData.idempotencyKey || '').startsWith('scheduled:');
382
+ if (!operatorNow && await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
378
383
  const claim = await acquireSendClaim(messageData);
379
384
  if (!claim.acquired) {
380
385
  return { success: false, messageId: null, status: 'duplicate_suppressed', duplicate: true, completed: claim.completed === true, delivered: false, deferred: false };
@@ -477,6 +482,7 @@ class NexusMessaging {
477
482
  }
478
483
 
479
484
  async sendAssistantReply(messageData) {
485
+ if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
480
486
  if (!messageData.contactCode && !messageData.preemptiveWindowRoute && !messageData.outreachStartedAt) {
481
487
  const contact = await replyContactFor(messageData.code);
482
488
  if (contact) messageData = { ...messageData, ...contact };
package/lib/fhir/index.js CHANGED
@@ -26,7 +26,7 @@ const {
26
26
  readPalliativeCarePlans,
27
27
  } = require('./services/palliativeService');
28
28
  const { storeTriage } = require('./services/triageService');
29
- const { storePatient, readPatient } = require('./services/patientService');
29
+ const { storePatient, storePatientDeceased, readPatient } = require('./services/patientService');
30
30
  const {
31
31
  storeContextFacts, readContextFacts, retractContextFacts, listContextFactPatients,
32
32
  } = require('./services/clinicalContextService');
@@ -85,6 +85,7 @@ module.exports = {
85
85
  readPalliativeCarePlans,
86
86
  storeTriage,
87
87
  storePatient,
88
+ storePatientDeceased,
88
89
  readPatient,
89
90
  storeContextFacts,
90
91
  readContextFacts,
@@ -19,9 +19,23 @@ async function storePatient({ patientId, profile = null }) {
19
19
  return { count: stored.length, ids: stored };
20
20
  }
21
21
 
22
+ // A null deceasedAt removes the mark, for a death recorded by mistake.
23
+ async function storePatientDeceased({ patientId, deceasedAt }) {
24
+ if (!String(patientId ?? '').trim()) throw new Error('storePatientDeceased patientId is required');
25
+ const patient = Patient.fromClinicalProfile({ patientId });
26
+ if (deceasedAt) patient.deceasedDateTime = deceasedAt;
27
+ const merge = (existing, next) => {
28
+ const merged = mergePatient(existing, next);
29
+ if (!deceasedAt) delete merged.deceasedDateTime;
30
+ return merged;
31
+ };
32
+ const { stored } = await storeResources([patient], { merge });
33
+ return { count: stored.length, ids: stored };
34
+ }
35
+
22
36
  async function readPatient({ patientId }) {
23
37
  if (!String(patientId ?? '').trim()) throw new Error('readPatient patientId is required');
24
38
  return getFhirStore().getByReference(`Patient/${fhirId(String(patientId))}`);
25
39
  }
26
40
 
27
- module.exports = { storePatient, readPatient, mergePatient };
41
+ module.exports = { storePatient, storePatientDeceased, readPatient, mergePatient };
@@ -29,4 +29,9 @@ async function pausedSince(code, since) {
29
29
  return Boolean(paused);
30
30
  }
31
31
 
32
- module.exports = { alertsMutedFor, botIsPaused, pausedSince };
32
+ async function patientIsDeceased(code) {
33
+ const deceased = await Thread.findOne({ code, deceasedAt: { $ne: null } }, { _id: 1 }).lean();
34
+ return Boolean(deceased);
35
+ }
36
+
37
+ module.exports = { alertsMutedFor, botIsPaused, patientIsDeceased, pausedSince };
@@ -135,6 +135,15 @@ class ScheduledMessageJob extends BaseJob {
135
135
  return { success: false, reason: 'duplicate_suppressed' };
136
136
  }
137
137
 
138
+ if (result?.status === 'patient_deceased') {
139
+ await ScheduledMessage.updateOne(
140
+ { _id: scheduledMessageId },
141
+ { $set: { status: 'cancelled', errorCode: result.status, errorMessage: 'The patient is deceased' } }
142
+ );
143
+ logger.info('[ScheduledMessageJob] Not sent to a deceased patient', { scheduledMessageId });
144
+ return { success: false, reason: result.status };
145
+ }
146
+
138
147
  const messageId = result?.messageId || result?.sid || null;
139
148
 
140
149
  await ScheduledMessage.updateOne(
@@ -12,6 +12,8 @@ const threadSchema = new mongoose.Schema({
12
12
  stopped: { type: Boolean, default: false },
13
13
  outreachOptOut: { type: Boolean, default: false },
14
14
  pausedAt: { type: Date, default: null },
15
+ deceasedAt: { type: Date, default: null },
16
+ programStatusBeforeDeath: { type: String, default: null },
15
17
  doNotAlertThrough: { type: Date, default: null },
16
18
  review: { type: Boolean, default: false },
17
19
  version: { type: Number, default: null },
@@ -76,6 +76,7 @@ const patientRouteDefinitions = {
76
76
  'GET /tasks/:code': 'getPatientTasksController',
77
77
  'PATCH /:code': 'updatePatientController',
78
78
  'PATCH /tasks/:code/:kind/:recordId': 'updatePatientTaskController',
79
+ 'PATCH /:code/clinical-status': 'setPatientClinicalStatusController',
79
80
  'POST /audit-log': 'logPatientChangeController'
80
81
  };
81
82
 
@@ -260,6 +261,7 @@ const builtInControllers = {
260
261
  getPatientRecommendationCarouselImageController: patientController.getPatientRecommendationCarouselImageController,
261
262
  updatePatientController: patientController.updatePatientController,
262
263
  updatePatientTaskController: patientController.updatePatientTaskController,
264
+ setPatientClinicalStatusController: patientController.setPatientClinicalStatusController,
263
265
  logPatientChangeController: patientController.logPatientChangeController,
264
266
 
265
267
  // Preset controllers
@@ -130,6 +130,7 @@ const processConversations = async (threads, airtableNameMap, openTaskMap, revie
130
130
  promptId: thread?.prompt_id || null,
131
131
  version: thread?.version || null,
132
132
  stopped: thread?.stopped ?? false,
133
+ deceasedAt: thread?.deceasedAt || null,
133
134
  review: thread?.review ?? false,
134
135
  unreadCount: thread?.unreadCount || 0,
135
136
  messageCount: thread?.messageCount || 0,
@@ -0,0 +1,135 @@
1
+ const { Historial_Clinico_ID } = require('../config/airtableConfig');
2
+
3
+ const { logger } = require('../utils/logger');
4
+ const { httpError } = require('../utils/httpErrorUtils');
5
+ const { WHATSAPP_PATIENT_CODE } = require('../utils/sanitizerUtils');
6
+
7
+ const { Thread } = require('../models/threadModel');
8
+ const { CANCELLABLE_STATUSES } = require('../models/escalationReviewModel');
9
+
10
+ const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
11
+ const { requirePatientIdentity } = require('../clinical/services/patientIdentityService');
12
+ const { standDownAllPendingRows } = require('../clinical/services/clinicalAirtableService');
13
+ const { updateRecordByFilter } = require('./airtableService');
14
+ const { logPatientChange } = require('./patientService');
15
+ const { openCaseIds, updatePatientTask } = require('./patientTaskService');
16
+ const { switchThreadStoppedStatus } = require('./threadService');
17
+ const { patientResourceWriteLive } = require('./patientResourceService');
18
+ const { cancelEscalationReview, listEscalationReviews } = require('./escalationReviewService');
19
+
20
+ const DECEASED = 'deceased';
21
+ const ACTIVE = 'active';
22
+ const PROGRAM_STATUS_BY_STATUS = { [DECEASED]: 'falleció', [ACTIVE]: 'active' };
23
+ const DECEASED_REASON = 'Paciente fallecido';
24
+ const ISO_DAY_RX = /^\d{4}-\d{2}-\d{2}$/;
25
+
26
+ function deceasedDayOf(value) {
27
+ const day = String(value ?? '').trim();
28
+ const date = new Date(`${day}T00:00:00Z`);
29
+ if (!ISO_DAY_RX.test(day) || Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== day) {
30
+ throw httpError(400, 'deceasedOn must be a YYYY-MM-DD date');
31
+ }
32
+ if (date.getTime() > Date.now()) throw httpError(400, 'deceasedOn cannot be in the future');
33
+ return day;
34
+ }
35
+
36
+ // Returns the program status the row had before this write.
37
+ async function writeProgramStatus(code, fields) {
38
+ const { recordId, record } = await requirePatientIdentity(Historial_Clinico_ID, code);
39
+ const filter = `AND(${recordIdIn([recordId])},${fieldEquals('whatsapp_id', code)})`;
40
+ const [updated] = await updateRecordByFilter(Historial_Clinico_ID, 'estado_general', filter, fields, code) || [];
41
+ if (!updated) throw httpError(502, 'The program status could not be written');
42
+ return record?.actual_status_program ?? null;
43
+ }
44
+
45
+ // Each follow-up step is attempted even when an earlier one fails; the failures are reported.
46
+ async function attempt(step, failed, work) {
47
+ try {
48
+ return await work();
49
+ } catch (error) {
50
+ logger.error('[patientClinicalStatus] Step failed', { step, error: error.message });
51
+ failed.push(step);
52
+ return null;
53
+ }
54
+ }
55
+
56
+ async function cancelOpenReviews({ code, updatedBy, requestId, closingCaseIds }) {
57
+ const reviews = await listEscalationReviews({ code });
58
+ const open = reviews.filter((review) => CANCELLABLE_STATUSES.includes(review.status));
59
+ for (const review of open) {
60
+ await cancelEscalationReview({ id: String(review._id), cancelledBy: updatedBy, reason: DECEASED_REASON, closingCaseIds, requestId });
61
+ }
62
+ return open.map((review) => String(review._id));
63
+ }
64
+
65
+ async function closeCases({ code, caseIds, updatedBy, source, requestId }) {
66
+ for (const recordId of caseIds) {
67
+ await updatePatientTask({ code, kind: 'cases', recordId, changes: { operationsStatus: 'No requiere' }, updatedBy, source, requestId });
68
+ }
69
+ return caseIds;
70
+ }
71
+
72
+ async function writeFhirDeceased(code, deceasedAt) {
73
+ if (!patientResourceWriteLive()) return;
74
+ const { storePatientDeceased } = require('../fhir');
75
+ await storePatientDeceased({ patientId: code, deceasedAt });
76
+ }
77
+
78
+ async function markThreadFields(code, fields) {
79
+ const { matchedCount } = await Thread.updateOne({ code }, { $set: fields });
80
+ if (!matchedCount) throw new Error('the patient has no thread');
81
+ }
82
+
83
+ async function markDeceased({ code, deceasedOn, updatedBy, source, requestId }) {
84
+ const previous = await writeProgramStatus(code, { actual_status_program: PROGRAM_STATUS_BY_STATUS[DECEASED], fecha_fallecimiento: deceasedOn });
85
+
86
+ const failed = [];
87
+ // A repeated mark keeps the status the patient had before the first one.
88
+ const kept = previous === PROGRAM_STATUS_BY_STATUS[DECEASED] ? {} : { programStatusBeforeDeath: previous };
89
+ await attempt('mark_thread', failed, () => markThreadFields(code, { deceasedAt: new Date(`${deceasedOn}T00:00:00Z`), ...kept }));
90
+ // Unread cases leave the review to close only what the team already saw, never everything it covers.
91
+ const caseIds = await attempt('read_cases', failed, () => openCaseIds(code));
92
+ // A cancelled review resumes the bot it paused, so the reviews go before the pause.
93
+ const cancelledReviewIds = await attempt('cancel_reviews', failed, () => cancelOpenReviews({ code, updatedBy, requestId, closingCaseIds: caseIds })) || [];
94
+ const closedCaseIds = await attempt('close_cases', failed, () => closeCases({ code, caseIds: caseIds || [], updatedBy, source, requestId })) || [];
95
+ await attempt('pause_bot', failed, () => switchThreadStoppedStatus(code, true, { byOperator: true }));
96
+ await attempt('stand_down_reminders', failed, async () => {
97
+ if (!(await standDownAllPendingRows({ code, reason: 'patient_deceased' }))) throw new Error('pending rows were not stood down');
98
+ });
99
+ await attempt('fhir_patient', failed, () => writeFhirDeceased(code, deceasedOn));
100
+
101
+ return { status: DECEASED, deceasedOn, cancelledReviewIds, closedCaseIds, failed };
102
+ }
103
+
104
+ // Undoes a death recorded by mistake, restoring the program status the patient had. Closed cases stay closed.
105
+ async function markActive({ code }) {
106
+ const thread = await Thread.findOne({ code }, { programStatusBeforeDeath: 1 }).lean();
107
+ await writeProgramStatus(code, { actual_status_program: thread?.programStatusBeforeDeath ?? null, fecha_fallecimiento: null });
108
+ const failed = [];
109
+ await attempt('clear_thread', failed, () => Thread.updateOne({ code }, { $set: { deceasedAt: null, programStatusBeforeDeath: null } }));
110
+ await attempt('fhir_patient', failed, () => writeFhirDeceased(code, null));
111
+ return { status: ACTIVE, failed };
112
+ }
113
+
114
+ async function setPatientClinicalStatus({ code, status, deceasedOn, updatedBy, source, requestId = null }) {
115
+ const whatsappId = String(code || '').trim();
116
+ if (!WHATSAPP_PATIENT_CODE.test(whatsappId)) throw httpError(400, 'A whatsapp:+<digits> patient code is required');
117
+ if (!updatedBy || !source) throw httpError(400, 'updatedBy and source are required');
118
+ if (!Object.hasOwn(PROGRAM_STATUS_BY_STATUS, status)) throw httpError(400, `Unknown status: ${status}`);
119
+
120
+ const result = status === DECEASED
121
+ ? await markDeceased({ code: whatsappId, deceasedOn: deceasedDayOf(deceasedOn), updatedBy, source, requestId })
122
+ : await markActive({ code: whatsappId });
123
+
124
+ await logPatientChange({
125
+ code: whatsappId,
126
+ updatedBy,
127
+ source,
128
+ requestId,
129
+ changes: { clinicalStatus: status, ...(result.deceasedOn && { deceasedOn: result.deceasedOn }) },
130
+ status: result.failed.length ? 'partial' : 'success',
131
+ });
132
+ return result;
133
+ }
134
+
135
+ module.exports = { setPatientClinicalStatus };
@@ -4,6 +4,7 @@ const runtimeConfig = require('../config/runtimeConfig.js');
4
4
  const { logger } = require('../utils/logger');
5
5
 
6
6
  const { Thread } = require('../models/threadModel.js');
7
+ const { patientIsDeceased } = require('../helpers/pausedThreadHelper.js');
7
8
 
8
9
  const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService.js');
9
10
  const { ensurePatientResource } = require('../services/patientResourceService.js');
@@ -36,6 +37,8 @@ const getThreadInfo = async (code, { rethrow = false } = {}) => {
36
37
  };
37
38
 
38
39
  const switchThreadStoppedStatus = async (code, stopped, { byOperator = false } = {}) => {
40
+ // A deceased patient's bot stays paused until the death is undone, whoever asks to resume it.
41
+ if (!stopped && await patientIsDeceased(code)) return { matchedCount: 0, modifiedCount: 0 };
39
42
  const result = stopped && byOperator
40
43
  ? await Thread.updateOne({ code, stopped: { $ne: true } }, { stopped, pausedAt: new Date() })
41
44
  : await Thread.updateOne({ code }, stopped ? { stopped } : { stopped, pausedAt: null });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.72.12",
3
+ "version": "5.72.13",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",