@peopl-health/nexus 6.6.3 → 6.6.4

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, escalationPatientTimerLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
11
- const { alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
11
+ const { ANSWER_ONLY, FEVER_CATEGORY, 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');
@@ -170,7 +170,22 @@ const MODE_PROPERTY = {
170
170
  'description': '`new`: primer aviso de este episodio. `update`: agrega lo nuevo a la escalación que sigue abierta para este paciente, sin generar otro aviso al equipo si el nivel no sube. El nivel aplicado es el mayor entre el abierto y el que pides: uno menor no baja la escalación, queda registrado como sugerencia para el equipo. Usa `update` para sumar lo que respondió el paciente y para subir el nivel en cuanto un dato nuevo haga plausible algo más grave.',
171
171
  };
172
172
 
173
- const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
173
+ const WHAT_CHANGED = ['new_symptom', 'higher_grade', 'new_red_flag', 'worse', 'persists_unanswered', ANSWER_ONLY];
174
+
175
+ const WHAT_CHANGED_PROPERTY = nullableEnum(WHAT_CHANGED);
176
+ WHAT_CHANGED_PROPERTY.description = 'Solo en `update`: qué trae de nuevo. `answer_only` cuando el paciente solo respondió lo que se le preguntó y su respuesta no agrega síntoma, grado, bandera roja ni empeoramiento (por ejemplo «no tengo fiebre, puedo tragar»). Si el equipo ya decidió el caso, un `answer_only` sin subir el nivel queda anotado en el caso sin volver a avisar al equipo. Ante cualquier duda usa el valor que corresponda o `null`: nunca `answer_only` si algo empeoró o apareció algo nuevo.';
177
+
178
+ const FEVER_RULED_OUT_PROPERTY = nullable({
179
+ 'type': 'boolean',
180
+ 'description': 'Solo en `update`; llénalo siempre (`null` si no aplica). `true` solo con una lectura en `fever_reading_c`: cuando el paciente dio una temperatura medida después del dato de fiebre, entre 36.0 y 37.4 °C, niega escalofríos y no tomó paracetamol, antiinflamatorio ni corticoide en las 6 h previas a esa medición. Con un antipirético o corticoide reciente, o con malestar mientras lo toma, la fiebre no está descartada: deja `null`. Entonces la alarma se registra como `treatment_concern` y el caso deja de tratarse como fiebre. Una fiebre que vuelva después va en una alarma nueva con `febrile_neutropenia`.',
181
+ });
182
+
183
+ const FEVER_READING_PROPERTY = nullable({
184
+ 'type': 'number',
185
+ 'description': 'Solo en `update`; llénalo siempre. La temperatura más reciente en °C que el paciente midió con termómetro y escribió como número en esta conversación (por ejemplo 36.4). `null` si no dio un número: «no tengo fiebre» o «me siento bien» sin lectura es `null`. Nunca la deduzcas ni la tomes de otro episodio.',
186
+ });
187
+
188
+ const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. En cada `update` llena siempre `what_changed`, `fever_reading_c` y `fever_ruled_out`: si dejas uno vacío, la alarma se trata como dato nuevo y como fiebre abierta, y el equipo vuelve a recibir el aviso. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
174
189
 
175
190
  const CLINICAL_ASSESSMENT_PROPERTY = nullable({
176
191
  'type': 'object',
@@ -222,6 +237,12 @@ function liveDefinition() {
222
237
  live.description += MODE_DESCRIPTION;
223
238
  properties.mode = MODE_PROPERTY;
224
239
  required.push('mode');
240
+ properties.what_changed = WHAT_CHANGED_PROPERTY;
241
+ required.push('what_changed');
242
+ properties.fever_reading_c = FEVER_READING_PROPERTY;
243
+ required.push('fever_reading_c');
244
+ properties.fever_ruled_out = FEVER_RULED_OUT_PROPERTY;
245
+ required.push('fever_ruled_out');
225
246
  }
226
247
  if (assessment) {
227
248
  properties.details.properties.clinical_assessment = CLINICAL_ASSESSMENT_PROPERTY;
@@ -231,6 +252,14 @@ function liveDefinition() {
231
252
  return live;
232
253
  }
233
254
 
255
+ const NORMAL_TEMP_C = [36.0, 37.4];
256
+
257
+ // A reading counts only as a plausible body temperature in °C.
258
+ function readingOf(value) {
259
+ const reading = typeof value === 'string' ? Number(value.replace(',', '.')) : value;
260
+ return typeof reading === 'number' && Number.isFinite(reading) && reading >= 30 && reading <= 45 ? reading : null;
261
+ }
262
+
234
263
  const yesNo = (value) => (value === true ? 'sí' : value === false ? 'no' : null);
235
264
 
236
265
  function knownExplanationNote(known) {
@@ -297,8 +326,14 @@ async function handler(args, context = {}) {
297
326
  const details = parsedDetails || {};
298
327
  const rawCategory = details.category ?? null;
299
328
  const requestedCategory = typeof rawCategory === 'string' ? rawCategory.trim() : rawCategory;
300
- const category = CATEGORIES.includes(requestedCategory) ? requestedCategory : null;
301
- const categoryCoerced = rawCategory !== null && category === null;
329
+ const listedCategory = CATEGORIES.includes(requestedCategory) ? requestedCategory : null;
330
+ const feverReading = updateMode ? readingOf(args?.fever_reading_c) : null;
331
+ const normalReading = feverReading !== null && feverReading >= NORMAL_TEMP_C[0] && feverReading <= NORMAL_TEMP_C[1];
332
+ const feverRuledOut = normalReading && args?.fever_ruled_out === true;
333
+ const category = feverRuledOut && listedCategory === FEVER_CATEGORY ? 'treatment_concern' : listedCategory;
334
+ const categoryCoerced = rawCategory !== null && listedCategory === null;
335
+ const claimedChange = updateMode && WHAT_CHANGED.includes(args?.what_changed) ? args.what_changed : null;
336
+ const whatChanged = claimedChange === ANSWER_ONLY && feverReading !== null && !normalReading ? null : claimedChange;
302
337
  const clinicalAssessment = escalationAssessmentLive() && isPlainObject(details.clinical_assessment) ? details.clinical_assessment : null;
303
338
  const strictlyParsed = typeof rawDetails === 'string' && isPlainObject(safeParse(rawDetails, null));
304
339
  const detailsArg = typeof rawDetails === 'string'
@@ -333,9 +368,13 @@ async function handler(args, context = {}) {
333
368
  .filter((indicator) => typeof indicator === 'string' && indicator.trim()),
334
369
  turnId: runtime.turnId || null,
335
370
  ...(clinicalAssessment ? { clinicalAssessment } : {}),
371
+ ...(feverRuledOut ? { feverRuledOut: true } : {}),
372
+ ...(feverReading !== null ? { feverReadingC: feverReading } : {}),
373
+ ...(whatChanged ? { whatChanged } : {}),
336
374
  },
337
375
  })
338
376
  : null;
377
+ const heldInFollowUp = whatChanged === ANSWER_ONLY && Boolean((review?.alarms ?? []).find((raised) => raised.alarmId === alarmId)?.isHeldInFollowUp);
339
378
  const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
340
379
  const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
341
380
  const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
@@ -364,7 +403,7 @@ async function handler(args, context = {}) {
364
403
  },
365
404
  });
366
405
 
367
- if (runtime.turnId && runtime.patientCode && raisesOpen) {
406
+ if (runtime.turnId && runtime.patientCode && raisesOpen && !heldInFollowUp) {
368
407
  try {
369
408
  await dispatcherService.dispatch({
370
409
  trace,
@@ -382,7 +421,9 @@ async function handler(args, context = {}) {
382
421
  let netReason = null;
383
422
 
384
423
  if (runtime.patientCode) {
385
- if (urgencyLevel === 'routine') {
424
+ if (heldInFollowUp) {
425
+ queued = true;
426
+ } else if (urgencyLevel === 'routine') {
386
427
  const { written, duplicate } = await writeUnresolvedRequest({
387
428
  code: runtime.patientCode,
388
429
  trace,
@@ -450,11 +491,15 @@ async function handler(args, context = {}) {
450
491
  safety_net_armed: netArmed,
451
492
  safety_net_reason: netReason,
452
493
  team_has_reviewed: false,
453
- means: queued
454
- ? 'The escalation is QUEUED for the care team. This is not confirmation that anyone has read or acted on it, and no reply has arrived. Do not tell the patient the team already reviewed it, and do not treat the topic as closed on the strength of this ack.'
455
- : 'The escalation was NOT recorded for the team. Say nothing to the patient implying they were notified, and report the failure.',
456
- follow_up: followUpNote(netArmed, netReason),
494
+ means: heldInFollowUp
495
+ ? 'Recorded on the case the team already decided; the team was not paged again. Tell the patient you noted it and keep to the team\'s indication.'
496
+ : queued
497
+ ? 'The escalation is QUEUED for the care team. This is not confirmation that anyone has read or acted on it, and no reply has arrived. Do not tell the patient the team already reviewed it, and do not treat the topic as closed on the strength of this ack.'
498
+ : 'The escalation was NOT recorded for the team. Say nothing to the patient implying they were notified, and report the failure.',
499
+ follow_up: heldInFollowUp ? 'The team\'s indication for this case stands; no new check-in was armed.' : followUpNote(netArmed, netReason),
457
500
  ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
501
+ ...(heldInFollowUp ? { held_in_follow_up: true } : {}),
502
+ ...(category !== listedCategory ? { category_recorded_as: category } : {}),
458
503
  ...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
459
504
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
460
505
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
@@ -34,6 +34,9 @@ const alarmSchema = new mongoose.Schema({
34
34
  emergencyRecordId: { type: String, default: null },
35
35
  appliedLevel: { type: String, default: null },
36
36
  isHeldInFollowUp: { type: Boolean, default: undefined },
37
+ feverRuledOut: { type: Boolean, default: undefined },
38
+ feverReadingC: { type: Number, default: undefined },
39
+ whatChanged: { type: String, default: null },
37
40
  raisedAt: { type: Date, required: true },
38
41
  }, { _id: false });
39
42
 
@@ -104,6 +104,7 @@ const DEFAULT_FEVER_TIMER_MINUTES = 15;
104
104
  const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
105
105
  const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
106
106
  const FEVER_CATEGORY = 'febrile_neutropenia';
107
+ const ANSWER_ONLY = 'answer_only';
107
108
  const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
108
109
  const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
109
110
  const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
@@ -583,7 +584,8 @@ async function closeStaleInterruption(EscalationReview, patientCode, now) {
583
584
  }
584
585
 
585
586
  function shouldHoldInFollowUp(review, alarm, mode) {
586
- if (mode !== 'update' || ALERTED_URGENCIES.includes(alarm.urgencyLevel)) return false;
587
+ if (mode !== 'update') return false;
588
+ if (ALERTED_URGENCIES.includes(alarm.urgencyLevel) && (alarm.whatChanged !== ANSWER_ONLY || alarm.category === FEVER_CATEGORY)) return false;
587
589
  const decided = effectiveUrgencyOf({ ...review, alarms: (review.alarms ?? []).filter((entry) => entry.alarmId !== alarm.alarmId) })?.urgency;
588
590
  return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
589
591
  }
@@ -615,11 +617,13 @@ async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date
615
617
  await closeStaleInterruption(EscalationReview, patientCode, now);
616
618
  const joined = await join();
617
619
  if (joined) {
620
+ if (FOLLOWUP_STATUSES.includes(joined.status) && shouldHoldInFollowUp(joined, entry, mode)) {
621
+ const held = await holdInFollowUp(joined, entry);
622
+ if (held !== joined) return held;
623
+ }
618
624
  await scheduleDoctorAlert(joined, entry, now);
619
625
  await armPatientTimerOnJoin(joined, entry, now);
620
- if (FOLLOWUP_STATUSES.includes(joined.status)) {
621
- return shouldHoldInFollowUp(joined, entry, mode) ? await holdInFollowUp(joined, entry) : await reopenFromFollowUp(joined, 'new_alarm');
622
- }
626
+ if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
623
627
  if (!DOCUMENTING_STATUSES.includes(joined.status)) {
624
628
  logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
625
629
  escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
@@ -1034,8 +1038,15 @@ const timerMs = (key, fallback) => {
1034
1038
 
1035
1039
  const appliedLevelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
1036
1040
 
1037
- const feverAlarmsOf = (review) => currentAlarms(review)
1038
- .filter((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
1041
+ const isLiveFeverOf = (review) => {
1042
+ const clearedMs = Math.max(-Infinity, ...(review.alarms ?? []).filter((alarm) => alarm.feverRuledOut).map((alarm) => new Date(alarm.raisedAt).getTime()));
1043
+ return (alarm) => alarm.category === FEVER_CATEGORY && new Date(alarm.raisedAt).getTime() > clearedMs;
1044
+ };
1045
+
1046
+ const feverAlarmsOf = (review) => {
1047
+ const isLiveFever = isLiveFeverOf(review);
1048
+ return currentAlarms(review).filter((alarm) => appliedLevelOf(alarm) === 'asap' && isLiveFever(alarm));
1049
+ };
1039
1050
 
1040
1051
  async function feverTimerGap(patientCode, now) {
1041
1052
  if (!chemoContextLive()) return 'chemo_context_off';
@@ -1072,7 +1083,8 @@ function timerLevelOf(review) {
1072
1083
  // level timers, a prompt that fires was armed as the fever prompt and fires as armed.
1073
1084
  async function patientTimerOf(review, level, now, { firing = false } = {}) {
1074
1085
  const levelTimer = escalationTimerLive() && Boolean(PATIENT_TIMER_PROMPT_IDS[level]);
1075
- const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
1086
+ const isLiveFever = isLiveFeverOf(review);
1087
+ const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && isLiveFever(alarm));
1076
1088
  const fever = level === 'asap' && feverTimerLive() && (armedAsFever || feverAlarmsOf(review).length > 0);
1077
1089
  const gap = fever && !armedAsFever ? await feverTimerGap(review.patientCode, now) : null;
1078
1090
  if (fever && !gap) {
@@ -2623,8 +2635,10 @@ module.exports = {
2623
2635
  DOCUMENTING_STATUSES,
2624
2636
  DRAFT_OPERATOR,
2625
2637
  MAX_DOCTOR_UPDATES,
2638
+ ANSWER_ONLY,
2626
2639
  FEVER_CATEGORY,
2627
2640
  appliedLevelOf,
2641
+ isLiveFeverOf,
2628
2642
  MAX_ALERT_ATTEMPTS,
2629
2643
  PRE_DECISION_STATUSES,
2630
2644
  _resetEscalationReviewIndexes,
@@ -9,7 +9,7 @@ const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntaken
9
9
 
10
10
  const { logPatientChange } = require('./patientService');
11
11
  const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
12
- const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
12
+ const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, PRE_DECISION_STATUSES, appliedLevelOf, isLiveFeverOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
13
13
  const { settleCharacterization } = require('./characterizationOutcomeService');
14
14
  const { sendTeamAlert } = require('./teamAlertService');
15
15
  const { digestDueAt, digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
@@ -56,6 +56,7 @@ function episodeStartOf(alarms) {
56
56
  }
57
57
 
58
58
  function untakenClockOf(review, policy) {
59
+ const isLiveFever = isLiveFeverOf(review);
59
60
  const entries = levelsOf(currentAlarms(review).filter((alarm) => !alarm.isHeldInFollowUp), review.urgencyReclassifications, appliedLevelOf).filter((entry) => UNTAKEN_LEVELS.includes(entry.level));
60
61
  const level = entries.reduce((top, entry) => (URGENCY_RANK[entry.level] > (URGENCY_RANK[top] || 0) ? entry.level : top), null);
61
62
  if (!level) return null;
@@ -68,7 +69,7 @@ function untakenClockOf(review, policy) {
68
69
  stagesFrom,
69
70
  symptom: oneLineOf(atLevel.at(-1).alarm.symptom),
70
71
  emergencyRecordId: atLevel.find((entry) => entry.alarm.emergencyRecordId)?.alarm.emergencyRecordId ?? null,
71
- stages: untakenStagesOf(level, stagesFrom, policy, { fever: level === 'asap' && feverPatientTimerLive() && atLevel.some((entry) => entry.alarm.category === FEVER_CATEGORY) }),
72
+ stages: untakenStagesOf(level, stagesFrom, policy, { fever: level === 'asap' && feverPatientTimerLive() && atLevel.some((entry) => isLiveFever(entry.alarm)) }),
72
73
  };
73
74
  }
74
75
 
@@ -98,7 +99,7 @@ function pendingQuestionOf(review, clock) {
98
99
  }
99
100
 
100
101
  function patientTimerLiveFor(review) {
101
- const fever = currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY);
102
+ const fever = currentAlarms(review).some(isLiveFeverOf(review));
102
103
  return fever ? feverPatientTimerLive() : escalationPatientTimerLive();
103
104
  }
104
105
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.6.3",
3
+ "version": "6.6.4",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",