@peopl-health/nexus 6.2.0-dev.18286 → 6.2.0-dev.18343

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.
@@ -1,4 +1,4 @@
1
- const FORMULARY_VERSION = '2026-09-28';
1
+ const FORMULARY_VERSION = '2026-10-29';
2
2
 
3
3
  const MEDICAL_REVIEW = 'valoración médica';
4
4
 
@@ -224,6 +224,17 @@ const TREATMENT_FORMULARY = deepFreeze([
224
224
  { drug: 'Hidrocortisona tópica', brand: 'LOCOID', strength: null, position: '1L', tableLabel: '1L en dermatitis/rash inflamatorio leve', class: 'corticoide_topico' },
225
225
  ],
226
226
  },
227
+ {
228
+ key: 'molestia_ocular_egfr',
229
+ label: 'Molestias en los ojos con panitumumab o cetuximab',
230
+ drugs: [
231
+ {
232
+ drug: 'Dexametasona/neomicina', strength: null, position: '1L', tableLabel: '1L gotas oftálmicas, solo con panitumumab o cetuximab', class: 'corticoide_antibiotico_oftalmico',
233
+ onlyWhen: ['panitumumab', 'cetuximab'],
234
+ instructions: '2 gotas oftálmicas cada 12 horas por 3 días; además, valoración por oftalmología',
235
+ },
236
+ ],
237
+ },
227
238
  {
228
239
  key: 'sindrome_mano_pie',
229
240
  label: 'Xerosis / síndrome mano-pie',
@@ -57,11 +57,12 @@ const graveDueAt = (review, clock, flag) => {
57
57
  function outcomeOf(review, clock, now) {
58
58
  const wait = pendingWaitMinutes(clock?.level);
59
59
  if (!wait || !OUTCOME_LEVELS.includes(clock.level) || !['draft_ready', 'awaiting_doctor'].includes(review.status)) return null;
60
- const handoffs = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) >= clock.since.getTime());
60
+ // Handoffs count since the last decision, so a higher alarm on a case already with the doctor goes as an update.
61
+ const decidedAt = Math.max(0, ...(review.decisions ?? []).map((decision) => timeOf(decision.createdAt)));
62
+ const handoffs = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) > decidedAt);
61
63
  const last = handoffs.at(-1);
62
64
  // After the bot's own handoff, a newer draft goes as an update, unless a person handed it over, the doctor already answered or the phone rang too often.
63
65
  if (handoffs.some((handoff) => handoff.sentBy !== OPERATOR) || handoffs.filter((handoff) => handoff.transport).length > MAX_DOCTOR_UPDATES) return null;
64
- if (last && (review.decisions ?? []).some((decision) => timeOf(decision.createdAt) > timeOf(last.createdAt))) return null;
65
66
  const latest = (review.drafts ?? []).at(-1);
66
67
  const after = Math.max(clock.since.getTime(), last ? timeOf(last.createdAt) + 1 : 0);
67
68
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < after || !isDraftCurrent(review, latest)) return null;
@@ -73,7 +74,11 @@ function outcomeOf(review, clock, now) {
73
74
  const present = latest.urgentPresentRedFlags ?? [];
74
75
  // An update reaches the doctor's phone only with a grave flag the draft they have did not show; the panel always shows the latest draft.
75
76
  const handedPresent = new Set((update ? review.drafts[last.draftNumber - 1]?.urgentPresentRedFlags ?? [] : []).map(flagKey));
76
- const notify = !update || present.some((flag) => !handedPresent.has(flagKey(flag)));
77
+ // A higher alarm already rang the doctor's phone since the last handoff, so its update shows in the panel only; Airtable's alert goes to the team.
78
+ const raisedSince = (level) => (review.alarms ?? []).some((alarm) => alarm.urgencyLevel === level && timeOf(alarm.raisedAt) > timeOf(last.createdAt));
79
+ const rangSince = update && (review.doctorAlerts ?? []).some((sent) => sent.kind === 'initial' && !sent.error
80
+ && sent.transport && sent.transport !== 'airtable' && timeOf(sent.sentAt) > timeOf(last.createdAt) && raisedSince(sent.urgencyLevel));
81
+ const notify = !update || (!rangSince && present.some((flag) => !handedPresent.has(flagKey(flag))));
77
82
  // A missing grave datum is the team's to get: a first handoff waits the level's wait after the team's alert falls due, unless a grave flag is present.
78
83
  const teamFirst = !update && !present.length && grave.length > 0;
79
84
  const held = teamFirst && grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000);
@@ -53,7 +53,7 @@ const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = re
53
53
  const { countMessages } = require('./messageService');
54
54
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
55
55
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
56
- const { effectiveUrgencyOf, patientTimerMinutes, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
56
+ const { effectiveUrgencyOf, levelsOf, patientTimerMinutes, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
57
57
  const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
58
58
  const { groupConfigured, sendTeamAlert, teamChannelConfigured } = require('./teamAlertService');
59
59
 
@@ -1027,9 +1027,12 @@ async function takenReason(review, since, timer, ownStart = null) {
1027
1027
  async function caseTakenReason(review, from, level) {
1028
1028
  const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
1029
1029
  if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
1030
- const stat = (alarm) => alarm.urgencyLevel === 'stat' || alarm.appliedLevel === 'stat';
1031
- if (level !== 'stat' && currentAlarms(review).some(stat)) return 'stat_alarm';
1032
- if ((review.urgencyReclassifications ?? []).some((change) => atOrAfter(change.at))) return 'reclassified';
1030
+ const changes = review.urgencyReclassifications ?? [];
1031
+ const levelsAt = (at) => levelsOf(currentAlarms(review).filter((alarm) => new Date(alarm.raisedAt) <= new Date(at)), changes.filter((change) => new Date(change.at) < new Date(at)), appliedLevelOf);
1032
+ if (level !== 'stat' && levelsAt(new Date(8.64e15)).some((entry) => entry.level === 'stat')) return 'stat_alarm';
1033
+ // Lowering the level, from what this episode's alarms were at, means someone looked at the case; a raise restarts the clock instead.
1034
+ const lowered = (change) => (URGENCY_RANK[change.toLevel] || 0) < Math.max(0, ...levelsAt(change.at).map((entry) => URGENCY_RANK[entry.level] || 0));
1035
+ if (changes.some((change) => atOrAfter(change.at) && lowered(change))) return 'reclassified';
1033
1036
  if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
1034
1037
  // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
1035
1038
  // anyway) skips the prompt.
@@ -2245,6 +2248,7 @@ module.exports = {
2245
2248
  setReviewCases,
2246
2249
  suggestDraft,
2247
2250
  suggestKeyQuestions,
2251
+ updatesDoctor,
2248
2252
  confirmNoteFacts,
2249
2253
  syncEscalationReviewCase,
2250
2254
  };
@@ -1,6 +1,6 @@
1
1
  const { normalizedKeyOf } = require('../utils/coercionUtils');
2
2
 
3
- const { AUTO_HANDOFF_OPERATOR, DOCUMENTING_STATUSES } = require('./escalationReviewService');
3
+ const { DOCUMENTING_STATUSES, updatesDoctor } = require('./escalationReviewService');
4
4
  const { pendingWaitMinutes } = require('./reviewDeadlineService');
5
5
 
6
6
  const keysOf = (flags) => [...new Set((flags ?? []).map(normalizedKeyOf).filter(Boolean))];
@@ -20,9 +20,8 @@ function pendingFlagsOf(review, since) {
20
20
  return { latest: drafts.at(-1) ?? null, flags: [...firstSeen].map(([flag, firstSeenAt]) => ({ flag, firstSeenAt, unobtainable: unobtainable.includes(flag) })) };
21
21
  }
22
22
 
23
- // The bot keeps documenting a case it handed to the doctor itself, so its grave questions still wait for the patient there.
24
- const stillDocumented = (review) => DOCUMENTING_STATUSES.includes(review.status)
25
- || (review.status === 'awaiting_doctor' && review.doctorHandoffs?.at(-1)?.sentBy === AUTO_HANDOFF_OPERATOR);
23
+ // The bot keeps documenting a case it handed to the doctor itself while it still redrafts it, so its grave questions still wait for the patient there.
24
+ const stillDocumented = (review) => DOCUMENTING_STATUSES.includes(review.status) || updatesDoctor(review);
26
25
 
27
26
  // The latest draft speaks for the case only while no newer patient turn or redraft is waiting to replace it.
28
27
  const isDraftCurrent = (review, latest) => !review.draftDueAt
@@ -45,17 +45,20 @@ function responseDeadlinePolicy() {
45
45
  };
46
46
  }
47
47
 
48
- function alarmLevelsOf(review) {
49
- const reclassifications = [...(review.urgencyReclassifications ?? [])].sort((a, b) => timeOf(a.at) - timeOf(b.at));
50
- return (review.alarms ?? []).map((alarm) => reclassifications
48
+ // Each alarm at the level the team set for it since it was raised; a raise restarts its clock, a lowering keeps it.
49
+ function levelsOf(alarms, reclassifications, startLevel = (alarm) => alarm.urgencyLevel) {
50
+ const changes = [...(reclassifications ?? [])].sort((a, b) => timeOf(a.at) - timeOf(b.at));
51
+ return (alarms ?? []).map((alarm) => changes
51
52
  .filter((change) => timeOf(alarm.raisedAt) <= timeOf(change.at))
52
53
  .reduce((entry, change) => ({
53
54
  alarm,
54
55
  level: change.toLevel,
55
56
  clockFrom: rankOf(change.toLevel) > rankOf(entry.level) ? change.at : entry.clockFrom,
56
- }), { alarm, level: alarm.urgencyLevel, clockFrom: alarm.raisedAt }));
57
+ }), { alarm, level: startLevel(alarm), clockFrom: alarm.raisedAt }));
57
58
  }
58
59
 
60
+ const alarmLevelsOf = (review) => levelsOf(review.alarms, review.urgencyReclassifications);
61
+
59
62
  function effectiveUrgencyOf(review) {
60
63
  const lead = alarmLevelsOf(review).reduce((top, entry) => (
61
64
  !top || rankOf(entry.level) > rankOf(top.level)
@@ -106,6 +109,7 @@ function responseDeadlineOf(review, policy) {
106
109
  module.exports = {
107
110
  BUSINESS_HOURS_LEVELS,
108
111
  effectiveUrgencyOf,
112
+ levelsOf,
109
113
  responseDeadlineOf,
110
114
  patientTimerMinutes,
111
115
  pendingWaitMinutes,
@@ -6,7 +6,7 @@ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableSer
6
6
  const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
7
7
 
8
8
  const { logPatientChange } = require('./patientService');
9
- const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
9
+ const { BUSINESS_HOURS_LEVELS, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
10
10
  const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, teamAlertIdentity } = require('./escalationReviewService');
11
11
  const { settleCharacterization } = require('./characterizationOutcomeService');
12
12
  const { sendTeamAlert } = require('./teamAlertService');
@@ -34,31 +34,37 @@ const duration = (minutes) => {
34
34
  return rest ? `${hours} h ${rest} min` : `${hours} h`;
35
35
  };
36
36
 
37
- // The clock runs at the highest level raised since the last decision, from the first alarm at that level.
37
+ // The clock runs at the highest level since the last decision, its stages from the first alarm or team raise at that level.
38
+ // The episode keeps the start the alarms' own levels give it, so a reclassification never re-keys its drafts or grave alerts.
39
+ function episodeStartOf(alarms) {
40
+ const top = alarms.reduce((level, alarm) => ((URGENCY_RANK[appliedLevelOf(alarm)] || 0) > (URGENCY_RANK[level] || 0) ? appliedLevelOf(alarm) : level), null);
41
+ return new Date(Math.min(...alarms.filter((alarm) => appliedLevelOf(alarm) === top).map((alarm) => new Date(alarm.raisedAt).getTime())));
42
+ }
43
+
38
44
  function untakenClockOf(review, policy) {
39
- const alarms = currentAlarms(review).filter((alarm) => UNTAKEN_LEVELS.includes(appliedLevelOf(alarm)));
40
- const level = alarms.reduce((top, alarm) => (
41
- URGENCY_RANK[appliedLevelOf(alarm)] > (URGENCY_RANK[top] || 0) ? appliedLevelOf(alarm) : top
42
- ), null);
45
+ const entries = levelsOf(currentAlarms(review), review.urgencyReclassifications, appliedLevelOf).filter((entry) => UNTAKEN_LEVELS.includes(entry.level));
46
+ const level = entries.reduce((top, entry) => (URGENCY_RANK[entry.level] > (URGENCY_RANK[top] || 0) ? entry.level : top), null);
43
47
  if (!level) return null;
44
- const atLevel = alarms.filter((alarm) => appliedLevelOf(alarm) === level);
45
- const since = new Date(atLevel[0].raisedAt);
48
+ const atLevel = entries.filter((entry) => entry.level === level);
49
+ const earliest = (dates) => new Date(Math.min(...dates.map((date) => new Date(date).getTime())));
50
+ const stagesFrom = earliest(atLevel.map((entry) => entry.clockFrom));
46
51
  return {
47
52
  level,
48
- since,
49
- symptom: oneLineOf(atLevel.at(-1).symptom),
50
- emergencyRecordId: atLevel.find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId ?? null,
51
- stages: untakenStagesOf(level, since, policy),
53
+ since: episodeStartOf(entries.map((entry) => entry.alarm)),
54
+ stagesFrom,
55
+ symptom: oneLineOf(atLevel.at(-1).alarm.symptom),
56
+ emergencyRecordId: atLevel.find((entry) => entry.alarm.emergencyRecordId)?.alarm.emergencyRecordId ?? null,
57
+ stages: untakenStagesOf(level, stagesFrom, policy),
52
58
  };
53
59
  }
54
60
 
55
- const sameStage = (clock, stage) => ({ level: clock.level, stage: stage.stage, since: clock.since });
61
+ const sameStage = (clock, stage) => ({ level: clock.level, stage: stage.stage, since: clock.stagesFrom });
56
62
 
57
63
  function dueStageOf(review, clock, now) {
58
64
  const due = clock.stages.filter((stage) => stage.dueAt && stage.dueAt <= now).at(-1);
59
65
  if (!due || now.getTime() - due.dueAt.getTime() > STALE_MS) return null;
60
66
  const recorded = (review.untakenAlerts ?? []).some((entry) => entry.level === clock.level
61
- && entry.stage === due.stage && new Date(entry.since).getTime() === clock.since.getTime());
67
+ && entry.stage === due.stage && new Date(entry.since).getTime() === clock.stagesFrom.getTime());
62
68
  return recorded ? null : due;
63
69
  }
64
70
 
@@ -172,7 +178,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
172
178
  closedAt: null,
173
179
  status: { $in: PRE_DECISION_STATUSES },
174
180
  alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
175
- }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
181
+ }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, quietReminders: 1, blockingAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
176
182
  'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
177
183
  'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
178
184
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.2.0-dev.18286",
3
+ "version": "6.2.0-dev.18343",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",