@peopl-health/nexus 6.0.0-dev.15840 → 6.0.0-dev.16228

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.
Files changed (31) hide show
  1. package/lib/clinical/flags/clinicalContextFlags.js +5 -0
  2. package/lib/clinical/flags/flagSnapshot.js +4 -1
  3. package/lib/clinical/helpers/chemoContextHelper.js +2 -1
  4. package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
  5. package/lib/clinical/memory/DefaultMemoryManager.js +4 -1
  6. package/lib/clinical/models/triageRecommendationEventModel.js +1 -0
  7. package/lib/clinical/providers/BaseLLMProvider.js +19 -10
  8. package/lib/clinical/providers/OpenAIResponsesProviderTools.js +6 -1
  9. package/lib/clinical/services/checkInDueService.js +2 -0
  10. package/lib/clinical/services/radiotherapyContextService.js +40 -0
  11. package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
  12. package/lib/clinical/services/triageRecommendationService.js +13 -0
  13. package/lib/clinical/tools/reportMedicalEscalationTool.js +11 -5
  14. package/lib/clinical/tools/schedulePatientReminderTool.js +1 -1
  15. package/lib/controllers/messageController.js +4 -0
  16. package/lib/controllers/patientController.js +21 -13
  17. package/lib/eval/EvalProvider.js +1 -1
  18. package/lib/helpers/airtableArchiveHelper.js +7 -1
  19. package/lib/helpers/patientMessageHelper.js +3 -1
  20. package/lib/index.d.ts +2 -2
  21. package/lib/models/airtableArchiveModel.js +1 -0
  22. package/lib/services/airtableArchivePlanService.js +12 -5
  23. package/lib/services/airtableArchiveReadService.js +31 -6
  24. package/lib/services/airtableArchiveService.js +4 -4
  25. package/lib/services/escalationReviewService.js +45 -4
  26. package/lib/services/recommendationCarouselService.js +58 -20
  27. package/lib/services/teamAlertService.js +13 -7
  28. package/lib/services/triageHistoryService.js +25 -4
  29. package/lib/utils/dateUtils.js +6 -0
  30. package/lib/utils/jsonUtils.js +21 -0
  31. package/package.json +1 -1
@@ -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 without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability.\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 → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside `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 `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` is the ONLY level that sends the patient now — 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. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — 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`, after the 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 make the fallback explicit to the patient whenever nothing is armed. `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 without a further clarifying question: `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.\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 — 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 make the fallback explicit to the patient whenever nothing is armed. `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',
@@ -34,7 +34,7 @@ const definition = {
34
34
  'urgent',
35
35
  'routine'
36
36
  ],
37
- 'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: ' + FEVER_RUBRIC_STAT + ' disnea severa, dolor de pecho con falta de aire clara, alteración del estado mental, sangrado mayor, compresión medular con déficit agudo.\n- `asap` (lo antes posible, gate urgencias) — máxima prioridad NO inmediata; objetivo interno de valoración en horas (no se le promete al paciente), porque la demora puede crear riesgo; el paciente no va a urgencias; el equipo decide dónde se le valora. Complicación seria sospechada pero aún no claramente inestable: dolor que empeora rápido, ' + FEVER_RUBRIC_ASAP + ' síntoma neurológico nuevo sin déficit agudo.\n- `urgent` (urgente, gate equipo_tratante_hoy) — objetivo interno de revisión en 24 h (no se le promete al paciente), por encima de rutina porque la demora podría importar clínicamente; el paciente puede seguir en casa: síntoma nuevo moderado, anormalidad de laboratorio preocupante pero estable, toxicidad de tratamiento que necesita input oportuno.\n- `routine` (rutina, sin gate o verdict suavizado) — prioridad normal, vía de atención habitual. Sin riesgo por demora: seguimiento, aclaración de medicación, síntoma >72h sin empeorar, contexto clínico desactualizado.'
37
+ 'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: ' + FEVER_RUBRIC_STAT + ' disnea severa, dolor de pecho con falta de aire clara, alteración del estado mental, sangrado mayor, compresión medular con déficit agudo, anafilaxia confirmada (hinchazón de lengua o garganta, dificultad para tragar, respirar o hablar, o ronchas en todo el cuerpo con mareo), choque (piel fría y sudorosa, manchada o grisácea junto con mareo al pararse, mucha debilidad, corazón acelerado o casi no orinar). Cualquier dato confirmado de la lista de ir sí o sí (descrita en la descripción de la herramienta, incluida la posible compresión medular aunque venga en horas o días) es `stat`, nunca `asap`.\n- `asap` (lo antes posible, gate urgencias) — máxima prioridad NO inmediata; objetivo interno de valoración en horas (no se le promete al paciente), porque la demora puede crear riesgo; el paciente no va a urgencias; el equipo decide dónde se le valora. Complicación seria sospechada pero aún no claramente inestable: dolor que empeora rápido, ' + FEVER_RUBRIC_ASAP + ' síntoma neurológico nuevo sin déficit agudo.\n- `urgent` (urgente, gate equipo_tratante_hoy) — objetivo interno de revisión en 24 h (no se le promete al paciente), por encima de rutina porque la demora podría importar clínicamente; el paciente puede seguir en casa: síntoma nuevo moderado, anormalidad de laboratorio preocupante pero estable, toxicidad de tratamiento que necesita input oportuno.\n- `routine` (rutina, sin gate o verdict suavizado) — prioridad normal, vía de atención habitual. Sin riesgo por demora: seguimiento, aclaración de medicación, síntoma >72h sin empeorar, contexto clínico desactualizado.'
38
38
  },
39
39
  'patient_check_in': {
40
40
  'anyOf': [
@@ -155,11 +155,17 @@ const MODE_PROPERTY = {
155
155
 
156
156
  const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
157
157
 
158
- const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, ≤36.0 °C, feeling feverish or chills with no thermometer, or malaise while on an antipyretic or steroid — is `asap` with `category: febrile_neutropenia`. It is `stat` only with a clear, confirmed red flag (clear shortness of breath, clear confusion, strong rigors, mottled skin, bleeding), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
158
+ // with the timer the fever rule sends to urgencias only from `stat`, like every other case
159
+ const FEVER_SIGNS = 'Outside a must-go `stat` and the fever rule, no warning signs';
160
+ const FEVER_SIGNS_TIMER = 'Outside a must-go `stat`, no warning signs';
161
+ const FEVER_URGENCIAS = '(two exceptions: the fever rule, and chest pain';
162
+ const FEVER_URGENCIAS_TIMER = '(one exception: chest pain';
163
+
164
+ const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, malaise while on an antipyretic or steroid, or ≤36.0 °C with malaise, chills or shivering — is `asap` with `category: febrile_neutropenia`. A low reading (≤36.0 °C) on its own is not fever: ask for an oral re-measure before escalating; still ≤36.0 °C with no other symptom is `urgent`, confirmed ≤35.0 °C is `asap`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
159
165
 
160
166
  const FEVER_RUBRIC_STAT_TIMER = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
161
167
 
162
- const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C o ≤36.0 °C en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
168
+ const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C, o ≤36.0 °C con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
163
169
 
164
170
  const CLINICAL_ASSESSMENT_PROPERTY = nullable({
165
171
  'type': 'object',
@@ -217,7 +223,7 @@ function liveDefinition() {
217
223
  properties.details.required.push('clinical_assessment');
218
224
  }
219
225
  if (feverTimer) {
220
- live.description = live.description.replace(FEVER_RULE, FEVER_RULE_TIMER);
226
+ live.description = live.description.replace(FEVER_RULE, FEVER_RULE_TIMER).replace(FEVER_SIGNS, FEVER_SIGNS_TIMER).replace(FEVER_URGENCIAS, FEVER_URGENCIAS_TIMER);
221
227
  properties.urgency_level.description = properties.urgency_level.description
222
228
  .replace(FEVER_RUBRIC_STAT, FEVER_RUBRIC_STAT_TIMER)
223
229
  .replace(FEVER_RUBRIC_ASAP, FEVER_RUBRIC_ASAP_TIMER);
@@ -23,7 +23,7 @@ const definition = {
23
23
  },
24
24
  reminder_description: {
25
25
  type: 'string',
26
- description: 'Short description of what the reminder is for (e.g. \'tomar ondansetrón antes del desayuno\', \'preguntarle cómo amaneció del dolor de cabeza\'). This becomes the WhatsApp message body. For a Programme activity name the format — la charla, tu sesión colectiva, tu sesión individual — never a bare \'tu sesión\': the text stays in the conversation and is what a later turn reads to tell them apart.',
26
+ description: 'Short description of what the reminder is for (e.g. \'tomar ondansetrón antes del desayuno\', \'preguntarle cómo amaneció del dolor de cabeza\'). This becomes the WhatsApp message body. For seguimiento, one question only — the one that matters most on that date — written as asked for the first time (never «te había preguntado»). For a Programme activity name the format — la charla, tu sesión colectiva, tu sesión individual — never a bare \'tu sesión\': the text stays in the conversation and is what a later turn reads to tell them apart.',
27
27
  },
28
28
  reminder_type: {
29
29
  type: 'string',
@@ -83,6 +83,10 @@ const sendMessageController = async (req, res) => {
83
83
  return res.status(400).json({ success: false, error: 'code is required' });
84
84
  }
85
85
 
86
+ if (!message && !fileUrl && !contentSid) {
87
+ return res.status(400).json({ success: false, error: 'message, fileUrl or contentSid is required' });
88
+ }
89
+
86
90
  try {
87
91
  let contact = {};
88
92
  if (contactCode) {
@@ -181,19 +181,27 @@ const getPatientRecommendationCarouselImageController = async (req, res) => {
181
181
  });
182
182
  if (!image) return res.status(404).json({ success: false, error: 'Carousel image not found' });
183
183
 
184
- const source = new URL(image.url);
185
- const allowed = source.protocol === 'https:'
186
- && isAllowedUrl(image.url, ['airtableusercontent.com', 'airtable.com']);
187
- if (!allowed) return res.status(502).json({ success: false, error: 'Unsupported carousel image source' });
188
-
189
- const response = await axios.get(image.url, {
190
- responseType: 'arraybuffer',
191
- timeout: 15000,
192
- maxContentLength: 10 * 1024 * 1024,
193
- maxRedirects: 0,
194
- });
195
- const contentType = String(response.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
196
- const body = Buffer.from(response.data);
184
+ let contentType;
185
+ let body;
186
+ if (image.body) {
187
+ // Archived carousels: the service already read the re-hosted image from the archive bucket.
188
+ contentType = String(image.contentType || '').split(';')[0].trim().toLowerCase();
189
+ body = image.body;
190
+ } else {
191
+ const source = new URL(image.url);
192
+ const allowed = source.protocol === 'https:'
193
+ && isAllowedUrl(image.url, ['airtableusercontent.com', 'airtable.com']);
194
+ if (!allowed) return res.status(502).json({ success: false, error: 'Unsupported carousel image source' });
195
+
196
+ const response = await axios.get(image.url, {
197
+ responseType: 'arraybuffer',
198
+ timeout: 15000,
199
+ maxContentLength: 10 * 1024 * 1024,
200
+ maxRedirects: 0,
201
+ });
202
+ contentType = String(response.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
203
+ body = Buffer.from(response.data);
204
+ }
197
205
  const signatures = {
198
206
  'image/png': () => body.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
199
207
  'image/jpeg': () => body.length >= 3 && body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff,
@@ -106,7 +106,7 @@ class EvalProvider {
106
106
  async _buildContext(numero, beforeCheckpoint) {
107
107
  const messages = await this.memoryManager.buildContext({
108
108
  thread: { code: numero },
109
- config: { beforeCheckpoint, beforeOperator: '$lt' },
109
+ config: { beforeCheckpoint, beforeOperator: '$lt', compactOlderTriage: true },
110
110
  });
111
111
 
112
112
  const lastUserMsg = [...messages].reverse().find(m => m.role === 'user');
@@ -28,7 +28,13 @@ const hashFields = (fields, skip = new Set()) => crypto.createHash('sha256')
28
28
  const schemaSnapshotId = (baseId, snapshot) => `${baseId}:${crypto.createHash('sha256').update(stableStringify(snapshot)).digest('hex').slice(0, 24)}`;
29
29
 
30
30
  // Same shape as airtableService.getRecordByFilter(..., withRecordId = true), flagged as archived.
31
- const toAirtableRow = (doc) => ({ ...doc.fields, _recordId: doc.recordId, _createdTime: new Date(doc.createdTime).toISOString(), _archived: true });
31
+ const toAirtableRow = (doc) => ({
32
+ ...doc.fields,
33
+ _recordId: doc.recordId,
34
+ _createdTime: new Date(doc.createdTime).toISOString(),
35
+ _archived: true,
36
+ ...(doc.attachments ? { _attachments: doc.attachments } : {}),
37
+ });
32
38
 
33
39
  // Union by record id, live row winning; archived rows are appended, so callers sort after merging.
34
40
  function mergeArchivedRows(liveRows = [], archivedRows = []) {
@@ -1,3 +1,5 @@
1
+ const { decodeLiteralUnicodeEscapes } = require('../utils/jsonUtils');
2
+
1
3
  const PATIENT_MESSAGE_OPEN = '<patient_message>';
2
4
  const PATIENT_MESSAGE_CLOSE = '</patient_message>';
3
5
  const PATIENT_MESSAGE_BLOCK_RX = /<patient_message(?:\s[^>]*)?>\s*([\s\S]*?)\s*<\/patient_message\s*>/i;
@@ -58,7 +60,7 @@ function stripTurnMarkers(text) {
58
60
  function sanitizeOutput(text) {
59
61
  if (!text || typeof text !== 'string') return text;
60
62
 
61
- let sanitized = text;
63
+ let sanitized = decodeLiteralUnicodeEscapes(text);
62
64
  sanitized = stripTurnMarkers(sanitized);
63
65
  sanitized = removeBracketContent(sanitized);
64
66
  sanitized = formatForWhatsApp(sanitized);
package/lib/index.d.ts CHANGED
@@ -468,7 +468,7 @@ declare module '@peopl-health/nexus' {
468
468
  lastInboundAt?: string | null;
469
469
  lastOutboundAt?: string | null;
470
470
  lastOutreach?: string | null;
471
- checkIn?: { type: string; reminderId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
471
+ checkIn?: { type: string; reminderId?: string | null; planId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
472
472
  recentCheckIns?: string[];
473
473
  exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number; sessionOpen?: boolean } | null;
474
474
  asOf?: string | null;
@@ -565,7 +565,7 @@ declare module '@peopl-health/nexus' {
565
565
  ultimaAplicacion: { fecha: string; ciclo?: number; sesion?: number; total?: number } | null;
566
566
  esquema: Array<{ farmaco: string; via?: string; tiempo?: string }>;
567
567
  inicioEsquema: { fecha: string; anteriorAlRegistro: boolean } | null;
568
- proximaSesion: { fecha: string; tipo: string; confirmada?: boolean } | null;
568
+ proximaSesion: { fecha: string; tipo: string; confirmada?: boolean; hora?: string | null } | null;
569
569
  esquemaPrevio: { farmacos: string[]; hasta: string } | null;
570
570
  [key: string]: any;
571
571
  }
@@ -42,6 +42,7 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
42
42
 
43
43
  airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, 'patient.whatsappId': 1, createdTime: -1 });
44
44
  airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, 'patient.recordId': 1, createdTime: -1 });
45
+ airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, createdTime: -1 });
45
46
  airtableArchiveRecordSchema.index({ baseId: 1, groupId: 1 });
46
47
  airtableArchiveRecordSchema.index({ runId: 1 });
47
48
 
@@ -171,13 +171,20 @@ function planArchive({ recordsByTable, patientsWithRecent = {}, schema }) {
171
171
  continue;
172
172
  }
173
173
  const patientEntry = records.map(({ id }) => entries.get(id)).find(patientOf);
174
+ const patient = {
175
+ recordId: patientEntry ? patientOf(patientEntry) : null,
176
+ whatsappId: firstString(patientEntry?.record.fields?.[schema.whatsappFields[patientEntry.table]]),
177
+ };
178
+ // A group can join two patients' records through a shared questionnaire; each record keeps its own patient.
179
+ const patientFor = (entry) => {
180
+ const own = patientOf(entry);
181
+ if (!own || own === patient.recordId) return patient;
182
+ return { recordId: own, whatsappId: firstString(entry.record.fields?.[schema.whatsappFields[entry.table]]) };
183
+ };
174
184
  eligible.push({
175
185
  groupId: groupIdOf(records.map(({ id }) => id)),
176
- patient: {
177
- recordId: patientEntry ? patientOf(patientEntry) : null,
178
- whatsappId: firstString(patientEntry?.record.fields?.[schema.whatsappFields[patientEntry.table]]),
179
- },
180
- records,
186
+ patient,
187
+ records: records.map((record) => ({ ...record, patient: patientFor(entries.get(record.id)) })),
181
188
  });
182
189
  }
183
190
 
@@ -1,25 +1,50 @@
1
+ const { getModelDatabase } = require('../config/mongoConfig');
1
2
  const { getAirtableArchiveRecord, archiveRecordId } = require('../models/airtableArchiveModel');
2
3
  const { toAirtableRow } = require('../helpers/airtableArchiveHelper');
3
4
 
4
- const READ_PROJECTION = { recordId: 1, createdTime: 1, fields: 1 };
5
+ // Only rows already deleted from Airtable: a copy whose source is still live must never reach a reader.
6
+ const DELETED_FROM_SOURCE = { sourceDeletedAt: { $ne: null } };
5
7
 
6
- async function findArchivedByPatient({ baseId, tableName, whatsappId, patientRecordId, since }) {
8
+ // Unmapped, the model would fall back to the default database and every read would come back empty.
9
+ function archiveRecords() {
10
+ if (!getModelDatabase('AirtableArchiveRecord')) throw new Error('AirtableArchiveRecord db not mapped (setModelDatabases)');
11
+ return getAirtableArchiveRecord();
12
+ }
13
+
14
+ function readProjection({ fields, withAttachments = false } = {}) {
15
+ const projection = { recordId: 1, createdTime: 1 };
16
+ if (fields?.length) fields.forEach((name) => { projection[`fields.${name}`] = 1; });
17
+ else projection.fields = 1;
18
+ if (withAttachments) projection.attachments = 1;
19
+ return projection;
20
+ }
21
+
22
+ async function findArchivedByPatient({ baseId, tableName, whatsappId, patientRecordId, since, fields, withAttachments }) {
7
23
  if (!whatsappId && !patientRecordId) return [];
8
- const query = { baseId, tableName };
24
+ const query = { baseId, tableName, ...DELETED_FROM_SOURCE };
9
25
  if (patientRecordId) query['patient.recordId'] = patientRecordId;
10
26
  else query['patient.whatsappId'] = whatsappId;
11
27
  if (since) query.createdTime = { $gte: since };
12
- const docs = await getAirtableArchiveRecord().find(query, READ_PROJECTION).sort({ createdTime: -1 }).lean();
28
+ const docs = await archiveRecords().find(query, readProjection({ fields, withAttachments })).sort({ createdTime: -1 }).lean();
13
29
  return docs.map(toAirtableRow);
14
30
  }
15
31
 
16
- async function findArchivedByRecordIds({ baseId, tableName, recordIds }) {
32
+ async function findArchivedByRecordIds({ baseId, tableName, recordIds, fields, withAttachments }) {
17
33
  if (!recordIds?.length) return [];
18
- const docs = await getAirtableArchiveRecord().find({ _id: { $in: recordIds.map((id) => archiveRecordId(baseId, id)) }, tableName }, READ_PROJECTION).lean();
34
+ const query = { _id: { $in: recordIds.map((id) => archiveRecordId(baseId, id)) }, tableName, ...DELETED_FROM_SOURCE };
35
+ const docs = await archiveRecords().find(query, readProjection({ fields, withAttachments })).lean();
36
+ return docs.map(toAirtableRow);
37
+ }
38
+
39
+ async function findArchivedByTable({ baseId, tableName, since, fields }) {
40
+ const query = { baseId, tableName, ...DELETED_FROM_SOURCE };
41
+ if (since) query.createdTime = { $gte: since };
42
+ const docs = await archiveRecords().find(query, readProjection({ fields })).sort({ createdTime: -1 }).lean();
19
43
  return docs.map(toAirtableRow);
20
44
  }
21
45
 
22
46
  module.exports = {
23
47
  findArchivedByPatient,
24
48
  findArchivedByRecordIds,
49
+ findArchivedByTable,
25
50
  };
@@ -237,7 +237,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
237
237
 
238
238
  const expected = new Map();
239
239
  const ops = [];
240
- for (const { table, record: scanned, group } of batch) {
240
+ for (const { table, record: scanned, group, patient } of batch) {
241
241
  if (changedGroups.has(group.groupId)) {
242
242
  counts[table].failed += 1;
243
243
  logger.error('[airtableArchive] Group changed or gone since the scan', { runId, table, recordId: scanned.id, groupId: group.groupId });
@@ -249,7 +249,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
249
249
  const fieldsHash = hashFields(normalized);
250
250
  const sourceHash = hashFields(normalized, schema.computed.get(table));
251
251
  const tableId = schema.tableIds[table];
252
- const placement = placementOf(table, group.groupId, group.patient, record.createdTime);
252
+ const placement = placementOf(table, group.groupId, patient, record.createdTime);
253
253
  const previous = existing.get(_id);
254
254
  const previousIntact = previous?.tableId && previous.schemaId && hashFields(previous.fields) === previous.fieldsHash;
255
255
  if (previousIntact && previous.sourceHash === sourceHash && placementOf(previous.tableName, previous.groupId, previous.patient, previous.createdTime) === placement) {
@@ -265,7 +265,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
265
265
  update: {
266
266
  $set: {
267
267
  baseId, tableId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
268
- fields: normalized, fieldsHash, sourceHash, patient: group.patient, groupId: group.groupId, schemaId, attachments: hosted,
268
+ fields: normalized, fieldsHash, sourceHash, patient, groupId: group.groupId, schemaId, attachments: hosted,
269
269
  schemaVersion: ARCHIVE_SCHEMA_VERSION,
270
270
  },
271
271
  $setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
@@ -337,7 +337,7 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
337
337
 
338
338
  Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
339
339
  const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
340
- const work = plan.eligible.map((group) => group.records.map(({ table, id }) => ({ table, record: recordsById.get(id), group })));
340
+ const work = plan.eligible.map((group) => group.records.map(({ table, id, patient }) => ({ table, record: recordsById.get(id), group, patient })));
341
341
  work.flat().forEach(({ table }) => { counts[table].eligible += 1; });
342
342
 
343
343
  if (mode === 'copy' && work.length) {
@@ -52,6 +52,7 @@ const { getEscalationApprover, listEscalationApprovers } = require('./physicianS
52
52
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
53
53
  const { effectiveUrgencyOf, patientTimerMinutes, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
54
54
  const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
55
+ const { groupConfigured, sendTeamAlert, teamChannelConfigured } = require('./teamAlertService');
55
56
 
56
57
  const getMessaging = () => require('../core/NexusMessaging');
57
58
 
@@ -89,6 +90,7 @@ const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
89
90
  const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
90
91
  const ALERT_OPERATOR = 'bot:escalationAlert';
91
92
  const AIRTABLE_TRANSPORT = 'airtable';
93
+ const NOT_RECORDED = 'no se registró en Airtable';
92
94
  const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
93
95
  const SAME_URGENCY = 'The review is already at that urgency';
94
96
  const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
@@ -1251,16 +1253,55 @@ async function fallbackRecipient() {
1251
1253
  return phone ? { name: null, email: null, phone } : soleApprover();
1252
1254
  }
1253
1255
 
1254
- // Airtable alerts the team only once its emergencies row exists; when that write failed, nexus alerts instead.
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) {
1260
+ let identity = { patientName: '', treatingDoctor: '' };
1261
+ try {
1262
+ identity = doctorIdentity(await getPatientInformation(review.patientCode));
1263
+ } catch (error) {
1264
+ logger.error('[EscalationReview] The patient record could not be read for the team notice', { escalationReviewId: String(review._id), error: redactedError(error) });
1265
+ }
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';
1269
+ const alarm = (alarmId && (review.alarms ?? []).find((raised) => raised.alarmId === alarmId))
1270
+ ?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1271
+ const what = [urgencyLevel.toUpperCase(), oneLine(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
1272
+ return {
1273
+ body: `⚠️ ${ALERT_MARKS[urgencyLevel]} ${what}\n${patient} (${doctor})\n${link}`,
1274
+ template: { 1: what, 2: patient, 3: doctor, 4: link },
1275
+ };
1276
+ }
1277
+
1278
+ async function alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId) {
1279
+ try {
1280
+ const result = await sendTeamAlert({ message: await teamFallbackNotice(review, urgencyLevel, alarmId), operator: ALERT_OPERATOR, notice: true });
1281
+ const missed = result.phones.filter((phone) => !phone.delivered).length + (groupConfigured() && !result.group.delivered ? 1 : 0);
1282
+ if (result.delivered && missed) logger.warn('[EscalationReview] The team notice missed some recipients', { escalationReviewId: String(review._id), delivered: result.delivered, missed });
1283
+ return result.delivered ? { transport: 'team' } : null;
1284
+ } catch (error) {
1285
+ logger.error('[EscalationReview] The team notice failed; falling back to one phone', { escalationReviewId: String(review._id), error: redactedError(error) });
1286
+ return null;
1287
+ }
1288
+ }
1289
+
1290
+ async function alertOneWithoutEmergencyRow(review, urgencyLevel, alarmId) {
1291
+ const recipient = await fallbackRecipient();
1292
+ const { approver, message } = await prepareDoctorAlert(review, urgencyLevel, { recipient, alarmId });
1293
+ return { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
1294
+ }
1295
+
1255
1296
  async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel, now = new Date() }) {
1256
1297
  if (escalationApproverAlertLive() || !ALERT_MARKS[urgencyLevel]) return null;
1257
1298
  let review;
1258
1299
  let delivery;
1259
1300
  try {
1260
1301
  review = await loadReview(reviewIdOf(reviewId));
1261
- const recipient = await fallbackRecipient();
1262
- const { approver, message } = await prepareDoctorAlert(review, urgencyLevel, { recipient, alarmId });
1263
- delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
1302
+ // Airtable alerts the team only once its emergencies row exists; a team notice that reached no one falls back to one phone.
1303
+ delivery = (teamChannelConfigured() && await alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId))
1304
+ || await alertOneWithoutEmergencyRow(review, urgencyLevel, alarmId);
1264
1305
  } catch (error) {
1265
1306
  delivery = { error: redactedError(error) };
1266
1307
  logger.error('[EscalationReview] The alert for a missing emergencies row was not sent', { escalationReviewId: String(reviewId), urgencyLevel, error: delivery.error });
@@ -1,11 +1,16 @@
1
1
  const { Symptoms_ID: symptomsId } = require('../config/airtableConfig');
2
+ const runtimeConfig = require('../config/runtimeConfig');
3
+ const { s3 } = require('../config/awsConfig');
4
+ const { logger } = require('../utils/logger');
2
5
  const { firstOf } = require('../utils/coercionUtils');
3
6
  const { paginate } = require('../utils/paginationUtils');
4
7
  const { MapCache } = require('../utils/MapCache');
5
8
  const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel');
6
9
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
7
10
  const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
11
+ const { mergeArchivedRows } = require('../helpers/airtableArchiveHelper');
8
12
  const { getRecordByFilter } = require('./airtableService');
13
+ const { findArchivedByPatient, findArchivedByRecordIds } = require('./airtableArchiveReadService');
9
14
  const { getMessages } = require('./messageService');
10
15
 
11
16
  const DEFAULT_LIMIT = 50;
@@ -35,6 +40,8 @@ const CAROUSEL_STATUS_FIELDS = [
35
40
  ];
36
41
 
37
42
  const RESOLUTION_FIELDS = ['rank', 'element_name_short'];
43
+ // What the live `Grid view` filter reads, so archived rows can be held to the same rule.
44
+ const VIEW_FIELDS = ['whatsapp_id', 'tipo (from triaje_symptoms)'];
38
45
  const FIRST_RESOLUTION_VARIABLE = '2';
39
46
  const UNSUCCESSFUL_SEND_STATUSES = ['failed', 'undelivered'];
40
47
  const carouselCache = new MapCache({ maxSize: 30, ttl: CACHE_TTL_MS });
@@ -158,15 +165,30 @@ function patientContentOf(recommendation) {
158
165
  };
159
166
  }
160
167
 
168
+ // Rows deleted from Airtable exist only in the archive; if it cannot be read, live rows are served alone.
169
+ async function readArchived(read, params) {
170
+ try {
171
+ return await read({ baseId: symptomsId, ...params });
172
+ } catch (error) {
173
+ logger.error('[recommendationCarouselService] Archive read failed, serving live rows only', { table: params.tableName, error: error.message });
174
+ return [];
175
+ }
176
+ }
177
+
178
+ // Same rule as the live `Grid view`: the patient's own carousels from production triages.
179
+ const inLiveView = (code) => (row) => firstOf(row.whatsapp_id) === code
180
+ && [].concat(row['tipo (from triaje_symptoms)'] ?? []).includes('prod');
181
+
182
+ async function readPatientCarouselsWithArchive(code, fields) {
183
+ const [live, archived] = await Promise.all([
184
+ getRecordByFilter(symptomsId, 'cluster_recommendations', fieldEquals('whatsapp_id', code), 'Grid view', fields, true),
185
+ readArchived(findArchivedByPatient, { tableName: 'cluster_recommendations', whatsappId: code, fields: [...fields, ...VIEW_FIELDS] }),
186
+ ]);
187
+ return mergeArchivedRows(live || [], archived.filter(inLiveView(code)));
188
+ }
189
+
161
190
  async function readPatientCarouselIndex(code) {
162
- const rows = await getRecordByFilter(
163
- symptomsId,
164
- 'cluster_recommendations',
165
- fieldEquals('whatsapp_id', code),
166
- 'Grid view',
167
- CAROUSEL_INDEX_FIELDS,
168
- true,
169
- ) || [];
191
+ const rows = await readPatientCarouselsWithArchive(code, CAROUSEL_INDEX_FIELDS);
170
192
 
171
193
  return rows.sort((a, b) => (
172
194
  Date.parse(b.Created || b._createdTime || 0) - Date.parse(a.Created || a._createdTime || 0)
@@ -186,7 +208,14 @@ async function readPatientCarouselRows(code, ids) {
186
208
  CAROUSEL_FIELDS,
187
209
  true,
188
210
  ) || [];
189
- rows.forEach((row) => {
211
+ const liveIds = new Set(rows.map((row) => row._recordId || row.recordID));
212
+ const archivedIds = missingIds.filter((id) => !liveIds.has(id));
213
+ const archived = archivedIds.length
214
+ ? (await readArchived(findArchivedByRecordIds, {
215
+ tableName: 'cluster_recommendations', recordIds: archivedIds, fields: [...CAROUSEL_FIELDS, ...VIEW_FIELDS], withAttachments: true,
216
+ })).filter(inLiveView(code))
217
+ : [];
218
+ [...rows, ...archived].forEach((row) => {
190
219
  const id = row._recordId || row.recordID;
191
220
  if (id && generation === cacheGeneration) {
192
221
  carouselRowCache.set(`${code}:${id}`, row);
@@ -211,9 +240,21 @@ async function resolutionMapFor(rows) {
211
240
  true,
212
241
  ) || []
213
242
  : [];
214
- return new Map(resolutionRows.map((row) => [row._recordId, row]));
243
+ const liveIds = new Set(resolutionRows.map((row) => row._recordId));
244
+ const archivedIds = resolutionIds.filter((id) => !liveIds.has(id));
245
+ const archived = archivedIds.length
246
+ ? await readArchived(findArchivedByRecordIds, { tableName: 'cluster_resolutions', recordIds: archivedIds, fields: RESOLUTION_FIELDS })
247
+ : [];
248
+ return new Map([...resolutionRows, ...archived].map((row) => [row._recordId, row]));
215
249
  }
216
250
 
251
+ // Airtable attachment URLs are gone once a row is archived; its image was re-hosted to S3.
252
+ const archivedImageKey = (row, attachment) => (
253
+ row?._archived && attachment?.id
254
+ ? (row._attachments || []).find((hosted) => hosted.field === 'images' && hosted.id === attachment.id)?.s3Key || null
255
+ : null
256
+ );
257
+
217
258
  function projectCarousel(row, resolutionById, sends) {
218
259
  const recommendations = parseRecommendations(row.recommendations);
219
260
  const images = Array.isArray(row.images) ? row.images : [];
@@ -235,7 +276,7 @@ function projectCarousel(row, resolutionById, sends) {
235
276
  recommendationId: recommendationIdOf(recommendation),
236
277
  title: titleOf(recommendation, resolution),
237
278
  resolutionId: resolution?._recordId || null,
238
- imageSourceUrl: attachment?.url || null,
279
+ imageSourceUrl: attachment?.url || archivedImageKey(row, attachment),
239
280
  patientContent: patientContentOf(recommendation),
240
281
  };
241
282
  });
@@ -254,14 +295,7 @@ const projectCarouselStatus = (row, sends) => ({
254
295
  });
255
296
 
256
297
  async function readPatientCarouselStatuses(code) {
257
- const rows = await getRecordByFilter(
258
- symptomsId,
259
- 'cluster_recommendations',
260
- fieldEquals('whatsapp_id', code),
261
- 'Grid view',
262
- CAROUSEL_STATUS_FIELDS,
263
- true,
264
- ) || [];
298
+ const rows = await readPatientCarouselsWithArchive(code, CAROUSEL_STATUS_FIELDS);
265
299
  const sends = await sendsByFirstResolution(code, rows);
266
300
  return rows
267
301
  .map((row) => projectCarouselStatus(row, sends))
@@ -343,7 +377,11 @@ async function getRecommendationCarouselImage({ code, carouselId, cardIndex }) {
343
377
  const rows = await readPatientCarouselRows(code, [carouselId]);
344
378
  const row = rows.find((entry) => (entry._recordId || entry.recordID) === carouselId);
345
379
  const attachment = Array.isArray(row?.images) ? row.images[Number(cardIndex)] : null;
346
- return attachment?.url ? { url: attachment.url } : null;
380
+ if (attachment?.url) return { url: attachment.url };
381
+ const key = archivedImageKey(row, attachment);
382
+ if (!key) return null;
383
+ const object = await s3.getObject({ Bucket: runtimeConfig.get('AIRTABLE_ARCHIVE_BUCKET'), Key: key }).promise();
384
+ return { body: Buffer.from(object.Body), contentType: object.ContentType || null };
347
385
  }
348
386
 
349
387
  function clearRecommendationCarouselCache() {
@@ -9,6 +9,7 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
9
9
  const WHAPI_MESSAGES_URL = 'https://gate.whapi.cloud/messages/text';
10
10
  const REQUEST_TIMEOUT_MS = 15000;
11
11
  const ALERT_TEMPLATE_KEY = 'ESCALATION_TEAM_ALERT_CONTENT_SID';
12
+ const NOTICE_TEMPLATE_KEY = 'ESCALATION_TEAM_NOTICE_CONTENT_SID';
12
13
 
13
14
  const getMessaging = () => require('../core/NexusMessaging');
14
15
 
@@ -26,10 +27,10 @@ function teamPhones() {
26
27
  }
27
28
 
28
29
  // Inside the 24-hour window the plain text goes out; outside it, the approved alert template.
29
- async function sendAlertTo({ code, message, operator }) {
30
+ async function sendAlertTo({ code, message, operator, templateKey }) {
30
31
  const inWindow = await isWithin24HourWindow(code);
31
- const contentSid = inWindow ? null : runtimeConfig.get(ALERT_TEMPLATE_KEY);
32
- if (!inWindow && !contentSid) throw new Error(`${ALERT_TEMPLATE_KEY} is not configured`);
32
+ const contentSid = inWindow ? null : runtimeConfig.get(templateKey);
33
+ if (!inWindow && !contentSid) throw new Error(`${templateKey} is not configured`);
33
34
  const outgoing = inWindow
34
35
  ? { code, body: message.body, triggeredBy: operator }
35
36
  : { code, contentSid, variables: message.template, triggeredBy: operator };
@@ -39,10 +40,14 @@ async function sendAlertTo({ code, message, operator }) {
39
40
  return { transport: inWindow ? 'text' : 'template', messageId: result?.messageId || null };
40
41
  }
41
42
 
43
+ const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'));
44
+
45
+ const teamChannelConfigured = () => groupConfigured() || teamPhones().length > 0;
46
+
42
47
  async function sendToGroup(body) {
48
+ if (!groupConfigured()) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
43
49
  const token = runtimeConfig.get('WHAPI_TOKEN');
44
50
  const group = runtimeConfig.get('ESCALATION_TEAM_GROUP_ID');
45
- if (!token || !group) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
46
51
  try {
47
52
  const res = await axios({
48
53
  url: WHAPI_MESSAGES_URL,
@@ -61,12 +66,13 @@ async function sendToGroup(body) {
61
66
 
62
67
  // Alerts the team group and every on-call phone. One failed recipient never stops the others,
63
68
  // and nothing throws: the caller records what reached whom.
64
- async function sendTeamAlert({ message, operator }) {
69
+ async function sendTeamAlert({ message, operator, notice = false }) {
70
+ const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
65
71
  const group = await sendToGroup(message.body);
66
72
  const phones = [];
67
73
  for (const code of teamPhones()) {
68
74
  try {
69
- phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator })) });
75
+ phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator, templateKey })) });
70
76
  } catch (error) {
71
77
  phones.push({ code, delivered: false, transport: null, messageId: null, error: redacted(error) });
72
78
  }
@@ -76,4 +82,4 @@ async function sendTeamAlert({ message, operator }) {
76
82
  return { group, phones, delivered };
77
83
  }
78
84
 
79
- module.exports = { sendTeamAlert, teamPhones };
85
+ module.exports = { groupConfigured, sendTeamAlert, teamChannelConfigured, teamPhones };