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

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.
@@ -9,7 +9,7 @@ const { MapCache } = require('../../utils/MapCache');
9
9
  const PLAN_TEXTS_TABLE = 'plan_instructions';
10
10
  const CACHE_TTL = 5 * 60 * 1000;
11
11
  const CACHE_KEY = 'planTexts';
12
- const NEEDS_HOURS = ['FOLLOW_UP_CHECK_IN', 'FOLLOW_UP_VIGILANCIA'];
12
+ const PLACEHOLDERS = { FOLLOW_UP_CHECK_IN: '{horas}', FOLLOW_UP_VIGILANCIA: '{horas}', PRESCRIBER: '{medico}' };
13
13
 
14
14
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
15
15
 
@@ -28,8 +28,8 @@ async function getPlanTexts() {
28
28
  const texts = Object.fromEntries(Object.entries(PLAN_TEXTS).map(([key, fallback]) => {
29
29
  const value = byKey[key];
30
30
  if (!value) return [key, fallback];
31
- if (NEEDS_HOURS.includes(key) && !value.includes('{horas}')) {
32
- logger.error('[planTextsConfig] follow-up text lacks {horas}; using the default', { key });
31
+ if (PLACEHOLDERS[key] && !value.includes(PLACEHOLDERS[key])) {
32
+ logger.error('[planTextsConfig] text lacks its placeholder; using the default', { key, placeholder: PLACEHOLDERS[key] });
33
33
  return [key, fallback];
34
34
  }
35
35
  return [key, value];
@@ -15,7 +15,7 @@ const durationTextOf = (item) => {
15
15
  };
16
16
  const itemLine = (item) => `${[item.drug, item.strength].filter(Boolean).join(' ')}: ${[item.dose, item.frequency, durationTextOf(item)].filter(Boolean).join(' ')}.`;
17
17
  const studyLine = (study) => `${study.name}${study.instructions ? `: ${study.instructions}` : ''}.`;
18
- // The defaults for the plan_instructions rows of the Config base; {horas} is filled with the follow-up hours.
18
+ // The defaults for the plan_instructions rows of the Config base; {horas} is filled with the follow-up hours, {medico} with the prescriber.
19
19
  const PLAN_TEXTS = Object.freeze({
20
20
  INTRO: 'Transmítele al paciente lo que indicó el médico, con tus palabras: no agregues medicamentos ni estudios que el médico no indicó, ni avisos de urgencia que no dio.',
21
21
  MEDS_HEADER: 'Medicamentos (no cambies dosis, frecuencia ni días; escríbelos con números, como vienen aquí, sin repetirlos con letra):',
@@ -23,6 +23,9 @@ const PLAN_TEXTS = Object.freeze({
23
23
  COMPLEMENTARY: 'Indicaciones complementarias: además de lo anterior, por cada síntoma que contó dale de 2 a 4 cuidados en casa concretos, accionables y de alto valor, diciendo qué hacer y cómo hacerlo, aunque el médico no los haya escrito. Escríbelos con palabras, sin números, cantidades ni frecuencias y sin avisos de urgencia, para que no se confundan con lo que indicó el médico. Solo medidas estándar de enfermería oncológica: sin medicamentos, suplementos, remedios caseros ni dietas restrictivas.',
24
24
  FOLLOW_UP_CHECK_IN: 'Seguimiento: le escribiremos en unas {horas} horas para ver cómo va.',
25
25
  FOLLOW_UP_VIGILANCIA: 'Seguimiento: queda en vigilancia las próximas {horas} horas; le escribiremos para ver cómo va.',
26
+ // The assistant otherwise names the treating oncologist from the patient's context.
27
+ PRESCRIBER: 'Quién lo indicó: {medico}. Si dices quién lo indicó, nombra a {medico} y a ningún otro médico.',
28
+ NO_PRESCRIBER: 'Quién lo indicó: el equipo médico del programa de acompañamiento. Si dices quién lo indicó, di eso y no nombres a ningún médico.',
26
29
  });
27
30
 
28
31
  const FOLLOW_UP_KEYS = { auto: 'FOLLOW_UP_CHECK_IN', check_in: 'FOLLOW_UP_CHECK_IN', vigilancia: 'FOLLOW_UP_VIGILANCIA' };
@@ -44,6 +47,11 @@ function planInstructions(plan, texts = PLAN_TEXTS) {
44
47
  return lines.join('\n');
45
48
  }
46
49
 
50
+ const prescriberLineOf = (plan, texts = PLAN_TEXTS) => {
51
+ const name = oneLineOf(plan.prescriber?.name);
52
+ return name ? texts.PRESCRIBER.replaceAll('{medico}', () => name) : texts.NO_PRESCRIBER;
53
+ };
54
+
47
55
  function planSummary(plan) {
48
56
  const lines = [...plan.items.map(itemLine), ...plan.studies.map((study) => `Estudio: ${studyLine(study)}`)];
49
57
  if (plan.homeCare.length) lines.push(`Cuidados en casa: ${plan.homeCare.join('; ')}.`);
@@ -101,6 +109,7 @@ module.exports = {
101
109
  planInstructions,
102
110
  planSummary,
103
111
  plannedTextOf,
112
+ prescriberLineOf,
104
113
  prescriptionText,
105
114
  proposedPlanOf,
106
115
  };
@@ -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)),
@@ -36,7 +36,7 @@ const { drugsNamedIn } = require('../clinical/services/treatmentProposalService'
36
36
  const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
37
37
  const { getPlanTexts } = require('../clinical/config/planTextsConfig');
38
38
  const { retireSilenceNets } = require('../clinical/services/contingencyDispatchService');
39
- const { DEFAULT_FOLLOW_UP_HOURS, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
39
+ const { DEFAULT_FOLLOW_UP_HOURS, needsPrescriber, planInstructions, planSummary, prescriberLineOf, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
40
40
  const { approvedInstructions, planOf, replyIssues } = require('../clinical/services/doctorPlanService');
41
41
  const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
42
42
  const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
@@ -2270,7 +2270,7 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
2270
2270
  try {
2271
2271
  if (needsPrescriber(plan) && !prescriberEmail) throw httpError(409, 'This plan names no doctor to sign the receta; record the plan again');
2272
2272
  ({ delivery = null, sendThrew = false, reply = null } = await getMessaging().processSystemMessage(
2273
- claimed.patientCode, [plan.instructions], 'system', { reply: true, triggeredBy: operator },
2273
+ claimed.patientCode, [`${plan.instructions}\n${prescriberLineOf(plan, await getPlanTexts())}`], 'system', { reply: true, triggeredBy: operator },
2274
2274
  ) ?? {});
2275
2275
  } catch (error) {
2276
2276
  // A turn refused by a deploy's drain never ran; any other failure after the instructions were stored may have answered.
@@ -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.1",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",