@peopl-health/nexus 6.0.18 → 6.0.19

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,6 +31,7 @@ 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;
36
37
 
@@ -40,8 +41,8 @@ function outcomeOf(review, clock, now) {
40
41
  if (!wait || !OUTCOME_LEVELS.includes(clock.level) || !['draft_ready', 'awaiting_doctor'].includes(review.status)) return null;
41
42
  const handoffs = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) >= clock.since.getTime());
42
43
  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;
44
+ // 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.
45
+ if (handoffs.some((handoff) => handoff.sentBy !== OPERATOR) || handoffs.filter((handoff) => handoff.transport).length > MAX_DOCTOR_UPDATES) return null;
45
46
  if (last && (review.decisions ?? []).some((decision) => timeOf(decision.createdAt) > timeOf(last.createdAt))) return null;
46
47
  const latest = (review.drafts ?? []).at(-1);
47
48
  const after = Math.max(clock.since.getTime(), last ? timeOf(last.createdAt) + 1 : 0);
@@ -52,16 +53,19 @@ function outcomeOf(review, clock, now) {
52
53
 
53
54
  const grave = graveMissingOf(review, clock, now);
54
55
  const present = latest.urgentPresentRedFlags ?? [];
56
+ // 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.
57
+ const handedPresent = new Set((update ? review.drafts[last.draftNumber - 1]?.urgentPresentRedFlags ?? [] : []).map(flagKey));
58
+ const notify = !update || present.some((flag) => !handedPresent.has(flagKey(flag)));
55
59
  if (grave.length || present.length) {
56
60
  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(' · '))) };
61
+ return { grave, update, notify, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
58
62
  }
59
63
  // A grave question still inside its wait holds the case even when the rest is enough.
60
64
  if (pendingFlagsOf(review, clock.since).flags.length) return null;
61
- if (latest.sufficientForDoctor === true) return { grave: [], update, note: withUpdate(null) };
65
+ if (latest.sufficientForDoctor === true) return { grave: [], update, notify, note: withUpdate(null) };
62
66
  // The latest draft follows the patient's latest answer, so its age is how long the question has gone unanswered.
63
67
  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ó)`)) };
68
+ return { grave: [], update, notify, note: withUpdate(noteOf(`Falta: ${latest.blockingQuestion || 'información'} (no contestó)`)) };
65
69
  }
66
70
 
67
71
  const audit = (review, changes) => logPatientChange({
@@ -102,7 +106,7 @@ const attemptsOf = (review, clock) => (timeOf(review.autoHandoffFailedAt) >= clo
102
106
 
103
107
  async function handOff(review, clock, outcome, now) {
104
108
  try {
105
- await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note });
109
+ await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note, notify: outcome.notify });
106
110
  } catch (error) {
107
111
  const attempt = attemptsOf(review, clock) + 1;
108
112
  await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
@@ -115,7 +119,7 @@ async function handOff(review, clock, outcome, now) {
115
119
  return false;
116
120
  }
117
121
  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) });
122
+ 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
123
  return true;
120
124
  }
121
125
 
@@ -191,7 +195,7 @@ const setOn = (review, entry, fields, filter = {}) => getEscalationReview().upda
191
195
  BOOKKEEPING,
192
196
  );
193
197
 
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).
198
+ // Sends the grave alerts that are due: to the team while nobody took the case, to the group once someone did; the doctor already has it in the handoff.
195
199
  async function sendDueGraveAlerts(review, clock, entries, now) {
196
200
  const due = entries.filter((entry) => !entry.sentAt && timeOf(entry.dueAt) <= now.getTime() && timeOf(entry.since) === clock.since.getTime());
197
201
  // A datum held for the night is dropped once a current draft written after it no longer lists it as pending.
@@ -213,7 +217,7 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
213
217
  try {
214
218
  delivered = taken
215
219
  ? Number((await sendGroupNotice(message.body, quoted, message.threadBody)).delivered)
216
- : (await sendTeamAlert({ message, operator: OPERATOR, quoted })).delivered;
220
+ : (await sendTeamAlert({ message, operator: OPERATOR, quoted, withDoctors: false })).delivered;
217
221
  } catch (error) {
218
222
  logger.error('[CharacterizationOutcome] The grave alert was not sent', {
219
223
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -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.19",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",