@peopl-health/nexus 6.0.0-dev.16614 → 6.0.0-dev.16616

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.
@@ -218,7 +218,7 @@ const GROUP_MESSAGE_ID_FIELD = 'group_message_id';
218
218
  async function readGroupMessageId(recordId, code) {
219
219
  if (!/^rec[A-Za-z0-9]+$/.test(String(recordId ?? ''))) return null;
220
220
  try {
221
- const rows = await airtableService.getRecordByFilter(Monitoreo_ID, 'emergencies', `RECORD_ID() = '${recordId}'`, null, [GROUP_MESSAGE_ID_FIELD]);
221
+ const rows = await airtableService.getRecordByFilter(Monitoreo_ID, 'emergencies', recordIdIn([recordId]), null, [GROUP_MESSAGE_ID_FIELD]);
222
222
  return String(rows?.[0]?.[GROUP_MESSAGE_ID_FIELD] ?? '').trim() || null;
223
223
  } catch (error) {
224
224
  logger.warn('[clinicalAirtableService] The group message id could not be read; the follow-up goes out unthreaded', { code, recordId, error: error.message });
@@ -493,4 +493,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
493
493
  return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
494
494
  }
495
495
 
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, ASAP_CHECK_IN_WINDOW };
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 };
@@ -9,6 +9,7 @@ const { readStructuredText } = require('../helpers/structuredTextHelper');
9
9
 
10
10
  const { getEscalationContext } = require('../../services/escalationContextService');
11
11
 
12
+ const { normalizedKeyOf } = require('../../utils/coercionUtils');
12
13
  const { logger } = require('../../utils/logger');
13
14
  const { arrayArg, safeParse } = require('../../utils/jsonUtils');
14
15
  const { withTiming } = require('../../utils/tracingDecorator');
@@ -90,7 +91,6 @@ function draftProvider() {
90
91
  }
91
92
 
92
93
  const MAX_URGENT_FLAGS = 2;
93
- const flagKey = (flag) => String(flag ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
94
94
 
95
95
  // The model does not always keep to two grave flags per symptom. Confirmed flags keep the mark first, then the pending ones the
96
96
  // previous draft already held (so their wait keeps running when the model reorders them), then the rest in its order.
@@ -100,7 +100,7 @@ function capUrgentFlags(block, held) {
100
100
  const rank = (flag) => {
101
101
  if (flag.present === true) return 0;
102
102
  if (flag.present === false) return 3;
103
- return held.has(flagKey(flag.flag)) ? 1 : 2;
103
+ return held.has(normalizedKeyOf(flag.flag)) ? 1 : 2;
104
104
  };
105
105
  const kept = new Set([...urgent].sort((a, b) => rank(a) - rank(b)).slice(0, MAX_URGENT_FLAGS));
106
106
  return { ...block, redFlags: block.redFlags.map((flag) => (urgent.includes(flag) && !kept.has(flag) ? { ...flag, urgentIfPositive: false } : flag)) };
@@ -148,7 +148,7 @@ async function generateEscalationDraft({
148
148
  const parsed = safeParse(readStructuredText(result), null);
149
149
  const patientMessage = trimmed(parsed?.patientMessage);
150
150
  // The schema is not strict, so the model sometimes sends the list JSON-encoded as a string.
151
- const held = new Set(heldUrgentFlags.map(flagKey));
151
+ const held = new Set(heldUrgentFlags.map(normalizedKeyOf));
152
152
  const blocks = (parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms)).map((block) => capUrgentFlags(block, held));
153
153
  if (!blocks.length) {
154
154
  const shape = parsed.symptoms;
@@ -1041,14 +1041,17 @@ async function armPatientTimerOnJoin(review, alarm, now) {
1041
1041
  }
1042
1042
  }
1043
1043
 
1044
+ // The alarm an alert is about: the one named, else the latest at its level, else the latest.
1045
+ const alarmFor = (review, urgencyLevel, alarmId) => (alarmId && (review.alarms ?? []).find((raised) => raised.alarmId === alarmId))
1046
+ ?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1047
+
1044
1048
  async function prepareDoctorAlert(review, urgencyLevel, { recipient = null, alarmId = null } = {}) {
1045
1049
  const identity = await readDoctorIdentity(review);
1046
1050
  if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
1047
1051
  const approver = recipient ?? await soleApprover();
1048
1052
  const link = conversationLink(review.patientCode);
1049
1053
  if (!link) throw new Error('missing the interface URL for the chat link');
1050
- const alarm = (alarmId && review.alarms?.find((raised) => raised.alarmId === alarmId))
1051
- ?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1054
+ const alarm = alarmFor(review, urgencyLevel, alarmId);
1052
1055
  const symptom = inlineOf(alarm?.symptom);
1053
1056
  const urgency = urgencyLevel.toUpperCase();
1054
1057
  const patient = `${identity.patientName} (${identity.treatingDoctor})`;
@@ -1274,8 +1277,7 @@ async function teamAlertIdentity(review) {
1274
1277
 
1275
1278
  async function teamFallbackNotice(review, urgencyLevel, alarmId) {
1276
1279
  const { patient, doctor, link } = await teamAlertIdentity(review);
1277
- const alarm = (alarmId && (review.alarms ?? []).find((raised) => raised.alarmId === alarmId))
1278
- ?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1280
+ const alarm = alarmFor(review, urgencyLevel, alarmId);
1279
1281
  const what = [urgencyLevel.toUpperCase(), oneLineOf(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
1280
1282
  return {
1281
1283
  body: `⚠️ ${ALERT_MARKS[urgencyLevel]} ${what}\n${patient} (${doctor})\n${link}`,
@@ -2183,7 +2185,6 @@ module.exports = {
2183
2185
  addCallLog,
2184
2186
  caseTakenReason,
2185
2187
  currentAlarms,
2186
- doctorIdentity,
2187
2188
  teamAlertIdentity,
2188
2189
  addDraft,
2189
2190
  alertWithoutEmergencyRow,
@@ -1,8 +1,9 @@
1
+ const { normalizedKeyOf } = require('../utils/coercionUtils');
2
+
1
3
  const { DOCUMENTING_STATUSES } = require('./escalationReviewService');
2
4
  const { pendingWaitMinutes } = require('./reviewDeadlineService');
3
5
 
4
- const keyOf = (flag) => String(flag ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
5
- const keysOf = (flags) => [...new Set((flags ?? []).map(keyOf).filter(Boolean))];
6
+ const keysOf = (flags) => [...new Set((flags ?? []).map(normalizedKeyOf).filter(Boolean))];
6
7
 
7
8
  // The urgent red flags still pending in the latest draft of this episode, and since when each has been pending without a break.
8
9
  function pendingFlagsOf(review, since) {
@@ -179,19 +179,32 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
179
179
  .lean();
180
180
  const policy = responseDeadlinePolicy();
181
181
  let sent = 0;
182
+ const failed = (message, review, error) => logger.error(message, {
183
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
184
+ });
182
185
  for (const review of reviews) {
186
+ let clock;
187
+ try {
188
+ clock = untakenClockOf(review, policy);
189
+ } catch (error) {
190
+ failed('[UntakenAlert] Could not check a review for an untaken alert', review, error);
191
+ continue;
192
+ }
193
+ // A failed team alert must not keep the case from the doctor, so each step fails on its own.
183
194
  try {
184
- const clock = untakenClockOf(review, policy);
185
195
  const stage = alerts && clock && dueStageOf(review, clock, now);
186
196
  if (stage && await alertIfUntaken(review, clock, stage, now)) sent += 1;
187
- if (autoHandoff) await settleCharacterization(review, clock, now);
188
197
  } catch (error) {
189
- logger.error('[UntakenAlert] Could not check a review for an untaken alert', {
190
- escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
191
- });
198
+ failed('[UntakenAlert] Could not check a review for an untaken alert', review, error);
199
+ }
200
+ if (!autoHandoff) continue;
201
+ try {
202
+ await settleCharacterization(review, clock, now);
203
+ } catch (error) {
204
+ failed('[UntakenAlert] Could not settle the characterization of a review', review, error);
192
205
  }
193
206
  }
194
207
  return sent;
195
208
  }
196
209
 
197
- module.exports = { sweepUntakenAlerts, untakenClockOf };
210
+ module.exports = { sweepUntakenAlerts };
@@ -4,7 +4,8 @@ const strList = (value) => arr(value).map(str).map((item) => item.trim()).filter
4
4
  const firstOf = (value) => (Array.isArray(value) ? value[0] : value);
5
5
  const inlineOf = (value) => String(firstOf(value) ?? '').trim();
6
6
  const oneLineOf = (value) => inlineOf(value).replace(/\s+/g, ' ');
7
+ const normalizedKeyOf = (value) => oneLineOf(value).toLowerCase();
7
8
 
8
9
  module.exports = {
9
- str, arr, strList, firstOf, inlineOf, oneLineOf,
10
+ str, arr, strList, firstOf, inlineOf, oneLineOf, normalizedKeyOf,
10
11
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.0-dev.16614",
3
+ "version": "6.0.0-dev.16616",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",