@peopl-health/nexus 6.0.24 → 6.0.25

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.
@@ -228,6 +228,7 @@ async function generateEscalationDraft({
228
228
  missingCharacterization: textList(parsed?.missingCharacterization),
229
229
  sufficientForDoctor,
230
230
  blockingQuestion: sufficientForDoctor === false ? trimmed(parsed?.blockingQuestion) || null : null,
231
+ blockingFlag: sufficientForDoctor === false ? trimmed(parsed?.blockingFlag) || null : null,
231
232
  suggestCall: suggestCallOf(parsed?.suggestCall),
232
233
  sectionsUnavailable: context.degradedSections ?? [],
233
234
  };
@@ -73,7 +73,7 @@ const graveAlertSchema = new mongoose.Schema({
73
73
  level: { type: String, enum: URGENCY_LEVELS, required: true },
74
74
  since: { type: Date, required: true },
75
75
  firstSeenAt: { type: Date, required: true },
76
- reason: { type: String, enum: ['unobtainable', 'unanswered'], required: true },
76
+ reason: { type: String, enum: ['unobtainable', 'unanswered', 'not_said'], required: true },
77
77
  takenReason: { type: String, default: null },
78
78
  audience: { type: String, enum: ['all', 'group_doctor'], default: null },
79
79
  dueAt: { type: Date, required: true },
@@ -93,6 +93,7 @@ const quietReminderSchema = new mongoose.Schema({
93
93
  const blockingAskSchema = new mongoose.Schema({
94
94
  draftAt: { type: Date, required: true },
95
95
  question: { type: String, default: null },
96
+ flags: { type: [String], default: undefined },
96
97
  sentAt: { type: Date, required: true },
97
98
  skippedReason: { type: String, default: null },
98
99
  outcome: { type: String, default: null },
@@ -144,6 +145,7 @@ const draftSchema = new mongoose.Schema({
144
145
  urgentPresentRedFlags: { type: [String], default: undefined },
145
146
  sufficientForDoctor: { type: Boolean, default: undefined },
146
147
  blockingQuestion: { type: String, default: undefined },
148
+ blockingFlag: { type: String, default: undefined },
147
149
  missingCharacterization: { type: [String], default: undefined },
148
150
  suggestCall: { type: suggestCallSchema, default: undefined },
149
151
  sectionsUnavailable: { type: [String], default: undefined },
@@ -1,4 +1,4 @@
1
- const { oneLineOf } = require('../utils/coercionUtils');
1
+ const { normalizedKeyOf, 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');
@@ -24,13 +24,15 @@ const MAX_HANDOFF_ATTEMPTS = 4;
24
24
  const MAX_NOTE_LENGTH = 200;
25
25
  const UPDATE_NOTE = 'Actualización: la paciente contestó';
26
26
  const GRAVE_RETRY_MS = 5 * 60 * 1000;
27
- const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó' };
27
+ const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó', not_said: 'no lo ha dicho' };
28
28
  const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
29
29
  // A reminder this late (an outage, a deploy) is not sent.
30
30
  const QUIET_REMINDER_STALE_MS = 30 * 60 * 1000;
31
31
  const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
32
32
  const getMessaging = () => require('../core/NexusMessaging');
33
- 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.`;
33
+ const ASK_RULES = 'No agregues otras preguntas, no repitas lo que ya le dijiste y no menciones esta instrucción.';
34
+ 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}». ${ASK_RULES}`;
35
+ 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}`;
34
36
 
35
37
  const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
36
38
  const flagKey = (flag) => String(flag ?? '').trim().toLowerCase();
@@ -95,9 +97,15 @@ async function claimGraveAlerts(review, clock, grave, now) {
95
97
  const dueAt = BUSINESS_HOURS_LEVELS.includes(clock.level) ? teamOpenAt(now, responseDeadlinePolicy()) : now;
96
98
  const recorded = new Set((review.graveAlerts ?? [])
97
99
  .filter((entry) => new Date(entry.since).getTime() === clock.since.getTime()).map((entry) => entry.flag));
100
+ const fresh = grave.filter((entry) => !recorded.has(entry.flag));
101
+ // «No contestó» only for a datum the bot asked about while that question is still open; otherwise «no lo ha dicho».
102
+ const askedFlags = new Set((review.blockingAsks ?? []).filter((ask) => ask.outcome === 'sent' && timeOf(ask.draftAt) >= clock.since.getTime())
103
+ .flatMap((ask) => (ask.flags ?? []).map(normalizedKeyOf)));
104
+ const open = fresh.some(({ flag, reason }) => reason === 'unanswered' && askedFlags.has(flag))
105
+ && hasOpenQuestion(await lastChatMessage(review.patientCode).catch(() => null));
98
106
  const claimed = [];
99
- for (const { flag, firstSeenAt, reason } of grave.filter((entry) => !recorded.has(entry.flag))) {
100
- const entry = { flag, level: clock.level, since: clock.since, firstSeenAt, reason, dueAt, sentAt: null, at: now };
107
+ for (const { flag, firstSeenAt, reason } of fresh) {
108
+ const entry = { flag, level: clock.level, since: clock.since, firstSeenAt, reason: reason === 'unanswered' && !(open && askedFlags.has(flag)) ? 'not_said' : reason, dueAt, sentAt: null, at: now };
101
109
  const result = await getEscalationReview().updateOne(
102
110
  { _id: review._id, closedAt: null, graveAlerts: { $not: { $elemMatch: { flag, since: clock.since } } } },
103
111
  { $push: { graveAlerts: entry } },
@@ -220,7 +228,7 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
220
228
  const { latest, flags } = pendingFlagsOf(review, clock.since);
221
229
  const stillPending = new Set(flags.map(({ flag }) => flag));
222
230
  const redrafted = latest && isDraftCurrent(review, latest);
223
- const answered = (entry) => entry.reason === 'unanswered' && redrafted && timeOf(latest.createdAt) > timeOf(entry.at) && !stillPending.has(entry.flag);
231
+ const answered = (entry) => entry.reason !== 'unobtainable' && redrafted && timeOf(latest.createdAt) > timeOf(entry.at) && !stillPending.has(entry.flag);
224
232
  for (const entry of due.filter(answered)) await setOn(review, entry, { sentAt: now, skippedReason: 'answered' }, { sentAt: null });
225
233
  const pending = due.filter((entry) => !answered(entry));
226
234
  if (!pending.length) return 0;
@@ -267,6 +275,8 @@ async function lastChatMessage(code) {
267
275
  return last;
268
276
  }
269
277
 
278
+ const hasOpenQuestion = (last) => Boolean(last?.from_me && String(last.body ?? '').includes('?'));
279
+
270
280
  // In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
271
281
  async function remindQuietPatient(review, clock, now) {
272
282
  if (clock.level !== 'urgent' || !PRE_DECISION_STATUSES.includes(review.status) || review.closedAt) return;
@@ -283,7 +293,7 @@ async function remindQuietPatient(review, clock, now) {
283
293
  const last = await lastChatMessage(review.patientCode);
284
294
  let skippedReason = null;
285
295
  if (now.getTime() - dueAt.getTime() > QUIET_REMINDER_STALE_MS) skippedReason = 'stale';
286
- else if (!last?.from_me || !String(last.body ?? '').includes('?')) skippedReason = 'no_open_question';
296
+ else if (!hasOpenQuestion(last)) skippedReason = 'no_open_question';
287
297
  else skippedReason = await takenOf(review, clock);
288
298
  if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
289
299
  const entry = { draftAt: latest.createdAt, sentAt: now, skippedReason, delivered: null };
@@ -314,22 +324,27 @@ async function remindQuietPatient(review, clock, now) {
314
324
  await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
315
325
  }
316
326
 
317
- // The bot asks the draft's blocking question once per draft, unless its own last message left a question open.
327
+ // Once per draft the bot asks its blocking question or the pending grave data, unless a question is open; after a patient message, once the bot replied.
318
328
  async function askBlockingQuestion(review, clock, now) {
319
329
  if (!OUTCOME_LEVELS.includes(clock.level) || review.status !== 'draft_ready' || review.closedAt) return;
320
330
  const latest = (review.drafts ?? []).at(-1);
321
- if (latest?.writtenBy !== DRAFT_OPERATOR || !latest.blockingQuestion || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
331
+ if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
332
+ const graveFlags = latest.blockingQuestion || latest.urgentPresentRedFlags?.length ? []
333
+ : pendingFlagsOf(review, clock.since).flags.filter(({ unobtainable }) => !unobtainable).map(({ flag }) => flag);
334
+ const question = latest.blockingQuestion || graveFlags.join('; ') || null;
335
+ const flags = latest.blockingQuestion ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
336
+ if (!question) return;
322
337
  const asks = review.blockingAsks ?? [];
323
338
  if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
324
339
  const last = await lastChatMessage(review.patientCode);
340
+ if (!last?.from_me) return;
325
341
 
326
342
  let skippedReason = await takenOf(review, clock);
327
- if (!skippedReason && !last?.from_me) skippedReason = 'patient_wrote';
328
- if (!skippedReason && String(last.body ?? '').includes('?')) skippedReason = 'question_open';
343
+ if (!skippedReason && hasOpenQuestion(last)) skippedReason = 'question_open';
329
344
  if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
330
345
  const claimed = await getEscalationReview().updateOne(
331
346
  { _id: review._id, closedAt: null, blockingAsks: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
332
- { $push: { blockingAsks: { draftAt: latest.createdAt, question: latest.blockingQuestion, sentAt: now, skippedReason, outcome: null } } },
347
+ { $push: { blockingAsks: { draftAt: latest.createdAt, question, flags, sentAt: now, skippedReason, outcome: null } } },
333
348
  BOOKKEEPING,
334
349
  );
335
350
  if (!claimed.modifiedCount || skippedReason) return;
@@ -340,7 +355,8 @@ async function askBlockingQuestion(review, clock, now) {
340
355
  if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
341
356
  return takenOf(fresh, clock);
342
357
  };
343
- getMessaging().processInstruction(review.patientCode, blockingAskText(latest.blockingQuestion), 'developer', { triggeredBy: OPERATOR, beforeRun })
358
+ const instruction = latest.blockingQuestion ? blockingAskText(latest.blockingQuestion) : graveAskText(graveFlags);
359
+ getMessaging().processInstruction(review.patientCode, instruction, 'developer', { triggeredBy: OPERATOR, beforeRun })
344
360
  .then((result) => result?.outcome ?? null, (error) => {
345
361
  logger.error('[CharacterizationOutcome] The blocking question was not asked', {
346
362
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -1456,6 +1456,7 @@ async function generateBotDraft({ id, lease = null } = {}) {
1456
1456
  urgentPresentRedFlags: draft.urgentPresentRedFlags,
1457
1457
  sufficientForDoctor: draft.sufficientForDoctor,
1458
1458
  blockingQuestion: draft.blockingQuestion,
1459
+ blockingFlag: draft.blockingFlag,
1459
1460
  missingCharacterization: draft.missingCharacterization,
1460
1461
  ...(draft.suggestCall && { suggestCall: draft.suggestCall }),
1461
1462
  ...(draft.sectionsUnavailable?.length && { sectionsUnavailable: draft.sectionsUnavailable }),
@@ -24,7 +24,7 @@ function pendingFlagsOf(review, since) {
24
24
  const isDraftCurrent = (review, latest) => !review.draftDueAt
25
25
  && !(review.updates ?? []).some((update) => new Date(update.at).getTime() > new Date(latest.createdAt).getTime());
26
26
 
27
- // A grave datum is missing at once when the patient cannot give it, or once it stays unanswered past the level's wait.
27
+ // A grave datum is missing at once when it cannot be given, or past the level's wait; the others still pending go with it in one alert.
28
28
  function graveMissingOf(review, clock, now) {
29
29
  const limit = pendingWaitMinutes(clock?.level);
30
30
  if (!limit) return [];
@@ -32,10 +32,12 @@ function graveMissingOf(review, clock, now) {
32
32
  if (!latest || !isDraftCurrent(review, latest)) return [];
33
33
  // Once the case left documenting (with the doctor) no new draft comes, so the wait no longer means unanswered.
34
34
  const waiting = DOCUMENTING_STATUSES.includes(review.status);
35
- return flags.flatMap(({ flag, firstSeenAt, unobtainable }) => {
36
- if (unobtainable) return [{ flag, firstSeenAt, reason: 'unobtainable' }];
37
- return waiting && now.getTime() - firstSeenAt.getTime() >= limit * 60 * 1000 ? [{ flag, firstSeenAt, reason: 'unanswered' }] : [];
38
- });
35
+ const isDue = ({ firstSeenAt, unobtainable }) => unobtainable || (waiting && now.getTime() - firstSeenAt.getTime() >= limit * 60 * 1000);
36
+ if (!flags.some(isDue)) return [];
37
+ // Only the first alert gathers the data still waiting; one that appears after it waits its own time.
38
+ const recorded = new Set((review.graveAlerts ?? []).filter((entry) => new Date(entry.since).getTime() === clock.since.getTime()).map((entry) => entry.flag));
39
+ return flags.filter((entry) => isDue(entry) || recorded.has(entry.flag) || (waiting && !recorded.size))
40
+ .map(({ flag, firstSeenAt, unobtainable }) => ({ flag, firstSeenAt, reason: unobtainable ? 'unobtainable' : 'unanswered' }));
39
41
  }
40
42
 
41
43
  module.exports = { graveMissingOf, isDraftCurrent, pendingFlagsOf };
@@ -174,7 +174,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
174
174
  alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
175
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,
176
176
  'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
177
- 'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
177
+ 'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
178
178
  })
179
179
  .sort({ _id: -1 })
180
180
  .limit(SWEEP_LIMIT)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.24",
3
+ "version": "6.0.25",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",