@peopl-health/nexus 6.0.18 → 6.0.20

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.
@@ -31,8 +31,15 @@ const getMessaging = () => require('../core/NexusMessaging');
31
31
  const blockingAskText = (question) => `La revisión de esta escalación necesita un dato que todavía falta. Pregúntale a la paciente, en un solo mensaje breve y con tus palabras: «${question}». No agregues otras preguntas, no repitas lo que ya le dijiste y no menciones esta instrucción.`;
32
32
 
33
33
  const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
34
+ const flagKey = (flag) => String(flag ?? '').trim().toLowerCase();
34
35
  const timeOf = (value) => new Date(value).getTime();
35
36
  const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
37
+ // 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.
38
+ const graveDueAt = (review, clock, flag) => {
39
+ const entry = (review.graveAlerts ?? []).find((alert) => alert.flag === flag && timeOf(alert.since) === clock.since.getTime());
40
+ if (!entry) return Infinity;
41
+ return BUSINESS_HOURS_LEVELS.includes(entry.level ?? clock.level) ? teamOpenAt(new Date(entry.at), responseDeadlinePolicy()).getTime() : timeOf(entry.at);
42
+ };
36
43
 
37
44
  // Whether the bot's latest draft goes to the doctor now, and with which note; null while the patient still has time to answer.
38
45
  function outcomeOf(review, clock, now) {
@@ -40,8 +47,8 @@ function outcomeOf(review, clock, now) {
40
47
  if (!wait || !OUTCOME_LEVELS.includes(clock.level) || !['draft_ready', 'awaiting_doctor'].includes(review.status)) return null;
41
48
  const handoffs = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) >= clock.since.getTime());
42
49
  const last = handoffs.at(-1);
43
- // After the bot's own handoff, a newer draft goes as an update, unless a person handed it over or the doctor already answered.
44
- if (handoffs.some((handoff) => handoff.sentBy !== OPERATOR) || handoffs.length > MAX_DOCTOR_UPDATES) return null;
50
+ // 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.
51
+ if (handoffs.some((handoff) => handoff.sentBy !== OPERATOR) || handoffs.filter((handoff) => handoff.transport).length > MAX_DOCTOR_UPDATES) return null;
45
52
  if (last && (review.decisions ?? []).some((decision) => timeOf(decision.createdAt) > timeOf(last.createdAt))) return null;
46
53
  const latest = (review.drafts ?? []).at(-1);
47
54
  const after = Math.max(clock.since.getTime(), last ? timeOf(last.createdAt) + 1 : 0);
@@ -52,16 +59,23 @@ function outcomeOf(review, clock, now) {
52
59
 
53
60
  const grave = graveMissingOf(review, clock, now);
54
61
  const present = latest.urgentPresentRedFlags ?? [];
62
+ // 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.
63
+ const handedPresent = new Set((update ? review.drafts[last.draftNumber - 1]?.urgentPresentRedFlags ?? [] : []).map(flagKey));
64
+ const notify = !update || present.some((flag) => !handedPresent.has(flagKey(flag)));
65
+ // 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.
66
+ const teamFirst = !update && !present.length && grave.length > 0;
67
+ const held = teamFirst && grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000);
55
68
  if (grave.length || present.length) {
56
- const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, grave.length && `Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}`];
57
- return { grave, update, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
69
+ const missing = grave.length && `Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
70
+ const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, missing];
71
+ return { grave, update, notify, held, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
58
72
  }
59
73
  // A grave question still inside its wait holds the case even when the rest is enough.
60
74
  if (pendingFlagsOf(review, clock.since).flags.length) return null;
61
- if (latest.sufficientForDoctor === true) return { grave: [], update, note: withUpdate(null) };
75
+ if (latest.sufficientForDoctor === true) return { grave: [], update, notify, note: withUpdate(null) };
62
76
  // The latest draft follows the patient's latest answer, so its age is how long the question has gone unanswered.
63
77
  if (latest.sufficientForDoctor !== false || minutesSince(latest.createdAt, now) < wait) return null;
64
- return { grave: [], update, note: withUpdate(noteOf(`Falta: ${latest.blockingQuestion || 'información'} (no contestó)`)) };
78
+ return { grave: [], update, notify, note: withUpdate(noteOf(`Falta: ${latest.blockingQuestion || 'información'} (no contestó)`)) };
65
79
  }
66
80
 
67
81
  const audit = (review, changes) => logPatientChange({
@@ -102,7 +116,7 @@ const attemptsOf = (review, clock) => (timeOf(review.autoHandoffFailedAt) >= clo
102
116
 
103
117
  async function handOff(review, clock, outcome, now) {
104
118
  try {
105
- await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note });
119
+ await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note, notify: outcome.notify });
106
120
  } catch (error) {
107
121
  const attempt = attemptsOf(review, clock) + 1;
108
122
  await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
@@ -115,7 +129,7 @@ async function handOff(review, clock, outcome, now) {
115
129
  return false;
116
130
  }
117
131
  if (review.autoHandoffAttempts) await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffAttempts: 0 } }, BOOKKEEPING);
118
- await audit(review, { action: outcome.update ? 'doctor_updated' : 'auto_handed_off', urgencyLevel: clock.level, grave: outcome.grave.length > 0, withNote: Boolean(outcome.note) });
132
+ await audit(review, { action: outcome.update ? 'doctor_updated' : 'auto_handed_off', urgencyLevel: clock.level, grave: outcome.grave.length > 0, withNote: Boolean(outcome.note), notified: outcome.notify });
119
133
  return true;
120
134
  }
121
135
 
@@ -170,7 +184,7 @@ async function postHandoffNotice(review, clock, { note }) {
170
184
  async function graveMessage(review, clock, entries) {
171
185
  const { patient, doctor, link } = await teamAlertIdentity(review);
172
186
  const missing = entries.map(({ flag, reason }) => `${flag} (${GRAVE_REASONS[reason]})`).join(', ');
173
- const action = 'Llamar a la paciente para conseguirlo y avisar al médico';
187
+ const action = 'Llamar a la paciente para conseguirlo y registrar la llamada';
174
188
  return {
175
189
  body: [
176
190
  `❗ Falta dato grave · ${LEVEL_LABELS[clock.level]}`,
@@ -191,7 +205,7 @@ const setOn = (review, entry, fields, filter = {}) => getEscalationReview().upda
191
205
  BOOKKEEPING,
192
206
  );
193
207
 
194
- // Sends the grave alerts that are due: to everyone while nobody took the case, to the group once someone did (the doctor already has it).
208
+ // Sends the grave alerts that are due: to the team while nobody took the case, to the group once someone did; the doctor gets it with the handoff.
195
209
  async function sendDueGraveAlerts(review, clock, entries, now) {
196
210
  const due = entries.filter((entry) => !entry.sentAt && timeOf(entry.dueAt) <= now.getTime() && timeOf(entry.since) === clock.since.getTime());
197
211
  // A datum held for the night is dropped once a current draft written after it no longer lists it as pending.
@@ -213,7 +227,7 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
213
227
  try {
214
228
  delivered = taken
215
229
  ? Number((await sendGroupNotice(message.body, quoted, message.threadBody)).delivered)
216
- : (await sendTeamAlert({ message, operator: OPERATOR, quoted })).delivered;
230
+ : (await sendTeamAlert({ message, operator: OPERATOR, quoted, withDoctors: false })).delivered;
217
231
  } catch (error) {
218
232
  logger.error('[CharacterizationOutcome] The grave alert was not sent', {
219
233
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -349,7 +363,8 @@ async function settleCharacterization(review, clock, now) {
349
363
  // Each failure doubles the wait; after the last attempt the team hands the case over by hand.
350
364
  const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
351
365
  || (attempts > 0 && now.getTime() - timeOf(review.autoHandoffFailedAt) < HANDOFF_RETRY_MS * 2 ** (attempts - 1));
352
- if (outcome && !backingOff && await handOff(review, clock, outcome, now) && (hospitalized || !outcome.grave.length)) await sendHandoffNotice(review, clock, outcome);
366
+ // A patient in the hospital gets no team call, so nothing holds the doctor's handoff.
367
+ if (outcome && (!outcome.held || hospitalized) && !backingOff && await handOff(review, clock, outcome, now) && (hospitalized || !outcome.grave.length)) await sendHandoffNotice(review, clock, outcome);
353
368
  if (hospitalized) await skipGraveAlerts(review, clock, now);
354
369
  else await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
355
370
  await remindQuietPatient(review, clock, now);
@@ -1406,7 +1406,8 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
1406
1406
  function updatesDoctor(review) {
1407
1407
  if (!escalationAutoHandoffLive() || review.status !== 'awaiting_doctor' || review.doctorHandoffs?.at(-1)?.sentBy !== AUTO_HANDOFF_OPERATOR) return false;
1408
1408
  const decidedAt = Math.max(0, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
1409
- const botHandoffs = review.doctorHandoffs.filter((handoff) => handoff.sentBy === AUTO_HANDOFF_OPERATOR && new Date(handoff.createdAt).getTime() > decidedAt);
1409
+ // Only handoffs that reached the doctor's phone count; one recorded silently costs the doctor nothing.
1410
+ const botHandoffs = review.doctorHandoffs.filter((handoff) => handoff.sentBy === AUTO_HANDOFF_OPERATOR && handoff.transport && new Date(handoff.createdAt).getTime() > decidedAt);
1410
1411
  return botHandoffs.length <= MAX_DOCTOR_UPDATES;
1411
1412
  }
1412
1413
 
@@ -1675,7 +1676,8 @@ async function soleApprover() {
1675
1676
  return approvers[0];
1676
1677
  }
1677
1678
 
1678
- async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, requestId = null } = {}) {
1679
+ // With notify false the case is handed over in the platform without a WhatsApp to the doctor.
1680
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, notify = true, requestId = null } = {}) {
1679
1681
  const reviewId = reviewIdOf(id);
1680
1682
  const operator = requiredText(sentBy, 'sentBy');
1681
1683
  if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
@@ -1718,8 +1720,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note =
1718
1720
  let delivery = {};
1719
1721
  let updated;
1720
1722
  try {
1721
- if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator })) };
1722
- const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : message.body;
1723
+ if (approver) delivery = { physicianEmail: approver.email, ...(notify ? await sendDoctorAlert({ message, approver, operator }) : {}) };
1724
+ const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : (notify ? message.body : null);
1723
1725
  const handoff = {
1724
1726
  $push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, sentBy: operator } },
1725
1727
  $addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
@@ -16,7 +16,8 @@ const REQUEST_TIMEOUT_MS = 15000;
16
16
  const ALERT_TEMPLATE_KEY = 'ESCALATION_TEAM_ALERT_CONTENT_SID';
17
17
  const NOTICE_TEMPLATE_KEY = 'ESCALATION_TEAM_NOTICE_CONTENT_SID';
18
18
  const ROSTER_TABLE = 'equipo_guardia';
19
- const ROSTER_FIELDS = ['whatsapp', 'sin_tomar'];
19
+ const ROSTER_FIELDS = ['whatsapp', 'sin_tomar', 'rol'];
20
+ const DOCTOR_ROLE = 'médico';
20
21
  const ROSTER_TTL_MS = 5 * 60 * 1000;
21
22
  const ROSTER_READ_TIMEOUT_MS = 5000;
22
23
 
@@ -44,7 +45,7 @@ async function readRoster() {
44
45
  const rows = await airtableService.getRecordByFilter(Monitoreo_ID, ROSTER_TABLE, `AND({activo}, ${programSourceFormula()})`, null, ROSTER_FIELDS);
45
46
  if (!Array.isArray(rows)) throw new Error('The on-call roster could not be read');
46
47
  return rows
47
- .map((row) => ({ code: whatsAppCodeOf(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [] }))
48
+ .map((row) => ({ code: whatsAppCodeOf(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [], doctor: row.rol === DOCTOR_ROLE }))
48
49
  .filter((member) => PATIENT_CODE.test(member.code));
49
50
  }
50
51
 
@@ -67,11 +68,13 @@ async function rosterMembers(now = Date.now()) {
67
68
  return reading;
68
69
  }
69
70
 
70
- // With a level, only the members who take that level's untaken alerts; without one, every active member.
71
- async function teamPhones(level = null) {
71
+ // With a level, only the members who take that level's untaken alerts; without one, every active member; doctors only when asked.
72
+ async function teamPhones(level = null, { withDoctors = true } = {}) {
72
73
  const members = await rosterMembers();
73
74
  if (!members) return configuredPhones();
74
- return members.filter((member) => !level || member.levels.includes(level)).map((member) => member.code);
75
+ return members
76
+ .filter((member) => (!level || member.levels.includes(level)) && (withDoctors || !member.doctor))
77
+ .map((member) => member.code);
75
78
  }
76
79
 
77
80
  const _resetRoster = () => {
@@ -123,12 +126,12 @@ async function sendToGroup(body, quoted = null, threadBody = null) {
123
126
  }
124
127
  }
125
128
 
126
- // Alerts the group and the on-call phones for `level` (all without one); one failed recipient never stops the others and nothing throws.
127
- async function sendTeamAlert({ message, operator, level = null, notice = false, quoted = null }) {
129
+ // Alerts the group and the on-call phones for `level` (all without one, doctors unless left out); one failed recipient never stops the others and nothing throws.
130
+ async function sendTeamAlert({ message, operator, level = null, notice = false, quoted = null, withDoctors = true }) {
128
131
  const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
129
132
  const group = await sendToGroup(message.body, quoted, message.threadBody);
130
133
  const phones = [];
131
- for (const code of await teamPhones(level)) {
134
+ for (const code of await teamPhones(level, { withDoctors })) {
132
135
  try {
133
136
  phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator, templateKey })) });
134
137
  } catch (error) {
@@ -171,7 +171,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
171
171
  closedAt: null,
172
172
  status: { $in: PRE_DECISION_STATUSES },
173
173
  alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
174
- }, { 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, quietReminders: 1, blockingAsks: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
174
+ }, { 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,
175
175
  'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
176
176
  'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
177
177
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.18",
3
+ "version": "6.0.20",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",