@peopl-health/nexus 6.0.0-dev.16333 → 6.0.0-dev.16335
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.
|
@@ -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 (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, unless it says otherwise, 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 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`).',
|
|
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, 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.'
|
|
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 (salvo que una instrucción interna del sistema lo indique); 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': [
|
|
@@ -266,7 +266,7 @@ function followUpNote(armed, reason) {
|
|
|
266
266
|
return 'An automatic check-in is armed for this escalation: if the patient goes silent, they will be contacted again about it.';
|
|
267
267
|
}
|
|
268
268
|
if (armed === null) {
|
|
269
|
-
return 'This urgency tier gets NO automatic check-in. Nobody will write again on its own — make the fallback explicit in your message to the patient.';
|
|
269
|
+
return 'This urgency tier gets NO automatic check-in. Nobody will write again on its own — make the fallback explicit in your message to the patient: invite them to write again if it changes or worries them, with no time and no urgencias.';
|
|
270
270
|
}
|
|
271
271
|
if (reason === 'level_without_check_in' && escalationPatientTimerLive()) {
|
|
272
272
|
return 'This level gets no automatic check-in by design: if nobody takes the case, the patient timer sends the numbers to call. Do not add a timed fallback; keep to the instruction for this level.';
|
|
@@ -274,7 +274,7 @@ function followUpNote(armed, reason) {
|
|
|
274
274
|
if (reason === 'active_net_exists') {
|
|
275
275
|
return 'No check-in was armed for THIS escalation because one is already open for this patient — it may be tracking a different concern, so do not assume the patient will be asked about this one.';
|
|
276
276
|
}
|
|
277
|
-
return `No automatic check-in is in place (${reason}). Nobody will write again on its own — make the fallback explicit in your message to the patient.`;
|
|
277
|
+
return `No automatic check-in is in place (${reason}). Nobody will write again on its own — make the fallback explicit in your message to the patient: invite them to write again if it changes or worries them, with no time and no urgencias.`;
|
|
278
278
|
}
|
|
279
279
|
|
|
280
280
|
const CATEGORIES = definition.parameters.properties.details.properties.category.anyOf.find((v) => v.enum).enum;
|
|
@@ -1300,7 +1300,7 @@ async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel
|
|
|
1300
1300
|
try {
|
|
1301
1301
|
review = await loadReview(reviewIdOf(reviewId));
|
|
1302
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))
|
|
1303
|
+
delivery = (await teamChannelConfigured() && await alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId))
|
|
1304
1304
|
|| await alertOneWithoutEmergencyRow(review, urgencyLevel, alarmId);
|
|
1305
1305
|
} catch (error) {
|
|
1306
1306
|
delivery = { error: redactedError(error) };
|
|
@@ -1,15 +1,23 @@
|
|
|
1
1
|
const axios = require('axios');
|
|
2
2
|
|
|
3
3
|
const runtimeConfig = require('../config/runtimeConfig');
|
|
4
|
+
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
4
5
|
const { logger } = require('../utils/logger');
|
|
5
6
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
7
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
6
8
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
7
9
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
8
10
|
|
|
11
|
+
const airtableService = require('./airtableService');
|
|
12
|
+
|
|
9
13
|
const WHAPI_MESSAGES_URL = 'https://gate.whapi.cloud/messages/text';
|
|
10
14
|
const REQUEST_TIMEOUT_MS = 15000;
|
|
11
15
|
const ALERT_TEMPLATE_KEY = 'ESCALATION_TEAM_ALERT_CONTENT_SID';
|
|
12
16
|
const NOTICE_TEMPLATE_KEY = 'ESCALATION_TEAM_NOTICE_CONTENT_SID';
|
|
17
|
+
const ROSTER_TABLE = 'equipo_guardia';
|
|
18
|
+
const ROSTER_FIELDS = ['whatsapp', 'sin_tomar'];
|
|
19
|
+
const ROSTER_TTL_MS = 5 * 60 * 1000;
|
|
20
|
+
const ROSTER_READ_TIMEOUT_MS = 5000;
|
|
13
21
|
|
|
14
22
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
15
23
|
|
|
@@ -17,7 +25,11 @@ const whatsAppCodeOf = (phone) => ensureWhatsAppFormat(String(phone ?? '').repla
|
|
|
17
25
|
|
|
18
26
|
const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
|
|
19
27
|
|
|
20
|
-
|
|
28
|
+
let roster = { members: null, readAt: 0 };
|
|
29
|
+
let reading = null;
|
|
30
|
+
|
|
31
|
+
// Used when the roster is unreadable or has no active phone; it ignores levels.
|
|
32
|
+
function configuredPhones() {
|
|
21
33
|
return String(runtimeConfig.get('ESCALATION_TEAM_ALERT_PHONES', '') ?? '')
|
|
22
34
|
.split(',')
|
|
23
35
|
.map((phone) => phone.trim())
|
|
@@ -26,6 +38,45 @@ function teamPhones() {
|
|
|
26
38
|
.filter((code) => PATIENT_CODE.test(code));
|
|
27
39
|
}
|
|
28
40
|
|
|
41
|
+
async function readRoster() {
|
|
42
|
+
const rows = await airtableService.getRecordByFilter(Monitoreo_ID, ROSTER_TABLE, '{activo}', null, ROSTER_FIELDS);
|
|
43
|
+
if (!Array.isArray(rows)) throw new Error('The on-call roster could not be read');
|
|
44
|
+
return rows
|
|
45
|
+
.map((row) => ({ code: whatsAppCodeOf(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [] }))
|
|
46
|
+
.filter((member) => PATIENT_CODE.test(member.code));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function refreshRoster(now) {
|
|
50
|
+
try {
|
|
51
|
+
const members = await withTimeout(readRoster(), ROSTER_READ_TIMEOUT_MS, 'on-call roster read');
|
|
52
|
+
roster = { members: members.length ? members : null, readAt: now };
|
|
53
|
+
if (!members.length) logger.warn('[TeamAlert] The on-call roster has no active phone; using ESCALATION_TEAM_ALERT_PHONES');
|
|
54
|
+
} catch (error) {
|
|
55
|
+
roster = { ...roster, readAt: now };
|
|
56
|
+
logger.error('[TeamAlert] The on-call roster could not be read; using the last one read', { error: redacted(error) });
|
|
57
|
+
}
|
|
58
|
+
return roster.members;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The Airtable roster, read at most every 5 min by one read at a time; a failed read keeps the last one and waits as long to retry.
|
|
62
|
+
async function rosterMembers(now = Date.now()) {
|
|
63
|
+
if (roster.readAt && now - roster.readAt < ROSTER_TTL_MS) return roster.members;
|
|
64
|
+
if (!reading) reading = refreshRoster(now).finally(() => { reading = null; });
|
|
65
|
+
return reading;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// With a level, only the members who take that level's untaken alerts; without one, every active member.
|
|
69
|
+
async function teamPhones(level = null) {
|
|
70
|
+
const members = await rosterMembers();
|
|
71
|
+
if (!members) return configuredPhones();
|
|
72
|
+
return members.filter((member) => !level || member.levels.includes(level)).map((member) => member.code);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const _resetRoster = () => {
|
|
76
|
+
roster = { members: null, readAt: 0 };
|
|
77
|
+
reading = null;
|
|
78
|
+
};
|
|
79
|
+
|
|
29
80
|
// Inside the 24-hour window the plain text goes out; outside it, the approved alert template.
|
|
30
81
|
async function sendAlertTo({ code, message, operator, templateKey }) {
|
|
31
82
|
const inWindow = await isWithin24HourWindow(code);
|
|
@@ -42,7 +93,7 @@ async function sendAlertTo({ code, message, operator, templateKey }) {
|
|
|
42
93
|
|
|
43
94
|
const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'));
|
|
44
95
|
|
|
45
|
-
const teamChannelConfigured = () => groupConfigured() || teamPhones().length > 0;
|
|
96
|
+
const teamChannelConfigured = async () => groupConfigured() || (await teamPhones()).length > 0;
|
|
46
97
|
|
|
47
98
|
async function postToGroup(body, quoted) {
|
|
48
99
|
const res = await axios({
|
|
@@ -68,13 +119,12 @@ async function sendToGroup(body, quoted = null) {
|
|
|
68
119
|
}
|
|
69
120
|
}
|
|
70
121
|
|
|
71
|
-
// Alerts the
|
|
72
|
-
|
|
73
|
-
async function sendTeamAlert({ message, operator, notice = false, quoted = null }) {
|
|
122
|
+
// Alerts the group and the on-call phones for `level` (all without one); one failed recipient never stops the others and nothing throws.
|
|
123
|
+
async function sendTeamAlert({ message, operator, level = null, notice = false, quoted = null }) {
|
|
74
124
|
const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
|
|
75
125
|
const group = await sendToGroup(message.body, quoted);
|
|
76
126
|
const phones = [];
|
|
77
|
-
for (const code of teamPhones()) {
|
|
127
|
+
for (const code of await teamPhones(level)) {
|
|
78
128
|
try {
|
|
79
129
|
phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator, templateKey })) });
|
|
80
130
|
} catch (error) {
|
|
@@ -86,4 +136,4 @@ async function sendTeamAlert({ message, operator, notice = false, quoted = null
|
|
|
86
136
|
return { group, phones, delivered };
|
|
87
137
|
}
|
|
88
138
|
|
|
89
|
-
module.exports = { groupConfigured, sendTeamAlert, teamChannelConfigured, teamPhones };
|
|
139
|
+
module.exports = { _resetRoster, groupConfigured, sendTeamAlert, teamChannelConfigured, teamPhones };
|
|
@@ -163,7 +163,7 @@ async function alertIfUntaken(review, clock, stage, now) {
|
|
|
163
163
|
// Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
|
|
164
164
|
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
165
165
|
if (!await claimStage(review, clock, stage, now)) return false;
|
|
166
|
-
const result = await sendTeamAlert({ message, operator: OPERATOR, quoted });
|
|
166
|
+
const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted });
|
|
167
167
|
const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
|
|
168
168
|
await getEscalationReview().updateOne(
|
|
169
169
|
{ _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
|