@peopl-health/nexus 6.0.0-dev.16335 → 6.0.0-dev.16339

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.
@@ -254,7 +254,7 @@ function recordEmergency(params) {
254
254
  return serializedEmergencyWrite(params.code, () => recordEmergencyNow(params));
255
255
  }
256
256
 
257
- async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true, anchor = null, keepOpenRow = false, onRecorded = null }) {
257
+ async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true, anchor = null, keepOpenRow = false, onRecorded = null, onMerging = null }) {
258
258
  const level = urgencyLevel || MEDICAL_URGENCY_TO_EMERGENCY_LEVEL[urgencyFhir] || 'Alta';
259
259
  const prior = anchor?.recordId ? anchor : (mergeWithRecent ? (await recentEmergencyCache.get(code) || null) : null);
260
260
  const rank = EMERGENCY_URGENCY_RANK[urgencyFhir];
@@ -281,6 +281,7 @@ async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '
281
281
 
282
282
  const open = mergeable ? await readEmergencyRow(prior.recordId, code) : null;
283
283
  if (open) {
284
+ onMerging?.(true);
284
285
  const incoming = belowPrior
285
286
  ? [symptom && `Síntoma: ${symptom}`, suspectedCondition && `Sospecha: ${suspectedCondition}`, recommendedAction && `Acción recomendada: ${recommendedAction}`]
286
287
  .filter(Boolean).join(' · ')
@@ -301,6 +302,7 @@ async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '
301
302
  }
302
303
  }
303
304
 
305
+ onMerging?.(false);
304
306
  if (documentation) fields['Documentación_emergencia'] = documentation;
305
307
  const created = await airtableService.addRecord(Monitoreo_ID, 'emergencies', [{ fields }], code);
306
308
  const record = Array.isArray(created) ? created[0] : created;
@@ -21,7 +21,7 @@ const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxi
21
21
 
22
22
  const definition = {
23
23
  'name': 'reportMedicalEscalation',
24
- 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go and asks nothing. In `asap`, ask the short neuro checklist in the same message (orientation, weakness on one side, speech, vision, vomiting, seizure) — the one exception to one question and to no lists.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\') and the availability line — no urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed (an invitation to write again if it changes or worries them — never a time, and no urgencias outside a must-go `stat`). `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
24
+ 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go and asks nothing. In `asap`, ask the short neuro checklist in the same message as ONE question on one line, not a numbered list (\'¿Sabes dónde estás y qué día es, puedes hablar bien, ves bien, sientes debilidad de un lado, has vomitado o convulsionado?\'), keeping the message ≤60 words — the one exception to asking about a single sign and to no lists.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\') and the availability line — no urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed (an invitation to write again if it changes or worries them — never a time, and no urgencias outside a must-go `stat`). `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
25
25
  'strict': true,
26
26
  'parameters': {
27
27
  'type': 'object',
@@ -392,6 +392,7 @@ async function handler(args, context = {}) {
392
392
  queued = written || duplicate;
393
393
  } else {
394
394
  let emergencyRecordId = null;
395
+ let merging = false;
395
396
  queued = await recordEmergency({
396
397
  code: runtime.patientCode,
397
398
  trace,
@@ -408,10 +409,11 @@ async function handler(args, context = {}) {
408
409
  anchor: anchor?.emergencyRecordId ? { recordId: anchor.emergencyRecordId, urgencyFhir: anchor.urgencyLevel } : null,
409
410
  keepOpenRow: keptOpenLevel,
410
411
  onRecorded: (recordId) => { emergencyRecordId = recordId; },
412
+ onMerging: (into) => { merging = into; },
411
413
  });
412
414
  if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
413
- // A merge into an existing row never alerts, so only a row that had to be created falls back.
414
- if (review && !queued && (raisesOpen || !anchor?.emergencyRecordId)) {
415
+ // A merge into an open row never alerts; any other failed write may have left the team without one.
416
+ if (review && !queued && !merging) {
415
417
  alertWithoutEmergencyRow({ reviewId: review._id, alarmId, urgencyLevel }).catch(() => {});
416
418
  }
417
419
  if (urgencyLevel !== 'routine') {
@@ -2,7 +2,7 @@ const mongoose = require('mongoose');
2
2
 
3
3
  const runtimeConfig = require('../config/runtimeConfig');
4
4
  const { httpError, requiredText } = require('../utils/httpErrorUtils');
5
- const { inlineOf } = require('../utils/coercionUtils');
5
+ const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
6
6
  const { logger } = require('../utils/logger');
7
7
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
8
  const { isoDay, mexicoDay } = require('../utils/dateUtils');
@@ -1253,22 +1253,26 @@ async function fallbackRecipient() {
1253
1253
  return phone ? { name: null, email: null, phone } : soleApprover();
1254
1254
  }
1255
1255
 
1256
- const oneLine = (value) => inlineOf(value).replace(/\s+/g, ' ');
1257
-
1258
- // A brief notice for the whole team; a patient record that cannot be read never holds it back.
1259
- async function teamFallbackNotice(review, urgencyLevel, alarmId) {
1256
+ // Who and where for a team alert; a patient record that cannot be read never holds the alert back.
1257
+ async function teamAlertIdentity(review) {
1260
1258
  let identity = { patientName: '', treatingDoctor: '' };
1261
1259
  try {
1262
1260
  identity = doctorIdentity(await getPatientInformation(review.patientCode));
1263
1261
  } catch (error) {
1264
- logger.error('[EscalationReview] The patient record could not be read for the team notice', { escalationReviewId: String(review._id), error: redactedError(error) });
1262
+ logger.error('[EscalationReview] The patient record could not be read; the team alert goes out without the name', { escalationReviewId: String(review._id), error: redactedError(error) });
1265
1263
  }
1266
- const patient = oneLine(identity.patientName) || 'sin nombre registrado';
1267
- const doctor = oneLine(identity.treatingDoctor) || 'sin médico registrado';
1268
- const link = conversationLink(review.patientCode) || 'abrir el chat en la plataforma';
1264
+ return {
1265
+ patient: oneLineOf(identity.patientName) || 'sin nombre registrado',
1266
+ doctor: oneLineOf(identity.treatingDoctor) || 'sin médico registrado',
1267
+ link: conversationLink(review.patientCode) || 'abrir el chat en la plataforma',
1268
+ };
1269
+ }
1270
+
1271
+ async function teamFallbackNotice(review, urgencyLevel, alarmId) {
1272
+ const { patient, doctor, link } = await teamAlertIdentity(review);
1269
1273
  const alarm = (alarmId && (review.alarms ?? []).find((raised) => raised.alarmId === alarmId))
1270
1274
  ?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1271
- const what = [urgencyLevel.toUpperCase(), oneLine(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
1275
+ const what = [urgencyLevel.toUpperCase(), oneLineOf(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
1272
1276
  return {
1273
1277
  body: `⚠️ ${ALERT_MARKS[urgencyLevel]} ${what}\n${patient} (${doctor})\n${link}`,
1274
1278
  template: { 1: what, 2: patient, 3: doctor, 4: link },
@@ -2146,6 +2150,7 @@ module.exports = {
2146
2150
  BOOKKEEPING,
2147
2151
  DOCUMENTING_STATUSES,
2148
2152
  FEVER_CATEGORY,
2153
+ appliedLevelOf,
2149
2154
  MAX_ALERT_ATTEMPTS,
2150
2155
  PRE_DECISION_STATUSES,
2151
2156
  _resetEscalationReviewIndexes,
@@ -2153,6 +2158,7 @@ module.exports = {
2153
2158
  caseTakenReason,
2154
2159
  currentAlarms,
2155
2160
  doctorIdentity,
2161
+ teamAlertIdentity,
2156
2162
  addDraft,
2157
2163
  alertWithoutEmergencyRow,
2158
2164
  attachEmergencyRow,
@@ -93,7 +93,8 @@ async function sendAlertTo({ code, message, operator, templateKey }) {
93
93
 
94
94
  const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'));
95
95
 
96
- const teamChannelConfigured = async () => groupConfigured() || (await teamPhones()).length > 0;
96
+ // Phones alone count only once the notice template exists, or a notice outside the 24-hour window reaches no one.
97
+ const teamChannelConfigured = async () => groupConfigured() || (Boolean(runtimeConfig.get(NOTICE_TEMPLATE_KEY)) && (await teamPhones()).length > 0);
97
98
 
98
99
  async function postToGroup(body, quoted) {
99
100
  const res = await axios({
@@ -1,13 +1,13 @@
1
- const { inlineOf } = require('../utils/coercionUtils');
1
+ const { oneLineOf } = require('../utils/coercionUtils');
2
2
  const { logger } = require('../utils/logger');
3
3
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
- const { conversationLink, readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
5
+ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
6
6
  const { escalationGravePendingShadow, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
7
7
 
8
- const { getPatientInformation, logPatientChange } = require('./patientService');
8
+ const { logPatientChange } = require('./patientService');
9
9
  const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
10
- const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, caseTakenReason, currentAlarms, doctorIdentity } = require('./escalationReviewService');
10
+ const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, teamAlertIdentity } = require('./escalationReviewService');
11
11
  const { recordGraveMissing } = require('./gravePendingService');
12
12
  const { sendTeamAlert } = require('./teamAlertService');
13
13
 
@@ -24,16 +24,8 @@ const ACTIONS = {
24
24
  asap: 'Tomar el caso: escribir o llamar y registrar la llamada',
25
25
  urgent: 'Tomar el caso: escribir o llamar y registrar la llamada',
26
26
  };
27
- const NO_NAME = 'sin nombre registrado';
28
- const NO_DOCTOR = 'sin médico registrado';
29
- const NO_LINK = 'abrir el chat en la plataforma';
30
27
  const MAX_QUESTION_LENGTH = 200;
31
28
 
32
- const appliedLevelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
33
-
34
- // A WhatsApp template variable cannot hold a line break.
35
- const oneLine = (value) => inlineOf(value).replace(/\s+/g, ' ');
36
-
37
29
  const duration = (minutes) => {
38
30
  const hours = Math.floor(minutes / 60);
39
31
  const rest = Math.round(minutes % 60);
@@ -53,7 +45,7 @@ function untakenClockOf(review, policy) {
53
45
  return {
54
46
  level,
55
47
  since,
56
- symptom: oneLine(atLevel.at(-1).symptom),
48
+ symptom: oneLineOf(atLevel.at(-1).symptom),
57
49
  emergencyRecordId: atLevel.find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId ?? null,
58
50
  stages: untakenStagesOf(level, since, policy),
59
51
  };
@@ -80,7 +72,7 @@ function deadlineText(clock, stage) {
80
72
  function pendingQuestionOf(review, clock) {
81
73
  const draft = (review.drafts ?? []).at(-1);
82
74
  if (!draft || new Date(draft.createdAt).getTime() < clock.since.getTime()) return null;
83
- const question = oneLine(draft.keyQuestions?.[0]);
75
+ const question = oneLineOf(draft.keyQuestions?.[0]);
84
76
  return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
85
77
  }
86
78
 
@@ -94,22 +86,8 @@ function patientPromptNote(review, stage, now) {
94
86
  return lead >= 1 ? `Si nadie lo toma, la paciente recibe los números para llamar en ${duration(lead)}` : null;
95
87
  }
96
88
 
97
- async function identityOf(review) {
98
- try {
99
- return doctorIdentity(await getPatientInformation(review.patientCode));
100
- } catch (error) {
101
- logger.error('[UntakenAlert] The patient record could not be read; the alert goes out without the name', {
102
- escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
103
- });
104
- return { patientName: '', treatingDoctor: '' };
105
- }
106
- }
107
-
108
89
  async function untakenMessage(review, clock, stage, now) {
109
- const { patientName, treatingDoctor } = await identityOf(review);
110
- const patient = patientName || NO_NAME;
111
- const doctor = treatingDoctor || NO_DOCTOR;
112
- const link = conversationLink(review.patientCode) || NO_LINK;
90
+ const { patient, doctor, link } = await teamAlertIdentity(review);
113
91
  const deadline = deadlineText(clock, stage);
114
92
  const level = LEVEL_LABELS[clock.level];
115
93
  const action = ACTIONS[clock.level];
@@ -3,7 +3,8 @@ const arr = (value) => (Array.isArray(value) ? value : []);
3
3
  const strList = (value) => arr(value).map(str).map((item) => item.trim()).filter(Boolean);
4
4
  const firstOf = (value) => (Array.isArray(value) ? value[0] : value);
5
5
  const inlineOf = (value) => String(firstOf(value) ?? '').trim();
6
+ const oneLineOf = (value) => inlineOf(value).replace(/\s+/g, ' ');
6
7
 
7
8
  module.exports = {
8
- str, arr, strList, firstOf, inlineOf,
9
+ str, arr, strList, firstOf, inlineOf, oneLineOf,
9
10
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.0-dev.16335",
3
+ "version": "6.0.0-dev.16339",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",