@peopl-health/nexus 6.5.0-dev.20074 → 6.5.0-dev.20076

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,6 +218,14 @@ function briefKeyLine(draft, entry) {
218
218
  return cutOnWord(parts.join(' · '), MAX_BRIEF_KEY);
219
219
  }
220
220
 
221
+ function briefCaseLine(identity, entry, alarmSymptom) {
222
+ const label = cutOnWord(entry?.symptom || alarmSymptom || 'Síntoma no especificado', MAX_BRIEF_SYMPTOM);
223
+ const graded = [1, 2, 3, 4, 5].includes(entry?.grade) && !/\bG[1-5]\b/i.test(label) ? `${label} G${entry.grade}` : label;
224
+ const patient = identity.age ? `${titleCased(oneLineOf(identity.patientName))}, ${identity.age}` : titleCased(oneLineOf(identity.patientName));
225
+ const doctor = titleCased(oneLineOf(identity.treatingDoctor));
226
+ return doctor ? `${patient} · ${graded} (${withTitle(doctor)})` : `${patient} · ${graded}`;
227
+ }
228
+
221
229
  // The four lines of the doctor's alert; each is a template variable, so none may be empty.
222
230
  function doctorBrief({ kind, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
223
231
  const entry = briefSymptomOf(draft, alarmSymptom);
@@ -225,17 +233,21 @@ function doctorBrief({ kind, level, identity, draft, alarmSymptom = null, deadli
225
233
  const actNow = kind === 'act_now' || namedFlags(draft?.urgentPresentRedFlags).length > 0;
226
234
  const verb = actNow ? BRIEF_VERBS.act_now : (briefDrugs(draft).length ? BRIEF_VERBS.proposal : BRIEF_VERBS.indication);
227
235
  const mark = actNow ? '🔴' : BRIEF_MARKS[level];
228
- const label = cutOnWord(entry?.symptom || alarmSymptom || 'Síntoma no especificado', MAX_BRIEF_SYMPTOM);
229
- const graded = [1, 2, 3, 4, 5].includes(entry?.grade) && !/\bG[1-5]\b/i.test(label) ? `${label} G${entry.grade}` : label;
230
- const patient = identity.age ? `${titleCased(oneLineOf(identity.patientName))}, ${identity.age}` : titleCased(oneLineOf(identity.patientName));
231
236
  return [
232
237
  [[mark, verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
233
- `${patient} · ${graded} (${withTitle(titleCased(oneLineOf(identity.treatingDoctor)))})`,
238
+ briefCaseLine(identity, entry, alarmSymptom),
234
239
  briefKeyLine(draft, entry),
235
240
  link,
236
241
  ];
237
242
  }
238
243
 
244
+ const doctorDigestTitle = (count) => `${LEVEL_MARKS.urgent} ${BRIEF_VERBS.indication}: ${count} ${count === 1 ? 'caso urgente' : 'casos urgentes'}`;
245
+
246
+ function doctorDigestLine({ identity, draft, alarmSymptom, deadline, now, timeZone, link }) {
247
+ const head = [briefCaseLine(identity, briefSymptomOf(draft, alarmSymptom), alarmSymptom), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · ');
248
+ return `${head}: ${link}`;
249
+ }
250
+
239
251
  module.exports = {
240
252
  REQUESTED_ACTION,
241
253
  ASSESSMENT_ACTION,
@@ -248,4 +260,6 @@ module.exports = {
248
260
  doctorAlertHeadline,
249
261
  doctorAlertOpener,
250
262
  doctorBrief,
263
+ doctorDigestLine,
264
+ doctorDigestTitle,
251
265
  };
@@ -1,7 +1,7 @@
1
1
  const { cutOnWord, normalizedKeyOf } = require('../utils/coercionUtils');
2
2
  const { logger } = require('../utils/logger');
3
3
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
- const { getEscalationReview } = require('../models/escalationReviewModel');
4
+ const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
5
  const { INTERNAL_ORIGINS } = require('../models/messageModel');
6
6
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
7
7
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
@@ -9,9 +9,9 @@ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableSer
9
9
  const { countMessages, getMessages } = require('./messageService');
10
10
  const { logPatientChange } = require('./patientService');
11
11
  const { getThreadInfo } = require('./threadService');
12
- const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
12
+ const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
13
13
  const { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented } = require('./gravePendingService');
14
- const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
14
+ const { BUSINESS_HOURS_LEVELS, levelsOf, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
15
15
  const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
16
16
  const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
17
17
 
@@ -39,7 +39,6 @@ const blockingAskText = (question) => `La revisión de esta escalación necesita
39
39
  const graveAskText = (flags) => `La revisión de esta escalación necesita saber si la paciente tiene: ${flags.join('; ')}. Pregúntale, en un solo mensaje breve y con palabras sencillas, por lo que ella pueda notar o medir, sin nombrar diagnósticos. ${ASK_RULES}`;
40
40
 
41
41
  const noteOf = (text) => cutOnWord(text, MAX_NOTE_LENGTH);
42
- const flagKey = (flag) => String(flag ?? '').trim().toLowerCase();
43
42
  const timeOf = (value) => new Date(value).getTime();
44
43
  const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
45
44
  // When the team's alert for this grave datum first fell due, which a failed send's retry does not move; one not recorded yet has not.
@@ -61,6 +60,13 @@ function teamGraveOf(review, clock, grave, now) {
61
60
  return { due: [], waiting: asked };
62
61
  }
63
62
 
63
+ function handedRankOf(review, handoff) {
64
+ const by = (date) => timeOf(date) <= timeOf(handoff.createdAt);
65
+ const alarms = currentAlarms(review).filter((alarm) => !alarm.isHeldInFollowUp && by(alarm.raisedAt));
66
+ const levels = levelsOf(alarms, (review.urgencyReclassifications ?? []).filter((change) => by(change.at)), appliedLevelOf);
67
+ return Math.max(0, ...levels.map(({ level }) => URGENCY_RANK[level]));
68
+ }
69
+
64
70
  // Whether the bot's latest draft goes to the doctor now, and with which note; null while the patient still has time to answer.
65
71
  function outcomeOf(review, clock, now) {
66
72
  const wait = pendingWaitMinutes(clock?.level);
@@ -80,13 +86,16 @@ function outcomeOf(review, clock, now) {
80
86
  const graveFlags = graveMissingOf(review, clock, now);
81
87
  const { due: grave, waiting } = teamGraveOf(review, clock, graveFlags, now);
82
88
  const present = latest.urgentPresentRedFlags ?? [];
83
- // 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.
84
- const handedPresent = new Set((update ? review.drafts[last.draftNumber - 1]?.urgentPresentRedFlags ?? [] : []).map(flagKey));
89
+ // The model rewords a flag on every redraft, so the flags' text cannot tell a new one; the panel always shows the latest draft.
90
+ // Only a handoff that rang told the doctor's phone about its grave flag.
91
+ const handedGrave = handoffs.some((handoff) => handoff.transport && (review.drafts[handoff.draftNumber - 1]?.urgentPresentRedFlags ?? []).length > 0);
92
+ const handedRank = update ? handedRankOf(review, last) : 0;
93
+ const rose = handedRank > 0 && URGENCY_RANK[clock.level] > handedRank;
85
94
  // Airtable's alert reaches the team, not the doctor's phone.
86
95
  const raisedSince = (level) => (review.alarms ?? []).some((alarm) => alarm.urgencyLevel === level && timeOf(alarm.raisedAt) > timeOf(last.createdAt));
87
96
  const rangSince = update && (review.doctorAlerts ?? []).some((sent) => sent.kind === 'initial' && !sent.error
88
97
  && sent.transport && sent.transport !== 'airtable' && timeOf(sent.sentAt) > timeOf(last.createdAt) && raisedSince(sent.urgencyLevel));
89
- const notify = !update || (!rangSince && present.some((flag) => !handedPresent.has(flagKey(flag))));
98
+ const notify = !update || (!rangSince && ((present.length > 0 && !handedGrave) || rose));
90
99
  // 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.
91
100
  const teamFirst = !update && !present.length && grave.length + waiting.length > 0;
92
101
  const held = teamFirst && (waiting.length > 0 || grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000));
@@ -5,13 +5,16 @@ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUti
5
5
  const { getEscalationReview } = require('../models/escalationReviewModel');
6
6
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
7
7
  const { whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
8
+ const { doctorDigestLine, doctorDigestTitle } = require('../clinical/helpers/doctorReviewMessageHelper');
8
9
 
9
10
  const { logPatientChange } = require('./patientService');
10
11
  const { listEscalationApprovers } = require('./physicianService');
11
- const { responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
12
+ const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
12
13
  const { BOOKKEEPING, doctorLink, teamAlertIdentity } = require('./escalationReviewService');
13
14
 
14
15
  const DIGEST_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_CONTENT_SID';
16
+ // Until Meta approves this template the earlier digest keeps going out.
17
+ const DIGEST_BRIEF_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_BRIEF_CONTENT_SID';
15
18
  const DEFAULT_WINDOW_MINUTES = 60;
16
19
  const DEFAULT_LEAD_MINUTES = 120;
17
20
  const MAX_CASES_PER_MESSAGE = 5;
@@ -29,7 +32,7 @@ const minutesOf = (key, fallback) => {
29
32
  const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
30
33
 
31
34
  // Urgent cases ready for the doctor go in a digest only once its template exists.
32
- const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_TEMPLATE_KEY));
35
+ const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DIGEST_TEMPLATE_KEY));
33
36
 
34
37
  // The approving doctor's WhatsApp, or null when there is none to send the digest to.
35
38
  async function digestRecipient() {
@@ -56,10 +59,23 @@ function digestDueAt(reviews, policy) {
56
59
  return teamOpenAt(new Date(Math.min(...times)), policy);
57
60
  }
58
61
 
59
- async function digestLines(reviews) {
62
+ async function digestLines(reviews, now, policy) {
63
+ const brief = Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY));
60
64
  const lines = [];
61
65
  for (const review of reviews) {
62
- const { patient } = await teamAlertIdentity(review);
66
+ const { patient, identity } = await teamAlertIdentity(review);
67
+ if (brief) {
68
+ lines.push(doctorDigestLine({
69
+ identity: { ...identity, patientName: identity.patientName || patient },
70
+ draft: review.drafts?.at(-1),
71
+ alarmSymptom: effectiveUrgencyOf(review)?.symptom,
72
+ deadline: responseDeadlineOf(review, policy)?.dueAt,
73
+ now,
74
+ timeZone: policy.teamHours.timeZone,
75
+ link: doctorLink(review),
76
+ }));
77
+ continue;
78
+ }
63
79
  const label = [patient, review.alarms?.at(-1)?.symptom].map((text) => oneLineOf(text).slice(0, MAX_FIELD_LENGTH).trim()).filter(Boolean).join(' · ');
64
80
  lines.push(`${label}: ${doctorLink(review)}`);
65
81
  }
@@ -80,10 +96,12 @@ function chunksOf(entries) {
80
96
 
81
97
  async function sendDigest(code, entries) {
82
98
  const lines = entries.map(({ line }) => line);
83
- const count = String(entries.length);
84
- const outgoing = await isWithin24HourWindow(code)
85
- ? { code, body: [`🟡 Casos urgentes listos para decidir: ${count}`, '', ...lines].join('\n'), triggeredBy: OPERATOR }
86
- : { code, contentSid: runtimeConfig.get(DIGEST_TEMPLATE_KEY), variables: { 1: count, 2: lines.join(' | ') }, triggeredBy: OPERATOR };
99
+ const briefSid = runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY);
100
+ const title = briefSid ? doctorDigestTitle(entries.length) : String(entries.length);
101
+ const inWindow = await isWithin24HourWindow(code);
102
+ const outgoing = inWindow
103
+ ? { code, body: (briefSid ? [title, ...lines] : [`🟡 Casos urgentes listos para decidir: ${title}`, '', ...lines]).join('\n'), triggeredBy: OPERATOR }
104
+ : { code, contentSid: briefSid || runtimeConfig.get(DIGEST_TEMPLATE_KEY), variables: { 1: title, 2: lines.join(' | ') }, triggeredBy: OPERATOR };
87
105
  const result = await getMessaging().sendMessage(outgoing);
88
106
  if (!result?.success && !result?.completed) throw new Error('The doctor digest could not be sent');
89
107
  if (result?.deferred) throw new Error('The doctor digest was queued for template approval, not sent');
@@ -117,7 +135,7 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
117
135
  logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the digest waits');
118
136
  return 0;
119
137
  }
120
- const lines = await digestLines(queued);
138
+ const lines = await digestLines(queued, now, policy);
121
139
  let sent = 0;
122
140
  // Each message claims its own cases just before it goes, so a crash in between leaves the rest for the next sweep.
123
141
  for (const chunk of chunksOf(queued.map((review, index) => ({ review, line: lines[index] })))) {
@@ -1377,6 +1377,7 @@ async function teamAlertIdentity(review) {
1377
1377
  return {
1378
1378
  patient: oneLineOf(identity.patientName) || 'sin nombre registrado',
1379
1379
  doctor: oneLineOf(identity.treatingDoctor) || 'sin médico registrado',
1380
+ identity,
1380
1381
  link: conversationLink(review.patientCode) || 'abrir el chat en la plataforma',
1381
1382
  };
1382
1383
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.0-dev.20074",
3
+ "version": "6.5.0-dev.20076",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",