@peopl-health/nexus 6.4.8 → 6.4.10

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.
@@ -36,6 +36,10 @@ function escalationWatchExpiryLive() {
36
36
  return flagNotOff('ESCALATION_WATCH_EXPIRY_LIVE');
37
37
  }
38
38
 
39
+ function escalationWatchTeamNoticeLive() {
40
+ return flagOn('ESCALATION_WATCH_TEAM_NOTICE_LIVE');
41
+ }
42
+
39
43
  module.exports = {
40
44
  escalationApproverAlertLive,
41
45
  escalationAssessmentLive,
@@ -44,5 +48,6 @@ module.exports = {
44
48
  escalationUntakenAlertsLive,
45
49
  escalationUpdateModeLive,
46
50
  escalationWatchExpiryLive,
51
+ escalationWatchTeamNoticeLive,
47
52
  feverPatientTimerLive,
48
53
  };
@@ -14,7 +14,7 @@ const PLAN_TEXTS = Object.freeze({
14
14
  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.',
15
15
  MEDS_HEADER: 'Medicamentos (no cambies dosis, frecuencia ni días; escríbelos con números, como vienen aquí, sin repetirlos con letra):',
16
16
  // Written without numbers so the reply check, which flags any amount or hour the plan lacks, stays quiet.
17
- 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, 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.',
17
+ 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.',
18
18
  FOLLOW_UP_CHECK_IN: 'Seguimiento: le escribiremos en unas {horas} horas para ver cómo va.',
19
19
  FOLLOW_UP_VIGILANCIA: 'Seguimiento: queda en vigilancia las próximas {horas} horas; le escribiremos para ver cómo va.',
20
20
  });
@@ -42,6 +42,8 @@ function planSummary(plan) {
42
42
  const lines = [...plan.items.map(itemLine), ...plan.studies.map((study) => `Estudio: ${studyLine(study)}`)];
43
43
  if (plan.homeCare.length) lines.push(`Cuidados en casa: ${plan.homeCare.join('; ')}.`);
44
44
  if (plan.note) lines.push(`Nota: ${plan.note}`);
45
+ if (plan.followUp?.kind === 'check_in') lines.push(`Seguimiento: check-in en ${plan.followUp.hours} h.`);
46
+ if (plan.followUp?.kind === 'vigilancia') lines.push(`Seguimiento: vigilancia ${plan.followUp.hours} h.`);
45
47
  return lines.join('\n');
46
48
  }
47
49
 
@@ -98,9 +98,16 @@ const numbersOf = (text) => new Set([...text.matchAll(NUMBER)].map(([number]) =>
98
98
  // Every number in the text, after the same spelling as dosingFactsOf.
99
99
  const allNumbersOf = (text) => numbersOf(dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2')));
100
100
 
101
+ // «un»/«una» before a word that is not a dose, a span or a count («una compresa fría») is an article; «toma una cada 8 horas» counts.
102
+ const COUNT_FOLLOWS = `${COUNTED_FORMS}|gota|${OTHER_FORMS}|${UNITS_SOURCE}|horas?|dias?|semanas?|mes(?:es)?|minutos?|ve(?:z|ces)|dosis|toma|cada|al|a|por|o|u|y|sola|mas|extra|adicional|en|de|diaria|diario`;
103
+ const ARTICLE = new RegExp(`\\b(?:un|una)\\s+(?=[a-z])(?!(?:${COUNT_FOLLOWS})\\b)`, 'g');
104
+ // What makes a sentence about a dose, a study or the follow-up rather than home care.
105
+ const DOSING_WORDS = new RegExp(`\\b(?:${COUNTED_FORMS}|gota|${OTHER_FORMS}|${UNITS_SOURCE}|dosis|medicamentos?|medicinas?|receta|ayun\\w*|estudios?|analisis|laboratorio|cita|consulta|contact\\w*|escrib\\w*|seguimiento|vigilancia)\\b`);
106
+ const isDosingSentence = (text) => DOSING_WORDS.test(folded(text));
107
+
101
108
  // The numbers left once the hours, days and amounts dosingFactsOf reads are taken out: what no pattern explains.
102
109
  function looseNumbersOf(text) {
103
- const dosing = dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2'));
110
+ const dosing = dosingTextOf(folded(String(text ?? '')).replace(LIST_MARKER, '$1$2').replace(ARTICLE, ''));
104
111
  return numbersOf([...NOT_DOSING, HOURS, DAYS, AMOUNTS, URGENCY_WORDS].reduce((rest, pattern) => rest.replace(pattern, ' '), dosing));
105
112
  }
106
113
 
@@ -111,4 +118,4 @@ function urgencyWordsIn(text) {
111
118
  .map((match) => match[1]));
112
119
  }
113
120
 
114
- module.exports = { allNumbersOf, dosingFactsOf, drugNameOf, looseNumbersOf, urgencyWordsIn };
121
+ module.exports = { allNumbersOf, dosingFactsOf, drugNameOf, isDosingSentence, looseNumbersOf, urgencyWordsIn };
@@ -1,9 +1,10 @@
1
1
  const { DEFAULT_FOLLOW_UP_HOURS, planInstructions, plannedTextOf } = require('../helpers/doctorPlanHelper');
2
- const { allNumbersOf, dosingFactsOf, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
2
+ const { allNumbersOf, dosingFactsOf, isDosingSentence, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
3
3
  const { httpError } = require('../../utils/httpErrorUtils');
4
4
  const { oneLineOf } = require('../../utils/coercionUtils');
5
5
  const { PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
6
- const { isDrugNamed, unplannedDrugsIn } = require('./treatmentProposalService');
6
+ const { normalizeForAnchor } = require('../../utils/textMatchUtils');
7
+ const { drugsNamedIn, isDrugNamed, unplannedDrugsIn } = require('./treatmentProposalService');
7
8
 
8
9
  const FIRST_LINE = '1L';
9
10
  const MAX_ENTRIES = 10;
@@ -82,8 +83,9 @@ function planOf(input) {
82
83
  note: textOf(input.note, 'plan.note', MAX_NOTE_LENGTH),
83
84
  followUp: followUpOf(input.followUp),
84
85
  };
85
- if (!plan.items.length && !plan.studies.length && !plan.homeCare.length && !plan.note) {
86
- throw httpError(400, 'plan needs a drug, a study, a home care measure or a note');
86
+ // A follow-up alone is a plan: the assistant adds its home care and the case stays open until the check-in.
87
+ if (!plan.items.length && !plan.studies.length && !plan.homeCare.length && !plan.note && plan.followUp.kind === 'none') {
88
+ throw httpError(400, 'plan needs a drug, a study, a home care measure, a note or a follow-up');
87
89
  }
88
90
  return plan;
89
91
  }
@@ -99,10 +101,20 @@ function approvedInstructions(plan, edited, texts) {
99
101
  const strays = (said, planned) => [...said].filter((value) => !planned.has(value));
100
102
  const everyOf = (hours) => (hours < 1 ? `cada ${Math.round(hours * 60)} minutos` : `cada ${hours} horas`);
101
103
 
104
+ // With no drug in the plan, only sentences about a dose, a study or the follow-up are read for numbers: home care may count gargles.
105
+ function checkedTextOf(plan, reply, planned) {
106
+ if (plan.items.length || drugsNamedIn(planned).length) return reply;
107
+ const studies = plan.studies.map((study) => normalizeForAnchor(study.name)).filter(Boolean);
108
+ return String(reply).split(/(?<=[.!?;:])\s+|\n+/)
109
+ .filter((sentence) => isDosingSentence(sentence) || drugsNamedIn(sentence).length || studies.some((name) => normalizeForAnchor(sentence).includes(name)))
110
+ .join('\n');
111
+ }
112
+
102
113
  function replyIssues(plan, reply) {
103
114
  if (!oneLineOf(reply)) return ['no se pudo leer el mensaje enviado'];
104
115
  const planned = plannedTextOf(plan);
105
- const said = dosingFactsOf(reply);
116
+ const checked = checkedTextOf(plan, reply, planned);
117
+ const said = dosingFactsOf(checked);
106
118
  const allowed = dosingFactsOf(planned);
107
119
  const issues = plan.items.filter((item) => !isDrugNamed(reply, item.drug)).map((item) => `no menciona ${item.drug}`);
108
120
  for (const hours of strays(said.hours, allowed.hours)) issues.push(`dice «${everyOf(hours)}», que no está en el plan`);
@@ -111,7 +123,7 @@ function replyIssues(plan, reply) {
111
123
  if (!allowed.amounts.has(amount)) issues.push(`dice «${written}», que no está en el plan`);
112
124
  }
113
125
  // A number no pattern reads («tómalo 5 días», «a las 10») still flags when the plan never names it.
114
- for (const number of strays(looseNumbersOf(reply), allNumbersOf(planned))) issues.push(`menciona «${number}», que no está en el plan`);
126
+ for (const number of strays(looseNumbersOf(checked), allNumbersOf(planned))) issues.push(`menciona «${number}», que no está en el plan`);
115
127
  for (const name of unplannedDrugsIn(reply, planned)) issues.push(`menciona ${name}, que el médico no indicó`);
116
128
  for (const word of strays(urgencyWordsIn(reply), urgencyWordsIn(planned))) issues.push(`usa «${word}», que el médico no indicó`);
117
129
  return issues;
@@ -2,7 +2,7 @@ const { logger } = require('../utils/logger');
2
2
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
3
  const { getEscalationReview } = require('../models/escalationReviewModel');
4
4
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
5
- const { escalationWatchExpiryLive } = require('../clinical/flags/escalationFlags');
5
+ const { escalationWatchExpiryLive, escalationWatchTeamNoticeLive } = require('../clinical/flags/escalationFlags');
6
6
 
7
7
  const { countMessages } = require('./messageService');
8
8
  const { logPatientChange } = require('./patientService');
@@ -24,6 +24,7 @@ const TEAM_WAIT_MS = 2 * 60 * 60 * 1000;
24
24
  // A reminder this late (an outage, a deploy) is not sent; the team notice still goes.
25
25
  const STALE_MS = 30 * 60 * 1000;
26
26
  const getMessaging = () => require('../core/NexusMessaging');
27
+ const REMINDED_UNTILS = { $map: { input: { $filter: { input: { $ifNull: ['$watchNotices', []] }, cond: { $eq: ['$$this.kind', 'reminder'] } } }, in: '$$this.until' } };
27
28
 
28
29
  const timeOf = (value) => new Date(value).getTime();
29
30
 
@@ -128,12 +129,16 @@ async function noticeTeam(review, reminder, now) {
128
129
  return true;
129
130
  }
130
131
 
131
- // A watch that ran out is never closed silently: the patient gets one reminder, then the team is told.
132
+ // A watch that ran out is never closed silently: the patient gets one reminder, then the team is told while its flag is on.
132
133
  async function sweepExpiredWatches({ now = new Date() } = {}) {
133
134
  if (!escalationWatchExpiryLive()) return 0;
135
+ const teamNotice = escalationWatchTeamNoticeLive();
136
+ const query = { closedAt: null, status: 'monitoring', monitoringUntil: { $lte: now } };
137
+ // With no team notice a reminded watch has nothing left to send, so it must not hold a sweep slot.
138
+ if (!teamNotice) query.$expr = { $not: [{ $in: ['$monitoringUntil', REMINDED_UNTILS] }] };
134
139
  const reviews = await getEscalationReview()
135
140
  .find(
136
- { closedAt: null, status: 'monitoring', monitoringUntil: { $lte: now } },
141
+ query,
137
142
  { patientCode: 1, status: 1, monitoringUntil: 1, watchNotices: 1, 'alarms.emergencyRecordId': 1 },
138
143
  )
139
144
  .sort({ monitoringUntil: 1 })
@@ -144,6 +149,7 @@ async function sweepExpiredWatches({ now = new Date() } = {}) {
144
149
  try {
145
150
  if (noticesOf(review, 'team').some((entry) => !failed(entry))) continue;
146
151
  const [reminder] = noticesOf(review, 'reminder');
152
+ if (reminder && !teamNotice) continue;
147
153
  if (await (reminder ? noticeTeam(review, reminder, now) : remindPatient(review, now))) sent += 1;
148
154
  } catch (error) {
149
155
  logger.error('[WatchExpiry] Could not check an expired watch', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.8",
3
+ "version": "6.4.10",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",