@peopl-health/nexus 6.0.21 → 6.0.23

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.
@@ -5,6 +5,7 @@ const { getSupportLightEvaluator } = require('../config/subAgentsConfig');
5
5
  const { getSupportLightSweepModel } = require('../models/supportLightModel');
6
6
  const { readStructuredText } = require('../helpers/structuredTextHelper');
7
7
  const { getMessages, aggregateMessages } = require('../../services/messageService');
8
+ const { INTERNAL_ORIGINS } = require('../../models/messageModel');
8
9
  const { safeParse } = require('../../utils/jsonUtils');
9
10
  const { logger } = require('../../utils/logger');
10
11
  const { LIGHT_SCALE } = require('./supportInvitability');
@@ -23,7 +24,7 @@ const CLAIM_MINUTES = 15;
23
24
  const SETTLED_OUTCOMES = ['evaluated', 'no_messages'];
24
25
  const MAX_REASON_CHARS = 500;
25
26
  const MAX_EVIDENCE = 5;
26
- const INTERNAL_ORIGINS = ['system', 'instruction'];
27
+ const HIDDEN_ORIGINS = [...INTERNAL_ORIGINS];
27
28
  const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
28
29
  const DUPLICATE_KEY_ERROR = 11000;
29
30
  const MINUTE_MS = 60 * 1000;
@@ -56,7 +57,7 @@ async function readRecentMessages(patientId, { now, windowDays, readMessages })
56
57
  const query = {
57
58
  numero: patientId,
58
59
  createdAt: { $gte: new Date(now.getTime() - windowDays * DAY_MS) },
59
- origin: { $nin: INTERNAL_ORIGINS },
60
+ origin: { $nin: HIDDEN_ORIGINS },
60
61
  'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
61
62
  body: { $regex: '\\S' },
62
63
  };
@@ -113,7 +114,7 @@ async function patientsToEvaluate({
113
114
  const selected = [];
114
115
  for (let page = 0; selected.length < limit && page < MAX_CANDIDATE_PAGES; page += 1) {
115
116
  const active = await aggregateMessages([
116
- { $match: { from_me: false, createdAt: { $gte: activeSince }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
117
+ { $match: { from_me: false, createdAt: { $gte: activeSince }, numero, origin: { $nin: HIDDEN_ORIGINS }, body: { $regex: '\\S' } } },
117
118
  { $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
118
119
  { $sort: { lastInboundAt: -1, _id: 1 } },
119
120
  { $skip: page * CANDIDATE_PAGE },
@@ -253,6 +253,9 @@ const escalationReviewSchema = new mongoose.Schema({
253
253
  graveAlerts: { type: [graveAlertSchema], default: [] },
254
254
  autoHandoffFailedAt: { type: Date, default: null },
255
255
  autoHandoffAttempts: { type: Number, default: 0 },
256
+ digestQueuedAt: { type: Date, default: null },
257
+ digestClaimedAt: { type: Date, default: null },
258
+ digestSentAt: { type: Date, default: null },
256
259
  quietReminders: { type: [quietReminderSchema], default: [] },
257
260
  blockingAsks: { type: [blockingAskSchema], default: [] },
258
261
  feverPromptStartedAt: { type: Date, default: null },
@@ -2,6 +2,7 @@ const { oneLineOf } = require('../utils/coercionUtils');
2
2
  const { logger } = require('../utils/logger');
3
3
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const { getEscalationReview } = require('../models/escalationReviewModel');
5
+ const { INTERNAL_ORIGINS } = require('../models/messageModel');
5
6
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
6
7
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
7
8
 
@@ -12,6 +13,7 @@ const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES,
12
13
  const { graveMissingOf, isDraftCurrent, pendingFlagsOf } = require('./gravePendingService');
13
14
  const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
14
15
  const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
16
+ const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
15
17
 
16
18
  const OPERATOR = AUTO_HANDOFF_OPERATOR;
17
19
  const AUDIT_SOURCE = 'escalation_review';
@@ -115,9 +117,14 @@ const takenOf = async (review, clock) => {
115
117
  const attemptsOf = (review, clock) => (timeOf(review.autoHandoffFailedAt) >= clock.since.getTime() ? review.autoHandoffAttempts ?? 0 : 0);
116
118
 
117
119
  async function handOff(review, clock, outcome, now) {
120
+ // An urgent case ready to decide waits for the doctor's digest, queued before the handoff so a failed write never strands it.
121
+ const digest = !outcome.update && clock.level === 'urgent' && !review.drafts.at(-1)?.urgentPresentRedFlags?.length && urgentDigestLive()
122
+ && Boolean(await digestRecipient().catch(() => null));
118
123
  try {
119
- await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note, notify: outcome.notify });
124
+ if (digest) await getEscalationReview().updateOne({ _id: review._id }, { $set: { digestQueuedAt: now, digestClaimedAt: null, digestSentAt: null } }, BOOKKEEPING);
125
+ await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note, notify: outcome.notify && !digest });
120
126
  } catch (error) {
127
+ if (digest) await getEscalationReview().updateOne({ _id: review._id, status: { $ne: 'awaiting_doctor' } }, { $set: { digestQueuedAt: null } }, BOOKKEEPING).catch(() => {});
121
128
  const attempt = attemptsOf(review, clock) + 1;
122
129
  await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
123
130
  // A 409 is mostly another sweep or a person who moved the case first.
@@ -129,15 +136,15 @@ async function handOff(review, clock, outcome, now) {
129
136
  return false;
130
137
  }
131
138
  if (review.autoHandoffAttempts) await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffAttempts: 0 } }, BOOKKEEPING);
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 });
133
- return true;
139
+ 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 && !digest, digest });
140
+ return digest ? 'digest' : true;
134
141
  }
135
142
 
136
143
  // Only the first handoff reaches the group; a later update to the doctor shows in the platform.
137
- async function sendHandoffNotice(review, clock, outcome) {
144
+ async function sendHandoffNotice(review, clock, outcome, queuedAt = null) {
138
145
  if (outcome.update) return;
139
146
  try {
140
- await postHandoffNotice(review, clock, outcome);
147
+ await postHandoffNotice(review, clock, outcome, queuedAt);
141
148
  } catch (error) {
142
149
  logger.error('[CharacterizationOutcome] The handoff notice was not sent', {
143
150
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -164,10 +171,11 @@ async function sendGaveUpNotice(review, clock) {
164
171
  }
165
172
  }
166
173
 
167
- async function postHandoffNotice(review, clock, { note }) {
174
+ async function postHandoffNotice(review, clock, { note }, queuedAt) {
168
175
  const { patient, doctor, link } = await teamAlertIdentity(review);
169
176
  const taken = await takenOf(review, clock);
170
- const header = taken ? '📋 Pasó al médico' : '📋 Pasó al médico · todavía sin tomar';
177
+ const passed = queuedAt ? `📋 Va al médico en el resumen de urgentes (a más tardar ${digestTimeOf(review, queuedAt)})` : '📋 Pasó al médico';
178
+ const header = taken ? passed : `${passed} · todavía sin tomar`;
171
179
  const action = !taken && 'Qué hacer: escribir o llamar a la paciente si nadie lo ha hecho';
172
180
  const body = [
173
181
  header,
@@ -254,7 +262,7 @@ async function skipGraveAlerts(review, clock, now) {
254
262
  // The last message the patient saw: the quiet reminder itself and a send that never arrived are no question of the bot's.
255
263
  async function lastChatMessage(code) {
256
264
  const [last] = await getMessages({
257
- numero: code, origin: { $nin: ['system', 'instruction'] }, body: { $ne: QUIET_REMINDER_TEXT }, 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
265
+ numero: code, origin: { $nin: [...INTERNAL_ORIGINS] }, body: { $ne: QUIET_REMINDER_TEXT }, 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
258
266
  }, { sort: { createdAt: -1 }, limit: 1, select: 'from_me body' });
259
267
  return last;
260
268
  }
@@ -364,7 +372,8 @@ async function settleCharacterization(review, clock, now) {
364
372
  const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
365
373
  || (attempts > 0 && now.getTime() - timeOf(review.autoHandoffFailedAt) < HANDOFF_RETRY_MS * 2 ** (attempts - 1));
366
374
  // 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);
375
+ const handed = outcome && (!outcome.held || hospitalized) && !backingOff ? await handOff(review, clock, outcome, now) : false;
376
+ if (handed && (hospitalized || !outcome.grave.length)) await sendHandoffNotice(review, clock, outcome, handed === 'digest' ? now : null);
368
377
  if (hospitalized) await skipGraveAlerts(review, clock, now);
369
378
  else await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
370
379
  await remindQuietPatient(review, clock, now);
@@ -0,0 +1,150 @@
1
+ const runtimeConfig = require('../config/runtimeConfig');
2
+ const { oneLineOf } = require('../utils/coercionUtils');
3
+ const { logger } = require('../utils/logger');
4
+ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
+ const { getEscalationReview } = require('../models/escalationReviewModel');
6
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
7
+ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
8
+
9
+ const { logPatientChange } = require('./patientService');
10
+ const { listEscalationApprovers } = require('./physicianService');
11
+ const { responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
12
+ const { BOOKKEEPING, doctorLink, teamAlertIdentity } = require('./escalationReviewService');
13
+
14
+ const DIGEST_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_CONTENT_SID';
15
+ const DEFAULT_WINDOW_MINUTES = 60;
16
+ const DEFAULT_LEAD_MINUTES = 120;
17
+ const MAX_CASES_PER_MESSAGE = 5;
18
+ // The template's fixed text plus the cases stay under WhatsApp's 1024 characters.
19
+ const MAX_LINES_LENGTH = 800;
20
+ const MAX_FIELD_LENGTH = 60;
21
+ const STALE_CLAIM_MS = 10 * 60 * 1000;
22
+ const OPERATOR = 'bot:doctorDigest';
23
+ const getMessaging = () => require('../core/NexusMessaging');
24
+
25
+ const minutesOf = (key, fallback) => {
26
+ const minutes = Number(runtimeConfig.get(key, fallback));
27
+ return Number.isFinite(minutes) && minutes > 0 ? minutes : fallback;
28
+ };
29
+ const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
30
+
31
+ // Urgent cases ready for the doctor go in a digest only once its template exists.
32
+ const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_TEMPLATE_KEY));
33
+
34
+ // The approving doctor's WhatsApp, or null when there is none to send the digest to.
35
+ async function digestRecipient() {
36
+ const [approver] = await listEscalationApprovers();
37
+ const code = ensureWhatsAppFormat(String(approver?.phone ?? '').replace(/[^\d+]/g, ''));
38
+ return PATIENT_CODE.test(code) ? code : null;
39
+ }
40
+
41
+ // The time a case queued now reaches the doctor at the latest, in the team's clock, for the group notice.
42
+ function digestTimeOf(review, now) {
43
+ const policy = responseDeadlinePolicy();
44
+ const dueAt = Math.max(now.getTime(), digestDueAt([{ ...review, digestQueuedAt: now }], policy).getTime());
45
+ return new Date(dueAt).toLocaleTimeString('es-MX', { timeZone: policy.teamHours.timeZone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
46
+ }
47
+
48
+ // The digest goes when the oldest queued case has waited the window, or earlier so every case keeps the lead before its deadline; at night, when the team day opens.
49
+ function digestDueAt(reviews, policy) {
50
+ const window = minutesOf('ESCALATION_DOCTOR_DIGEST_WINDOW_MINUTES', DEFAULT_WINDOW_MINUTES) * 60000;
51
+ const lead = minutesOf('ESCALATION_DOCTOR_DIGEST_LEAD_MINUTES', DEFAULT_LEAD_MINUTES) * 60000;
52
+ const times = reviews.flatMap((review) => {
53
+ const deadline = responseDeadlineOf(review, policy)?.dueAt;
54
+ return [new Date(review.digestQueuedAt).getTime() + window, ...(deadline ? [deadline.getTime() - lead] : [])];
55
+ });
56
+ return teamOpenAt(new Date(Math.min(...times)), policy);
57
+ }
58
+
59
+ async function digestLines(reviews) {
60
+ const lines = [];
61
+ for (const review of reviews) {
62
+ const { patient } = await teamAlertIdentity(review);
63
+ const label = [patient, review.alarms?.at(-1)?.symptom].map((text) => oneLineOf(text).slice(0, MAX_FIELD_LENGTH).trim()).filter(Boolean).join(' · ');
64
+ lines.push(`${label}: ${doctorLink(review)}`);
65
+ }
66
+ return lines;
67
+ }
68
+
69
+ // Cases go in order, five at most per message and within the length the template allows.
70
+ function chunksOf(entries) {
71
+ const chunks = [];
72
+ for (const entry of entries) {
73
+ const last = chunks.at(-1);
74
+ const length = last ? [...last, entry].map(({ line }) => line).join(' | ').length : 0;
75
+ if (last && last.length < MAX_CASES_PER_MESSAGE && length <= MAX_LINES_LENGTH) last.push(entry);
76
+ else chunks.push([entry]);
77
+ }
78
+ return chunks;
79
+ }
80
+
81
+ async function sendDigest(code, entries) {
82
+ 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 };
87
+ const result = await getMessaging().sendMessage(outgoing);
88
+ if (!result?.success && !result?.completed) throw new Error('The doctor digest could not be sent');
89
+ if (result?.deferred) throw new Error('The doctor digest was queued for template approval, not sent');
90
+ }
91
+
92
+ const audit = (review, delivered) => logPatientChange({
93
+ code: review.patientCode,
94
+ updatedBy: OPERATOR,
95
+ source: 'escalation_review',
96
+ requestId: null,
97
+ changes: { escalationReviewId: String(review._id), action: delivered ? 'doctor_digest_sent' : 'doctor_digest_failed' },
98
+ }).catch((error) => logger.error('[DoctorDigest] The audit was not written', { escalationReviewId: String(review._id), error: redacted(error) }));
99
+
100
+ // Sends the queued urgent cases still waiting for the doctor in one message per few cases, once the digest is due.
101
+ async function sendDueDoctorDigests({ now = new Date() } = {}) {
102
+ if (!urgentDigestLive()) return 0;
103
+ const unclaimed = { $or: [{ digestClaimedAt: null }, { digestClaimedAt: { $lt: new Date(now.getTime() - STALE_CLAIM_MS) } }] };
104
+ const found = await getEscalationReview()
105
+ .find({ closedAt: null, status: 'awaiting_doctor', digestQueuedAt: { $ne: null }, digestSentAt: null, ...unclaimed })
106
+ .sort({ digestQueuedAt: 1 })
107
+ .lean();
108
+ // A case whose doctor's phone already rang after it was queued (a grave flag on an update) is not repeated.
109
+ const queued = found.filter((review) => !(review.doctorHandoffs ?? [])
110
+ .some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime()));
111
+ if (!queued.length) return 0;
112
+ const policy = responseDeadlinePolicy();
113
+ if (now.getTime() < digestDueAt(queued, policy).getTime()) return 0;
114
+
115
+ const code = await digestRecipient();
116
+ if (!code) {
117
+ logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the digest waits');
118
+ return 0;
119
+ }
120
+ const lines = await digestLines(queued);
121
+ let sent = 0;
122
+ // Each message claims its own cases just before it goes, so a crash in between leaves the rest for the next sweep.
123
+ for (const chunk of chunksOf(queued.map((review, index) => ({ review, line: lines[index] })))) {
124
+ const claimed = [];
125
+ for (const entry of chunk) {
126
+ const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', digestSentAt: null, ...unclaimed };
127
+ if ((await getEscalationReview().updateOne(filter, { $set: { digestClaimedAt: now } }, BOOKKEEPING)).modifiedCount) claimed.push(entry);
128
+ }
129
+ if (!claimed.length) continue;
130
+ const ids = claimed.map(({ review }) => review._id);
131
+ let delivered = false;
132
+ try {
133
+ await sendDigest(code, claimed);
134
+ delivered = true;
135
+ sent += claimed.length;
136
+ } catch (error) {
137
+ logger.error('[DoctorDigest] The digest was not sent; it goes again on the next sweep', { cases: claimed.length, error: redacted(error) });
138
+ await getEscalationReview().updateMany({ _id: { $in: ids }, digestClaimedAt: now }, { $set: { digestClaimedAt: null } }, BOOKKEEPING);
139
+ }
140
+ // A sent digest keeps its claim even when this write fails, so it is not sent again before the claim goes stale.
141
+ if (delivered) {
142
+ await getEscalationReview().updateMany({ _id: { $in: ids }, digestClaimedAt: now }, { $set: { digestSentAt: now } }, BOOKKEEPING)
143
+ .catch((error) => logger.error('[DoctorDigest] The digest went out but was not marked as sent', { cases: claimed.length, error: redacted(error) }));
144
+ }
145
+ for (const { review } of claimed) await audit(review, delivered);
146
+ }
147
+ return sent;
148
+ }
149
+
150
+ module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
@@ -2187,6 +2187,7 @@ module.exports = {
2187
2187
  addCallLog,
2188
2188
  caseTakenReason,
2189
2189
  currentAlarms,
2190
+ doctorLink,
2190
2191
  teamAlertIdentity,
2191
2192
  addDraft,
2192
2193
  alertWithoutEmergencyRow,
@@ -7,6 +7,7 @@ const { escapeRegExp } = require('../utils/textMatchUtils');
7
7
  const { logger } = require('../utils/logger');
8
8
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
9
9
  const { OfficeReadMarker } = require('../models/officeReadMarkerModel');
10
+ const { INTERNAL_ORIGINS } = require('../models/messageModel');
10
11
  const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
11
12
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
12
13
  const { prepareMessageMedia } = require('../helpers/mediaHelper');
@@ -18,7 +19,7 @@ const { aggregateMessages, getMessages } = require('./messageService');
18
19
  const { getPatientInformation } = require('./patientService');
19
20
 
20
21
  const PATIENT_FIELDS = ['whatsapp_id', 'name', 'doctor'];
21
- const HIDDEN_ORIGINS = ['system', 'instruction'];
22
+ const HIDDEN_ORIGINS = [...INTERNAL_ORIGINS];
22
23
  const DEFAULT_MESSAGE_LIMIT = 30;
23
24
  const MAX_MESSAGE_LIMIT = 50;
24
25
  const MAX_TEXT_LENGTH = 1500;
@@ -10,6 +10,7 @@ const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = requi
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');
13
+ const { sendDueDoctorDigests } = require('./doctorDigestService');
13
14
 
14
15
  const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
15
16
  const LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
@@ -205,6 +206,9 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
205
206
  failed('[UntakenAlert] Could not settle the characterization of a review', review, error);
206
207
  }
207
208
  }
209
+ if (autoHandoff) {
210
+ await sendDueDoctorDigests({ now }).catch((error) => logger.error('[UntakenAlert] Could not send the doctor digest', { error: redactDirectIdentifiers(String(error?.message || error)) }));
211
+ }
208
212
  return sent;
209
213
  }
210
214
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.21",
3
+ "version": "6.0.23",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",