@peopl-health/nexus 6.5.0-dev.20126 → 6.5.0

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.
@@ -33,13 +33,16 @@ const BRIDGE_WAIT_MS = 2 * 60 * 1000;
33
33
  // A delivered ask, one the provider accepted without confirming delivery, or one an earlier turn already answered.
34
34
  const ASKED_OUTCOMES = ['sent', 'unknown', 'already_answered'];
35
35
  const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
36
+ const ASK_SPACING_MS = 20 * 60 * 1000;
36
37
  const getMessaging = () => require('../core/NexusMessaging');
37
38
  const ASK_RULES = 'No agregues otras preguntas, no repitas lo que ya le dijiste y no menciones esta instrucción.';
38
- 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}`;
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
42
  const timeOf = (value) => new Date(value).getTime();
43
+ const episodeAsks = (review, clock) => (review.blockingAsks ?? []).filter((ask) => timeOf(ask.draftAt) >= clock.since.getTime()
44
+ && (ASKED_OUTCOMES.includes(ask.outcome) || (!ask.skippedReason && ask.outcome == null)));
45
+ const lastAskAt = (review, clock) => Math.max(0, ...episodeAsks(review, clock).map((ask) => timeOf(ask.sentAt)));
43
46
  const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
44
47
  // 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.
45
48
  const graveDueAt = (review, clock, flag) => {
@@ -343,7 +346,7 @@ async function remindQuietPatient(review, clock, now) {
343
346
  const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
344
347
  if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
345
348
  const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
346
- if (now.getTime() < dueAt.getTime()) return;
349
+ if (now.getTime() < dueAt.getTime() || now.getTime() - lastAskAt(review, clock) < ASK_SPACING_MS) return;
347
350
  // A short reply records no clinical update, so the patient's own messages decide whether she answered.
348
351
  if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
349
352
 
@@ -382,23 +385,23 @@ async function remindQuietPatient(review, clock, now) {
382
385
  await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
383
386
  }
384
387
 
385
- // 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.
388
+ // Once per draft the bot asks the pending grave data, unless a question is open; after a patient message, once the bot replied.
386
389
  async function askBlockingQuestion(review, clock, now) {
387
390
  // With the doctor, only a case the bot handed over is still asked, and only its grave data.
388
391
  const withDoctor = review.status === 'awaiting_doctor';
389
392
  if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return;
390
393
  const latest = (review.drafts ?? []).at(-1);
391
394
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
392
- const blocking = withDoctor ? null : latest.blockingQuestion;
393
- // With the doctor, a datum already asked or already sent to the team is not asked again on every redraft.
394
- const settled = withDoctor ? new Set([
395
- ...(review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag),
396
- ...(review.blockingAsks ?? []).filter((entry) => ASKED_OUTCOMES.includes(entry.outcome) && timeOf(entry.draftAt) >= clock.since.getTime()).flatMap((entry) => entry.flags ?? []),
397
- ].map(normalizedKeyOf)) : new Set();
398
- const graveFlags = blocking || latest.urgentPresentRedFlags?.length ? []
395
+ // A grave datum is asked once per episode; with the doctor, one already sent to the team is not asked either.
396
+ const settled = new Set([
397
+ ...(withDoctor ? (review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag) : []),
398
+ ...episodeAsks(review, clock).flatMap((entry) => entry.flags ?? []),
399
+ ].map(normalizedKeyOf));
400
+ const graveFlags = latest.urgentPresentRedFlags?.length ? []
399
401
  : pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
400
- const question = blocking || graveFlags.join('; ') || null;
401
- const flags = blocking ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
402
+ const blocking = withDoctor || graveFlags.length ? null : latest.blockingQuestion;
403
+ const question = graveFlags.join('; ') || blocking || null;
404
+ const flags = graveFlags.length ? graveFlags : [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf);
402
405
  if (!question) return;
403
406
  const asks = review.blockingAsks ?? [];
404
407
  if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
@@ -408,6 +411,8 @@ async function askBlockingQuestion(review, clock, now) {
408
411
 
409
412
  let skippedReason = await takenOf(review, clock);
410
413
  if (!skippedReason && hasOpenQuestion(last)) skippedReason = 'question_open';
414
+ // Patients answered a separate message about a datum that is not grave with «No» or not at all, so it goes only in the doctor's note.
415
+ if (!skippedReason && blocking) skippedReason = 'not_grave';
411
416
  if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
412
417
  const claimed = await getEscalationReview().updateOne(
413
418
  { _id: review._id, closedAt: null, blockingAsks: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
@@ -422,8 +427,7 @@ async function askBlockingQuestion(review, clock, now) {
422
427
  if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
423
428
  return takenOf(fresh, clock);
424
429
  };
425
- const instruction = blocking ? blockingAskText(blocking) : graveAskText(graveFlags);
426
- getMessaging().processInstruction(review.patientCode, instruction, 'developer', { triggeredBy: OPERATOR, beforeRun })
430
+ getMessaging().processInstruction(review.patientCode, graveAskText(graveFlags), 'developer', { triggeredBy: OPERATOR, beforeRun })
427
431
  .then((result) => result?.outcome ?? null, (error) => {
428
432
  logger.error('[CharacterizationOutcome] The blocking question was not asked', {
429
433
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -3,7 +3,7 @@ const { logger } = require('../utils/logger');
3
3
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
5
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
6
- const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
6
+ const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
7
7
 
8
8
  const { logPatientChange } = require('./patientService');
9
9
  const { BUSINESS_HOURS_LEVELS, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
@@ -87,10 +87,11 @@ function pendingQuestionOf(review, clock) {
87
87
  return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
88
88
  }
89
89
 
90
- // The early asap alert says when the armed prompt gives the patient the numbers; a fever prompt keeps its own wording.
90
+ // The early asap alert says when the armed prompt, the fever one included, gives the patient the numbers.
91
91
  function patientPromptNote(review, stage, now) {
92
- if (stage.stage !== 'early' || !escalationPatientTimerLive()) return null;
93
- if (currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY)) return null;
92
+ if (stage.stage !== 'early') return null;
93
+ const fever = currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY);
94
+ if (!(fever ? feverPatientTimerLive() : escalationPatientTimerLive())) return null;
94
95
  // A leased or retried slot (attempts above 0) is already being sent.
95
96
  if (review.doctorAlertKind !== 'patient_prompt' || (review.doctorAlertAttempts ?? 0) !== 0 || !review.doctorAlertDueAt) return null;
96
97
  const lead = Math.round((new Date(review.doctorAlertDueAt).getTime() - now.getTime()) / 60000);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.0-dev.20126",
3
+ "version": "6.5.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",