@peopl-health/nexus 6.0.0-dev.15739 → 6.0.0-dev.15740

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.
@@ -8,7 +8,7 @@ const { dispatcherService } = require('../services/dispatcherService');
8
8
  const { armEscalationNet } = require('../services/contingencyDispatchService');
9
9
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
10
10
  const { escalationAssessmentLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
11
- const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
11
+ const { alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
12
12
  const { URGENCY_RANK } = require('../../models/escalationReviewModel');
13
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
14
14
  const { logger } = require('../../utils/logger');
@@ -401,6 +401,10 @@ async function handler(args, context = {}) {
401
401
  onRecorded: (recordId) => { emergencyRecordId = recordId; },
402
402
  });
403
403
  if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
404
+ // A merge into an existing row never alerts, so only a row that had to be created falls back.
405
+ if (review && !queued && (raisesOpen || !anchor?.emergencyRecordId)) {
406
+ alertWithoutEmergencyRow({ reviewId: review._id, alarmId, urgencyLevel }).catch(() => {});
407
+ }
404
408
  if (urgencyLevel !== 'routine') {
405
409
  try {
406
410
  const net = queued ? await armEscalationNet({
@@ -44,7 +44,7 @@ const impressionUpdateSchema = new mongoose.Schema({
44
44
  }, { _id: false });
45
45
 
46
46
  const doctorAlertSchema = new mongoose.Schema({
47
- kind: { type: String, enum: ['initial', 'realert', 'patient_prompt'], required: true },
47
+ kind: { type: String, enum: ['initial', 'realert', 'patient_prompt', 'fallback'], required: true },
48
48
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, default: null },
49
49
  physicianEmail: { type: String, default: null },
50
50
  transport: { type: String, default: null },
@@ -78,7 +78,7 @@ const SETTLEABLE_STATUSES = ['indications_sent', 'monitoring'];
78
78
  const DRAFTLESS_DECISIONS = ['monitor', 'returned'];
79
79
  const SETTLED_TRAJECTORIES = ['improving', 'stable'];
80
80
  const ALERTED_URGENCIES = ['stat', 'asap'];
81
- const ALERT_MARKS = { stat: '🔴', asap: '🟠' };
81
+ const ALERT_MARKS = { stat: '🔴', asap: '🟠', urgent: '🟡' };
82
82
  const DEFAULT_FEVER_TIMER_MINUTES = 15;
83
83
  const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
84
84
  const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
@@ -1031,13 +1031,14 @@ async function armPatientTimerOnJoin(review, alarm, now) {
1031
1031
  }
1032
1032
  }
1033
1033
 
1034
- async function prepareDoctorAlert(review, urgencyLevel) {
1034
+ async function prepareDoctorAlert(review, urgencyLevel, { recipient = null, alarmId = null } = {}) {
1035
1035
  const identity = await readDoctorIdentity(review);
1036
1036
  if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
1037
- const approver = await soleApprover();
1037
+ const approver = recipient ?? await soleApprover();
1038
1038
  const link = conversationLink(review.patientCode);
1039
1039
  if (!link) throw new Error('missing the interface URL for the chat link');
1040
- const alarm = (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1040
+ const alarm = (alarmId && review.alarms?.find((raised) => raised.alarmId === alarmId))
1041
+ ?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1041
1042
  const symptom = inlineOf(alarm?.symptom);
1042
1043
  const urgency = urgencyLevel.toUpperCase();
1043
1044
  const patient = `${identity.patientName} (${identity.treatingDoctor})`;
@@ -1241,6 +1242,37 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1241
1242
  return updated;
1242
1243
  }
1243
1244
 
1245
+ async function fallbackRecipient() {
1246
+ const phone = String(runtimeConfig.get('ESCALATION_FALLBACK_ALERT_PHONE', '') ?? '').trim();
1247
+ return phone ? { name: null, email: null, phone } : soleApprover();
1248
+ }
1249
+
1250
+ // Airtable alerts the team only once its emergencies row exists; when that write failed, nexus alerts instead.
1251
+ async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel, now = new Date() }) {
1252
+ if (escalationApproverAlertLive() || !ALERT_MARKS[urgencyLevel]) return null;
1253
+ let review;
1254
+ let delivery;
1255
+ try {
1256
+ review = await loadReview(reviewIdOf(reviewId));
1257
+ const recipient = await fallbackRecipient();
1258
+ const { approver, message } = await prepareDoctorAlert(review, urgencyLevel, { recipient, alarmId });
1259
+ delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
1260
+ } catch (error) {
1261
+ delivery = { error: redactedError(error) };
1262
+ logger.error('[EscalationReview] The alert for a missing emergencies row was not sent', { escalationReviewId: String(reviewId), urgencyLevel, error: delivery.error });
1263
+ }
1264
+ if (!review) return null;
1265
+ const sent = { kind: 'fallback', urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
1266
+ try {
1267
+ const updated = await getEscalationReview().findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1268
+ await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'emergency_row_fallback_alerted', urgencyLevel, delivered: !sent.error, transport: sent.transport });
1269
+ return updated;
1270
+ } catch (error) {
1271
+ logger.error('[EscalationReview] The fallback alert was not recorded', { escalationReviewId: String(reviewId), error: redactedError(error) });
1272
+ return null;
1273
+ }
1274
+ }
1275
+
1244
1276
  async function reopenFromFollowUp(review, reason) {
1245
1277
  const reopened = await getEscalationReview()
1246
1278
  .findOneAndUpdate({ _id: review._id, status: review.status }, { $set: { status: 'documenting', updatedSinceSeen: true } }, { new: true })
@@ -2069,6 +2101,7 @@ module.exports = {
2069
2101
  _resetEscalationReviewIndexes,
2070
2102
  addCallLog,
2071
2103
  addDraft,
2104
+ alertWithoutEmergencyRow,
2072
2105
  attachEmergencyRow,
2073
2106
  cancelEscalationReview,
2074
2107
  closeEscalationReview,
@@ -19,7 +19,7 @@ const dueQuery = (now) => ({
19
19
  {
20
20
  doctorAlertDueAt: null,
21
21
  status: { $in: PRE_DECISION_STATUSES },
22
- 'doctorAlerts.0': { $exists: false },
22
+ doctorAlerts: { $not: { $elemMatch: { kind: 'initial' } } },
23
23
  alarms: { $elemMatch: { urgencyLevel: { $in: ALERTED_URGENCIES }, raisedAt: { $gte: new Date(now.getTime() - SELF_HEAL_WINDOW_MS) } } },
24
24
  },
25
25
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.0-dev.15739",
3
+ "version": "6.0.0-dev.15740",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",