Compare commits

...

56 Commits

Author SHA1 Message Date
edgar 88c1eb33be Risk batches: one decision at a time, so a double click doesn't send it twice 2026-11-22 09:35:01 -06:00
edgar 73b88de0ca Patient risk: a column per outcome, the index visit's sentence, and the model's details folded
The record reads every RiskAssessment of the patient. CaCu's table always has the LIEAG+ and cancer columns, each
risk with its interval in parentheses; a column with no current model says "No disponible", and one whose model
didn't estimate her says so, with the reason under the table. Another outcome (a survival model's death) shows only
when she has its risk, with its own index date in its header. The models' details fold under the table, without the
interval's method; the collapsible curves draw one line per outcome with the index date on the x axis, under a
sentence that words the index cytology's results and each outcome's risk at the longest common horizon.
2026-11-22 09:35:01 -06:00
edgar 6039e6b741 Patient risk: what the model's number is, and its curve with the interval
The record reads the RiskAssessment's `estimando` extension and shows the quantity, the outcome, the index date and
the interval's method, and names the table's columns with the quantity and the horizons' unit. Below the table, a
collapsible curve of the risk at each horizon, with its interval as a band (or as error bars when a horizon lacks
one); Plotly is loaded only when it's opened.
2026-11-22 07:48:42 -06:00
edgar b5bff7e0c6 Governance: a version lists only the routines its run recorded
Not every model has each of the five routines, and the registry doesn't require them; the dialog showed the missing
ones as failures. It now lists the recorded ones and says so when there are none.
2026-11-22 07:48:42 -06:00
edgar ddb203857f CaCu route chart: a card of its own, last in the clinical section, following the general filter
It was a loose section above the cards. It is now a card like the cytology pair, as wide as the grid and last, and it
takes the general filter's interval (semester or month) and, when the filter names periods, opens on the newest one it
publishes; another filter drops the period picked inside the card.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar 0f0f85db39 CaCu page: the times to treatment are real cards again (the strip's hiding is what was reverted)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar 7fcc0091d7 CaCu page: the opportunity strip is as it was; only the clinical section drops the empty cards
With the route chart the strip had lost its time cards. Those were not the ones to remove: they are the cards of the
clinical indicators section (the times, IND1, EU13, risk by band), which stay out.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar 5d3603740a CaCu page: with the screening route there, no cards for the times, the unfigured proportions or the risk by band
Once the catalog publishes the route, the page keeps the cytology count, the cytology result and its confirmation,
and the route chart; the times (also to treatment), IND1, EU13 and the risk by band are in the history. The route's
explanatory note goes. Without the route the page is as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar 3e3ec5fd03 CaCu history: no reserved panels, no notice, and widening the periods twice no longer drops the second answer
The times to treatment and the risk by band had a reserved panel each, and the tab carried a notice about clinical
validation: both go. Widening the window from 5 to 10 to 'Todos' before the first answer arrived dropped the second
answer (it was compared with the load it started from), so the periods did not update. An answer now joins whatever
load is current, and a period two widenings asked for is kept once.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar a15e37ed77 Screening route: without a requested period, open on the newest one that has published boxes
A semester that has just begun has no events and the chart opened on it, empty, while earlier ones had data.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar 245622b490 CaCu: the two times to treatment get their ids and cards (pending until published)
The API's treatment measures reached the page unmapped (upper case, wrong periods URL) and the cards were fixed
'Indicador no disponible' placeholders. The ids are now mapped, the cards are drawn once the catalog publishes the
measures, and wait as 'Integración pendiente' (as CaMa's do) until then.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar ea2664f324 Risk record: the evaluation instant reads as a day and minute in UTC
The index date is a calendar day and the evaluation time was the raw ISO instant, so the two looked inconsistent. The
instant now shows as 'YYYY-MM-DD HH:MM UTC' (the full value stays in the <time> element's datetime).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar 1342b1712d Indicators: a typed page size is brought into 1 to the maximum, one maximum for both lists
An input's max only flags the field and still lets a larger number be typed. The follow-up table and the tracking
list now clamp the value when it changes and when the query is sent, and both read the single PAGE_SIZE_MAX instead
of a literal 200.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:40:00 -06:00
edgar dc631d9827 Merge feature/historico-cacu into dev: the configurable CaCu history 2026-11-22 04:40:00 -06:00
edgar 2a48c28245 Merge pull request 'CaCu indicators: screening route chart, proportion intervals and survival notebook chooser' (#19) from integration/cacu-indicadores into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/19
2026-11-22 01:01:26 -06:00
edgar e1a8127c22 feat(indicadores): add the screening route chart to CaCu
Horizontal bars of the days from the sample to each event of the route (cytology result, colposcopy, biopsy result and
diagnosis), cumulative with the Q1 to Q3 interval or step by step with each step starting where the previous one ends.
It reads the seven duration measures of the route and shows up in CaCu's page once the catalog publishes all of them;
the measures only it draws get no card of their own.
2026-11-22 00:23:36 -06:00
edgar 6de193f44e fix(indicadores): draw CaCu's proportions in the history
The WebApi names the group of a proportion `principal`; the page read it as `total` only for CaMa, so the EU13 and
IND1 trends of CaCu came out empty. The rename now applies to every domain.
2026-11-22 00:23:33 -06:00
edgar 0059427179 fix(indicadores): read a proportion's interval as percentages
The ic-bajo and ic-alto of a proportion's score travel as proportions; the rows hold percentages, like the value,
so the history trend draws its confidence band on the same axis.
2026-11-22 00:23:28 -06:00
edgar 8192f92be9 Governance: choose a notebook kept in the code or upload one
The "Correr un notebook" dialog offers "Del código" (the domain's templates from /governance/notebook-templates, each
with the scenarios it can run for) or "Subir archivo". Choosing a template fills its scenario; a scenario it doesn't
serve keeps "Correr" disabled. The request sends the template's id and no file. A domain without templates opens on
the upload, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-22 00:23:28 -06:00
Angel Capetillo Zavala ab10cc9025 feat(cacu): add configurable historical indicators dashboard
CaCu gets the Histórico tab, built on CaMa's through a per-domain config
(indicadores-historico-config.ts): panel list and order, expected contract,
unit labels, initial period window and a notice.

Six panels read the measures dev publishes: EU7, IND1, EU13, biopsy result
after high-grade cytology, days from sample to result and to diagnosis.
Three more (time to treatment, time from diagnosis to treatment, CIN2+ risk
bands) are reserved: they show a title, a description and their state, and
never request a report, whatever the catalog publishes.

Adapter and figures: the primary group of a C1 is read as `total` in every
domain, CaCu composition reports keep their units so the history can fail on
categories that do not add up, periods without units are «sin dato» for CaCu
only, and `examen` reads «citologías» there. Only the latest five periods are
requested at first; wider windows request what is missing.

The recorded FHIR mapping is regenerated for these two additions.
2026-11-21 22:39:24 -06:00
roberto 1fef7812b4 Merge pull request 'CaMa recurrence figure: the y axis follows the months it draws' (#17) from fix/cama-recurrence-axis into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/17
2026-11-21 15:37:58 -06:00
angel 6465165e34 CaMa recurrence figure: the y axis follows the months it draws 2026-11-21 15:36:00 -06:00
angel a26df55214 Merge pull request 'CaMa patient record: survival and recurrence figures; governance trains any scenario' (#16) from feature/cama-roundtrip into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/16
2026-11-21 15:03:15 -06:00
rockdrigo 72e5f9bf93 CaMa record: the recurrence analysis only for patients after treatment 2026-11-21 14:57:30 -06:00
rockdrigo 08f1d812ac CaMa patient record as specified: recurrence and survival analyses with a scenario selector and their risk factors 2026-11-21 14:43:46 -06:00
rockdrigo ce207a72a5 Merge origin/dev 2026-11-21 13:50:16 -06:00
rockdrigo 5094880622 CaMa patient record: the recurrence figures of the scenarios she meets 2026-11-21 13:34:56 -06:00
Angel Capetillo Zavala 093ceffa36 feat(indicadores): rename the Seguimiento tab to Análisis de riesgos in CaCu, TEA and CaMa
The tab has the same name in every domain, and the texts that point to it
(patient lists opened from the analysis, the patient file error) use it.
2026-11-21 13:27:15 -06:00
Angel Capetillo Zavala 6a7c1d0cbd feat(home): drop the topbar section label, shorten the eyebrow and rename the indicators action
The topbar no longer shows «Análisis de información» next to the logo; the
breadcrumb stays on the workspace routes. The home eyebrow reads «ISSSTELEON»
and the «Indicadores» action is «Modelos predictivos de riesgo».
2026-11-21 13:27:14 -06:00
rockdrigo fb5a4ed5cc CaMa patient record: the pipeline's figure of each clinical scenario she belongs to, without a curve of her own 2026-11-21 13:14:06 -06:00
rockdrigo e8ce7a487b CaMa patient record: no subgroup panel, one legend entry for the patient 2026-11-21 13:03:19 -06:00
angel a3a552ad0e Merge pull request 'Integration/tea eeg analysis into dev' (#15) from integration/tea-eeg-analysis-into-dev into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/15
2026-11-21 12:35:52 -06:00
rockdrigo 7adceb86bf CaMa patient record: the pipeline's survival figure with her curve, computed live and comparable with her subgroup 2026-11-21 12:07:21 -06:00
rockdrigo a7b5f4c50b CaMa patient survival figure: the legend claims an interval only when one is drawn 2026-11-21 10:53:41 -06:00
rockdrigo 4d159ae0d0 CaMa survival figure in the patient's risk evaluation instead of a tab; no test-data tags on the risk record 2026-11-21 10:13:47 -06:00
rockdrigo 4fba4fa861 CaMa development view reads each table's column order 2026-11-21 05:03:52 -06:00
rockdrigo db4d743413 Governance: spec for the risk batches panel's domains 2026-11-21 04:48:43 -06:00
rockdrigo d6c52c8536 Governance: risk batches of CaMa beside CaCu's 2026-11-21 04:24:19 -06:00
rockdrigo 1969ffdb5f Merge origin/dev 2026-11-21 04:00:07 -06:00
rockdrigo 699d4b13e1 Merge remote-tracking branch 'origin/feature/cohorts-dbt-canonical' into dev-mvp 2026-11-21 03:59:50 -06:00
rockdrigo c5cbaaab13 CaMa development view on the survival tab; governance trains any scenario in the background 2026-11-21 03:28:13 -06:00
rockdrigo cc802cbb57 The CaMa risk spec builds a summary with the clinical scenario 2026-11-21 03:00:10 -06:00
rockdrigo e7a6398168 Merge origin/feature/tea-eeg-analysis 2026-11-21 02:51:31 -06:00
rockdrigo 62027f2216 Merge origin/ulises/tea-seguimiento 2026-11-21 02:51:31 -06:00
rockdrigo 88dc7537c2 Merge origin/feature/163-cama-risk-curves 2026-11-21 02:51:31 -06:00
rockdrigo 0cb9395cd6 Merge feature/cama-roundtrip 2026-11-21 02:51:31 -06:00
rockdrigo e74e3d8fd4 CaMa: a patient's risk in her record and a Supervivencia tab with the model's curves
The risk table takes a domain (CaCu by default); the CaMa record shows the mortality at 6, 12 and 18 months from the
model's index date. The Supervivencia tab draws the cohort's Kaplan-Meier with its band, the adjusted curve, the fractional
Weibull and the model's survival with its bootstrap interval; its wording comes from the model's settings.
2026-11-21 02:07:34 -06:00
edgar 0fc80bd29a Merge remote-tracking branch 'origin/feature/163-cama-risk-curves' into feature/cohorts-dbt-canonical 2026-11-21 02:06:26 -06:00
rockdrigo dae8bc517e CaMa follow-up: the clinical scenario as Post-tratamiento or En observación in the list, the record and its PDF 2026-11-21 01:55:05 -06:00
ulises efe4404c4e Seguimiento TEA: gráfica de la norma por edad con el paciente
El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas
5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:27:16 -06:00
edgar 7d180417d8 Merge dev into feature/cohorts-dbt-canonical
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:23:11 -06:00
edgar 00f773dd75 CaCu patient record reads the patient's FHIR RiskAssessment
The record asks GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> and validates the searchset Bundle at the
boundary (simulado tag, the patient asked for, one index date, probabilities and intervals); it shows the model, the
risk's index date, the outcome, the evaluation and one row per horizon from each prediction's whenPeriod. The cohort's
definition and the PIMM variables are no longer shown; an empty Bundle is a patient without a confirmed risk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:11:56 -06:00
edgar 3bb1c8dd84 CaCu patient record shows the risk's index date
The record's index date is riesgo.fecha_indice (the model's decision point the horizons count from), not the cohort
member's; the field is optional in the contract and validated as an ISO date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:48 -06:00
ulises 54b3e50ca5 TEA: el panel de relación con el ADOS-2 muestra solo las zonas alteradas del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:35:24 -06:00
ulises 680cc0adc6 TEA: panel «Relación con el ADOS-2» en la ficha del paciente (prototipo) y modo simulado local
El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del
paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado.
El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración
«simulado» de Angular) es solo para trabajar en local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:06:15 -06:00
rockdrigo 7aa3d2c6e6 Stratified bars: a sidebar to show or hide each stratum, and the breakdown in counts or in percent of each stratum 2026-11-20 17:03:41 -06:00
104 changed files with 4110 additions and 523 deletions
+15
View File
@@ -62,6 +62,17 @@
"optimization": false,
"extractLicenses": false,
"sourceMap": true
},
"simulado": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/app/app.config.ts",
"with": "src/app/app.config.simulado.ts"
}
]
}
},
"defaultConfiguration": "production"
@@ -77,6 +88,10 @@
},
"development": {
"buildTarget": "WebApp:build:development"
},
"simulado": {
"buildTarget": "WebApp:build:simulado",
"proxyConfig": "simulado/proxy.simulado.json"
}
},
"defaultConfiguration": "development"
+38
View File
@@ -0,0 +1,38 @@
# Modo simulado (solo nuestra copia local, rama `ulises/tea-seguimiento`)
Para ver y modificar la página de seguimiento de TEA sin la plataforma completa ni su preproceso.
Todo es **inventado**. No forma parte de la WebApp que se entrega.
| Archivo | Qué es |
|---|---|
| `datos_tea.json` | 120 niños inventados: lista, ficha y la relación con el ADOS-2 (modelo de OR de E27). Se genera; no se versiona |
| `servidor.py` | Servidor de prueba (Python, sin instalar nada) en `localhost:5051` |
| `proxy.simulado.json` | Las rutas de la API, al servidor de prueba |
| `../src/app/app.config.simulado.ts` | Igual que `app.config.ts`, pero el seguimiento de TEA lee el contrato JSON (`/tea/seguimiento`) |
## Cómo se usa
1. Generar los datos (una vez, o cuando cambie el modelo), desde `biomarcadores-tea/`:
```
python experimentos/E27_modelo_or/simulado_plataforma.py
```
2. Levantar el servidor de prueba, desde `webapp-tea/`:
```
python simulado/servidor.py
```
3. En otra terminal, la página, desde `webapp-tea/`:
```
npx ng serve --configuration simulado --port 4300
```
4. Abrir `http://localhost:4300/indicadores/tea`, entrar a **Seguimiento** y abrir un paciente.
## El panel nuevo: «Relación con el ADOS-2»
En la ficha del paciente (`tea-paciente-resumen.*`) muestra, por cada asociación clara de la cohorte (q < 0.05):
- la zona del EEG y el z del paciente, marcada si está alterada (|z| ≥ 2);
- el aspecto del ADOS-2 (reactivo o dominio);
- el OR de la cohorte con su intervalo y su q;
- la probabilidad que el modelo da a este paciente (con su edad y módulo) frente a la de un niño con z = 0;
- lo que muestra su ADOS-2.
El campo `relacion_ados2` es opcional: sin él (la plataforma real hoy), el panel no aparece.
+47
View File
@@ -0,0 +1,47 @@
{
"/api": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/imports": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/data": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/health": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/cacu": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/cama": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/tea": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/governance": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
},
"/reportes": {
"target": "http://localhost:5051",
"secure": false,
"changeOrigin": true
}
}
+110
View File
@@ -0,0 +1,110 @@
"""
servidor.py — Servidor de prueba con datos SIMULADOS para ver la página de TEA sin la plataforma completa.
Solo para nuestra copia local (rama ulises/tea-seguimiento): no forma parte de la WebApp que se entrega.
Responde lo que pide la sección de seguimiento de TEA en su contrato JSON:
- `/tea/seguimiento`: la lista, con filtros y páginas;
- `/tea/seguimiento/<id>`: la ficha, incluido el campo nuevo `relacion_ados2`.
A lo demás de `/tea/...` contesta vacío, para que la página cargue.
Los datos los escribe `biomarcadores-tea/experimentos/E27_modelo_or/simulado_plataforma.py` en `datos_tea.json`.
python simulado/servidor.py # http://localhost:5051
npx ng serve --configuration simulado --port 4300
"""
from __future__ import annotations
import json
import math
import sys
from datetime import date, timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
PUERTO = 5051
DATOS = json.loads((Path(__file__).with_name("datos_tea.json")).read_text(encoding="utf-8"))
VACIO_FHIR = {"resourceType": "Bundle", "type": "searchset", "total": 0, "entry": []}
def _num(q, k):
v = q.get(k, [None])[0]
try:
return float(v) if v is not None else None
except ValueError:
return None
def lista(q: dict) -> dict:
meses = int(q.get("meses", ["12"])[0]) if q.get("meses", ["12"])[0] in ("1", "3", "6", "12") else 12
corte = q.get("corte", [date.today().isoformat()])[0]
page = max(1, int(q.get("page", ["1"])[0]))
size = min(200, max(1, int(q.get("page_size", ["25"])[0])))
filtro = q.get("alteraciones_eeg", [None])[0]
ps = DATOS["pacientes"]
if filtro in ("normal", "anormal"):
ps = [p for p in ps if p["alteraciones_eeg"] == filtro]
elif filtro == "sin_eeg_valido":
ps = [p for p in ps if p["ultimo_eeg"] is None]
if q.get("grupo_edad"):
ps = [p for p in ps if p["grupo_edad"].startswith(q["grupo_edad"][0].replace("_", "-"))]
for campo, lo, hi in (("mchat", "mchat_min", "mchat_max"), ("css_ados2", "css_min", "css_max")):
a, b = _num(q, lo), _num(q, hi)
if a is not None:
ps = [p for p in ps if p[campo] is not None and a <= p[campo] <= (b if b is not None else 99)]
if q.get("estado_caso"):
ps = [p for p in ps if p["estado_caso"] == q["estado_caso"][0]]
if q.get("alteracion"):
ps = [p for p in ps if q["alteracion"][0] in p["alteraciones"]]
total = len(ps)
por_alt = [{"codigo": t["codigo"], "etiqueta": t["etiqueta"], "n": sum(t["codigo"] in p["alteraciones"] for p in ps)}
for t in DATOS["tipos_alteracion"]]
hasta = date.fromisoformat(corte)
return {
"simulado": True, "corte": corte,
"ventana": {"meses": meses, "desde": (hasta - timedelta(days=30 * meses)).isoformat(), "hasta": corte},
"filtros": {"alteraciones_eeg": filtro},
"paginacion": {"page": page, "page_size": size, "total_items": total, "total_pages": max(1, math.ceil(total / size))},
"items": ps[(page - 1) * size: page * size],
"tipos_alteracion": DATOS["tipos_alteracion"],
"resumen_eeg": {"validadas": True, "con_eeg_valido": total,
"normales": sum(p["alteraciones_eeg"] == "normal" for p in ps),
"anormales": sum(p["alteraciones_eeg"] == "anormal" for p in ps), "sin_eeg": 0,
"por_alteracion": por_alt},
}
class Manejador(BaseHTTPRequestHandler):
def _json(self, cuerpo, codigo=200):
datos = json.dumps(cuerpo, ensure_ascii=False).encode("utf-8")
self.send_response(codigo)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(datos)))
self.end_headers()
self.wfile.write(datos)
def do_GET(self): # noqa: N802
u = urlparse(self.path)
ruta, q = u.path.rstrip("/"), parse_qs(u.query)
if ruta == "/tea/seguimiento":
return self._json(lista(q))
if ruta.startswith("/tea/seguimiento/"):
d = DATOS["detalles"].get(unquote(ruta.rsplit("/", 1)[1]))
return self._json(d) if d else self._json({"error": "no encontrado"}, 404)
if "/fhir/" in ruta:
return self._json(VACIO_FHIR)
if ruta.endswith("/indicadores"):
return self._json([])
if ruta == "/health":
return self._json({"status": "ok", "simulado": True})
return self._json({"error": "sin datos simulados para esta ruta"}, 404)
def log_message(self, fmt, *args):
sys.stderr.write(" " + fmt % args + "\n")
if __name__ == "__main__":
print(f"Servidor simulado en http://localhost:{PUERTO} ({len(DATOS['pacientes'])} niños inventados)")
ThreadingHTTPServer(("127.0.0.1", PUERTO), Manejador).serve_forever()
+2 -1
View File
@@ -80,7 +80,8 @@ describe('Encabezado del marco', () => {
await ir(url);
expect(selector()).toBeNull();
expect(root().querySelector('.platform-title')).toBeNull();
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
expect(root().querySelector('.site-header__section')).toBeNull();
expect(root().querySelector('.site-header__nav')?.textContent).not.toContain('Análisis de información');
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
});
+21
View File
@@ -0,0 +1,21 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { IndicadoresService } from './features/indicadores/indicadores.service';
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento
// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`).
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(),
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
]
};
+1 -2
View File
@@ -20,9 +20,8 @@
}
} @else {
<nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
<span class="site-header__crumb" aria-current="page">{{ crumb }}</span>
}
</nav>
}
-13
View File
@@ -41,14 +41,6 @@
font-weight: 600;
}
.site-header__section {
text-decoration: none;
color: var(--color-text);
font-size: 15px;
font-weight: 500;
letter-spacing: 0.01em;
}
.app-main {
display: flex;
flex: 1;
@@ -89,11 +81,6 @@
width: clamp(132px, 42vw, 170px);
}
.site-header__section {
font-size: 13px;
text-align: right;
}
.site-footer__content {
min-height: 76px;
padding: 0 20px;
+9
View File
@@ -60,6 +60,15 @@ describe('App', () => {
expect(page.querySelector('.site-footer')).not.toBeNull();
});
it('home shows only the brand name as eyebrow and names the risk models action', async () => {
// Fails if the eyebrow regains the section text or the action goes back to «Indicadores».
const page = await render('/');
expect(page.querySelector('.home__eyebrow')?.textContent?.trim()).toBe('ISSSTELEON');
const acciones = Array.from(page.querySelectorAll('.home__action')).map(a => a.textContent?.replace(/\s+/g, ' ').trim());
expect(acciones.some(t => t?.endsWith('Modelos predictivos de riesgo'))).toBe(true);
expect(acciones.some(t => t?.endsWith('Indicadores'))).toBe(false);
});
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
const page = await render('/conectar');
expect(page.querySelector('app-connect-page')).not.toBeNull();
@@ -3,11 +3,12 @@ import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
import { identidadDe, identidadesDe } from './paciente-identidad';
import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
export function validSeguimientoQuery(q: SeguimientoQuery) {
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= 200;
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX;
}
export function seguimientoResponse(v: unknown): SeguimientoResponse {
// The current authorization covers demonstration records only. Validate this
@@ -18,7 +19,7 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
const c = item['ultima_citologia'], h = item['ultimo_vph'];
@@ -7,14 +7,19 @@ const HISTOLOGIA: Readonly<Record<string, string>> = {
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
};
const ESCENARIOS: Readonly<Record<string, string>> = { POST_TRATAMIENTO: 'Post-tratamiento', EN_OBSERVACION: 'En observación' };
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
/** The patient's clinical scenario at the cut-off: «Post-tratamiento» or «En observación». */
export const etiquetaEscenario = (codigo: string) => ESCENARIOS[codigo] ?? codigo;
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = {
birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia, escenario_clinico: etiquetaEscenario,
};
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
@@ -46,6 +46,10 @@
"version": "0.1.2",
"contrato": "C2",
"unidad": "paciente",
"unidades_periodo": {
"2021-S1": 0,
"2025-S2": 1
},
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
@@ -384,7 +388,7 @@
"estrato": null,
"valores_estrato": [],
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -410,7 +414,7 @@
"filas": [
{
"periodo": "2021-S1",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 0,
@@ -423,7 +427,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 1,
@@ -463,7 +467,7 @@
"<25": "<25"
},
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -489,7 +493,7 @@
"filas": [
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "25-34",
"suprimido": 0,
"numerador": 0,
@@ -502,7 +506,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "35-44",
"suprimido": 0,
"numerador": 0,
@@ -515,7 +519,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "45-54",
"suprimido": 0,
"numerador": 1,
@@ -528,7 +532,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "55-64",
"suprimido": 0,
"numerador": 0,
@@ -541,7 +545,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "<25",
"suprimido": 0,
"numerador": 0,
@@ -573,7 +577,7 @@
"PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA"
},
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -599,7 +603,7 @@
"filas": [
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "PRE_COLPOSCOPIA",
"suprimido": 0,
"numerador": 1,
@@ -662,6 +666,10 @@
"version": "0.3.3",
"contrato": "C2",
"unidad": "paciente",
"unidades_periodo": {
"2021-S1": 0,
"2025-S2": 89
},
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
@@ -747,6 +755,10 @@
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"unidades_periodo": {
"2021-S1": 0,
"2025-S2": 0
},
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
@@ -845,7 +857,7 @@
"estrato": null,
"valores_estrato": [],
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -871,7 +883,7 @@
"filas": [
{
"periodo": "2021-S1",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 0,
@@ -884,7 +896,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 19,
@@ -16,7 +16,7 @@ import { c2Capability, c2Figure } from './indicadores-c2-adapter';
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified';
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
import { c2GeneralSelection } from './indicadores-c2-general-selection';
import { MatTooltipModule } from '@angular/material/tooltip';
@@ -25,8 +25,48 @@ import { MatTooltipModule } from '@angular/material/tooltip';
selector: 'app-indicador-figure-panel',
imports: [IndicadorFigureCard, MatTooltipModule],
template: `
<section class="figure-panel" [attr.aria-labelledby]="titleId">
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
@if (sidebar) {
<aside class="strata-sidebar" aria-label="Estratificación">
<fieldset class="sidebar-group">
<legend>Estratificar por</legend>
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
(click)="changeDimension('')">Sin estratificar</button>
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
@if (dimension && estratos.length > 1) {
<fieldset class="sidebar-group">
<legend>Mostrar</legend>
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
@for (e of estratos; track e.valor) {
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
}
</div>
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
</fieldset>
}
@if (dimension) {
<fieldset class="sidebar-group">
<legend>Medida</legend>
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
</fieldset>
}
</aside>
}
<header class="panel-controls">
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
@@ -36,7 +76,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
</span>
}
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
<legend>Distribución</legend>
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
@@ -49,10 +89,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
}
@if (dimension) {
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
}
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
}
@@ -71,8 +117,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
<details><summary>Valores publicados</summary>
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
</tbody></table></div>
</details>
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
@@ -117,6 +163,30 @@ import { MatTooltipModule } from '@angular/material/tooltip';
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
.donut-periods button:disabled { opacity: .45; }
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
shared with the neighbouring panel, so the bars line up with the donut. */
:host { container-type: inline-size; }
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
.sidebar-list { display: grid; gap: .25rem; }
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.sidebar-reset { margin-top: .5rem; }
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
@container (max-width: 559px) {
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
.strata-sidebar { position: static; }
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
}
.visually-hidden {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
@@ -165,7 +235,39 @@ export class IndicadorFigurePanel implements OnChanges {
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
}
dimension: DimensionEstrato | '' = '';
readonly etiquetaDimension = etiquetaDimension;
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
private medidaElegida?: MedidaEstrato;
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
changeMedida(medida: MedidaEstrato) {
if (medida === this.medida) return;
this.medidaElegida = medida;
this.representStratified();
}
cells: StratifiedCell[] = [];
/** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */
get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; }
estratos: StratumOption[] = [];
ocultos = new Set<string>();
toggleEstrato(valor: string) {
const ocultos = new Set(this.ocultos);
if (ocultos.has(valor)) ocultos.delete(valor);
else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor);
else return;
this.ocultos = ocultos;
this.representStratified();
}
mostrarTodos() {
if (!this.ocultos.size) return;
this.ocultos = new Set();
this.representStratified();
}
private representStratified() {
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
try { this.result.set(this.presentStratified(this.stratifiedData)); }
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
}
}
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
private stratifiedData?: IndicadorDatos;
@@ -177,14 +279,18 @@ export class IndicadorFigurePanel implements OnChanges {
changeDimension(value: DimensionEstrato | '') {
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
if (this.dimension === value) return;
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set();
this.requestFigure();
}
chooseStratified() {
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
}
private presentStratified(data: IndicadorDatos): FigureState {
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
this.estratos = stratumOptions(data);
const publicados = new Set(this.estratos.map(e => e.valor));
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos);
this.cells = adapted.cells;
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
@@ -349,7 +455,9 @@ export class IndicadorFigurePanel implements OnChanges {
}
}
ngOnChanges(changes: SimpleChanges) {
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) {
this.dimension = ''; this.estratos = []; this.ocultos = new Set();
}
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
this.titleId = identityElementId(identity) + '-title';
@@ -187,7 +187,7 @@ describe('KPI integración con autoridad global', () => {
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Integración pendiente', 'Integración pendiente']
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
@@ -0,0 +1,37 @@
<mat-card class="route" aria-label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje">
<header><div class="card-identity"><h2 class="figure-title">Tiempos de la ruta del tamizaje</h2></div></header>
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando los tiempos de la ruta del tamizaje" /><p role="status">Cargando los tiempos de la ruta…</p> }
@case ('error') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (model(); as m) {
<div class="controls">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodo</mat-label>
<mat-select [value]="m.period" (selectionChange)="selectPeriod($event.value)" aria-label="Periodo de la ruta del tamizaje">
@for (period of m.periods; track period) { <mat-option [value]="period">{{ periodLabel(period) }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
</mat-button-toggle-group>
</div>
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
@else if (figure(); as figure) {
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
}
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
<table><caption>Días por evento en {{ m.period ? periodLabel(m.period) : 'el periodo' }}</caption>
<thead><tr><th scope="col">Evento</th><th scope="col">Desde la toma</th><th scope="col">Desde el paso anterior</th></tr></thead>
<tbody>@for (row of m.rows; track row.step.id) {
<tr><th scope="row">{{ row.step.label }}</th><td>{{ cellText(row.fromSample) }}</td><td>{{ cellText(row.fromPrevious) }}</td></tr>
}</tbody>
</table>
</div>
</details>
}
</mat-card>
@@ -0,0 +1,13 @@
// A card of its own, as wide as the grid like the pair of cards above it.
:host { display: block; min-width: 0; grid-column: 1 / -1; }
.route { min-width: 0; margin: 0; }
.figure-title { margin: 0; font-size: 1.25rem; }
p, h2, summary { overflow-wrap: anywhere; }
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
app-plotly-chart { --plot-height: 360px; }
summary { cursor: pointer; padding-block: .75rem; }
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.table-scroll { overflow: auto; max-height: 28rem; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; }
@@ -0,0 +1,128 @@
// What this module covers: the screening route component: when it loads, the seven requests it makes, what it draws for
// each view and period, and its empty, error and incompatible states. The model and the figure have their own spec
// (`screening-route.spec.ts`).
// Fixtures: `payload`, synthetic C3r /datos shaped like /cacu/indicadores/<id>/datos; `ChartStub` stands for the chart.
import { Component, input } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorScreeningRoute } from './indicador-screening-route';
import { IndicadorDatos } from './indicadores.models';
import { ROUTE_IDS } from './screening-route';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
const row = (periodo: string, n: number, q1: number, mediana: number, q3: number, suprimido = 0) =>
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
const MEDIANAS: Record<string, number> = {
cacu_eu_tiempo_reporte: 7.9, cacu_dias_toma_colposcopia: 35.7, cacu_dias_resultado_colposcopia: 27.8, cacu_dias_toma_biopsia: 52.1,
cacu_dias_colposcopia_biopsia: 16.4, cacu_dias_toma_diagnostico: 18.4, cacu_dias_biopsia_diagnostico: 12.8,
};
const payload = (id: string, suprimido = 0): IndicadorDatos => ({
id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], version: '1',
filas: [row('2025-S1', 100, 3, MEDIANAS[id] + 1, MEDIANAS[id] + 9, suprimido), row('2025-S2', 120, 4, MEDIANAS[id], MEDIANAS[id] + 8, suprimido)],
});
describe('Ruta del tamizaje: componente', () => {
let f: ReturnType<typeof TestBed.createComponent<IndicadorScreeningRoute>>;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadorScreeningRoute], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorScreeningRoute, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
f = TestBed.createComponent(IndicadorScreeningRoute);
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('tema', 'claro');
});
afterEach(() => { f.destroy(); http.match(() => true); http.verify(); });
// The shared request queue runs a few at a time: answer in waves until nothing is left.
function responder(entrega: (id: string) => IndicadorDatos = id => payload(id)) {
const vistos: string[] = [];
for (;;) {
const pendientes = http.match(r => r.url.endsWith('/datos'));
if (!pendientes.length) return vistos;
for (const r of pendientes) { const id = r.request.url.split('/').at(-2)!; vistos.push(id); r.flush(entrega(id)); }
f.detectChanges();
}
}
const charts = () => f.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
it('carga diferida; pide las siete medidas; dibuja una gráfica y cambia de vista y de periodo sin otra petición', () => {
// Pins down: nothing is requested while hidden, each of the seven measures is requested once, the view and the period
// are chosen without new requests, and the theme redraws the same data. Fails if the region loads before it is
// visible, a measure is missing or repeated, or a control triggers a request.
f.componentRef.setInput('visible', false); f.detectChanges();
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
f.componentRef.setInput('visible', true); f.detectChanges();
expect(f.componentInstance.status()).toBe('loading');
expect(responder().sort()).toEqual([...ROUTE_IDS].sort());
expect(f.componentInstance.status()).toBe('ready');
expect(charts()).toHaveLength(1);
expect(charts()[0].figure()).toBe(f.componentInstance.figure());
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
f.componentInstance.selectView('steps'); f.detectChanges();
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
f.componentInstance.selectPeriod('2025-S1'); f.detectChanges();
expect(f.componentInstance.model()!.period).toBe('2025-S1');
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
http.expectNone(() => true);
});
it('la tabla de valores publicados dice la mediana de cada evento y el estado si no hay caja', () => {
// Fails if the table drops an event or shows a suppressed box as a number.
f.detectChanges();
responder(id => (id === 'cacu_dias_toma_biopsia' ? payload(id, 1) : payload(id)));
const text = f.nativeElement.querySelector('table').textContent as string;
expect(text).toContain('Resultado de citología');
expect(text).toContain('mediana 35.7');
expect(text).toContain('Suprimido');
});
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
// Fails if an empty route draws a chart or hides the reason.
f.detectChanges();
responder(id => payload(id, 1));
expect(f.componentInstance.status()).toBe('empty');
expect(charts()).toHaveLength(0);
expect(f.nativeElement.textContent).toContain('No hay tiempos publicados');
});
it('un fallo del servicio se anuncia como error y reintentar vuelve a pedir', () => {
// Fails if an error leaves a stale chart, hides the alert, or retry does not request again.
f.detectChanges();
http.match(r => r.url.endsWith('/datos'))[0].flush({}, { status: 500, statusText: 'Server Error' });
f.detectChanges();
expect(f.componentInstance.status()).toBe('error');
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
expect(charts()).toHaveLength(0);
http.match(() => true); // the other requests of the first try were cancelled with it
f.componentInstance.retry(); f.detectChanges();
expect(f.componentInstance.status()).toBe('loading');
expect(responder().length).toBe(ROUTE_IDS.length);
expect(f.componentInstance.status()).toBe('ready');
});
it('datos de otro contrato quedan incompatibles y no se dibujan', () => {
// Fails if a payload that is not a duration is drawn as one.
f.detectChanges();
responder(id => (id === 'cacu_dias_toma_biopsia' ? { ...payload(id), contrato: 'C1' } : payload(id)));
expect(f.componentInstance.status()).toBe('incompatible');
expect(charts()).toHaveLength(0);
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
});
it('es una tarjeta con su encabezado y abre en el periodo del filtro general; otro filtro suelta el periodo elegido adentro', () => {
// Fails if the chart is not a card of its own, ignores the periods of the general filter, or keeps a period picked
// inside it after the filter changed.
f.componentRef.setInput('periodos', ['2025-S1']);
f.detectChanges(); responder();
expect(f.nativeElement.querySelector('mat-card h2')?.textContent).toContain('Tiempos de la ruta del tamizaje');
expect(f.componentInstance.model()?.period).toBe('2025-S1');
f.componentInstance.selectPeriod('2025-S2');
expect(f.componentInstance.model()?.period).toBe('2025-S2');
f.componentRef.setInput('periodos', ['2025-S2']); f.detectChanges();
expect(f.componentInstance.requestedPeriod()).toBeUndefined();
expect(f.componentInstance.model()?.period).toBe('2025-S2');
// A period the route does not publish falls back to the newest that has data.
f.componentRef.setInput('periodos', ['2019-S1']); f.detectChanges();
expect(f.componentInstance.model()?.period).toBe('2025-S2');
});
});
@@ -0,0 +1,98 @@
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { etiquetaPeriodo } from './indicadores-historico-figures';
import { httpMessage } from './indicadores-http';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, routeHasData, routeModel } from './screening-route';
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
@Component({
selector: 'app-indicador-screening-route',
imports: [MatButtonModule, MatButtonToggleModule, MatCardModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
templateUrl: './indicador-screening-route.html',
styleUrl: './indicador-screening-route.scss',
})
export class IndicadorScreeningRoute {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
/** The general filter's interval (semester or month) and, when it names periods, those periods. */
readonly tipo = input<TipoPeriodo>('semestre');
readonly periodos = input<readonly string[] | undefined>(undefined);
/** The measures load once the region is visible. */
readonly visible = input(true);
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
readonly message = signal('');
readonly view = signal<RouteView>('cumulative');
readonly requestedPeriod = signal<string | undefined>(undefined);
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
readonly model = computed(() => {
const data = this.payloads();
return data ? routeModel(data, this.tipo(), this.requestedPeriod() ?? this.periodoDelFiltro(data)) : undefined;
});
readonly figure = computed(() => {
const model = this.model();
return model && routeHasData(model) ? routeFigure(model, this.view(), this.tema()) : undefined;
});
// The newest period of the general filter that the route publishes; the chart shows one period at a time.
private periodoDelFiltro(data: Record<string, IndicadorDatos>) {
const pedidos = this.periodos();
if (!pedidos?.length) return undefined;
const publicados = new Set(ROUTE_IDS.flatMap(id => data[id].periodos));
return [...pedidos].sort().reverse().find(p => publicados.has(p));
}
readonly periodLabel = etiquetaPeriodo;
readonly cellText = routeCellText;
private readonly snapshots = inject(IndicadoresSnapshots);
private subscription?: Subscription;
constructor() {
effect(() => {
const dominio = this.dominio(), tipo = this.tipo();
if (!this.visible()) { this.status.set('deferred'); return; }
untracked(() => this.load(dominio, tipo));
});
// Another general filter is another question: the period picked inside the card no longer holds.
effect(() => { this.tipo(); this.periodos(); untracked(() => this.requestedPeriod.set(undefined)); });
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
}
retry() { this.load(this.dominio(), this.tipo()); }
selectPeriod(period: string) { this.requestedPeriod.set(period); }
selectView(view: RouteView) { this.view.set(view); }
private load(dominio: Dominio, tipo: TipoPeriodo) {
this.subscription?.unsubscribe();
this.payloads.set(undefined);
this.status.set('loading');
const requests = Object.fromEntries(ROUTE_IDS.map(id => [id, this.snapshots.datos(dominio, id, tipo)]));
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
next: data => {
try {
const model = routeModel(data, tipo, this.requestedPeriod());
this.payloads.set(data);
this.status.set(routeHasData(model) ? 'ready' : 'empty');
} catch (error) { this.failure(error); }
},
error: error => this.failure(error),
});
}
private failure(error: unknown) {
this.payloads.set(undefined);
this.message.set(error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof RouteIncompatible ? error.message : httpMessage(error));
this.status.set(error instanceof RouteIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError))
? 'incompatible' : 'error');
}
}
@@ -97,13 +97,13 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
<tbody>@for (i of d.items; track i.codigo) {
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Análisis de riesgos'">Ver pacientes</button> }</td></tr>
}</tbody></table>
</div>
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
@@ -155,7 +155,7 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
}
@if (m(); as mm) {
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Análisis de riesgos.</p>
<details><summary>Valores publicados</summary>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
@@ -127,7 +127,7 @@ describe('Pestaña Análisis epidemiológico', () => {
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
expect(text()).toContain('abrir la lista en Seguimiento');
expect(text()).toContain('abrir la lista en Análisis de riesgos');
});
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
// Fails if the cards stay on screen without an answer with categories.
@@ -177,7 +177,7 @@ describe('Pestaña Análisis epidemiológico', () => {
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Análisis de riesgos');
});
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
@@ -93,18 +93,18 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
<p class="aviso" role="status">{{ aviso() }}</p>
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
label="Pacientes por categoría BI-RADS" />
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Análisis de riesgos. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
<table>
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
<tbody>
@for (g of d.grupos; track g.codigo) {
<tr [attr.data-grupo]="g.codigo">
<th scope="row">{{ etiqueta(g.codigo) }}</th>
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Análisis de riesgos'">Ver pacientes</button> }</td>
</tr>
}
</tbody>
@@ -10,6 +10,7 @@ import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { historicoFigura } from './indicadores-historico-figures';
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
const ENDPOINT = ['CACU-CONFIRMACION-CITOLOGIA', 'CACU-DIAS-TOMA-DIAGNOSTICO', 'CACU-EU-TIEMPO-REPORTE', 'CACU-EU13', 'CACU-EU7',
@@ -130,4 +131,37 @@ describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas
expect(dibujo.status).toBe('supported');
}
});
it('un C1 publicado con su intervalo de Wilson llena la banda del histórico, en porcentaje', () => {
// Pins down: the `ic-bajo` and `ic-alto` of a proportion's score (proportions) reach the rows as percentages and
// the history trend draws them as its band. Fails if the bounds are read unconverted or dropped.
const eu13 = medida('CACU-EU13');
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
const reporte13 = { resourceType: 'MeasureReport', id: 'CACU-EU13-1', period: { start: '2025-01-01', end: '2025-06-30' },
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
measureScore: { value: 0.25, extension: [{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 }, { url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 }] } }] } as unknown as Report;
const datos = datosDeReportes(eu13, [reporte13], 'semestre');
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
const banda = (historicoFigura(datos, 'claro').figure as unknown as { data: { name: string; y: number[] }[] }).data[0];
expect(banda.name).toBe('Intervalo de confianza');
expect(banda.y).toEqual([69.9, 4.6]);
});
it('un C1 de CaCu cuyo grupo se llama principal dibuja su tendencia en el histórico', () => {
// Pins down: the WebApi names the group of a proportion `principal`; the page reads it as `total`, the group the
// history trend draws, for CaCu as for CaMa. Fails if the rows keep the group `principal` and the trend comes out
// empty, with its period listed as having no data.
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
for (const id of ['CACU-EU13', 'IND1']) {
const medida13 = medida(id);
const reporte = { resourceType: 'MeasureReport', id: id + '-1', period: { start: '2025-01-01', end: '2025-06-30' },
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
measureScore: { value: 0.25 } }] } as unknown as Report;
const datos = datosDeReportes(medida13, [reporte], 'semestre');
expect(datos.filas[0]['grupo']).toBe('total');
const figura = historicoFigura(datos, 'claro');
expect((figura.figure as unknown as { data: { y: number[] }[] }).data[1].y).toEqual([25]);
expect(figura.sinDato).toEqual([]);
}
});
});
@@ -6,7 +6,14 @@
// the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule.
export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
'CACU-DIAS-BIOPSIA-DIAGNOSTICO': 'cacu_dias_biopsia_diagnostico',
'CACU-DIAS-COLPOSCOPIA-BIOPSIA': 'cacu_dias_colposcopia_biopsia',
'CACU-DIAS-DIAGNOSTICO-TRATAMIENTO': 'cacu_dias_diagnostico_tratamiento',
'CACU-DIAS-RESULTADO-COLPOSCOPIA': 'cacu_dias_resultado_colposcopia',
'CACU-DIAS-TOMA-BIOPSIA': 'cacu_dias_toma_biopsia',
'CACU-DIAS-TOMA-COLPOSCOPIA': 'cacu_dias_toma_colposcopia',
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
'CACU-DIAS-TOMA-TRATAMIENTO': 'cacu_dias_toma_tratamiento',
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
'CACU-EU13': 'cacu_eu13',
'CACU-EU7': 'cacu_eu7',
@@ -87,8 +87,8 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
]);
for (const kpi of kpis.slice(3)) {
expect(kpi.querySelectorAll('p')).toHaveLength(1);
expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
expect(kpi.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
expect(kpi.textContent).toContain('aún no está publicado');
}
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
@@ -9,7 +9,7 @@ import { strFromU8, unzipSync } from 'fflate';
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf';
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte';
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaEscenario, etiquetaHistologia } from './etiquetas-cohorte';
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
@@ -33,6 +33,17 @@ describe('Etiquetas de la cohorte', () => {
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
expect(['POST_TRATAMIENTO', 'EN_OBSERVACION', 'CONTROL'].map(etiquetaEscenario)).toEqual(['Post-tratamiento', 'En observación', 'CONTROL']);
});
it('el escenario clínico de una fila se lee «Post-tratamiento» o «En observación» en la lista y en la ficha, con su código guardado', () => {
// Fails if the list or the record show the scenario's code, or the code the filter sends is lost.
const cruda = listaCohorte();
const items = cruda['items'] as Record<string, unknown>[];
items[0]['escenario_clinico'] = 'POST_TRATAMIENTO'; items[1]['escenario_clinico'] = 'EN_OBSERVACION';
const r = seguimientoTablaResponse(cruda);
expect(r.items[0]).toMatchObject({ escenario_clinico: 'Post-tratamiento', escenario_clinico_codigo: 'POST_TRATAMIENTO' });
expect(r.items[1]).toMatchObject({ escenario_clinico: 'En observación', escenario_clinico_codigo: 'EN_OBSERVACION' });
expect(toCamaPatientSummary(r.items[0], '2026-01-01')?.clinicalScenario).toBe('Post-tratamiento');
});
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
@@ -15,6 +15,8 @@ import {
} from './indicadores-cama-fhir';
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
const esMedidaCacu = (measureId: string | undefined): boolean => measureId !== undefined && Object.hasOwn(CACU_MEASURE_IDS, measureId);
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
// by the same rules as before.
@@ -56,6 +58,8 @@ function decimal(score: Score | undefined, name: string): number | null {
return typeof value === 'number' ? value : null;
}
const round1 = (value: number) => Math.round(value * 10) / 10;
// A proportion's bounds travel as proportions; the rows hold percentages, like `valor`.
const percent = (value: number | null) => value === null ? null : round1(value * 100);
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
// keeps every category ungrouped.
@@ -146,7 +150,7 @@ function proporcion(populations: Population[] | undefined, score: Score | undefi
return {
suprimido: 0, numerador, denominador,
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
ic_bajo: percent(decimal(score, 'ic-bajo')), ic_alto: percent(decimal(score, 'ic-alto')),
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
};
@@ -235,7 +239,9 @@ function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly
// The `/datos` answer for `measure`, from one report per period.
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id), cacu = esMedidaCacu(measure.id);
// What each period's report says its units are (CaCu's compositions): the history checks its categories against them.
const unidadesPeriodo: Record<string, number> = {};
const declaradas = categorias(measure);
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
@@ -251,10 +257,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
: { ...declaradas,
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
const totales: Record<string, unknown>[] = [];
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
// The page names the primary group of a proportion `total`; the WebApi names it `principal`.
const nombre = (codigo: string | undefined) => {
const grupo = codigo ?? 'TOTAL';
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
return kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
};
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = nombre(code(g.code));
@@ -306,6 +312,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) {
throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
if (cacu && units !== null) unidadesPeriodo[periodo] = units;
Object.keys(cats).forEach((categoria, orden) =>
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
continue;
@@ -338,6 +345,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
...(cacu && kind === 'C2' ? { unidades_periodo: unidadesPeriodo } : {}),
grupos,
categorias: cats,
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
@@ -0,0 +1,161 @@
// What this module covers: how CaCu's FHIR measures, as the WebApi publishes them, reach the history figures: the
// primary group of a proportion (`principal`), the page ids, the unit labels, the reconciliation of a composition and
// the periods without units. The Measures are the catalog fixture (`fixtures/cacu_fhir_measures.json`); the reports
// are synthetic and carry what the WebApi serialises, `group.code` included: the older bundle fixtures name the group
// with `group.id` only, which hides the `principal` / `TOTAL` mismatch this spec pins down.
import { Bundle, resources } from './fhir';
import { Measure, Report, datosDeReportes, indicadorDeMeasure } from './indicadores-fhir';
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
import { disponibilidadDe, HISTORICO_CACU, historicoDeDominio } from './indicadores-historico-config';
import { historicoFigura, HistoricoOpciones } from './indicadores-historico-figures';
import measuresData from './fixtures/cacu_fhir_measures.json';
import camaMeasuresData from './fixtures/cama_fhir_measures.json';
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const medida = (id: string) => publicadas.find(m => m.id === id)!;
const cod = (c: string) => ({ coding: [{ code: c }] });
const pob = (c: string, count: number) => ({ code: cod(c), count });
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
const SEMESTRE = { start: '2025-01-01', end: '2025-06-30' };
const SEMESTRE_2 = { start: '2025-07-01', end: '2025-12-31' };
// A proportion as the WebApi serialises it: group `principal`, a score only when the denominator is positive.
const c1 = (period: { start: string; end: string }, numerador: number, denominador: number): Report => ({
resourceType: 'MeasureReport', id: 'r', period,
group: [{ code: cod('principal'), population: [pob('initial-population', denominador), pob('denominator', denominador), pob('numerator', numerador)],
...(denominador > 0 ? { measureScore: { value: numerador / denominador } } : {}) }],
} as unknown as Report);
// A composition: the categories as the first stratifier, the units as the initial population.
const c2 = (m: Measure, period: { start: string; end: string }, conteos: Record<string, number>, unidades?: number): Report => ({
resourceType: 'MeasureReport', id: 'r', period,
group: [{ code: cod('TOTAL'), population: [pob('initial-population', unidades ?? Object.values(conteos).reduce((a, b) => a + b, 0))],
stratifier: [{ code: [cod('categoria')], stratum: Object.entries(conteos).map(([c, n]) => ({ value: cod(c), population: [pob('initial-population', n)] })) }] }],
} as unknown as Report);
// A duration: the median and the quartiles as extensions of the score.
const c3r = (period: { start: string; end: string }, n: number, mediana?: number): Report => ({
resourceType: 'MeasureReport', id: 'r', period,
group: [{ code: cod('TOTAL'), population: [pob('initial-population', n + 1), pob('measure-observation', n), pob('measure-population-exclusion', 1)],
...(mediana === undefined ? {} : { measureScore: { value: mediana, unit: 'd', extension: [
{ url: `${STRUCTURE}/q1`, valueDecimal: mediana - 2 }, { url: `${STRUCTURE}/q3`, valueDecimal: mediana + 3 }] } }) }],
} as unknown as Report);
const traza = (datos: ReturnType<typeof datosDeReportes>, i: number, opciones?: HistoricoOpciones) =>
historicoFigura(datos, 'claro', opciones).figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
const CACU: HistoricoOpciones = { unidades: historicoDeDominio('cacu')!.unidades, conciliarC2: true, c2SinPoblacionSinDato: true };
describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
it('EU13 con el grupo `principal` que publica el WebApi: el cero es un valor y el panel no queda vacío', () => {
// Pins down: the proportion's group reaches the history as the total. Fails if `principal` stays as it is and the
// selector of the total drops every row, which left EU13's panel empty.
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 4)], 'semestre');
expect(datos.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 4, valor: 0 });
expect(Object.keys(datos['grupos'] as object)).toEqual(['total']);
const figura = historicoFigura(datos, 'claro');
expect(traza(datos, 1).y).toEqual([0]);
expect(figura.sinDato).toEqual([]);
});
it('IND1 se publica como `ind1` y conserva su valor', () => {
const datos = datosDeReportes(medida('IND1'), [c1(SEMESTRE, 1, 4), c1(SEMESTRE_2, 1, 4)], 'semestre');
expect(datos.id).toBe('ind1');
expect(traza(datos, 1).y).toEqual([25, 25]);
});
it('un denominador cero es «sin dato», no un cero', () => {
// The WebApi omits the score when there is no denominator: the period is listed as missing, not drawn at zero.
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 0), c1(SEMESTRE_2, 1, 4)], 'semestre');
expect(datos.filas[0]).toMatchObject({ valor: null, denominador: 0 });
expect(traza(datos, 1).y).toEqual([null, 25]);
expect(historicoFigura(datos, 'claro').sinDato).toEqual(['2025 S1']);
});
it('sin intervalo publicado la banda queda vacía: el cliente no lo calcula ni lo inventa', () => {
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 1, 4)], 'semestre');
expect(datos.filas[0]).toMatchObject({ ic_bajo: null, ic_alto: null });
expect(traza(datos, 0)).toMatchObject({ name: 'Intervalo de confianza', x: [], y: [] });
});
it('en CaMa el grupo principal sigue siendo `total`', () => {
// Regression: the normalisation CaCu shares with CaMa keeps CaMa's own result.
const cama = (resources(camaMeasuresData as unknown as Bundle, 'Measure') as Measure[]).find(m => m.id === 'CAMA-CONFIRMACION-BIRADS45')!;
const datos = datosDeReportes(cama, [c1(SEMESTRE, 2, 4)], 'semestre');
expect(datos.filas[0]).toMatchObject({ grupo: 'total', valor: 50 });
});
it('los paneles activos usan ids de página y contratos que el catálogo publica', () => {
// Pins down the compatibility of the identifiers: every active panel is a measure `dev` publishes, under the id
// the page gives it, and with the contract the panel expects.
const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)]));
const activos = HISTORICO_CACU.filter(p => disponibilidadDe(p) === 'activo');
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']);
for (const panel of activos) {
expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id);
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
}
});
it('todos los paneles del Histórico están activos; las medidas sin panel siguen en el catálogo', () => {
expect(HISTORICO_CACU.filter(p => disponibilidadDe(p) !== 'activo')).toEqual([]);
expect(HISTORICO_CACU.map(p => p.id)).not.toContain('cacu_riesgo_banda');
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
});
});
describe('Histórico de CaCu: composiciones (C2)', () => {
const eu7 = () => medida('CACU-EU7');
const conteos = (extra: Record<string, number> = {}) => ({ ...Object.fromEntries(declaradas(eu7()).map((c, i) => [c, [8, 3, 2, 1, 1, 0, 1][i]])), ...extra });
it('el reporte de EU7 conserva las unidades de cada periodo y la conciliación pasa', () => {
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos())], 'semestre');
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 16 });
const figura = historicoFigura(datos, 'claro', CACU);
expect(figura.figure.data.map(t => (t['y'] as number[])[0])).toEqual([8, 3, 2, 1, 1, 0, 1]);
expect(figura.sinDato).toEqual([]);
});
it('una categoría que el Measure no declara rompe la conciliación del Histórico y no cambia el Resumen', () => {
// Pins down: a category the report counts but the Measure does not declare (the glandular results are still an open
// decision) is no longer a shorter bar. The adapter itself reads the report as before.
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos({ AGC: 2 }))], 'semestre');
expect(datos.filas.map(f => f['categoria'])).not.toContain('AGC');
expect(() => historicoFigura(datos, 'claro', CACU)).toThrow('Los conteos por categoría no suman las unidades del periodo');
expect(() => historicoFigura(datos, 'claro')).not.toThrow();
});
it('un periodo sin pacientes es «sin dato» en CaCu y no barras en cero', () => {
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0), c2(eu7(), SEMESTRE_2, conteos())], 'semestre');
const figura = historicoFigura(datos, 'claro', CACU);
expect(figura.sinDato).toEqual(['2025 S1']);
expect(figura.figure.data.every(t => (t['y'] as (number | null)[])[0] === null)).toBe(true);
expect((figura.figure.data[0]['y'] as number[])[1]).toBe(8);
});
it('sin la opción de CaCu un periodo sin unidades se dibuja como antes (CaMa no cambia)', () => {
// Regression: the rule is the domain's, not the figure module's.
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0)], 'semestre');
const figura = historicoFigura(datos, 'claro');
expect(figura.sinDato).toEqual([]);
expect(figura.figure.data.every(t => (t['y'] as number[])[0] === 0)).toBe(true);
});
it('la confirmación por citología declara sus categorías y se concilia igual', () => {
const m = medida('CACU-CONFIRMACION-CITOLOGIA');
const datos = datosDeReportes(m, [c2(m, SEMESTRE, Object.fromEntries(declaradas(m).map((c, i) => [c, i])))], 'semestre');
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 21 });
expect(() => historicoFigura(datos, 'claro', CACU)).not.toThrow();
});
});
describe('Histórico de CaCu: tiempos (C3r) y etiquetas de unidad', () => {
const m = () => medida('CACU-EU-TIEMPO-REPORTE');
it('la mediana y los cuartiles hablan de citologías en CaCu', () => {
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12), c3r(SEMESTRE_2, 0)], 'semestre');
expect(datos.filas[0]).toMatchObject({ mediana: 12, q1: 10, q3: 15, n: 6, unidad: 'dias' });
const figura = historicoFigura(datos, 'claro', CACU);
expect(traza(datos, 1, CACU)['text'][0]).toBe('Mediana: 12 días<br>Q1 a Q3: 10 a 15 días<br>6 citologías');
expect(figura.comoLeer).toContain('las citologías');
expect(figura.comoLeer).not.toContain('mastograf');
// A period without observations is missing, not zero.
expect(traza(datos, 1, CACU)['y']).toEqual([12, null]);
expect(figura.sinDato).toEqual(['2025 S2']);
});
it('sin la configuración de CaCu el texto de los exámenes sigue siendo el de CaMa', () => {
// Regression: `examen` keeps reading «mastografías» wherever the domain does not name it otherwise.
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12)], 'semestre');
expect(traza(datos, 1)['text'][0]).toContain('6 mastografías');
expect(historicoFigura(datos, 'claro').comoLeer).toContain('las mastografías');
});
});
@@ -0,0 +1,198 @@
// Covers CaCu's history tab: its six panels (the times to treatment and the risk by band have none), what is requested
// and when (nothing until the tab is open, only the latest periods at first), the states of a panel, and the notice. Responses are synthetic, shaped like /cacu/indicadores/<id>/periodos and /datos.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { MatDialog } from '@angular/material/dialog';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresHistorico } from './indicadores-historico';
import { HISTORICO_CACU } from './indicadores-historico-config';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub { figure?: { data: { name?: string; y?: (number | null)[]; text?: string[] }[] }; label?: string; }
const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStart(2, '0')}`);
const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1'];
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico'];
// Measures the catalog can publish that the history has no panel for.
const SIN_PANEL = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
// Every measure the catalog could publish: publishing the ones without a panel must not add one.
const CATALOGO = [...ACTIVOS, ...SIN_PANEL].map(item);
function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) {
const contrato = opciones.contrato ?? CONTRATOS[id];
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
const vacio = (p: string) => p === opciones.sinPoblacion;
const filas = contrato === 'C2'
? periodos.flatMap(p => [fila(p, { categoria: 'NORMAL', n: vacio(p) ? 0 : 7, orden: 0 }), fila(p, { categoria: 'ASC-US', n: vacio(p) ? 0 : 5, orden: 1 })])
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 0, numerador: 0, denominador: 10, ic_bajo: null, ic_alto: null }))
: periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' }));
return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' ? 'paciente' : 'examen', filas,
categorias: { NORMAL: { etiqueta: 'Normal', color: '#9DBFE3' }, 'ASC-US': { etiqueta: 'ASC-US', color: '#2F6DB3' } },
...(contrato === 'C2' ? { unidades_periodo: Object.fromEntries(periodos.map(p => [p, vacio(p) ? 0 : 12])) } : {}) };
}
describe('Histórico de CaCu', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
const abrirDialogo = vi.fn();
function montar(catalog: Indicador[] = CATALOGO, active = false) {
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }] });
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog);
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active);
fixture.detectChanges();
}
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
// Answers in waves, because the shared request queue runs four at a time. `pedidos` keeps what each data request asked for.
const pedidos: { id: string; periodos: string[] }[] = [];
function responder(opciones: { fallo?: (r: TestRequest) => boolean; datos?: (id: string) => { contrato?: string; sinPoblacion?: string } } = {}) {
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
const url = r.request.url, id = url.split('/').at(-2)!;
if (opciones.fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; }
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
else {
const periodos = r.request.params.get('periodos')!.split(',');
pedidos.push({ id, periodos });
r.flush(datos(id, periodos[0].includes('S') ? 'semestre' : 'mes', periodos, opciones.datos?.(id)));
}
}
fixture.detectChanges();
}
}
beforeEach(() => { pedidos.length = 0; });
const root = () => fixture.nativeElement as HTMLElement;
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!;
const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo;
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!;
it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => {
// Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it.
montar();
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const vistos = new Set<string>();
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
vistos.add(r.request.url.split('/').at(-2)!);
const id = r.request.url.split('/').at(-2)!;
if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: MESES.map(periodo => ({ periodo, tipo: 'mes' })) });
else r.flush(datos(id, 'mes', r.request.params.get('periodos')!.split(',')));
}
fixture.detectChanges();
}
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
for (const id of SIN_PANEL) expect(vistos.has(id)).toBe(false);
});
it('dibuja seis paneles en orden, todos con gráfica, aunque el catálogo publique medidas sin panel', () => {
montar(CATALOGO, true); responder();
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
expect(paneles()).toHaveLength(6);
expect(graficas()).toHaveLength(6);
expect(root().querySelector('[data-reservado]')).toBeNull();
for (const titulo of ['Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento', 'Riesgo CIN2+ por banda']) expect(root().textContent).not.toContain(titulo);
});
it('ampliar dos veces seguidas (de 5 a 10 y a «Todos») sin esperar la primera respuesta deja todos los periodos', () => {
// Fails if the second answer is dropped because the first one arrived before it: the periods stop at the 10.
montar(CATALOGO, true); responder();
pedidos.length = 0;
fixture.componentInstance.elegirVentana(10); fixture.detectChanges();
fixture.componentInstance.elegirVentana(0); fixture.detectChanges();
responder();
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
});
it('el Histórico de CaCu no lleva un aviso de validación clínica', () => {
montar();
expect(root().querySelector('[data-aviso="historico"]')).toBeNull();
expect(root().textContent).not.toContain('supresión estadística');
});
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
montar(CATALOGO, true); responder();
expect(pedidos).toHaveLength(6);
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5));
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
});
it('elegir «Todos» pide solo los periodos que faltan y los suma', () => {
montar(CATALOGO, true); responder();
pedidos.length = 0;
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
expect(pedidos).toHaveLength(6);
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7));
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
// Going back to five is local: nothing is asked again.
pedidos.length = 0;
fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); responder();
expect(pedidos).toEqual([]);
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
});
it('cambiar a Semestral pide los últimos cinco semestres una vez y volver a Mensual no repite', () => {
montar(CATALOGO, true); responder();
pedidos.length = 0;
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
expect(pedidos).toHaveLength(6);
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
pedidos.length = 0;
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
expect(pedidos).toEqual([]);
});
it('una medida activa que el catálogo no publica es «Integración pendiente» y no se consulta', () => {
montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder();
const panel = panelDe(tituloDe('cacu_eu13'));
expect(panel.textContent).toContain('Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.');
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
expect(graficas()).toHaveLength(5);
});
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
montar(CATALOGO, true);
responder({ fallo: r => r.request.url.includes('/cacu_eu13/') && r.request.url.endsWith('/datos') });
const panel = panelDe(tituloDe('cacu_eu13'));
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
expect(panel.textContent).not.toContain('private');
expect(graficas()).toHaveLength(5);
const reintentar = panel.querySelector('button') as HTMLButtonElement;
reintentar.click(); fixture.detectChanges(); responder();
expect(graficas()).toHaveLength(6);
});
it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => {
// Pins down the expected contract: the panel does not draw a C1 where it declared a composition.
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} });
const panel = panelDe(tituloDe('cacu_eu7'));
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1');
expect(graficas()).toHaveLength(5);
});
it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => {
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} });
expect(graficaDe(tituloDe('cacu_eu13')).figure!.data[1].y).toEqual([0, 0, 0, 0, 0]);
expect(panelDe(tituloDe('cacu_eu13')).querySelector('[data-plegable="sin-dato"]')).toBeNull();
const eu7 = panelDe(tituloDe('cacu_eu7'));
expect(eu7.querySelector('[data-plegable="sin-dato"]')?.textContent).toContain('Periodos sin dato (1)');
expect(eu7.textContent).toContain('oct 2025');
expect(graficaDe(tituloDe('cacu_eu7')).figure!.data[0].y).toEqual([7, 7, null, 7, 7]);
});
it('los tiempos hablan de citologías', () => {
montar(CATALOGO, true); responder();
for (const id of ['cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']) {
expect(graficaDe(tituloDe(id)).figure!.data[1].text![0]).toContain('20 citologías');
expect(panelDe(tituloDe(id)).textContent).toContain('las citologías');
expect(panelDe(tituloDe(id)).textContent).not.toContain('mastograf');
}
});
it('sin ninguna medida activa en el catálogo no hay paneles ni consultas', () => {
montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true);
expect(paneles()).toEqual([]);
http.expectNone(() => true);
});
});
@@ -0,0 +1,83 @@
import { Dominio } from './indicadores.models';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
// What each domain's history tab draws, declared as data: the panels and their order, the contract each one is
// expected to carry, the labels of its unit and what the tab may ask for. A domain without an entry here (TEA) draws
// its whole catalog.
export type ContratoHistorico = 'C1' | 'C2' | 'C3r';
// The mark each contract gets in `historicoFigura`: counts add up to a total, percentages and medians do not.
export type GraficaHistorico = 'barras_apiladas' | 'linea_porcentaje' | 'linea_mediana';
// `activo`: the tab asks for its data when the catalog publishes it. The other two are reserved: the panel shows its
// title, its description and the reason, and never asks for a report, whatever the catalog publishes. Activating a
// reserved panel is an explicit edit of this table, once its contract, its tests and its approval are in place.
export type DisponibilidadPanel = 'activo' | 'integracion_pendiente' | 'pendiente_validacion';
export interface PanelHistorico {
// The page's id of the measure (what `indicadorId` gives).
id: string;
titulo: string;
contrato?: ContratoHistorico;
grafica?: GraficaHistorico;
estado?: DisponibilidadPanel;
descripcion?: string;
// The FHIR ids the measure is expected to have, for the reserved panels whose measure is not in the catalog yet.
fhir?: readonly string[];
}
export interface UnidadHistorico { plural: string; eje: string }
export interface HistoricoDominio {
paneles: readonly PanelHistorico[];
// The unit a measure publishes (`examen`) named as the domain calls it; overrides the figure module's default.
unidades?: Readonly<Record<string, UnidadHistorico>>;
// How many of the latest periods are requested when the tab opens. Without it, every period is requested.
periodosIniciales?: number;
// A composition (C2) whose categories do not add up to the report's units is an error, not a shorter bar.
conciliarC2?: boolean;
// A composition period with no units is «sin dato», not a bar of zeros.
c2SinPoblacionSinDato?: boolean;
// Shown above the panels.
aviso?: string;
}
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
];
// Whether CaCu offers the history tab: the switch that takes it out.
export const HISTORICO_CACU_HABILITADO = true;
// CaCu's history: the six measures `dev` publishes. The times to treatment and the risk by band have no panel here.
export const HISTORICO_CACU: readonly PanelHistorico[] = [
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica', contrato: 'C1', grafica: 'linea_porcentaje' },
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
];
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
cama: { paneles: HISTORICO_CAMA },
cacu: {
paneles: HISTORICO_CACU,
// `examen` is the citology here.
unidades: { examen: { plural: 'citologías', eje: 'Citologías' } },
periodosIniciales: 5,
conciliarC2: true,
c2SinPoblacionSinDato: true,
},
};
// The domain's declared history, if it has one and the tab is on.
export function historicoDeDominio(dominio: Dominio): HistoricoDominio | undefined {
return dominio === 'cacu' && !HISTORICO_CACU_HABILITADO ? undefined : HISTORICOS[dominio];
}
export const disponibilidadDe = (panel: PanelHistorico): DisponibilidadPanel => panel.estado ?? 'activo';
@@ -31,12 +31,19 @@ export interface HistoricoOpciones {
// Same vertical scale across small charts, so their heights compare.
yMax?: number;
pequena?: boolean;
// The unit a measure publishes, named as the domain calls it; falls back to the defaults below (CaMa's).
unidades?: Readonly<Record<string, { plural: string; eje: string }>>;
// A composition whose categories do not add up to the report's units (`unidades_periodo`) is an error.
conciliarC2?: boolean;
// A composition period with no units is «sin dato», not a bar of zeros.
c2SinPoblacionSinDato?: boolean;
}
// What the unit a measure publishes is called in the charts' texts.
const UNIDADES: Readonly<Record<string, { plural: string; eje: string }>> = {
paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' },
};
const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' };
const unidadDe = (data: IndicadorDatos, propias?: HistoricoOpciones['unidades']) =>
propias?.[String(data['unidad'])] ?? UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' };
function validar(data: IndicadorDatos) {
for (const row of data.filas) {
if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida');
@@ -115,7 +122,7 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
};
}
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
const periodos = validar(data), unidad = unidadDe(data);
const periodos = validar(data), unidad = unidadDe(data, opciones.unidades);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
const trazo = colorDeLinea(data.id, tema);
return {
@@ -137,8 +144,8 @@ const CONTEOS: Readonly<Record<string, { eje: string; comoLeer: string }>> = {
M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' },
M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' },
};
function conteo(data: IndicadorDatos, tema: Tema): Trazo {
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data);
function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): Trazo {
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data, opciones.unidades);
const celdas = new Map<string, Record<string, unknown>>(), categorias = new Map<string, number>();
for (const row of data.filas) {
const id = row['categoria'], key = JSON.stringify([id, row['periodo']]);
@@ -151,7 +158,22 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
const orden = [...[...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id), ...Object.keys(catalogo).filter(id => !categorias.has(id))];
const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo])));
const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1));
const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])));
// The units each report says it has, when the adapter kept them: what the categories of a period must add up to.
const unidades = record(data['unidades_periodo']) ? data['unidades_periodo'] : undefined;
const suma = (p: string) => {
const valores = estadoDe(p).map(row => row?.['n']);
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
};
if (opciones.conciliarC2 && unidades) {
for (const p of periodos) {
const total = unidades[p], contado = suma(p);
if (numero(total) && contado !== null && contado !== total) throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
}
// A period with no units is not a period of zeros: it is drawn as a gap and listed.
const sinPoblacion = new Set(opciones.c2SinPoblacionSinDato
? periodos.filter(p => !suprimidos.includes(p) && (numero(unidades?.[p]) ? unidades![p] === 0 : suma(p) === 0)) : []);
const sinDato = periodos.filter(p => sinPoblacion.has(p) || (!suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))));
const curso = { frio: 0, calido: 0, neutro: 0 };
return {
figure: { data: orden.map((id, i) => {
@@ -159,7 +181,7 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined;
const tono = tonoDe(typeof meta['grupo'] === 'string' ? meta['grupo'] : id);
const slot = tono === 'neutro' ? i : curso[tono]++;
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) && !sinPoblacion.has(p) ? n : null; });
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
@@ -176,7 +198,7 @@ function etiquetaCategoria(meta: Record<string, unknown>, id: string) {
// The plot follows from what the contract's numbers mean: counts add up to a total, percentages
// and medians do not, so those two are never stacked.
export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura {
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? porcentaje(data, tema)
: data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined;
if (!figura) throw new Error('Representación no soportada');
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
@@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => {
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
fixture.componentInstance.changeSection('analisis');
fixture.detectChanges();
@@ -38,17 +38,18 @@ describe('Pestaña Histórico', () => {
expect(root().querySelector('#panel-analisis')).toBeNull();
http.expectNone(request => request.url.startsWith('/cama/analisis'));
});
it('cacu no tiene la pestaña Histórico', () => {
// Fails if the history tab of TEA or CaMa leaks into CaCu.
it('cacu tiene Histórico y no Análisis epidemiológico', () => {
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
abrir('cama', []);
abrir('cacu', [item('cacu_x', 'C2')]);
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).toBeNull();
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
expect(root().querySelector('#panel-analisis')).toBeNull();
});
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
abrir('cama', []);
abrir('tea', [item('tea_x', 'C2')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
expect(root().querySelector('#panel-analisis')).toBeNull();
});
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Resumen se oculta', () => {
@@ -14,27 +14,28 @@ import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadore
import { IndicadoresPeriodos } from './indicadores-periodos';
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
import { disponibilidadDe, DisponibilidadPanel, HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
export { HISTORICO_CAMA };
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato'] }; rango?: string } & (
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
// `disponibles` is every period the indicator publishes for the interval, kept when only the latest were requested.
type Carga = { estado: 'listo'; datos: IndicadorDatos; disponibles?: string[] } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato']; descripcion?: string }; rango?: string } & (
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'reservado'; disponibilidad: Exclude<DisponibilidadPanel, 'activo'> } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
const CASOS = 'M28_casos_por_estado';
const PERSONALIZADO = -1;
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
];
// What two answers for the same indicator give together: the periods, rows and reports of both.
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
// A period both have (two widenings asked for it) is kept once, from `a`.
const nuevos = b.periodos.filter(p => !a.periodos.includes(p));
const deNuevos = (fila: unknown) => !fila || typeof fila !== 'object' || !('periodo' in fila) || nuevos.includes(String((fila as { periodo: unknown }).periodo));
const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'].filter(deNuevos) : [])];
const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) };
return { ...a, periodos: [...a.periodos, ...nuevos], filas: [...a.filas, ...b.filas.filter(deNuevos)],
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
}
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
@@ -62,6 +63,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: `
@if (aviso(); as texto) { <p class="aviso" role="note" data-aviso="historico">{{ texto }}</p> }
<div class="controles compacto">
<h2>Filtros</h2>
<div class="controles-fila">
@@ -88,6 +90,14 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
@switch (panel.estado) {
@case ('pendiente') { <p role="status">Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.</p> }
@case ('reservado') {
@if (panel.item.descripcion) { <p>{{ panel.item.descripcion }}</p> }
@if (panel.disponibilidad === 'pendiente_validacion') {
<p role="status" data-reservado="validacion">Pendiente de validación. Este indicador no se consulta hasta que su contrato, sus pruebas y su autorización estén aprobados.</p>
} @else {
<p role="status" data-reservado="integracion">Integración pendiente. Este indicador no se consulta hasta que su integración se active de forma explícita.</p>
}
}
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
@case ('error') {
@@ -130,6 +140,8 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
@use '@angular/material' as mat;
:host { display: block; min-width: 0; }
.aviso { margin: 0 0 var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-left-width: 4px; border-radius: var(--issste-radius); font: var(--mat-sys-body-medium); }
.controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
@@ -171,9 +183,17 @@ export class IndicadoresHistorico {
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere.
private readonly publicados = computed(() => this.dominio() === 'cama'
? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog());
// What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog.
private readonly config = computed(() => historicoDeDominio(this.dominio()));
readonly aviso = computed(() => this.config()?.aviso);
// The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active;
// the whole catalog elsewhere. A reserved panel is never one of them, whatever the catalog publishes.
private readonly publicados = computed(() => {
const config = this.config();
return config
? config.paneles.filter(entrada => disponibilidadDe(entrada) === 'activo').flatMap(entrada => this.catalog().filter(item => item.id === entrada.id))
: this.catalog();
});
// Only the granularities some indicator publishes; monthly first when there is one.
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
@@ -183,15 +203,23 @@ export class IndicadoresHistorico {
});
// How many of the latest periods to show, per granularity; 0 shows them all.
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
// Until the user picks one, the domain's initial window (when it declares one and there are more periods) or all.
readonly ventana = computed(() => {
const elegida = this.ventanas()[this.tipo()];
if (elegida !== undefined) return elegida;
const inicial = this.config()?.periodosIniciales ?? 0, total = this.totalDisponibles();
return inicial && (!total || total > inicial) ? inicial : 0;
});
readonly PERSONALIZADO = PERSONALIZADO;
// The periods the user picked in the dialog, per granularity.
private readonly personalizados = signal<Partial<Record<TipoPeriodo, readonly string[]>>>({});
private readonly dialogo = inject(MatDialog);
private readonly selector = viewChild<MatSelect>('selector');
// Every period published for the granularity by any indicator.
private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {})
.flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : [])));
private readonly disponibles = computed(() => cronologico([...new Set(Object.values(this.cargas()[this.tipo()] ?? {})
.flatMap(carga => carga.estado === 'listo' ? carga.disponibles ?? carga.datos.periodos : []))]));
private readonly totalDisponibles = computed(() => Math.max(0, ...Object.values(this.cargas()[this.tipo()] ?? {})
.map(carga => carga.estado === 'listo' ? (carga.disponibles ?? carga.datos.periodos).length : 0)));
// The periods on screen, out of those an indicator publishes.
private recortar(periodos: readonly string[]) {
const orden = cronologico(periodos), ventana = this.ventana();
@@ -209,7 +237,7 @@ export class IndicadoresHistorico {
// Steps of five, up to what the indicator with the most periods has published.
readonly opciones = computed(() => {
const tipo = this.tipo();
const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0));
const total = this.totalDisponibles();
const opciones = [];
for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` });
const elegidos = this.personalizados()[tipo]?.length;
@@ -236,16 +264,26 @@ export class IndicadoresHistorico {
const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`;
const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`;
try {
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos };
const esperado = this.config()?.paneles.find(entrada => entrada.id === item.id)?.contrato;
if (esperado && datos.contrato !== esperado) throw new Error(`Contrato inesperado: se esperaba ${esperado} y llegó ${datos.contrato}`);
const propias = this.config();
const opciones = { ...(TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}),
...(propias ? { unidades: propias.unidades, conciliarC2: propias.conciliarC2, c2SinPoblacionSinDato: propias.c2SinPoblacionSinDato } : {}) };
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, opciones), datos };
} catch (error) {
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
}
};
if (this.dominio() === 'cama') {
const config = this.config();
if (config) {
if (!this.publicados().length) return [];
return HISTORICO_CAMA.map((entrada): Panel => {
return config.paneles.map((entrada: PanelHistorico): Panel => {
const disponibilidad = disponibilidadDe(entrada);
// Reserved: title, description and reason, whatever the catalog says. Nothing is requested for it.
if (disponibilidad !== 'activo') return { item: { id: entrada.id, titulo: entrada.titulo, descripcion: entrada.descripcion }, estado: 'reservado', disponibilidad };
const item = this.catalog().find(i => i.id === entrada.id);
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
const visible = { id: entrada.id, titulo: entrada.titulo };
return item ? { ...panelDe(item), item: { ...visible, contrato: item.contrato } } : { item: visible, estado: 'pendiente' };
});
}
return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
@@ -268,17 +306,55 @@ export class IndicadoresHistorico {
});
});
}
// The periods the window on screen needs out of those published: all of them, unless the domain declares an
// initial window, in which case only those. Choosing a wider window later requests the rest (`ampliar`).
private necesarios(disponibles: readonly string[]): string[] {
if (!this.config()?.periodosIniciales) return [...disponibles];
const orden = cronologico(disponibles), ventana = this.ventana();
if (ventana === PERSONALIZADO) return orden.filter(p => (this.personalizados()[this.tipo()] ?? []).includes(p));
return ventana ? orden.slice(-ventana) : orden;
}
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
const limitada = !!this.config()?.periodosIniciales;
return this.periodos.periodos(this.dominio(), item.id).pipe(
map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)),
switchMap((periodos): Observable<Carga> => periodos.length
? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos })))
? this.service.datos(this.dominio(), item.id, tipo, this.necesarios(periodos)).pipe(
map(datos => ({ estado: 'listo', datos, ...(limitada ? { disponibles: periodos } : {}) })))
: of({ estado: 'vacio' })),
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
}
// The window got wider than what was requested: asks only for the periods that are missing, and adds them.
private ampliar() {
const tipo = this.tipo(), cargas = this.cargas()[tipo];
if (!cargas || !this.config()?.periodosIniciales) return;
for (const item of this.publicados()) {
const carga = cargas[item.id];
if (carga?.estado !== 'listo' || !carga.disponibles) continue;
const faltan = this.necesarios(carga.disponibles).filter(p => !carga.datos.periodos.includes(p));
if (!faltan.length) continue;
this.service.datos(this.dominio(), item.id, tipo, faltan).pipe(takeUntilDestroyed(this.destruccion)).subscribe({
// The load may have been replaced by an earlier widening's answer: what counts is that the item is still ready, and
// `unir` keeps a period once if two widenings asked for it. Comparing with the load this request started from
// dropped the second answer when the first arrived before it (5 -> 10 -> Todos).
next: datos => this.cargas.update(actual => {
const vigente = actual[tipo]?.[item.id];
return vigente?.estado === 'listo'
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { ...vigente, datos: unir(vigente.datos, datos) } } } : actual;
}),
error: error => this.cargas.update(actual => {
const vigente = actual[tipo]?.[item.id];
return vigente?.estado === 'listo' && faltan.some(p => !vigente.datos.periodos.includes(p))
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { estado: 'error', mensaje: httpMessage(error) } } } : actual;
}),
});
}
}
private readonly destruccion = inject(DestroyRef);
elegirVentana(valor: number) {
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
this.ampliar();
}
abrirPersonalizado() {
const tipo = this.tipo(), periodos = this.disponibles();
@@ -290,6 +366,7 @@ export class IndicadoresHistorico {
if (resultado?.length) {
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
this.ampliar();
}
// Cancelled, the selector goes back to what's on screen.
this.selector()?.writeValue(this.ventana());
@@ -130,7 +130,8 @@ describe('P0-C.1: cinco tarjetas de oportunidad', () => {
expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]);
expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]);
for (const card of cards.slice(3)) {
expect(card.querySelectorAll('p')).toHaveLength(1); expect(card.querySelector('p')!.textContent).toBe('Indicador no disponible');
expect(card.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
expect(card.textContent).toContain('aún no está publicado');
}
http.expectNone(() => true);
} finally { f.destroy(); vi.unstubAllGlobals(); http.verify(); }
@@ -0,0 +1,22 @@
// What this module covers: CaCu's two times to treatment: their ids from the API's measures, and their cards, which wait
// as pending until the catalog publishes them and then give way to the real ones.
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
import { CACU_TRATAMIENTO_KPIS, cacuPendingKpiCards } from './indicadores-kpi';
describe('Tiempos a tratamiento de CaCu', () => {
it('las medidas del API se traducen a los ids de la web, sin quedar en mayúsculas', () => {
// Fails if a measure is missing from the map: it would reach the page as CACU_DIAS_TOMA_TRATAMIENTO.
expect(CACU_MEASURE_IDS['CACU-DIAS-TOMA-TRATAMIENTO']).toBe('cacu_dias_toma_tratamiento');
expect(CACU_MEASURE_IDS['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO']).toBe('cacu_dias_diagnostico_tratamiento');
expect(CACU_TRATAMIENTO_KPIS.map(k => k.id)).toEqual(['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']);
});
it('sin ninguna tarjeta dibujada no se agrega nada', () => {
expect(cacuPendingKpiCards([])).toEqual([]);
});
it('las que el catálogo aún no publica quedan pendientes, y las publicadas ya no', () => {
expect(cacuPendingKpiCards(['cacu_eu7']).map(c => [c.definition.id, c.pending])).toEqual([
['cacu_dias_toma_tratamiento', true], ['cacu_dias_diagnostico_tratamiento', true]]);
expect(cacuPendingKpiCards(['cacu_eu7', 'cacu_dias_toma_tratamiento']).map(c => c.definition.id)).toEqual(['cacu_dias_diagnostico_tratamiento']);
expect(cacuPendingKpiCards(['cacu_eu7', ...CACU_TRATAMIENTO_KPIS.map(k => k.id)])).toEqual([]);
});
});
@@ -79,6 +79,16 @@ export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[]
const cards = CAMA_OPORTUNIDAD_KPIS.map(definition => ({ definition, pending: !published(definition.id) }));
return cards.some(card => !card.pending) ? cards : [];
}
// CaCu's two times to treatment stay outside KPI_BY_DOMAIN: they are queried only once the catalog publishes them, and
// keep their cards, pending, until then. Nothing is added until some other card is drawn.
export const CACU_TRATAMIENTO_KPIS: KpiDefinition[] = [
{ id: 'cacu_dias_toma_tratamiento', title: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', unit: 'días (mediana)' },
{ id: 'cacu_dias_diagnostico_tratamiento', title: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', unit: 'días (mediana)' },
];
export function cacuPendingKpiCards(drawn: readonly string[]): KpiCardSlot[] {
if (!drawn.length) return [];
return CACU_TRATAMIENTO_KPIS.filter(definition => !drawn.includes(definition.id)).map(definition => ({ definition, pending: true }));
}
// Published CaMa indicators whose card the summary does not draw.
// The summary draws the paired card and the histopathology card; the rest of CaMa's indicators are in Histórico
// and in Datos y definiciones, which still list the whole catalog.
@@ -52,7 +52,7 @@
</div>
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)">
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cama' ? 1 : 0)">
@for (card of kpis; track dominio + ':' + card.definition.id) {
@if (card.pending) {
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
@@ -62,10 +62,7 @@
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
}
}
@if (dominio === 'cacu') {
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
} @else if (dominio === 'cama') {
@if (dominio === 'cama') {
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible"
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
}
@@ -121,6 +118,10 @@
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
}
@if (screeningRouteAvailable && filters; as general) {
<app-indicador-screening-route [dominio]="dominio" [tema]="tema" [tipo]="general.applied.tipo"
[periodos]="general.applied.selection.mode === 'explicit' ? general.applied.selection.periodos : undefined" />
}
</div>
}
</section>
@@ -17,9 +17,11 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { esSocioConteos } from './indicadores-conteos-pareados';
import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, cacuPendingKpiCards, camaKpiCards } from './indicadores-kpi';
import { TeaResumenPeriodo } from './tea-resumen-periodo';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadorScreeningRoute } from './indicador-screening-route';
import { CACU_SIN_TARJETA, ROUTE_IDS } from './screening-route';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
import { identityElementId, indicatorIdentity } from './indicadores-identities';
@@ -31,16 +33,17 @@ import { IndicadoresTracking } from './indicadores-tracking';
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { historicoDeDominio } from './indicadores-historico-config';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
{ id: 'seguimiento', label: 'Seguimiento' },
{ id: 'seguimiento', label: 'Análisis de riesgos' },
{ id: 'datos', label: 'Datos y definiciones' },
];
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
// TEA, CaMa and CaCu (while its tab is on, see `HISTORICO_CACU_HABILITADO`) have a history; the epidemiological analysis is CaMa's,
// between its history and its follow-up list.
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
@@ -48,17 +51,17 @@ export const CAMA_ANALYSIS_ENABLED = false;
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
{ id: 'seguimiento', label: 'Análisis de Riesgos' }, SECTIONS_WITH_HISTORY[3]];
SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; }
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
@@ -334,8 +337,15 @@ export class IndicadoresPage {
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
}
// CaCu's screening route chart, once the catalog publishes every measure it reads.
get screeningRouteAvailable() {
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
}
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
get availableKpis() {
const definitions = this.dominio === 'cacu' ? [...this.kpisByDomain.cacu, ...CACU_TRATAMIENTO_KPIS] : this.kpisByDomain[this.dominio];
return definitions.filter(definition => this.catalog().some(item => item.id === definition.id));
}
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
get teaResumenPeriodo(): string | undefined {
const selection = this.filters?.applied.selection;
@@ -352,7 +362,8 @@ export class IndicadoresPage {
// What the KPI grid draws. CaMa adds explicit pending cards for opportunity indicators the catalog does not publish.
get kpiCards(): KpiCardSlot[] {
if (this.dominio === 'cama') return camaKpiCards(id => this.catalog().some(item => item.id === id));
return this.opportunityKpis.map(definition => ({ definition, pending: false }));
const cards = this.opportunityKpis.map(definition => ({ definition, pending: false }));
return this.dominio === 'cacu' ? [...cards, ...cacuPendingKpiCards(cards.map(card => card.definition.id))] : cards;
}
private readonly catalogRequests = new Subject<void>();
readonly catalog = signal<Indicador[]>([]);
@@ -363,8 +374,11 @@ export class IndicadoresPage {
// Stable presentation order. Pins no longer reorder the summary.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
// CaCu's page draws the cytology result and the confirmation as cards, and the route chart. The times of the route
// get no card of their own once the chart is there; the rest live in the history (they have no figure here).
const hidden = this.screeningRouteAvailable ? [...ROUTE_IDS, ...CACU_SIN_TARJETA] : [];
return this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !hidden.includes(item.id))]
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
});
@@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
dominio === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
expect(e.root.querySelector('#panel-analisis')).toBeNull();
}
e.page.changeDominio('cama'); e.harness.detectChanges();
@@ -11,7 +11,7 @@ describe('Regresión del mapeo FHIR en CaCu y TEA', () => {
it('las 16 medidas se mapean igual que antes: ids, catálogo, ficha y filas de datos', () => {
// Pins down: ids, catalog entries, sheets and data rows of CaCu's seven and TEA's nine measures, over real reports,
// equal the recorded ones; an error counts as a result too. Fails if a change meant for CaMa (its id table, its
// group name, its undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
// undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
// regenerate the recorded mapping and say why in the change.
const actual = mapeoDeCacuYTea({ indicadorId, indicadorDeMeasure, metadatosDeMeasure, datosDeReportes });
expect(Object.keys(actual)).toEqual(Object.keys(esperado));
@@ -0,0 +1,74 @@
// What this module covers: the screening route chart in CaCu's page: it appears only when the catalog publishes the seven
// measures it reads, and then those measures that nothing else draws lose their own cards. Catalogs are synthetic,
// shaped like /cacu/indicadores.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorScreeningRoute } from './indicador-screening-route';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresMemory } from './indicadores-memory';
import { Dominio } from './indicadores.models';
import { CACU_SIN_TARJETA, ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] });
describe('Ruta del tamizaje: página de CaCu', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
function abrir(domain: Dominio, catalog: unknown[]) {
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
http.match(() => true);
}
const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route');
const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id);
it('con las siete medidas publicadas aparece la gráfica y CaCu deja solo las tarjetas que la gráfica no dibuja', () => {
// Pins down: the chart replaces the cards of every measure it reads, the proportions without a figure and the times to
// treatment live in the history, and the cytology result and its confirmation keep theirs. Fails if the chart stops
// appearing, or one of those measures also shows as a card.
abrir('cacu', [item('cacu_eu7', 'C2'), item('cacu_confirmacion_citologia', 'C2'), item('ind1', 'C1'), item('cacu_eu13', 'C1'),
item('cacu_riesgo_banda', 'C2'), item('cacu_dias_toma_tratamiento'), item('cacu_dias_diagnostico_tratamiento'), ...ROUTE_IDS.map(id => item(id))]);
expect(ruta()).not.toBeNull();
const ids = tarjetas();
for (const id of [...ROUTE_IDS, ...CACU_SIN_TARJETA]) expect(ids).not.toContain(id);
expect(ids).toEqual(['cacu_eu7', 'cacu_confirmacion_citologia']);
});
it('la ruta es la última de la sección clínica, en su tarjeta y con el intervalo del filtro general', () => {
// Fails if the chart is not the last card of the grid, is not inside a card, or does not follow the general filter's interval.
abrir('cacu', [item('cacu_eu7', 'C2'), item('cacu_confirmacion_citologia', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
const grid = fixture.nativeElement.querySelector('.catalog-grid') as HTMLElement;
expect(grid.lastElementChild?.tagName).toBe('APP-INDICADOR-SCREENING-ROUTE');
expect(grid.lastElementChild?.querySelector('mat-card h2')?.textContent).toContain('Tiempos de la ruta del tamizaje');
const ruta = fixture.debugElement.query(By.directive(IndicadorScreeningRoute)).componentInstance as IndicadorScreeningRoute;
expect(ruta.tipo()).toBe(fixture.componentInstance.filters!.applied.tipo);
});
it('con la ruta, la franja de oportunidad conserva sus tarjetas: solo se retiran las de la sección clínica', () => {
// Fails if the opportunity strip loses a card when the route chart appears.
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
const titulos = [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card h3')].map((h: HTMLElement) => h.textContent);
expect(titulos).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
});
it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => {
// Fails if the chart appears with a measure missing, or the cards of the others disappear anyway.
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.filter(id => id !== 'cacu_dias_toma_biopsia').map(id => item(id))]);
expect(ruta()).toBeNull();
const ids = tarjetas();
for (const id of ROUTE_ONLY_IDS.filter(id => id !== 'cacu_dias_toma_biopsia')) expect(ids).toContain(id);
});
it('las otras áreas no la tienen', () => {
// Fails if the CaCu chart leaks into TEA or CaMa.
abrir('cama', [item('cama_eu38a'), ...ROUTE_IDS.map(id => item(id))]);
expect(ruta()).toBeNull();
});
});
@@ -39,9 +39,8 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
// TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain.
const esperadas = ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
@@ -195,13 +195,12 @@ describe('Seguimiento de CaMa (tabla)', () => {
expect(root().querySelector('[role=alert]')?.textContent).toBe('La respuesta del servicio no tiene el formato esperado.');
expect(root().querySelector('table')).toBeNull(); expect(root().textContent).not.toContain('M-0081');
});
it('un tamaño de página inválido no sale del navegador', async () => {
it('un tamaño de página mayor al máximo se acota y no sale del navegador sin acotar', async () => {
await cargado();
const tam = campo('Registros por página').querySelector('input') as HTMLInputElement;
tam.value = '500'; tam.dispatchEvent(new Event('input')); fixture.detectChanges();
tam.value = '500'; tam.dispatchEvent(new Event('input')); tam.dispatchEvent(new Event('change')); fixture.detectChanges();
boton('Consultar').click(); fixture.detectChanges();
http.expectNone(() => true);
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha');
expect(parametros(solicitud())).toMatchObject({ page_size: '200' });
});
});
@@ -9,7 +9,7 @@ import { TrackingExportBar } from './export/tracking-export-bar';
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import {
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, acotarTamano, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor,
} from './seguimiento-tabla.service';
@@ -76,7 +76,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
@for (o of filtro.opciones; track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
</select></label>
}
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" /></label>
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
<button type="submit" [disabled]="estado() === 'loading'">Consultar</button>
</form>
@switch (estado()) {
@@ -163,6 +163,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
private readonly consultas = new Subject<Consulta | null>();
readonly etiquetaVentana = etiquetaVentana;
readonly tamanoMaximo = PAGE_SIZE_MAX;
readonly acotar = acotarTamano;
readonly estado = signal<Estado>('idle');
readonly mensaje = signal('');
readonly data = signal<SeguimientoTablaResponse | undefined>(undefined);
@@ -315,7 +316,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
this.appliedEtiqueta = etiqueta;
// Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one.
const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte;
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros,
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: acotarTamano(this.draft.page_size), filtros,
contexto: otroCorte ? undefined : contexto };
// A new query of the cohort starts from nothing on screen: what was there belongs to the previous one.
if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); }
@@ -48,7 +48,9 @@ describe('Barras estratificadas: activación y caché',()=>{
toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges();
expect(fixture.componentInstance.dimension).toBe('grupo_edad');
expect(toggle[1].getAttribute('aria-checked')).toBe('true');
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2);
// The dimensions, apart from the counts or percentage toggle that follows them.
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions:not(.distribution-medida) [role="radio"]')).toHaveLength(2);
expect(fixture.nativeElement.querySelectorAll('.distribution-medida [role="radio"]')).toHaveLength(2);
for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); }
});
it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{
@@ -93,3 +95,46 @@ describe('Barras estratificadas: activación y caché',()=>{
expect(TestBed.inject(IndicadoresSnapshots).reading('cacu',item,applied)?.data).toEqual(general());
});
});
describe('Barra lateral de estratificación', () => {
// Fija: con más de dos estratificadores, la elección de dimensión, los valores visibles y la medida van en una
// barra lateral; ocultar y volver a mostrar valores redibuja sin pedir datos. Falla si la barra no aparece, si un
// valor oculto sigue en la figura, si se puede ocultar el último o si un cambio local vuelve a consultar.
let fixture:ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>, http:HttpTestingController;
const tres:Indicador={...item,filtros:[...item.filtros!,{estrato:'estadio',etiqueta:'Estadio clínico',valores:[{valor:'I',etiqueta:'I'}]}]};
const general=()=>({...c2Fixture(),id:item.id,version:item.version});
beforeEach(()=>{
TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]});
TestBed.overrideComponent(IndicadorFigureCard,{remove:{imports:[PlotlyChart]},add:{imports:[ChartStub]}});
fixture=TestBed.createComponent(IndicadorFigurePanel); http=TestBed.inject(HttpTestingController);
for(const [k,v] of Object.entries({dominio:'cama',indicador:tres,figuraId:'fig_c2_barras',tema:'claro',applied})) fixture.componentRef.setInput(k,v);
});
afterEach(()=>{fixture.destroy();http.verify();});
const request=()=>http.expectOne(r=>r.url.endsWith('/datos'));
const aside=()=>fixture.nativeElement.querySelector('.strata-sidebar') as HTMLElement;
it('lista los estratificadores y oculta o muestra valores sin consultar',()=>{
fixture.detectChanges(); request().flush(general()); fixture.detectChanges();
expect(aside()).not.toBeNull(); expect(fixture.nativeElement.querySelector('.distribution-toggle')).toBeNull();
const opciones=[...aside().querySelectorAll('[role="radiogroup"] [role="radio"]')] as HTMLButtonElement[];
expect(opciones.map(b=>b.textContent!.trim())).toEqual(['Sin estratificar','Por grupo de edad','Por estatus de seguimiento','Por estadio clínico']);
opciones[1].click(); request().flush(age); fixture.detectChanges();
const valores=()=>[...aside().querySelectorAll('.stratum-toggle')] as HTMLButtonElement[];
expect(valores()).toHaveLength(age.valores_estrato.length);
valores()[0].click(); fixture.detectChanges();
expect(fixture.componentInstance.result().figure?.data.map(t=>t['name'])).not.toContain('&lt;25');
expect(valores()[0].getAttribute('aria-pressed')).toBe('false');
for(const b of valores().slice(1,-1)) b.click(); fixture.detectChanges();
expect(valores().at(-1)!.disabled).toBe(true); expect(fixture.componentInstance.result().figure?.data).toHaveLength(1);
(aside().querySelector('.sidebar-reset') as HTMLButtonElement).click(); fixture.detectChanges();
expect(fixture.componentInstance.result().figure?.data).toHaveLength(age.valores_estrato.length);
http.expectNone(()=>true);
});
it('cambiar de estratificador muestra de nuevo todos los valores',()=>{
fixture.detectChanges(); request().flush(general());
fixture.componentInstance.changeDimension('grupo_edad'); request().flush(age);
fixture.componentInstance.toggleEstrato('<25'); expect(fixture.componentInstance.ocultos.size).toBe(1);
fixture.componentInstance.changeDimension('estatus_seguimiento'); request().flush(status);
expect(fixture.componentInstance.ocultos.size).toBe(0);
expect(fixture.componentInstance.estratos.map(e=>e.valor)).toEqual(status.valores_estrato);
});
});
@@ -1,6 +1,6 @@
import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json';
import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json';
import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified';
import { etiquetaDimension, stratifiedBars, stratifiedCapabilities, stratumOptions } from './indicadores-stratified';
import { DimensionEstrato, Indicador } from './indicadores.models';
const age = { ...ageJson, tipo_periodo: 'semestre' as const };
@@ -61,3 +61,52 @@ describe('Contratos simulados de estratificación de los analistas', () => {
expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow();
});
});
// A CaMa quantity of interest broken down by a stratifier: two strata of different size, one with a suppressed total.
const porEtapa = () => ({
id: 'cama_birads_cancer_invasor', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], estrato: 'etapa',
valores_estrato: ['TEMPRANA', 'AVANZADA', 'SIN'], etiquetas_estrato: { TEMPRANA: 'Temprana', AVANZADA: 'Avanzada', SIN: 'Sin dato' },
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, categorias: { B4A: { etiqueta: 'BI-RADS 4A' }, B5: { etiqueta: 'BI-RADS 5' } },
totales_estrato: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'TEMPRANA', n: 40, suprimido: 0 }, { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'AVANZADA', n: 10, suprimido: 0 },
{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'SIN', n: null, suprimido: 1 }],
filas: [['TEMPRANA', 'B4A', 10], ['TEMPRANA', 'B5', 30], ['AVANZADA', 'B4A', 1], ['AVANZADA', 'B5', 9], ['SIN', 'B4A', null], ['SIN', 'B5', null]]
.map(([estrato, categoria, n], i) => ({ periodo: '2025-S1', grupo: 'TOTAL', estrato, categoria, n, orden: i % 2, suprimido: n === null ? 1 : 0 })),
});
describe('Porcentaje en cada estrato', () => {
it('cada categoría es la parte de su estrato, y un estrato con total suprimido no tiene porcentaje', () => {
// Fails if the share is taken over the whole period instead of the stratum, or drawn over an unknown total.
const { figure, cells } = stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro', {}, 'porcentaje');
expect(cells.filter(c => c.stratum !== 'Sin dato').map(c => c.percent)).toEqual([25, 75, 10, 90]);
expect(cells.filter(c => c.stratum === 'Sin dato').map(c => c.percent)).toEqual([null, null]);
expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje del estrato');
expect(stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro').figure.data[0]['x']).toEqual([10, 30]);
});
it('las dimensiones de CaMa toman su etiqueta del catálogo, y CaCu conserva la suya', () => {
// Fails if a new stratifier is offered without its published label, or CaCu's wording changes.
const item = { id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] as ['semestre'],
filtros: [{ estrato: 'etapa', etiqueta: 'Etapa (temprana o avanzada)', valores: [{ valor: 'TEMPRANA', etiqueta: 'Temprana' }] },
{ estrato: 'grupo_edad', etiqueta: 'Grupo de edad', valores: [{ valor: '40-49', etiqueta: '40-49' }] }] };
expect(stratifiedCapabilities(item)).toEqual(['grupo_edad', 'etapa']);
expect(etiquetaDimension(item, 'etapa')).toBe('Por etapa (temprana o avanzada)');
expect(etiquetaDimension(item, 'grupo_edad')).toBe('Por grupo de edad');
});
});
describe('Estratos ocultos', () => {
// Fija: ocultar valores de un estrato quita sus series y sus celdas, cada estrato conserva su trama y nunca se
// quedan todas fuera. Falla si el filtro deja de aplicarse, si las tramas se recorren o si se puede vaciar la figura.
it('quita las series ocultas, conserva la trama de cada estrato y no deja la figura vacía', () => {
const todos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro');
const patron = (f: typeof todos.figure, nombre: string) => (f.data.find(t => t['name'] === nombre)!['marker'] as Record<string, Record<string, unknown>>)['pattern']['shape'];
const algunos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(['<25', '35-44']));
expect(algunos.figure.data.map(t => t['name'])).toEqual(['25-34', '45-54', '55-64', '65+', 'Sin dato']);
expect(new Set(algunos.cells.map(c => c.stratum))).toEqual(new Set(['25-34', '45-54', '55-64', '65+', 'Sin dato']));
for (const nombre of ['25-34', '65+', 'Sin dato']) expect(patron(algunos.figure, nombre)).toEqual(patron(todos.figure, nombre));
const ninguno = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(age.valores_estrato));
expect(ninguno.figure.data).toHaveLength(todos.figure.data.length);
});
it('lista los valores del estrato con su etiqueta, en el orden publicado', () => {
expect(stratumOptions(age).map(e => e.etiqueta)).toEqual(['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'Sin dato']);
expect(stratumOptions(age).at(-1)).toEqual({ valor: 'sin_dato', etiqueta: 'Sin dato' });
});
});
@@ -4,9 +4,19 @@ import { c2Theme, seriesColors } from './indicadores-c2-palette';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The dimensions a C2's bars can be broken down by, in this order; `citologia_alto_grado` belongs to CaCu's C1 donut.
const ESTRATIFICABLES: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'birads', 'brca', 'estadio', 'tamano', 'etapa'];
/** The button of a dimension: CaCu's two keep their wording; the rest take the label the catalog publishes. */
export function etiquetaDimension(item: Indicador, d: DimensionEstrato): string {
if (d === 'grupo_edad') return 'Por grupo de edad';
if (d === 'estatus_seguimiento') return 'Por estatus de seguimiento';
const etiqueta = item.filtros?.find(f => f.estrato === d)?.etiqueta;
return 'Por ' + (etiqueta ? etiqueta.charAt(0).toLowerCase() + etiqueta.slice(1) : d);
}
export type MedidaEstrato = 'conteo' | 'porcentaje';
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
return item.contrato === 'C2' && Array.isArray(item.filtros)
? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
}
@@ -17,24 +27,37 @@ export function declaraEstrato(item: Indicador, estrato: DimensionEstrato): bool
const declarados = (item as Indicador & { estratos?: unknown }).estratos;
return item.contrato === 'C2' && Array.isArray(declarados) && declarados.includes(estrato);
}
export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } {
/** A stratum a reader can show or hide: its published value and label, in the published order. */
export interface StratumOption { valor: string; etiqueta: string; }
export function stratumOptions(data: IndicadorDatos): StratumOption[] {
const valores = Array.isArray(data['valores_estrato']) ? data['valores_estrato'] as unknown[] : [];
const etiquetas = record(data['etiquetas_estrato']) ? data['etiquetas_estrato'] : {};
return valores.filter((v): v is string => typeof v === 'string')
.map(valor => ({ valor, etiqueta: typeof etiquetas[valor] === 'string' ? etiquetas[valor] as string : valor }));
}
// `percent`: the cell's share of its stratum, when the stratum's total is known.
export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
/** The bars of one period broken down by `dimension`; the strata in `hidden` are left out of the figure and the cells,
* unless that would leave none. */
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet<string> = new Set()): { figure: PlotlyFigure; cells: StratifiedCell[] } {
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
|| !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos'])
|| Object.keys(data['grupos']).length !== 1
|| !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length
|| !data['valores_estrato'].every(v => typeof v === 'string')
|| new Set(data['valores_estrato']).size !== data['valores_estrato'].length || !record(data['etiquetas_estrato'])) throw new Error('Distribución estratificada inválida');
const strata = data['valores_estrato'] as string[], labels = data['etiquetas_estrato'];
const published = data['valores_estrato'] as string[], labels = data['etiquetas_estrato'];
const shown = published.filter(s => !hidden.has(s));
const strata = shown.length ? shown : published;
const statisticalGroup = Object.keys(data['grupos'])[0];
if (strata.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas');
if (published.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas');
const catalog = data['categorias'], groups = data['grupos_de_categoria'];
const entries = new Map<string, { order: number; label: string; color?: string; parent?: string }>();
const rows = new Map<string, Record<string, unknown>>();
for (const row of data.filas) {
const id = row['categoria'], stratum = row['estrato'], n = row['n'];
if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id
|| typeof stratum !== 'string' || !strata.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden'])
|| typeof stratum !== 'string' || !published.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden'])
|| ![0, 1].includes(row['suprimido'] as number) || (row['suprimido'] === 1 ? n !== null : n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) throw new Error('Fila estratificada inválida');
const key = JSON.stringify([id, stratum]);
if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas');
@@ -51,21 +74,39 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
const cells: StratifiedCell[] = [];
const theme = c2Theme(tema);
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
const figure: PlotlyFigure = { data: strata.map((s, series) => {
// The stratum's total: the one published, or else the sum of its cells when every one is published. A share is
// only drawn over a known total; a suppressed or missing total leaves the stratum without percentages.
const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record<string, unknown>[] : [];
const totalDe = (s: string): number | null => {
const publicado = totales.find(t => t['periodo'] === period && t['estrato'] === s && t['grupo'] === statisticalGroup);
if (publicado) return publicado['suprimido'] === 0 && typeof publicado['n'] === 'number' && publicado['n'] > 0 ? publicado['n'] : null;
const propias = [...entries.keys()].map(id => rows.get(JSON.stringify([id, s])));
if (propias.some(r => !r || r['suprimido'] !== 0 || typeof r['n'] !== 'number')) return null;
const suma = propias.reduce((a, r) => a + (r!['n'] as number), 0);
return suma > 0 ? suma : null;
};
const porcentaje = medida === 'porcentaje';
const figure: PlotlyFigure = { data: strata.map(s => {
const series = published.indexOf(s); // a stratum keeps its pattern when others are hidden
const selected = categories.map(([id, c]) => {
const row = rows.get(JSON.stringify([id, s]));
const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible';
const value = status === 'Publicado' ? row!['n'] as number : null;
cells.push({ category: c.label, stratum: labels[s] as string, value, status });
return value;
const total = totalDe(s);
const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null;
cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status });
return { value, percent, total };
});
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
const x = selected.map(v => porcentaje ? v.percent : v.value);
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)),
customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']),
marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
hovertemplate: '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
}), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
}), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true,
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 },
xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid }
: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true },
legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } };
return { figure, cells };
@@ -39,7 +39,7 @@ const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFi
const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0;
const fail = (message: string): never => { throw new TiemposIncompatibles(message); };
function caja(fila: Record<string, unknown> | undefined): Caja {
export function caja(fila: Record<string, unknown> | undefined): Caja {
if (!fila) return { estado: 'No disponible' };
if (fila['suprimido'] === 1) return { estado: 'Suprimido' };
const { n, q1, mediana, q3 } = fila;
@@ -48,7 +48,7 @@
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
</select></label>
}
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></label>
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
</form>
@if (status === 'loading') { <p role="status">Cargando seguimiento…</p> }
@@ -4,6 +4,7 @@ import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, Subject, switchMap } from 'rxjs';
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service';
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
import { MatButtonModule } from '@angular/material/button';
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
@@ -30,6 +31,8 @@ export class IndicadoresTracking implements OnChanges {
@Input() seleccion?: SeleccionSeguimiento;
/** CaMa: the way back to the analysis the selection came from. */
readonly volverAlAnalisis = output<void>();
readonly tamanoMaximo = PAGE_SIZE_MAX;
readonly acotar = acotarTamano;
private readonly service = inject(CacuSeguimientoService);
private readonly indicators = inject(IndicadoresService);
private readonly teaService = inject(TeaSeguimientoService);
@@ -119,11 +122,11 @@ export class IndicadoresTracking implements OnChanges {
}
private load(q: SeguimientoQuery) {
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
if (!validSeguimientoQuery(q)) { this.message = `Revisa la fecha, la ventana y el tamaño de página (1 a ${PAGE_SIZE_MAX}).`; return; }
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
}
apply() { this.load({ ...this.draft, page: 1 }); }
apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); }
retry() { this.load(this.applied); }
navigate(page: number) {
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
@@ -18,8 +18,16 @@ export interface Indicador {
filtros?: IndicadorFiltro[];
// Tabs that show it; without this field, all of them.
vistas?: string[];
// Interactive donut and bars by one stratum, like CaCu's EU7.
escenario?: VistaEscenario;
// How the breakdown by stratum opens: counts, or each category's share of its stratum.
medida_estrato?: 'conteo' | 'porcentaje';
}
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads';
// CaMa's stratifiers (brca, estadio, tamano, etapa) break down its quantities of interest.
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads' | 'brca' | 'estadio' | 'tamano' | 'etapa';
export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads', 'brca', 'estadio', 'tamano', 'etapa'];
// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico».
export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; }
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
@@ -0,0 +1,33 @@
@let r = respuesta();
<section aria-labelledby="analisis-recurrencia-titulo">
<h5 id="analisis-recurrencia-titulo">Análisis de recurrencia</h5>
@if (r === undefined) { <p role="status">Buscando el análisis de recurrencia…</p> }
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
@if (r) {
@if (r.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos de recurrencia para mostrar.</p> }
@else {
<label class="selector">Cohorte
<select [value]="cohorte()" (change)="elegirCohorte($any($event.target).value)">
@for (c of cohortes; track c.id) { <option [value]="c.id" [selected]="c.id === cohorte()">{{ c.nombre }}</option> }
</select>
</label>
<label class="selector">Escenario clínico
<select [value]="escenario()?.escenario" (change)="elegirEscenario($any($event.target).value)">
@for (f of escenarios(); track f.escenario) { <option [value]="f.escenario" [selected]="f.escenario === escenario()?.escenario">{{ f.escenario }}</option> }
</select>
</label>
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + escenario()?.escenario + ', ' + escenario()?.cohorte_nombre" /> }
}
}
</section>
<section aria-labelledby="factores-recurrencia-titulo">
<h5 id="factores-recurrencia-titulo">Factores de riesgo</h5>
@if (r && r.escenarios.length) {
<label class="selector horizons">Horizonte
<select [value]="horizonte()" (change)="elegirHorizonte(+$any($event.target).value)">
@for (h of horizontes(); track h) { <option [value]="h" [selected]="h === horizonte()">{{ h }} meses</option> }
</select>
</label>
<app-cama-factores-riesgo [fila]="factores()" />
} @else { <p class="pending">Se muestran al elegir un escenario clínico.</p> }
</section>
@@ -0,0 +1,51 @@
import { Component, computed, inject, input, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { switchMap } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
import { figuraRecurrencia } from './cama-recurrencia-figura';
import { CamaRecurrenciaService } from './cama-recurrencia.service';
export const COHORTES: { id: string; nombre: string }[] = [{ id: 'metabric', nombre: 'METABRIC' }, { id: 'scanb', nombre: 'SCAN-B' }];
export const HORIZONTE_PREDETERMINADO = 60;
/**
* «Análisis de recurrencia» and its «Factores de riesgo»: two chained menus, the cohort (METABRIC or SCAN-B) and then its clinical
* scenarios; the scenario chosen decides the curve and the label at once, one at a time, and the cohorts are never mixed. The label has
* a horizon (12, 36 or 60 months, 60 by default). The menu opens on the scenario the patient's covariates place her in, when one does.
*/
@Component({
selector: 'app-cama-analisis-recurrencia',
imports: [PlotlyChart, CamaFactoresRiesgo],
templateUrl: './cama-analisis-recurrencia.component.html',
styleUrl: './cama-analisis.component.scss',
})
export class CamaAnalisisRecurrencia {
readonly pacId = input.required<string>();
private readonly service = inject(CamaRecurrenciaService);
readonly cohortes = COHORTES;
/** The analysis; `undefined` while it loads, `null` when there is no recurrence model in production. */
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
private readonly cohorteElegida = signal<string | null>(null);
private readonly escenarioElegido = signal<string | null>(null);
readonly horizonte = signal<number>(HORIZONTE_PREDETERMINADO);
readonly cohorte = computed(() => this.cohorteElegida() ?? this.respuesta()?.predeterminado?.cohorte
?? COHORTES.find(c => this.respuesta()?.escenarios.some(f => f.cohorte === c.id))?.id ?? null);
/** The scenarios of the cohort chosen, from the list of that cohort only. */
readonly escenarios = computed(() => this.respuesta()?.escenarios.filter(f => f.cohorte === this.cohorte()) ?? []);
readonly escenario = computed(() => {
const lista = this.escenarios();
const pedido = this.escenarioElegido() ?? (this.respuesta()?.predeterminado?.cohorte === this.cohorte() ? this.respuesta()?.predeterminado?.escenario : null);
return lista.find(f => f.escenario === pedido) ?? lista[0] ?? null;
});
readonly figura = computed(() => { const f = this.escenario(); return f ? figuraRecurrencia(f) : null; });
readonly horizontes = computed(() => this.respuesta()?.horizontes ?? []);
readonly factores = computed(() => {
const f = this.escenario();
return f ? this.respuesta()?.resumen.find(r => r.cohorte === f.cohorte && r.escenario === f.escenario && r.horizonte_meses === this.horizonte()) ?? null : null;
});
elegirCohorte(id: string): void { this.cohorteElegida.set(id); this.escenarioElegido.set(null); }
elegirEscenario(nombre: string): void { this.escenarioElegido.set(nombre); }
elegirHorizonte(meses: number): void { this.horizonte.set(meses); }
}
@@ -0,0 +1,26 @@
<section aria-labelledby="analisis-supervivencia-titulo">
<h5 id="analisis-supervivencia-titulo">Análisis de supervivencia</h5>
@let m = menu();
@if (m === undefined) { <p role="status">Buscando los escenarios clínicos…</p> }
@if (m === null) { <p role="status">Todavía no hay un modelo de supervivencia en producción.</p> }
@if (m) {
@if (m.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
@else {
<label class="selector">Escenario clínico
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
@for (e of m.escenarios; track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
</select>
</label>
@let l = lectura();
@if (l?.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
@if (l?.tipo === 'rechazada') { <p role="status">{{ $any(l).motivo }}</p> }
@if (l?.tipo === 'error') { <p role="alert">No se pudo calcular la supervivencia de este escenario.</p> }
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Supervivencia: ' + escenario()" /> }
}
}
</section>
<section aria-labelledby="factores-supervivencia-titulo">
<h5 id="factores-supervivencia-titulo">Factores de riesgo</h5>
@if (lectura()?.tipo === 'lista') { <app-cama-factores-riesgo [fila]="factores()" /> }
@else { <p class="pending">Se muestran al elegir un escenario clínico.</p> }
</section>
@@ -0,0 +1,37 @@
import { Component, computed, inject, input, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of, startWith, switchMap } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { CamaCurvasService, EscenarioConFactores, SeleccionRechazada } from './cama-curvas.service';
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
import { figuraSupervivencia } from './cama-supervivencia-figura';
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: EscenarioConFactores };
/**
* «Análisis de supervivencia» and its «Factores de riesgo»: a menu of clinical scenarios; the one chosen decides the curve and the label
* at once, one scenario at a time. The curve is computed from the data ingested so far with the model in production; the menu opens on
* the scenario the patient belongs to.
*/
@Component({
selector: 'app-cama-analisis-supervivencia',
imports: [PlotlyChart, CamaFactoresRiesgo],
templateUrl: './cama-analisis-supervivencia.component.html',
styleUrl: './cama-analisis.component.scss',
})
export class CamaAnalisisSupervivencia {
readonly pacId = input.required<string>();
private readonly service = inject(CamaCurvasService);
/** The menu; `undefined` while it loads, `null` when there is no model in production. */
readonly menu = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id))));
private readonly elegido = signal<string | null>(null);
readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null);
readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of<Lectura | null>(null) : this.service.consulta(nombre).pipe(
map((datos): Lectura => ({ tipo: 'lista', datos })),
catchError(error => of<Lectura>(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })),
startWith<Lectura>({ tipo: 'cargando' })))), { initialValue: null as Lectura | null });
readonly figura = computed(() => { const l = this.lectura(); return l?.tipo === 'lista' ? figuraSupervivencia(l.datos.respuesta.curvas) : null; });
readonly factores = computed(() => { const l = this.lectura(); return l?.tipo === 'lista' ? l.datos.factores : null; });
elegir(nombre: string): void { this.elegido.set(nombre); }
}
@@ -0,0 +1,5 @@
:host { display: block; }
.selector { display: inline-flex; flex-direction: column; gap: .25rem; margin: 0 1.5rem .75rem 0; font-size: .85rem; }
.selector select { font: inherit; padding: .35rem .5rem; min-width: 16rem; max-width: 100%; }
.horizons { margin: 0 0 .5rem; }
.pending { color: var(--mat-sys-outline, #777); margin: 0; }
@@ -0,0 +1,177 @@
// Covers Luis's specification of CaMa's record: the risk-factor label built from a summary row (the factors present in at least 95 % and in
// 50-95 % of the scenario, robust solid and suggestive outlined, grey "none" message), the survival analysis (one menu of scenarios; the
// one chosen decides the curve and the label at once; it opens on the patient's) and the recurrence analysis (two chained menus, the
// cohorts never mixed, a horizon for the label with 60 months by default). Fixtures: stubs of `CamaCurvasService` and
// `CamaRecurrenciaService` with a record like the API answers.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { vi } from 'vitest';
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
import { CamaCurvasService, respuestaCurvas } from './cama-curvas.service';
import { CamaFactoresRiesgo, entradasDe } from './cama-factores-riesgo.component';
import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service';
import { figuraRecurrencia } from './cama-recurrencia-figura';
const meses = Array.from({ length: 25 }, (_, i) => i);
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24));
const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) });
const curvas = (escenario: string, n = 245) => ({ modelo: { nombre: 'cama-survival', version: '3' }, curvas: {
version: 1, escenario, n, events: 67, median_follow_up_months: 9, horizons_months: [6, 12, 18], months_max: 24, bootstrap_replicas: 200,
km: { months: meses, S: decreciente(0.7), low: decreciente(0.6), high: decreciente(0.8) }, km_adjusted: { months: meses, S: decreciente(0.72) },
weibull: { t: [0, 12, 24], S: [1, 0.85, 0.72] }, weibull_fractional: { t: [0, 12, 24], S: [1, 0.84, 0.71] },
points: { LR: serie([0.93, 0.85, 0.78]), HBN: serie([0.92, 0.84, 0.77]), COMB: serie([0.925, 0.845, 0.775]) }, etiquetas: {} } });
const fila = (escenario: string, extra: object = {}) => ({ escenario, riesgo_definitorios: 'Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)', riesgo_mayoritarios: 'HER2=H3 (sugerente, 60%)',
n_factores_riesgo_incluidos: 3, incluye_factor_riesgo: true, ...extra });
const texto = (f: { nativeElement: unknown }) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
function plotly() {
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
const runtime = { react: vi.fn(() => Promise.resolve()), purge: vi.fn(), Plots: { resize: vi.fn(() => Promise.resolve()) },
addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) };
return { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) };
}
function elegir(f: { nativeElement: unknown; detectChanges(): void }, etiqueta: string, valor: string) {
const select = [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!.querySelector('select')!;
select.value = valor;
select.dispatchEvent(new Event('change'));
f.detectChanges();
}
describe('Factores de riesgo: la etiqueta', () => {
const montar = (f: object | null) => {
const fx = TestBed.createComponent(CamaFactoresRiesgo);
fx.componentRef.setInput('fila', f);
fx.detectChanges();
return fx;
};
// Fails if an entry is cut at the wrong place or its strength is read from anything but its own parentheses.
it('reads the entries of a cell and whether each is robust', () => {
expect(entradasDe('Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)')).toEqual([
{ texto: 'Grado=G3 (robusto, 97%)', robusto: true }, { texto: 'Ki67=alto (sugerente, 96%)', robusto: false }]);
expect(entradasDe('')).toEqual([]);
});
// Fails if the two groups lose their order or a robust factor is not told from a suggestive one.
it('lists the defining factors, then the majority ones, a robust one solid and a suggestive one outlined', () => {
const fx = montar(fila('< 45 años'));
const items = [...(fx.nativeElement as HTMLElement).querySelectorAll('li')];
expect(texto(fx)).toContain('Factores de riesgo de este escenario');
expect(items.map(i => i.textContent!.trim())).toEqual(['Grado=G3 (robusto, 97%)', 'Ki67=alto (sugerente, 96%)', 'HER2=H3 (sugerente, 60%)']);
expect(items.map(i => i.classList.contains('robust'))).toEqual([true, false, false]);
});
// Fails if a scenario with no factors is shown empty, or with a different message.
it.each([[null], [fila('X', { incluye_factor_riesgo: false })], [fila('X', { n_factores_riesgo_incluidos: 0 })]])('says there are none (%#)', f => {
const fx = montar(f);
expect(texto(fx)).toContain('Sin factores de riesgo identificados en este escenario.');
expect((fx.nativeElement as HTMLElement).querySelector('li')).toBeNull();
});
});
describe('Análisis de supervivencia', () => {
let consulta: ReturnType<typeof vi.fn>;
beforeEach(() => {
consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: nombre === 'Estadio I' ? null : fila(nombre) }));
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], predeterminado: 'Estadio I' }), consulta } }] });
});
afterEach(() => vi.unstubAllGlobals());
const montar = () => {
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
f.componentRef.setInput('pacId', '7');
f.detectChanges();
f.detectChanges();
return f;
};
// Fails if the menu does not open on the patient's scenario, or offers anything but the scenarios the API listed.
it('opens on the patient\'s scenario with the menu the API gave', () => {
const f = montar();
const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim());
expect(opciones).toEqual(['< 45 años', 'Estadio I']);
expect(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I');
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
});
// Fails if choosing a scenario changes only the curve or only the label: the selector decides both at once, one scenario at a time.
it('changes the curve and the label together when another scenario is chosen, and never draws two', () => {
const f = montar();
expect(texto(f)).toContain('Sin factores de riesgo identificados'); // Estadio I has no row
elegir(f, 'Escenario clínico', '< 45 años');
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
});
});
describe('Análisis de recurrencia', () => {
// Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2.
it('scales the y axis to the months it draws', () => {
const largo = { ...figura('metabric', 'Largo'), observado_hasta: 300, months_max: 72,
km: { months: Array.from({ length: 301 }, (_, i) => i), S: Array.from({ length: 301 }, (_, i) => 1 - i / 400), low: Array.from({ length: 301 }, (_, i) => (i <= 72 ? 0.85 : 0.2)), high: Array.from({ length: 301 }, () => 1) } };
expect((figuraRecurrencia(respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios: [largo], resumen: [], predeterminado: null }).escenarios[0]).layout as any).yaxis.range[0]).toBeGreaterThan(0.5);
});
const figura = (cohorte: string, escenario: string) => ({ cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, n: 300, recaidas: 180,
horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72,
km: { months: Array.from({ length: 61 }, (_, i) => i), S: Array.from({ length: 61 }, (_, i) => 1 - i / 200), low: Array.from({ length: 61 }, (_, i) => 1 - i / 190), high: Array.from({ length: 61 }, () => 1) },
weibull: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, weibull_fractional: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, points: { COMB: { S: [0.9, 0.8, 0.7], low: [0.85, 0.75, 0.65], high: [0.95, 0.85, 0.75] } } });
const resumen = (cohorte: string, escenario: string, h: number) => ({ cohorte, escenario, horizonte_meses: h, riesgo_definitorios: `Marca=${cohorte}-${h} (robusto, 99%)`, riesgo_mayoritarios: '',
n_factores_riesgo_incluidos: 1, incluye_factor_riesgo: true });
const respuesta = () => respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60],
escenarios: [figura('metabric', '< 45 años'), figura('metabric', 'Tumor >50 mm'), figura('scanb', '< 45 años'), figura('scanb', 'Grado 3')],
resumen: ['metabric', 'scanb'].flatMap(c => [12, 36, 60].flatMap(h => [resumen(c, '< 45 años', h), resumen(c, 'Tumor >50 mm', h), resumen(c, 'Grado 3', h)])),
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' } });
beforeEach(() => TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(respuesta()) } }] }));
afterEach(() => vi.unstubAllGlobals());
const montar = () => {
const f = TestBed.createComponent(CamaAnalisisRecurrencia);
f.componentRef.setInput('pacId', '7');
f.detectChanges();
f.detectChanges();
return f;
};
const opciones = (f: { nativeElement: unknown }, etiqueta: string) => [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!
.querySelectorAll('option');
// Fails if the menus do not open on the patient's cohort and scenario, or the scenario list is not that of the cohort chosen.
it('opens on the patient\'s cohort and scenario, with only that cohort\'s scenarios', () => {
const f = montar();
expect([...opciones(f, 'Cohorte')].map(o => o.textContent!.trim())).toEqual(['METABRIC', 'SCAN-B']);
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Grado 3']);
expect(texto(f)).toContain('Marca=scanb-60'); // her scenario, the label at 60 months
});
// Fails if a change of cohort leaves the other cohort's scenarios, curve or label on screen: the cohorts are never mixed.
it('reloads the scenarios, the curve and the label when the cohort changes, and keeps one curve', () => {
const f = montar();
elegir(f, 'Cohorte', 'metabric');
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Tumor >50 mm']);
expect(texto(f)).toContain('Marca=metabric-60');
expect(texto(f)).not.toContain('scanb');
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
});
// Fails if the label ignores the horizon, or does not open on 60 months.
it('shows the label at the horizon chosen, 60 months by default', () => {
const f = montar();
expect((f.nativeElement as HTMLElement).querySelector<HTMLSelectElement>('.horizons select')!.value).toBe('60');
elegir(f, 'Horizonte', '12');
expect(texto(f)).toContain('Marca=scanb-12');
expect(texto(f)).not.toContain('Marca=scanb-60');
});
});
@@ -0,0 +1,122 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, map, Observable, of, throwError } from 'rxjs';
// The cohort's survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the
// model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the
// version they come from and says when the data are simulated. A 404 is "no model in production yet".
export interface SerieDeSupervivencia { S: number[]; low: number[]; high: number[]; }
export interface CurvasSupervivencia {
escenario?: string;
n: number; events: number; median_follow_up_months: number;
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
km: { months: number[]; S: number[]; low: number[]; high: number[] };
km_adjusted: { months: number[]; S: number[] };
weibull: { t: number[]; S: number[] };
weibull_fractional: { t: number[]; S: number[] };
points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia };
etiquetas: Record<string, string>;
}
export interface RespuestaCurvas {
modelo: { nombre: string; version: string };
curvas: CurvasSupervivencia;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length);
const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
function invalid(): never {
throw new Error('Respuesta de curvas de supervivencia inválida');
}
function serie(v: unknown, horizons: number): SerieDeSupervivencia {
if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid();
const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[];
if (low.some((l, i) => l > high[i])) invalid();
return { S: s, low, high };
}
/** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */
export function respuestaCurvas(v: unknown): RespuestaCurvas {
if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid();
const m = v['modelo'] as Record<string, unknown>, c = v['curvas'] as Record<string, unknown>;
if (!text(m['nombre']) || !text(m['version'])) invalid();
const horizons = c['horizons_months'];
if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events'])
|| !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid();
const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points'];
if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length)
|| !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid();
if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid();
for (const curve of [weibull, fractional]) {
if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid();
}
if (!record(points)) invalid();
const p = points as Record<string, unknown>, h = (horizons as number[]).length;
const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record<string, string> : {};
return {
modelo: { nombre: m['nombre'] as string, version: m['version'] as string },
curvas: {
escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined,
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'],
points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas,
},
};
}
/** The scenario summary's row of a scenario: its risk factors. `riesgo_*` are entries `Variable=Categoría (robusto|sugerente, porcentaje)`
* separated by `;`; `horizonte_meses` and `cohorte` only in the recurrence analysis. */
export interface FilaFactores {
escenario: string; riesgo_definitorios: string; riesgo_mayoritarios: string;
n_factores_riesgo_incluidos: number; incluye_factor_riesgo: boolean; horizonte_meses?: number; cohorte?: string;
}
export function filaFactores(v: unknown): FilaFactores {
if (!record(v) || typeof v['escenario'] !== 'string') invalid();
const f = v as Record<string, any>;
return { escenario: f['escenario'], riesgo_definitorios: typeof f['riesgo_definitorios'] === 'string' ? f['riesgo_definitorios'] : '',
riesgo_mayoritarios: typeof f['riesgo_mayoritarios'] === 'string' ? f['riesgo_mayoritarios'] : '',
n_factores_riesgo_incluidos: Number.isFinite(f['n_factores_riesgo_incluidos']) ? f['n_factores_riesgo_incluidos'] : 0,
incluye_factor_riesgo: f['incluye_factor_riesgo'] === true || f['incluye_factor_riesgo'] === 'True',
...(Number.isFinite(f['horizonte_meses']) ? { horizonte_meses: f['horizonte_meses'] } : {}), ...(typeof f['cohorte'] === 'string' ? { cohorte: f['cohorte'] } : {}) };
}
/** The scenarios the menu offers, and the one the patient belongs to first. */
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; predeterminado: string | null; }
/** A scenario's figure with its risk factors (`null`: it has no summary row). */
export interface EscenarioConFactores { respuesta: RespuestaCurvas; factores: FilaFactores | null; }
/** The selection was refused with a reason (a 422): a scenario with too few patients, or one that does not exist. */
export class SeleccionRechazada extends Error {}
@Injectable({ providedIn: 'root' })
export class CamaCurvasService {
private readonly http = inject(HttpClient);
/** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */
escenarios(pacId: string): Observable<MenuEscenarios | null> {
return this.http.get<unknown>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe(
map(r => {
if (!record(r) || !Array.isArray(r['escenarios'])) invalid();
const lista = (r['escenarios'] as unknown[]).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
return { escenarios: lista, predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
}),
catchError(() => of(null)),
);
}
/** The figure of one scenario scored with the production version over the data ingested so far, and its risk factors. A refused
* scenario fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */
consulta(escenario: string): Observable<EscenarioConFactores> {
return this.http.post<unknown>('/cama/modelo/curvas/consulta', { escenario }).pipe(
map(r => ({ respuesta: respuestaCurvas(r), factores: record(r) && r['factores'] ? filaFactores(r['factores']) : null })),
catchError(error => error instanceof HttpErrorResponse && error.status === 422
? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'El escenario no se puede calcular.')))
: throwError(() => error)),
);
}
}
@@ -0,0 +1,17 @@
@if (hay()) {
<p class="title">Factores de riesgo de este escenario</p>
@if (definitorios().length) {
<div class="group"><span class="marker" aria-hidden="true">▲</span>
<ul aria-label="Presentes en al menos 95 % del escenario">
@for (e of definitorios(); track e.texto) { <li [class.robust]="e.robusto" [class.suggestive]="!e.robusto">{{ e.texto }}</li> }
</ul></div>
}
@if (mayoritarios().length) {
<div class="group"><span class="marker" aria-hidden="true">▲</span>
<ul aria-label="Presentes en 50 a 95 % del escenario">
@for (e of mayoritarios(); track e.texto) { <li [class.robust]="e.robusto" [class.suggestive]="!e.robusto">{{ e.texto }}</li> }
</ul></div>
}
} @else {
<p class="none">Sin factores de riesgo identificados en este escenario.</p>
}
@@ -0,0 +1,9 @@
:host { display: block; }
.title { font-weight: 600; margin: 0 0 .5rem; }
.group { display: flex; gap: .5rem; align-items: flex-start; margin: .25rem 0; }
.marker { color: var(--mat-sys-error, #b3261e); line-height: 1.9; }
ul { display: flex; flex-wrap: wrap; gap: .4rem; list-style: none; margin: 0; padding: 0; }
li { border: 1px solid var(--mat-sys-error, #b3261e); border-radius: 1rem; padding: .15rem .7rem; font-size: .9rem; }
li.robust { background: var(--mat-sys-error, #b3261e); color: var(--mat-sys-on-error, #fff); }
li.suggestive { background: transparent; color: var(--mat-sys-error, #b3261e); }
.none { color: var(--mat-sys-outline, #777); margin: 0; }
@@ -0,0 +1,26 @@
import { Component, computed, input } from '@angular/core';
import { FilaFactores } from './cama-curvas.service';
export interface EntradaFactor { texto: string; robusto: boolean; }
/** The entries of a summary cell, `Variable=Categoría (robusto|sugerente, porcentaje)` separated by `;`. */
export function entradasDe(celda: string): EntradaFactor[] {
return celda.split(';').map(e => e.trim()).filter(Boolean).map(texto => ({ texto, robusto: /\(\s*robusto\b/i.test(texto) }));
}
/**
* The risk factors of one clinical scenario, from its row of the scenario summary: the factors present in at least 95 % of the scenario
* and those in 50 to 95 %, a robust one solid and a suggestive one outlined. A scenario with none says so, in grey.
*/
@Component({
selector: 'app-cama-factores-riesgo',
templateUrl: './cama-factores-riesgo.component.html',
styleUrl: './cama-factores-riesgo.component.scss',
})
export class CamaFactoresRiesgo {
readonly fila = input<FilaFactores | null>(null);
readonly definitorios = computed(() => entradasDe(this.fila()?.riesgo_definitorios ?? ''));
readonly mayoritarios = computed(() => entradasDe(this.fila()?.riesgo_mayoritarios ?? ''));
readonly hay = computed(() => (this.fila()?.incluye_factor_riesgo ?? false) && (this.fila()?.n_factores_riesgo_incluidos ?? 0) > 0
&& this.definitorios().length + this.mayoritarios().length > 0);
}
@@ -11,6 +11,7 @@
<dl class="summary">
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
<div><dt>Escenario clínico</dt><dd>{{ p.clinicalScenario ?? notAvailable }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
<div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div>
@@ -36,12 +37,21 @@
<mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title">
<mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header>
<mat-card-content>
<ul>
@for (item of placeholders; track item.key) {
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
}
</ul>
<p class="availability">{{ recommendationsUnavailable }}</p>
@if (p.idField === 'pac_id' && p.clinicalScenario === postTreatment) { <app-cama-analisis-recurrencia [pacId]="p.patientId" /> }
<section aria-labelledby="recomendaciones-pronostico-title">
<h5 id="recomendaciones-pronostico-title">Recomendaciones</h5>
<p class="availability">{{ recommendationsUnavailable }}</p>
</section>
</mat-card-content>
</mat-card>
<mat-card class="risk-card" appearance="outlined" aria-labelledby="riesgo-individual-title">
<mat-card-header><h3 id="riesgo-individual-title">Riesgo de muerte</h3></mat-card-header>
<mat-card-content>
@if (p.idField === 'pac_id') { <app-cama-analisis-supervivencia [pacId]="p.patientId" /> }
<section aria-labelledby="recomendaciones-riesgo-title">
<h5 id="recomendaciones-riesgo-title">Recomendaciones</h5>
<p class="availability">{{ recommendationsUnavailable }}</p>
</section>
</mat-card-content>
</mat-card>
</div>
@@ -1,22 +1,27 @@
// Covers CaMa's individual record: how a follow-up row becomes its summary, what the card shows (only fields the list
// carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus
// carries, "No disponible" for the rest, the two analyses with their risk factors in the order Luis's specification gives), and its focus
// and back behaviour. Fixture: fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { EMPTY, of } from 'rxjs';
import { CamaCurvasService } from './cama-curvas.service';
import { CamaRecurrenciaService } from './cama-recurrencia.service';
import { PACIENTE_RIESGO_PROVIDER } from '../paciente-riesgo.provider';
import fixtureData from '../../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
import { CamaPatientCard } from './cama-patient-card';
import { CamaPatientSummary, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
import { CamaPatientSummary, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
const rows = () => seguimientoTablaResponse(structuredClone(fixtureData)).items;
const complete = () => rows().find(r => r['biopsia'] !== null && r['dias_mastografia_diagnostico'] !== null)!;
const incomplete = () => rows().find(r => r['biopsia'] === null)!;
const withPacId = (escenario: string | null = null) => ({ ...complete(), pac_id: '7', id_seudonimo: null, escenario_clinico: escenario });
describe('Ficha CaMa: resumen', () => {
// Fails if a field of the row is mapped to another one or lost on the way to the card.
it('reads every field the follow-up row carries', () => {
const row = complete();
expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], clinicalScenario: null, status: row['estatus'], priority: row['prioridad'],
birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'],
daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'],
});
@@ -39,6 +44,11 @@ describe('Ficha CaMa: resumen', () => {
describe('Ficha CaMa: componente', () => {
let fixture: ReturnType<typeof TestBed.createComponent<CamaPatientCard>>;
const root = () => fixture.nativeElement as HTMLElement;
// The record asks for the analyses; here there is no model in production, so the card shows what the list carries.
beforeEach(() => TestBed.configureTestingModule({ providers: [
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } },
{ provide: CamaCurvasService, useValue: { escenarios: () => of(null), consulta: () => EMPTY } },
{ provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(null) } }] }));
function montar(summary: CamaPatientSummary) {
fixture = TestBed.createComponent(CamaPatientCard);
fixture.componentRef.setInput('summary', summary);
@@ -71,17 +81,28 @@ describe('Ficha CaMa: componente', () => {
expect(text).toContain('Días de mastografía a diagnóstico');
});
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
it('has placeholders, with no figures, for recurrence, survival and prognostic factors', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
const items = [...root().querySelectorAll('[data-pronostico]')];
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'survival', 'factors']);
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico']);
for (const item of items) {
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
expect(item.textContent).not.toMatch(/\d/);
}
expect(root().textContent).toContain(RECOMMENDATIONS_UNAVAILABLE);
// Fails if the cards or their subsections leave the order and the names of the specification: recurrence first, then death, each with
// its risk factors, and the recommendations unchanged (not available) in both.
it('has "Pronóstico y recomendaciones" (recurrence, risk factors, recommendations) before "Riesgo de muerte" (survival, risk factors, recommendations)', () => {
montar(toCamaPatientSummary(withPacId('Post-tratamiento'), '2026-10-20')!);
const card = (selector: string) => root().querySelector(selector) as HTMLElement;
const subsections = (selector: string) => [...card(selector).querySelectorAll('h5')].map(h => h.textContent!.trim());
expect([...root().querySelectorAll('mat-card h3')].map(h => h.textContent!.trim()).slice(-2)).toEqual(['Pronóstico y recomendaciones', 'Riesgo de muerte']);
expect(subsections('.prognosis-card')).toEqual(['Análisis de recurrencia', 'Factores de riesgo', 'Recomendaciones']);
expect(subsections('.risk-card')).toEqual(['Análisis de supervivencia', 'Factores de riesgo', 'Recomendaciones']);
expect(root().textContent!.split(RECOMMENDATIONS_UNAVAILABLE).length - 1).toBe(2);
expect(root().textContent).not.toMatch(/Información simulada|Entorno DEV|Riesgo individual CaMa|Probabilidad de recurrencia|Factores pronóstico/);
});
// Fails if a patient who has not been treated is shown the recurrence analysis (and its factors), which only makes sense after treatment.
it('shows the recurrence analysis only to a patient after treatment', () => {
montar(toCamaPatientSummary(withPacId('En observación'), '2026-10-20')!);
const subsections = (selector: string) => [...(root().querySelector(selector) as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim());
expect(subsections('.prognosis-card')).toEqual(['Recomendaciones']);
expect(subsections('.risk-card')).toEqual(['Análisis de supervivencia', 'Factores de riesgo', 'Recomendaciones']);
expect(root().textContent).not.toContain('Análisis de recurrencia');
});
// Fails if the record opens without moving focus to its title, which strands keyboard and screen-reader users.
@@ -3,17 +3,20 @@ import { downloadBlob, exportFilename } from '../../export/download-file';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
CamaPatientSummary, NOT_AVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models';
/**
* Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
* survival and prognostic factors are placeholders until a validated model supplies them.
* Individual record of a CaMa follow-up patient. It shows what the follow-up list carries, the recurrence analysis with its risk
* factors ("Pronóstico y recomendaciones") and the survival analysis with its risk factors ("Riesgo de muerte"), one clinical
* scenario at a time (the recurrence analysis only for patients after treatment); the recommendations are not available yet.
*/
@Component({
selector: 'app-cama-patient-card',
imports: [MatButtonModule, MatCardModule, MatIconModule],
imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia],
templateUrl: './cama-patient-card.html',
styleUrl: './cama-patient-card.scss',
})
@@ -21,8 +24,8 @@ export class CamaPatientCard implements AfterViewInit {
readonly summary = input.required<CamaPatientSummary>();
readonly back = output<void>();
readonly notAvailable = NOT_AVAILABLE;
readonly placeholders = PROGNOSIS_PLACEHOLDERS;
readonly prognosisUnavailable = PROGNOSIS_UNAVAILABLE;
/** The recurrence analysis is for patients who have been treated: it is shown only in this clinical scenario. */
readonly postTreatment = 'Post-tratamiento';
readonly recommendationsUnavailable = RECOMMENDATIONS_UNAVAILABLE;
private readonly title = viewChild<ElementRef<HTMLElement>>('title');
readonly generating = signal(false);
@@ -21,6 +21,7 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo
...section('Resumen', [
[patient.idLabel, patient.patientId],
['Grupo de edad', patient.ageGroup],
['Escenario clínico', patient.clinicalScenario],
['Estatus de seguimiento', patient.status],
['Prioridad', patient.priority],
['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis],
@@ -14,6 +14,8 @@ export interface CamaPatientSummary {
idLabel: string;
cutoff: string;
ageGroup: string | null;
/** «Post-tratamiento» or «En observación» at the cut-off. */
clinicalScenario: string | null;
status: string | null;
priority: string | null;
birads: string | null;
@@ -25,7 +27,8 @@ export interface CamaPatientSummary {
daysMammographyToDiagnosis: number | null;
}
/** Placeholders for results that exist only once a validated model and its clinical definition do. */
/** Placeholders for results that exist only once a validated model and its clinical definition do: what the exported PDF of the
* record says about them (on screen, the analyses and their risk factors are drawn from the models). */
export const PROGNOSIS_PLACEHOLDERS = [
{ key: 'recurrence', label: 'Probabilidad de recurrencia' },
{ key: 'survival', label: 'Supervivencia' },
@@ -51,6 +54,7 @@ export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas:
idLabel: ETIQUETA_IDENTIDAD[identity.campo],
cutoff,
ageGroup: text(row['grupo_edad']),
clinicalScenario: text(row['escenario_clinico']),
status: text(row['estatus']),
priority: text(row['prioridad']),
birads: text(row['birads']),
@@ -0,0 +1,53 @@
import { PlotlyFigure, Tema } from '../../indicadores.models';
import { FiguraRecurrencia } from './cama-recurrencia.service';
export const ETIQUETAS_RECURRENCIA = {
eje_x: 'Meses desde el diagnóstico', eje_y: 'Libre de recaída S(t)', km: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull',
weibull_fraccional: 'Weibull fraccional', puntos: 'LR + HBN combinado (IC 95 % bootstrap)',
} as const;
export const COLORES_RECURRENCIA = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a' } as const;
/** A curve in two parts: solid up to the follow-up the cohort has, dotted after it (the extrapolation). */
function curva(t: number[], S: number[], hasta: number, color: string, nombre: string, dash?: string): Record<string, unknown>[] {
const dentro = t.map((x, i) => i).filter(i => t[i] <= hasta), fuera = t.map((x, i) => i).filter(i => t[i] >= hasta);
return [
{ type: 'scatter', mode: 'lines', x: dentro.map(i => t[i]), y: dentro.map(i => S[i]), line: { color, width: 3, ...(dash ? { dash } : {}) }, name: nombre, legendgroup: nombre,
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + nombre + '</extra>' },
{ type: 'scatter', mode: 'lines', x: fuera.map(i => t[i]), y: fuera.map(i => S[i]), line: { color, width: 1.8, dash: 'dot' }, showlegend: false, legendgroup: nombre, hoverinfo: 'skip' },
];
}
/**
* The recurrence analysis' figure of one scenario of one cohort, as the pipeline draws it: the Kaplan-Meier curve of the scenario's
* patients with its Greenwood band, the classic and the fractional Weibull (dotted past the follow-up), and the recurrence-free
* probability at each horizon by the combination of the LR and the HBN, as diamonds with their bootstrap interval.
*/
export function figuraRecurrencia(f: FiguraRecurrencia, tema: Tema = 'claro'): PlotlyFigure {
const L = ETIQUETAS_RECURRENCIA, d = f.points.COMB, km = f.km;
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
const visibles = (t: number[], S: number[]) => S.filter((_, i) => t[i] <= f.months_max);
const minimo = Math.max(0, Math.floor((Math.min(...visibles(km.months, km.low), ...visibles(f.weibull.t, f.weibull.S), ...visibles(f.weibull_fractional.t, f.weibull_fractional.S), ...d.low) - 0.02) * 20) / 20);
const data: Record<string, unknown>[] = [
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES_RECURRENCIA.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES_RECURRENCIA.km, width: 2, shape: 'hv' }, name: L.km, legendgroup: 'km',
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + L.km + '</extra>' },
...curva(f.weibull.t, f.weibull.S, f.observado_hasta, COLORES_RECURRENCIA.weibull, L.weibull),
...curva(f.weibull_fractional.t, f.weibull_fractional.S, f.observado_hasta, COLORES_RECURRENCIA.fraccional, L.weibull_fraccional, 'dash'),
{ type: 'scatter', mode: 'markers', name: L.puntos, x: f.horizons_months, y: d.S,
marker: { symbol: 'diamond', size: 15, color: COLORES_RECURRENCIA.modelo, line: { color: 'white', width: 1.5 } },
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES_RECURRENCIA.modelo, thickness: 2, width: 6,
array: d.high.map((hi, i) => Math.max(0, hi - d.S[i])), arrayminus: d.S.map((s, i) => Math.max(0, s - d.low[i])) },
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + L.puntos + '</extra>' },
];
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
const layout: Record<string, unknown> = {
title: { text: `${f.escenario}<br>${f.cohorte_nombre} · n=${f.n.toLocaleString('es-MX')}, recaídas=${f.recaidas.toLocaleString('es-MX')}`, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
xaxis: { ...eje, title: { text: L.eje_x }, range: [0, f.months_max + 0.8], dtick: 12 },
yaxis: { ...eje, title: { text: L.eje_y }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
};
return { data, layout, config: { responsive: true, displaylogo: false } };
}
@@ -0,0 +1,65 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, map, Observable, of } from 'rxjs';
import { FilaFactores, filaFactores } from './cama-curvas.service';
// CaMa's recurrence figures of a patient, `GET /cama/modelo/recurrencia?paciente=`: the clinical scenarios her covariates meet,
// each as the recurrence analysis of an external cohort (METABRIC or SCAN-B) drew it. They describe the scenario's patients in
// that cohort, not her; the answer names the version that published them. A 404 or a failure is "none to show".
export interface FiguraRecurrencia {
cohorte: string; cohorte_nombre: string; escenario: string; n: number; recaidas: number;
horizons_months: number[]; observado_hasta: number; months_max: number;
km: { months: number[]; S: number[]; low: number[]; high: number[] };
weibull: { t: number[]; S: number[] };
weibull_fractional: { t: number[]; S: number[] };
points: { COMB: { S: number[]; low: number[]; high: number[] } };
}
export interface RespuestaRecurrencia {
modelo: { nombre: string; version: string }; horizontes: number[]; escenarios: FiguraRecurrencia[];
/** The summary's rows, one per cohort, scenario and horizon: the risk-factor label. */
resumen: FilaFactores[];
/** The cohort and scenario the patient's own covariates place her in first, if any. */
predeterminado: { cohorte: string; escenario: string } | null;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number' && Number.isFinite(x)) && (length === undefined || v.length === length);
const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1);
function invalid(): never { throw new Error('Respuesta de recurrencia inválida'); }
function figura(v: unknown, horizons: number): FiguraRecurrencia {
if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte_nombre'] !== 'string' || typeof v['cohorte'] !== 'string') invalid();
const f = v as Record<string, any>;
if (!numbers(f['horizons_months'], horizons) || !Number.isFinite(f['n']) || !Number.isFinite(f['recaidas']) || !Number.isFinite(f['observado_hasta']) || !Number.isFinite(f['months_max'])) invalid();
const km = f['km'], w = f['weibull'], k = f['weibull_fractional'], p = f['points']?.['COMB'];
const n = Array.isArray(km?.months) ? km.months.length : -1;
if (!numbers(km?.months) || !probabilities(km?.S, n) || !probabilities(km?.low, n) || !probabilities(km?.high, n)) invalid();
for (const c of [w, k]) if (!numbers(c?.t) || !probabilities(c?.S, c.t.length)) invalid();
if (!probabilities(p?.S, horizons) || !probabilities(p?.low, horizons) || !probabilities(p?.high, horizons)) invalid();
if ((p.low as number[]).some((l, i) => l > p.high[i])) invalid();
return f as FiguraRecurrencia;
}
/** Validate at the boundary: the shapes and ranges, so the chart never draws a partial or impossible curve. */
export function respuestaRecurrencia(v: unknown): RespuestaRecurrencia {
if (!record(v) || !record(v['modelo']) || !Array.isArray(v['escenarios']) || !numbers(v['horizontes'])) invalid();
const m = v['modelo'] as Record<string, unknown>, h = (v['horizontes'] as number[]).length;
if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid();
if (!Array.isArray(v['resumen'])) invalid();
const d = v['predeterminado'];
return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, horizontes: v['horizontes'] as number[],
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)), resumen: (v['resumen'] as unknown[]).map(filaFactores),
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null };
}
@Injectable({ providedIn: 'root' })
export class CamaRecurrenciaService {
private readonly http = inject(HttpClient);
/** The recurrence analysis of both cohorts and the patient's default, or `null` when there is no recurrence model in production or it fails. */
recurrencia(pacId: string): Observable<RespuestaRecurrencia | null> {
return this.http.get<unknown>('/cama/modelo/recurrencia', { params: { paciente: pacId } }).pipe(
map(respuestaRecurrencia), catchError(() => of(null)));
}
}
@@ -0,0 +1,49 @@
import { PlotlyFigure, Tema } from '../../indicadores.models';
import { CurvasSupervivencia } from './cama-curvas.service';
/** The wording of the chart, as the SEER pipeline's own figure has it. The model's run can publish another wording for any
* of these (`[config.etiquetas]`), so the clinicians define it, not the code. */
export const ETIQUETAS_PREDETERMINADAS: Readonly<Record<string, string>> = {
eje_x: 'Meses desde el diagnóstico', eje_y: 'Supervivencia S(t)',
km_crudo: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull', weibull_fraccional: 'Weibull fraccional',
puntos: 'LR + HBN combinado (IC 95 % bootstrap)',
};
export const COLORES = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a' } as const;
const etiqueta = (c: CurvasSupervivencia, clave: string) => c.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave;
/**
* The SEER pipeline's survival figure of one clinical scenario: the Kaplan-Meier curve of its patients with its Greenwood band,
* the classic and the fractional Weibull, and the model's survival at each horizon as diamonds with their bootstrap interval.
* Titled with the scenario, its patients and its deaths.
*/
export function figuraSupervivencia(c: CurvasSupervivencia, tema: Tema = 'claro'): PlotlyFigure {
const km = c.km, diamantes = c.points.COMB, t = (clave: string) => etiqueta(c, clave);
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
const minimo = Math.max(0, Math.floor((Math.min(...km.low, ...c.weibull_fractional.S, ...diamantes.low) - 0.02) * 20) / 20);
const data: Record<string, unknown>[] = [
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km, width: 2, shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km',
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('km_crudo') + '</extra>' },
{ type: 'scatter', mode: 'lines', x: c.weibull.t, y: c.weibull.S, line: { color: COLORES.weibull, width: 3 }, name: t('weibull'),
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull') + '</extra>' },
{ type: 'scatter', mode: 'lines', x: c.weibull_fractional.t, y: c.weibull_fractional.S, line: { color: COLORES.fraccional, width: 3, dash: 'dash' }, name: t('weibull_fraccional'),
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull_fraccional') + '</extra>' },
{ type: 'scatter', mode: 'markers', name: t('puntos'), x: c.horizons_months, y: diamantes.S,
marker: { symbol: 'diamond', size: 15, color: COLORES.modelo, line: { color: 'white', width: 1.5 } },
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.modelo, thickness: 2, width: 6,
array: diamantes.high.map((hi, i) => hi - diamantes.S[i]), arrayminus: diamantes.S.map((s, i) => s - diamantes.low[i]) },
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('puntos') + '</extra>' },
];
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
const layout: Record<string, unknown> = {
title: { text: `${c.escenario ?? 'Toda la cohorte'}<br>n=${c.n.toLocaleString('es-MX')}, fallecidos=${c.events.toLocaleString('es-MX')}`, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
xaxis: { ...eje, title: { text: t('eje_x') }, range: [0, c.months_max + 0.8], dtick: 5 },
yaxis: { ...eje, title: { text: t('eje_y') }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
};
return { data, layout, config: { responsive: true, displaylogo: false } };
}
@@ -13,7 +13,7 @@
</header>
@if (estado.tipo === 'cargando') { <p role="status">Cargando información…</p> }
@if (estado.tipo === 'no-disponible') { <p class="availability" role="status">Información no disponible.</p> }
@if (estado.tipo === 'error') { <p class="availability" role="alert">No se pudo cargar la información de este paciente. Regresa a Seguimiento para intentar de nuevo.</p> }
@if (estado.tipo === 'error') { <p class="availability" role="alert">No se pudo cargar la información de este paciente. Regresa a Análisis de riesgos para intentar de nuevo.</p> }
@if (registrosTemporales.length) { <p class="pending-changes" role="status">Cambios sin guardar</p> }
<div class="detail-grid">
<mat-card class="history-card" appearance="outlined" aria-labelledby="historial-title">
@@ -0,0 +1,100 @@
// Covers the patient's risk in CaMa's record: the table asks the CaMa endpoint (and CaCu's calls stay as they were), says
// whose model scored her, shows the mortality at the horizons the model gives (6, 12 and 18 months) and the model's
// index date; the CaMa record does not show it (its two analyses replace it). Fixtures: a Bundle like `GET /cama/fhir/RiskAssessment?subject=
// Patient/7` answers it (`riesgoCamaEjemplo`), and a provider that returns it.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { CamaPatientCard } from './cama/cama-patient-card';
import { CamaPatientSummary } from './cama/cama-patient.models';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
import { EMPTY } from 'rxjs';
import { CamaCurvasService } from './cama/cama-curvas.service';
import { CamaRecurrenciaService } from './cama/cama-recurrencia.service';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { INTERVALO, prediccion } from './paciente-riesgo.testing';
const CS = 'https://isssteleon.org/fhir/CodeSystem';
/** TEST ONLY. Patient 7's current CaMa `RiskAssessment`: mortality at 6, 12 and 18 months from the model's index date. */
function riesgoCamaEjemplo(): any {
const muerte = (p: number, fin: string) => {
const item = prediccion(p, '2025-06-19', fin);
item.outcome = { coding: [{ system: `${CS}/desenlace`, code: 'muerte', display: 'Muerte por cualquier causa' }] };
return item;
};
return {
resourceType: 'Bundle', type: 'searchset', total: 1,
entry: [{
fullUrl: 'http://localhost/cama/fhir/RiskAssessment/3-7',
resource: {
resourceType: 'RiskAssessment', id: '3-7', status: 'final',
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
subject: { reference: 'Patient/7' }, occurrenceDateTime: '2026-01-02T10:00:00Z',
method: { coding: [{ system: `${CS}/modelo`, code: 'cama-survival', version: '1' }] },
prediction: [muerte(0.07, '2025-12-19'), muerte(0.178, '2026-06-19'), muerte(0.251, '2026-12-19')],
},
search: { mode: 'match' },
}],
};
}
const resumen = (idField: 'pac_id' | 'id_seudonimo'): CamaPatientSummary => ({
patientId: '7', idField, idLabel: 'pac_id', cutoff: '2026-01-01', ageGroup: '50-59', status: null, priority: null,
birads: 'B5', mammographyDate: '2025-06-01', histopathology: 'CARCINOMA_INVASOR', biopsyDate: '2025-06-19',
daysMammographyToDiagnosis: null, clinicalScenario: null,
});
describe('Riesgo individual de la paciente CaMa', () => {
const obtener = vi.fn();
beforeEach(() => {
obtener.mockReset().mockImplementation(() => of(riesgoCamaEjemplo()));
TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener } },
{ provide: CamaCurvasService, useValue: { escenarios: () => of(null), consulta: () => EMPTY } },
{ provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(null) } }] });
});
// Fails if the table stops asking the domain it was given, or if CaCu's call changes shape (`obtener(pacId)` only).
it('asks its domain for the patient, and CaCu with the id alone', () => {
const cama = TestBed.createComponent(PacienteRiesgoTabla);
cama.componentRef.setInput('pacId', '7');
cama.componentRef.setInput('dominio', 'cama');
cama.detectChanges();
const cacu = TestBed.createComponent(PacienteRiesgoTabla);
cacu.componentRef.setInput('pacId', '7');
cacu.detectChanges();
expect(obtener).toHaveBeenNthCalledWith(1, '7', 'cama');
expect(obtener).toHaveBeenNthCalledWith(2, '7');
expect(cama.nativeElement.textContent).toContain('Riesgo individual CaMa');
expect(cacu.nativeElement.textContent).toContain('Riesgo individual CaCu');
});
// Fails if the mortality, its outcome, the model or the index date of the Bundle are not what the card shows.
it('shows the model, the index date, the outcome and the mortality at each horizon', () => {
const f = TestBed.createComponent(PacienteRiesgoTabla);
f.componentRef.setInput('pacId', '7');
f.componentRef.setInput('dominio', 'cama');
f.detectChanges();
const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
expect(text).toContain('cama-survival');
expect(text).toContain('2025-06-19');
expect(text).toContain('Muerte por cualquier causa');
expect(text).toContain('7 %');
expect(text).toContain('17.8 %');
expect(text).toContain('25.1 %');
expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/);
expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
});
// Fails if the CaMa record goes back to showing the individual risk table, which its two analyses replace.
it('is not in the CaMa record: its analyses and their risk factors are', () => {
const f = TestBed.createComponent(CamaPatientCard);
f.componentRef.setInput('summary', resumen('pac_id'));
f.detectChanges();
expect(obtener).not.toHaveBeenCalled();
expect(f.nativeElement.querySelector('app-paciente-riesgo-tabla')).toBeNull();
expect(INTERVALO).toContain('intervalo-confianza');
});
});
@@ -0,0 +1,137 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { of } from 'rxjs';
import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoCacuCancerSinEstimar, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
import { conIntervalo, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
// What the patient's risk says about its number (the model's `[estimand]`) and the curve of its horizons.
describe('Riesgo individual: qué se estima y su curva', () => {
function setup(data: unknown) {
const react = vi.fn(() => Promise.resolve());
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(data) } },
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ react, purge: vi.fn(), Plots: { resize: vi.fn() },
addFrames: vi.fn(), deleteFrames: vi.fn() }) }] });
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
fixture.componentRef.setInput('pacId', '42');
fixture.detectChanges();
fixture.detectChanges();
return { fixture, root: fixture.nativeElement as HTMLElement };
}
it('lee el estimando conocido e ignora claves que no conoce (también el método del intervalo, que es del reporte); sin extensión queda en null', () => {
expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({
quantity: 'Riesgo acumulado', description: 'Probabilidad de CIN2+ antes de cada horizonte.',
outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años' });
expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista());
});
it('rechaza un estimando mal formado', () => {
const data = riesgoCacuConEstimando();
data.entry[0].resource.extension[0].extension = 'texto';
expect(() => riesgoPacienteResponse(data, '42')).toThrow();
});
it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => {
const { root } = setup(riesgoCacuConEstimando());
expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim()))
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
expect(root.querySelector('details.risk-details summary')!.textContent).toContain('Detalle del modelo');
for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma']) {
expect(root.textContent).toContain(value);
}
expect(root.textContent).not.toContain('método delta');
});
it('dibuja la curva solo al abrir su sección', async () => {
const { fixture, root } = setup(riesgoCacuConEstimando());
const details = root.querySelector('details.risk-curve') as HTMLDetailsElement;
expect(details.querySelector('summary')!.textContent).toContain('Curva de riesgo acumulado');
expect(root.querySelector('app-plotly-chart')).toBeNull();
details.open = true;
details.dispatchEvent(new Event('toggle'));
fixture.detectChanges();
expect(root.querySelector('app-plotly-chart')).not.toBeNull();
});
it('la figura une los horizontes y pone el intervalo como banda, o como barras si falta en alguno', () => {
const riesgo = riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo;
const banda = figuraRiesgoPaciente([riesgo]);
expect(banda.data).toHaveLength(3);
expect(banda.data[2]['y']).toEqual([8, 21, 34]);
expect(banda.data[1]['y']).toEqual([5, 15, 26]);
expect((banda.layout['yaxis'] as any).title.text).toBe('Riesgo acumulado (%)');
const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) };
const barras = figuraRiesgoPaciente([parcial]);
expect(barras.data).toHaveLength(1);
expect((barras.data[0]['error_y'] as any).array[0]).toBe(0);
});
it('pone una columna por desenlace, LIEAG+ primero, con el IC entre paréntesis', () => {
const { root } = setup(riesgoCacuDosDesenlaces());
expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim()))
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
const fila = [...root.querySelectorAll('tbody tr')][2];
expect([...fila.querySelectorAll('td')].map(td => td.textContent!.replace(/\s+/g, ' ').trim()))
.toEqual(['34 % (26 – 44 %)', '1.5 % (0.8 – 2.8 %)']);
});
it('la frase dice los resultados índice y los dos riesgos al horizonte más largo, respectivamente', () => {
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
expect(riesgos.map(r => r.desenlace)).toEqual(['cin2_mas', 'cancer']);
expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen un riesgo '
+ 'acumulado a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), '
+ 'respectivamente.');
expect(fraseRiesgo(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')!.riesgos)).toBeNull();
});
it('dibuja una curva por desenlace, cada una con su banda', () => {
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
const figura = figuraRiesgoPaciente(riesgos);
const lineas = figura.data.filter(t => t['mode'] === 'lines+markers');
expect(lineas.map(t => t['name'])).toEqual(['LIEAG+', 'cáncer']);
expect((lineas[1]['y'] as number[]).map(v => Math.round(v * 10) / 10)).toEqual([0.4, 0.9, 1.5]);
expect(figura.data.filter(t => t['fill'] === 'tonexty')).toHaveLength(2);
expect((figura.layout['xaxis'] as any).title.text).toBe('Horizonte (años desde la fecha índice (2026-06-01))');
});
it('escribe los porcentajes con los decimales que un riesgo pequeño necesita', () => {
expect([0.34, 0.178, 0.015, 0.004, 0.00123, 0, 0.1, 1].map(porcentaje))
.toEqual(['34', '17.8', '1.5', '0.4', '0.123', '0', '10', '100']);
expect(conIntervalo({ horizonte_anios: 1, probabilidad: 0.2, ic_bajo: null, ic_alto: null })).toBe('20 % (IC no disponible)');
});
it('un desenlace con otra fecha índice la dice en su columna y queda fuera de la frase', () => {
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
const muerte = { ...riesgos[1], desenlace: 'muerte', fecha_indice: '2024-03-01' };
expect(encabezado(muerte, riesgos[0].fecha_indice)).toBe('Probabilidad a muerte desde 2024-03-01');
expect(fraseRiesgo([riesgos[0], muerte])).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) '
+ 'tienen un riesgo acumulado a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).');
});
it('sin modelo de un desenlace su columna dice No disponible', () => {
const { root } = setup(riesgoCacuConEstimando());
const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
expect(celdas).toEqual(['No disponible', 'No disponible', 'No disponible']);
});
it('con un modelo que no la estima su columna lo dice, con el motivo, y no entra en la curva ni en la frase', () => {
const data = riesgoCacuCancerSinEstimar();
const { root } = setup(data);
const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
expect(celdas).toEqual(['No estimada para su grupo', 'No estimada para su grupo', 'No estimada para su grupo']);
expect(root.querySelector('.unavailable-note')!.textContent).toContain('queda fuera de su población');
const { riesgos, riesgo } = riesgoPacienteResponse(data, '42')!;
expect(riesgo.desenlace).toBe('cin2_mas');
expect(riesgos[1]).toMatchObject({ desenlace: 'cancer', horizontes: [], sin_estimacion: 'queda fuera de su población' });
expect(figuraRiesgoPaciente(riesgos.filter(r => r.horizontes.length)).data.filter(t => t['mode'] === 'lines+markers'))
.toHaveLength(1);
});
});
@@ -0,0 +1,60 @@
import { PlotlyFigure } from '../indicadores.models';
import { conIntervalo, etiquetaDesenlace } from './paciente-riesgo.presentacion';
import { tieneIntervalo } from './paciente-riesgo.validation';
import { LoteRiesgoCacu } from './paciente-riesgo.models';
/** One color per curve, in the order of the outcomes (CIN2+, cancer, any other). */
const COLORES = ['#6a3d9a', '#b2182b', '#1f78b4'];
const BANDAS = ['rgba(106,61,154,.18)', 'rgba(178,24,43,.16)', 'rgba(31,120,180,.16)'];
/**
* The patient's risk of each outcome at the model's horizons as small curves on one axis: the points joined by a
* line, with the interval as a band where every horizon has one and as error bars otherwise. In percent; the axis
* names follow the first model's estimand, and the x axis says the index date the horizons count from.
*/
export function figuraRiesgoPaciente(riesgos: LoteRiesgoCacu[]): PlotlyFigure {
const data: Record<string, unknown>[] = [];
let maximo = 0;
riesgos.forEach((riesgo, k) => {
const h = riesgo.horizontes, x = h.map(p => p.horizonte_anios), y = h.map(p => p.probabilidad * 100);
const color = COLORES[k % COLORES.length], nombre = etiquetaDesenlace(riesgo);
const conIc = h.map(tieneIntervalo);
const banda = conIc.length > 1 && conIc.every(Boolean);
if (banda) {
data.push(
{ type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_alto! * 100), line: { width: 0 }, showlegend: false,
hoverinfo: 'skip', legendgroup: nombre },
{ type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_bajo! * 100), fill: 'tonexty',
fillcolor: BANDAS[k % BANDAS.length], line: { width: 0 }, name: `IC 95 % ${nombre}`, hoverinfo: 'skip',
legendgroup: nombre },
);
}
const barras = !banda && conIc.some(Boolean) ? {
error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 2, width: 6,
array: h.map((p, i) => conIc[i] ? (p.ic_alto! - p.probabilidad) * 100 : 0),
arrayminus: h.map((p, i) => conIc[i] ? (p.probabilidad - p.ic_bajo!) * 100 : 0) },
} : {};
data.push({
type: 'scatter', mode: 'lines+markers', x, y, name: nombre, legendgroup: nombre, line: { color, width: 2 },
marker: { color, size: 9, line: { color: 'white', width: 2 } }, ...barras,
customdata: h.map(conIntervalo),
hovertemplate: `%{x} ${riesgo.estimando?.horizons_unit ?? 'años'}: %{customdata}<extra>${nombre}</extra>`,
});
maximo = Math.max(maximo, ...h.map(p => (tieneIntervalo(p) ? p.ic_alto! : p.probabilidad) * 100));
});
const primero = riesgos[0];
const unidad = primero?.estimando?.horizons_unit ?? 'años';
const fechas = [...new Set(riesgos.map(r => r.fecha_indice))];
const desde = fechas.length === 1 ? `la fecha índice (${fechas[0]})`
: `la fecha índice de cada desenlace (${riesgos.map(r => `${etiquetaDesenlace(r)}: ${r.fecha_indice}`).join('; ')})`;
return {
data,
layout: {
margin: { l: 56, r: 16, t: 16, b: 48 }, showlegend: true, legend: { orientation: 'h', y: -0.25 },
xaxis: { title: { text: `Horizonte (${unidad} desde ${desde})` },
tickvals: [...new Set(riesgos.flatMap(r => r.horizontes.map(p => p.horizonte_anios)))], zeroline: false },
yaxis: { title: { text: `${primero?.estimando?.quantity ?? 'Probabilidad'} (%)` }, rangemode: 'tozero',
range: [0, Math.max(maximo * 1.15, 1)], zeroline: false },
},
};
}
@@ -1,4 +1,4 @@
<h4>Riesgo individual CaCu</h4>
<h4>Riesgo individual {{ rotulo() }}</h4>
@let lectura = estado();
@switch (lectura.tipo) {
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
@@ -7,61 +7,66 @@
}
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
@case ('disponible') {
<p class="simulated-label" id="riesgo-simulado">Información simulada · Entorno DEV · Sin evaluación clínica</p>
@if (lectura.datos.cohorte; as cohorte) {
<h5>Cohorte</h5>
<dl class="metadata">
<div><dt>Definición de cohorte</dt><dd>{{ cohorte.url }}</dd></div>
<div><dt>Versión de cohorte</dt><dd>{{ cohorte.version }}</dd></div>
<div><dt>Fecha índice</dt><dd>{{ cohorte.fecha_indice }}</dd></div>
</dl>
<details>
<summary>Variables del modelo PIMM</summary>
<p class="availability">Códigos técnicos del modelo; no constituyen un diagnóstico.</p>
<dl class="metadata">
<div><dt>tipo_censura</dt><dd>{{ cohorte.tipo_censura ?? 'No disponible' }}</dd></div>
<div><dt>c (estado basal)</dt><dd>{{ cohorte.c ?? 'No disponible' }}</dd></div>
<div><dt>l (años desde índice)</dt><dd>{{ cohorte.l ?? 'No disponible' }}</dd></div>
<div><dt>r (años desde índice)</dt><dd>{{ cohorte.r ?? 'No disponible' }}</dd></div>
<div><dt>pap_0 (citología índice)</dt><dd>{{ cohorte.pap_0 ?? 'No disponible' }}</dd></div>
<div><dt>hpv_0 (VPH índice)</dt><dd>{{ cohorte.hpv_0 ?? 'No disponible' }}</dd></div>
</dl>
@let todos = lectura.datos.riesgos;
@let riesgos = conRiesgo(todos);
@let riesgo = lectura.datos.riesgo;
@let columnas = columnasDe(todos);
@let filas = filasDe(lotesDe(columnas));
@if (filas.length) {
<div class="risk-scroll" role="region" aria-label="Riesgos por horizonte, tabla desplazable" tabindex="0">
<table>
<caption>{{ riesgo.estimando?.quantity ?? 'Probabilidad' }} por horizonte desde la fecha índice
({{ riesgo.fecha_indice }}), con su intervalo de confianza entre paréntesis</caption>
<thead><tr>
<th scope="col">Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }})</th>
@for (c of columnas; track c.encabezado) { <th scope="col">{{ c.encabezado }} (%)</th> }
</tr></thead>
<tbody>
@for (f of filas; track f.horizonte_anios) {
<tr>
<th scope="row">{{ f.horizonte_anios }}</th>
@for (c of f.celdas; track $index; let i = $index) {
<td>@if (columnas[i].vacia; as vacia) {<span class="unavailable">{{ vacia }}</span>} @else if (c) {<span class="percentage">{{ porcentaje(c.probabilidad) }} %</span>{{ ' ' }}<span class="interval">@if (tieneIntervalo(c)) {({{ porcentaje(c.ic_bajo!) }} – {{ porcentaje(c.ic_alto!) }} %)} @else {(IC no disponible)}</span>} @else {—}</td>
}
</tr>
}
</tbody>
</table>
</div>
@for (c of columnas; track c.encabezado) {
@if (c.lote?.sin_estimacion; as motivo) { <p class="unavailable-note">{{ c.encabezado }}: {{ motivo }}.</p> }
}
<details class="risk-details">
<summary>Detalle del modelo</summary>
@for (r of riesgos; track r.id) {
@if (riesgos.length > 1) { <h6>{{ encabezado(r) }}</h6> }
<dl class="metadata">
<div><dt>Modelo</dt><dd>{{ r.modelo_nombre }}</dd></div>
<div><dt>Versión del modelo</dt><dd>{{ r.modelo_version }}</dd></div>
<div><dt>Fecha índice</dt><dd>{{ r.fecha_indice }}</dd></div>
<div><dt>Desenlace</dt><dd>{{ r.desenlace_texto ?? r.desenlace }}</dd></div>
<div><dt>Evaluado en</dt><dd><time [attr.datetime]="r.evaluado_en">{{ instante(r.evaluado_en) }}</time></dd></div>
<div><dt>Estado del lote</dt><dd>{{ r.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
@if (r.estimando; as e) {
@if (e.quantity) { <div><dt>Qué se estima</dt><dd>{{ e.quantity }}@if (e.description) {: {{ e.description }}}</dd></div> }
@if (e.outcome) { <div><dt>Desenlace del modelo</dt><dd>{{ e.outcome }}</dd></div> }
@if (e.index_date) { <div><dt>Desde</dt><dd>{{ e.index_date }}</dd></div> }
@if (e.horizons_unit) { <div><dt>Horizontes en</dt><dd>{{ e.horizons_unit }}</dd></div> }
}
</dl>
}
</details>
} @else {
<p role="status">Sin membresía en la cohorte vigente.</p>
}
@if (lectura.datos.riesgo; as riesgo) {
<h5>Modelo y evaluación</h5>
<dl class="metadata">
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
</dl>
@if (riesgo.horizontes.length) {
<div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0">
<table aria-describedby="riesgo-simulado">
<caption>Probabilidades simuladas por horizonte desde la fecha índice</caption>
<thead><tr>
<th scope="col">Horizonte (años)</th>
<th scope="col">Probabilidad (%)</th>
<th scope="col">Intervalo de confianza (%)</th>
<th scope="col">Estado de evaluación</th>
</tr></thead>
<tbody>
@for (h of riesgo.horizontes; track h.horizonte_anios) {
<tr>
<th scope="row">{{ h.horizonte_anios }}</th>
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
<td>{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</td>
</tr>
}
</tbody>
</table>
</div>
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
} @else { <p role="status">Sin riesgo disponible: no hay lote vigente.</p> }
@if (filas.length > 1) {
<details class="risk-curve" (toggle)="curvaAbierta.set($any($event.target).open)">
<summary>Curva{{ riesgos.length > 1 ? 's' : '' }} de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo</summary>
@if (frase(riesgos); as texto) { <p class="risk-sentence">{{ texto }}</p> }
@if (curvaAbierta()) {
<app-plotly-chart [style.--plot-height]="'300px'" [showNotes]="false" [figure]="figura(riesgos)"
[label]="'Curvas de riesgo individual ' + rotulo() + ' por horizonte'" />
}
</details>
}
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
}
}
<p class="recommendations">Recomendaciones no disponibles.</p>
@@ -18,3 +18,9 @@ thead th { position: sticky; top: 0; background: var(--issste-background, var(--
tbody th, td { background: var(--issste-surface); }
tbody tr:last-child > * { border-bottom: 0; }
.percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; }
.risk-curve { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; }
.risk-sentence { margin: .25rem 0 .75rem; line-height: 1.5; }
.risk-details { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; }
.risk-details h6 { margin: .75rem 0 .25rem; font-size: .95rem; }
.unavailable { color: var(--issste-text-secondary); }
.unavailable-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; }
@@ -1,11 +1,22 @@
import { Component, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { Component, computed, effect, inject, input, signal } from '@angular/core';
import { LowerCasePipe } from '@angular/common';
import { PlotlyChart } from '../../../shared/plotly/plotly-chart';
import { PlotlyFigure } from '../indicadores.models';
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
import { ColumnaRiesgo, columnasRiesgo, conRiesgo, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models';
import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation';
/** A UTC instant as the day and the minute it happened, so it reads next to the index date (a calendar day, not an instant). */
export const instanteUtc = (iso: string) => {
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(iso);
return m ? `${m[1]} ${m[2]} UTC` : iso;
};
@Component({
selector: 'app-paciente-riesgo-tabla',
imports: [DecimalPipe],
imports: [LowerCasePipe, PlotlyChart],
providers: [PacienteRiesgoState],
templateUrl: './paciente-riesgo-tabla.html',
styleUrl: './paciente-riesgo-tabla.scss',
@@ -13,11 +24,29 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
export class PacienteRiesgoTabla {
/** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */
readonly pacId = input.required<string | null>();
/** The domain whose model scored her: CaCu unless said otherwise. */
readonly dominio = input<DominioRiesgo>('cacu');
readonly rotulo = computed(() => this.dominio() === 'cama' ? 'CaMa' : 'CaCu');
private readonly state = inject(PacienteRiesgoState);
readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo;
readonly instante = instanteUtc;
/** The curve is drawn only while its section is open, so Plotly isn't loaded for a closed one. */
readonly curvaAbierta = signal(false);
readonly porcentaje = porcentaje;
readonly encabezado = encabezado;
readonly etiqueta = etiquetaDesenlace;
readonly frase = fraseRiesgo;
readonly filasDe = filasRiesgo;
readonly conRiesgo = conRiesgo;
columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio()); }
lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); }
private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure };
figura(riesgos: LoteRiesgoCacu[]): PlotlyFigure {
if (this.figuraDe?.riesgos !== riesgos) this.figuraDe = { riesgos, figura: figuraRiesgoPaciente(riesgos) };
return this.figuraDe.figura;
}
constructor() {
effect(() => this.state.pacId.set(this.pacId()));
effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); });
}
}
@@ -1,48 +1,72 @@
import { Observable } from 'rxjs';
export type EstadoEvaluacionCacu = 'preliminary' | 'final';
export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo';
export interface CohorteRiesgoCacu {
url: string;
version: string;
fecha_indice: string;
tipo_censura: TipoCensuraCacu | null;
c: number | null;
l: number | null;
r: number | null;
pap_0: string | null;
hpv_0: string | null;
}
/** The domain whose patient's risk is read: its FHIR endpoint is `/<dominio>/fhir`. CaCu unless said otherwise. */
export type DominioRiesgo = 'cacu' | 'cama';
export interface HorizonteRiesgoCacu {
/** Years from the risk's index date: the length of the prediction's `whenPeriod`; 0 is the immediate risk. */
horizonte_anios: number;
/** Transport values remain probabilities in [0, 1], never percentages. */
probabilidad: number;
ic_bajo?: number | null;
ic_alto?: number | null;
estado: EstadoEvaluacionCacu;
}
/** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */
export interface EstimandoRiesgo {
/** e.g. "Riesgo acumulado"; also `method.text`. */
quantity?: string;
description?: string;
outcome?: string;
index_date?: string;
/** The unit the horizons are counted in, e.g. "años". */
horizons_unit?: string;
}
/** The results of the cytology sampled on the risk's index date (extension `resultados-indice`), as recorded. */
export interface ResultadosIndice {
escamosas?: string;
glandulares?: string;
/** `POSITIVO`, `NEGATIVO` or `INDETERMINADO`. */
vph?: string;
}
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
export interface LoteRiesgoCacu {
lote_id: number;
/** The resource's id, `<lote_id>-<pac_id>`. */
id: string;
modelo_nombre: string;
modelo_version: string;
/** The model's index date for this patient (the predictions' `whenPeriod.start`): the horizons count from it. */
fecha_indice: string;
evaluado_en: string;
estado_lote: EstadoEvaluacionCacu;
/** The prediction's outcome code (e.g. `cin2_mas`) and its display. */
desenlace: string;
desenlace_texto: string | null;
horizontes: HorizonteRiesgoCacu[];
/** `null` for a model whose scenario doesn't say. */
estimando: EstimandoRiesgo | null;
/** `null` when no cytology was sampled on the index date (or the domain doesn't give it). */
resultados_indice: ResultadosIndice | null;
/** Why a current model of this outcome has no risk for her (extension `sin-estimacion`; then `horizontes` is
* empty and `fecha_indice` too); `null` when it scored her. */
sin_estimacion: string | null;
}
/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
/** DEV-only: the patient's current `RiskAssessment` of each outcome, from a `searchset` Bundle tagged `simulado`.
* `riesgos` holds them CIN2+ first, then cancer, then any other; `riesgo` is the first. */
export interface RiesgoPacienteCacu {
simulado: true;
cohorte: CohorteRiesgoCacu | null;
riesgo: LoteRiesgoCacu | null;
riesgo: LoteRiesgoCacu;
riesgos: LoteRiesgoCacu[];
}
/** `null` when the patient has no risk data. */
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider {
obtener(pacId: string): Observable<unknown>;
obtener(pacId: string, dominio?: DominioRiesgo): Observable<unknown>;
}
export type PacienteRiesgoEstado =
@@ -0,0 +1,115 @@
import { HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice } from './paciente-riesgo.models';
import { tieneIntervalo } from './paciente-riesgo.validation';
/** How the record names an outcome in its columns, curves and sentence. */
export function etiquetaDesenlace(lote: LoteRiesgoCacu): string {
if (lote.desenlace.startsWith('cin2')) return 'LIEAG+';
if (lote.desenlace === 'cancer') return 'cáncer';
if (lote.desenlace === 'muerte') return 'muerte';
return lote.desenlace_texto ?? lote.desenlace;
}
/** A column's header: "Probabilidad a LIEAG+", "Probabilidad a cáncer"; with its own index date when it isn't
* `fechaComun` (a survival model counts from the invasive biopsy, not from the cytology). */
export function encabezado(lote: LoteRiesgoCacu, fechaComun: string | null = null): string {
const desde = fechaComun && lote.fecha_indice !== fechaComun ? ` desde ${lote.fecha_indice}` : '';
return `Probabilidad a ${etiquetaDesenlace(lote)}${desde}`;
}
/** A probability as a percentage with the decimals a small risk needs, without trailing zeros: 0.178 -> "17.8",
* 0.015 -> "1.5", 0.00123 -> "0.123", 0.34 -> "34". */
export function porcentaje(p: number): string {
const v = p * 100;
const decimales = v === 0 ? 0 : v < 1 ? 3 : v < 10 ? 2 : 1;
const texto = v.toFixed(decimales);
return texto.includes('.') ? texto.replace(/\.?0+$/, '') : texto;
}
/** The risk with its interval in parentheses, as the table and the sentence write it. */
export function conIntervalo(h: HorizonteRiesgoCacu): string {
const punto = `${porcentaje(h.probabilidad)} %`;
return tieneIntervalo(h) ? `${punto} (${porcentaje(h.ic_bajo!)} – ${porcentaje(h.ic_alto!)} %)` : `${punto} (IC no disponible)`;
}
/** The outcomes a domain's record always has a column for, even with no model: CaCu's CIN2+ and cancer. */
const COLUMNAS_FIJAS: Record<string, { desenlace: string; etiqueta: string }[]> = {
cacu: [{ desenlace: 'cin2', etiqueta: 'LIEAG+' }, { desenlace: 'cancer', etiqueta: 'cáncer' }],
};
const esDe = (lote: LoteRiesgoCacu, desenlace: string) =>
desenlace === 'cin2' ? lote.desenlace.startsWith('cin2') : lote.desenlace === desenlace;
export interface ColumnaRiesgo {
encabezado: string;
/** Its model's risks; `null` when no model of the outcome is current. */
lote: LoteRiesgoCacu | null;
/** What the cells say when there's no risk: no model, or a model that doesn't estimate her. */
vacia: string | null;
}
/** The table's columns: the domain's fixed outcomes (CaCu: LIEAG+ and cancer), with or without a model, then any
* other outcome she has a risk of. A column's index date shows when it isn't the first risk's. */
export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu'): ColumnaRiesgo[] {
const fecha = riesgos.find(r => r.horizontes.length)?.fecha_indice ?? null;
const fijas = COLUMNAS_FIJAS[dominio] ?? [];
const columnas: ColumnaRiesgo[] = fijas.map(({ desenlace, etiqueta }) => {
const lote = riesgos.find(r => esDe(r, desenlace)) ?? null;
if (!lote) return { encabezado: `Probabilidad a ${etiqueta}`, lote: null, vacia: 'No disponible' };
return { encabezado: encabezado(lote, fecha), lote,
vacia: lote.horizontes.length ? null : 'No estimada para su grupo' };
});
for (const lote of riesgos) {
if (fijas.some(f => esDe(lote, f.desenlace)) || !lote.horizontes.length) continue;
columnas.push({ encabezado: encabezado(lote, fecha), lote, vacia: null });
}
return columnas;
}
/** The risks the record can draw and describe: the ones with horizons. */
export const conRiesgo = (riesgos: LoteRiesgoCacu[]) => riesgos.filter(r => r.horizontes.length);
export interface FilaRiesgo {
horizonte_anios: number;
/** One cell per column, in their order; `null` where that column has no risk at this horizon. */
celdas: (HorizonteRiesgoCacu | null)[];
}
/** The table's rows: every horizon any of the columns has, ascending, with each column's risk there. */
export function filasRiesgo(lotes: (LoteRiesgoCacu | null)[]): FilaRiesgo[] {
const horizontes = [...new Set(lotes.flatMap(r => r?.horizontes.map(h => h.horizonte_anios) ?? []))]
.sort((a, b) => a - b);
return horizontes.map(horizonte_anios => ({
horizonte_anios,
celdas: lotes.map(r => r?.horizontes.find(h => h.horizonte_anios === horizonte_anios) ?? null),
}));
}
function resultado(r: ResultadosIndice | null): string | null {
if (!r) return null;
const vph = r.vph === 'POSITIVO' ? 'VPH positivo' : r.vph === 'NEGATIVO' ? 'VPH negativo'
: r.vph ? `VPH ${r.vph.toLowerCase()}` : 'sin resultado de VPH';
const citologia = [r.escamosas, r.glandulares].filter(Boolean).join(' con ');
return `Un resultado de ${vph} y una citología ${citologia || 'sin resultado'}`;
}
/**
* The sentence over the curves: the index results and, at the longest horizon the outcomes of the first one's index
* date share, each outcome's
* cumulative risk of being present at the index visit or developing afterwards, "respectivamente" when there are
* several. `null` without the index results.
*/
export function fraseRiesgo(todos: LoteRiesgoCacu[]): string | null {
const scored = conRiesgo(todos);
const riesgos = scored.filter(r => r.fecha_indice === scored[0]?.fecha_indice); // the outcomes of the same visit
const inicio = resultado(riesgos.find(r => r.resultados_indice)?.resultados_indice ?? null);
if (!inicio) return null;
const comunes = filasRiesgo(riesgos).filter(f => f.celdas.every(c => c !== null));
const ultima = comunes[comunes.length - 1];
if (!ultima) return null;
const fecha = riesgos[0].fecha_indice;
const junta = (xs: string[]) => xs.length > 1 ? `${xs.slice(0, -1).join(', ')} y ${xs[xs.length - 1]}` : xs[0];
const desenlaces = junta(riesgos.map(etiquetaDesenlace));
const valores = junta(ultima.celdas.map(c => conIntervalo(c!)));
const anios = ultima.horizonte_anios === 1 ? '1 año' : `${ultima.horizonte_anios} años`;
return `${inicio} (${fecha}) tienen un riesgo acumulado a ${anios} de estar presente o de aparecer ${desenlaces} `
+ `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`;
}
@@ -1,14 +1,18 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { inject, InjectionToken } from '@angular/core';
import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
// The patient's risk is a FHIR `RiskAssessment` searched by `subject=Patient/<pac_id>`, the identifier a follow-up row
// carries as `pac_id`, in the domain's endpoint (`/cacu/fhir`, or `/cama/fhir`); an empty Bundle (or a 404) is a patient
// without risk data.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
obtener: (pacId: string, dominio = 'cacu') => http.get<unknown>(`/${dominio}/fhir/RiskAssessment`, {
params: new HttpParams().set('subject', `Patient/${pacId}`),
}).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
),
};
@@ -4,8 +4,8 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
import { of, Subject, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { instanteUtc, PacienteRiesgoTabla } from './paciente-riesgo-tabla';
describe('RIESGO-CACU-02: presentación y aislamiento', () => {
function setup(provider?: PacienteRiesgoProvider) {
@@ -22,10 +22,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.inject(HttpTestingController).verify();
});
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
it('pide el RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => {
const f = setup(), root: HTMLElement = f.nativeElement;
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42')
.flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' });
f.detectChanges();
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.textContent).toContain('Recomendaciones no disponibles');
@@ -33,27 +33,34 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
});
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
it('un Bundle vacío es una paciente sin riesgo confirmado', () => {
const f = setup({ obtener: () => of({ resourceType: 'Bundle', type: 'searchset', total: 0 }) });
expect(f.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(f.nativeElement.querySelector('table')).toBeNull();
});
it('renderiza el ejemplo contractual, metadatos y porcentajes sin alterar los datos', () => {
const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data));
data.riesgo!.horizontes[1].estado = 'preliminary';
const baseline = structuredClone(data);
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
expect(root.querySelectorAll('thead th')).toHaveLength(4);
// horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval
expect(root.querySelectorAll('thead th')).toHaveLength(3);
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)');
expect(root.textContent).toContain('Final (final)');
expect(root.textContent).toContain('Preliminar (preliminary)');
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) {
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) {
expect(root.textContent).toContain(value);
}
expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado');
expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV');
// The record no longer shows the cohort's internals (its definition, version or model variables).
expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/);
// The record never says its data are test data: with real information it makes real predictions.
expect(root.textContent).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica|simuladas/);
expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/);
// Internal batch key stays in the contract, never in a UI label.
expect(root.textContent).not.toContain('lote_id');
// The resource id (batch and patient) stays in the contract, never in a UI label.
expect(root.textContent).not.toMatch(/lote_id|12-42/);
expect(data).toEqual(baseline);
});
@@ -67,50 +74,26 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM');
expect(root.textContent).toContain('no constituyen un diagnóstico');
});
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
const data = riesgoCacuEjemplo();
data.riesgo!.estado_lote = 'preliminary';
data.riesgo!.horizontes = [
{ horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' },
{ horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' },
{ horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' },
data.entry[0].resource.status = 'preliminary';
data.entry[0].resource.prediction = [
prediccion(0, '2026-06-01', '2026-12-01', [0, 0]),
prediccion(1, '2026-06-01', '2034-06-01'),
prediccion(0.00123, '2026-06-01', '2038-09-01'),
];
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']);
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']);
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']);
expect(root.textContent).toContain('Preliminar (preliminary)');
});
it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
const data = riesgoCacuEjemplo();
data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null };
const f = setup({ obtener: () => of(data) });
const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent);
expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']);
expect(f.nativeElement.textContent).not.toMatch(/undefined|null/);
});
it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => {
const data = riesgoCacuEjemplo();
if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null;
if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null;
if (caso === 'horizontes') data.riesgo!.horizontes = [];
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente');
if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente');
if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados');
if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull();
expect(root.textContent).toContain('Información simulada');
expect(root.textContent).toContain('Recomendaciones no disponibles');
});
it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => {
const data = { ...riesgoCacuEjemplo(), simulado };
if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag;
const f = setup({ obtener: () => of(data) });
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
@@ -118,7 +101,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
});
it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12;
const f = setup({ obtener: () => of(data) });
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
@@ -134,14 +117,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
it('aísla estado y fixture entre instancias sin reutilizar información', () => {
const source = new Subject<unknown>(), f = setup({ obtener: () => source });
const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges();
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
data.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges();
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
f.destroy();
const otra = TestBed.createComponent(PacienteRiesgoTabla);
otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
expect(otra.nativeElement.querySelector('table')).toBeNull();
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
expect(riesgoCacuEjemplo().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08);
otra.destroy(); expect(source.observed).toBe(false);
});
@@ -153,3 +136,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles');
});
});
describe('instanteUtc', () => {
it('shows the day and the minute of a UTC instant, and leaves anything else as it came', () => {
expect(instanteUtc('2026-11-21T23:17:45.120Z')).toBe('2026-11-21 23:17 UTC');
expect(instanteUtc('no es una fecha')).toBe('no es una fecha');
});
});
@@ -1,7 +1,7 @@
import { Injectable, inject, signal } from '@angular/core';
import { Injectable, computed, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
import { DominioRiesgo, PacienteRiesgoEstado } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
@@ -12,10 +12,15 @@ export class PacienteRiesgoState {
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
// `undefined` until the input is set; `null` is a patient without `pac_id`.
readonly pacId = signal<string | null | undefined>(undefined);
readonly estado = toSignal(toObservable(this.pacId).pipe(
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
readonly dominio = signal<DominioRiesgo>('cacu');
// The patient and her domain are one query, so changing both never asks for the patient in the wrong domain.
private readonly consulta = computed(() => ({ id: this.pacId(), dominio: this.dominio() }));
readonly estado = toSignal(toObservable(this.consulta).pipe(
switchMap(({ id, dominio }) => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => dominio === 'cacu' ? this.provider.obtener(id) : this.provider.obtener(id, dominio)).pipe(
map((respuesta): PacienteRiesgoEstado => {
const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id);
return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos };
}),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
startWith(CARGANDO),
)),
@@ -1,21 +1,113 @@
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
import { LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
export function riesgoCacuEjemplo(): RiesgoPacienteCacu {
const CS = 'https://isssteleon.org/fhir/CodeSystem';
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
export const ESTIMANDO = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
return {
simulado: true,
cohorte: {
url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15',
tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO',
},
riesgo: {
lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0',
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final',
horizontes: [
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' },
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' },
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' },
],
},
outcome: { coding: [{ system: `${CS}/desenlace`, code: 'cin2_mas', display: 'CIN2+ por biopsia' }] },
probabilityDecimal: p, whenPeriod: { start: inicio, end: fin },
...(ic ? { extension: [{ url: INTERVALO, valueRange: { low: { value: ic[0] }, high: { value: ic[1] } } }] } : {}),
};
}
/** TEST ONLY. The external contract example: a `searchset` Bundle with patient 42's current `RiskAssessment`, as
* `GET /cacu/fhir/RiskAssessment?subject=Patient/42` answers it; never belongs to the selected patient. */
export function riesgoCacuEjemplo(): any {
return {
resourceType: 'Bundle', type: 'searchset', total: 1,
entry: [{
fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/12-42',
resource: {
resourceType: 'RiskAssessment', id: '12-42', status: 'final',
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
subject: { reference: 'Patient/42' }, occurrenceDateTime: '2026-10-01T00:00:00Z',
method: { coding: [{ system: `${CS}/modelo`, code: 'modelo-cacu', version: '2.1.0' }] },
prediction: [
prediccion(0.08, '2026-06-01', '2027-06-01', [0.05, 0.12]),
prediccion(0.21, '2026-06-01', '2029-06-01', [0.15, 0.28]),
prediccion(0.34, '2026-06-01', '2031-06-01', [0.26, 0.44]),
],
},
search: { mode: 'match' },
}],
};
}
/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */
export function riesgoCacuVista(): RiesgoPacienteCacu {
const riesgo: LoteRiesgoCacu = {
id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01',
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia',
horizontes: [
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 },
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 },
],
estimando: null,
resultados_indice: null,
sin_estimacion: null,
};
return { simulado: true, riesgo, riesgos: [riesgo] };
}
/** TEST ONLY. `riesgoCacuEjemplo()` from a model whose scenario says what its number is (extension `estimando`). */
export function riesgoCacuConEstimando(): any {
const data = riesgoCacuEjemplo();
const resource = data.entry[0].resource;
resource.method.text = 'Riesgo acumulado';
resource.extension = [{ url: ESTIMANDO, extension: [
{ url: 'quantity', valueString: 'Riesgo acumulado' },
{ url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' },
{ url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' },
{ url: 'horizons_unit', valueString: 'años' },
{ url: 'interval', valueString: 'IC 95 % por método delta' },
{ url: 'otra', valueString: 'se ignora' },
] }];
return data;
}
export const RESULTADOS_INDICE = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice';
/** TEST ONLY. `riesgoCacuConEstimando()` plus a cancer `RiskAssessment` of the same visit, both with the index
* cytology's results: the Bundle a patient scored by the CIN2+ and the cancer models gets. Cancer comes first, as
* the newer batch would. */
export function riesgoCacuDosDesenlaces(): any {
const data = riesgoCacuConEstimando();
const cin2 = data.entry[0].resource;
const resultados = { url: RESULTADOS_INDICE, extension: [
{ url: 'escamosas', valueString: 'LIEBG' }, { url: 'vph', valueString: 'POSITIVO' }] };
cin2.extension.push(resultados);
const cancer = structuredClone(cin2);
cancer.id = '13-42';
cancer.method.coding[0].code = 'modelo-cacu-cancer';
cancer.extension[0].extension = cancer.extension[0].extension.map((e: any) =>
e.url === 'outcome' ? { ...e, valueString: 'Cáncer: biopsia de carcinoma' } : e);
cancer.prediction = [
prediccion(0.004, '2026-06-01', '2027-06-01', [0.002, 0.008]),
prediccion(0.009, '2026-06-01', '2029-06-01', [0.005, 0.016]),
prediccion(0.015, '2026-06-01', '2031-06-01', [0.008, 0.028]),
].map(p => ({ ...p, outcome: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/desenlace', code: 'cancer',
display: 'Cáncer cervicouterino por biopsia' }] } }));
data.entry.unshift({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer });
data.total = 2;
return data;
}
export const SIN_ESTIMACION = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion';
/** TEST ONLY. `riesgoCacuConEstimando()` plus a current cancer model that didn't score her: a `RiskAssessment` with
* no prediction, marked `sin-estimacion`. */
export function riesgoCacuCancerSinEstimar(): any {
const data = riesgoCacuConEstimando();
const cancer = structuredClone(data.entry[0].resource);
cancer.id = '13-42';
delete cancer.prediction;
cancer.extension = [{ url: SIN_ESTIMACION, extension: [{ url: 'desenlace', valueCode: 'cancer' },
{ url: 'motivo', valueString: 'queda fuera de su población' }] }];
data.entry.push({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer });
data.total = 2;
return data;
}
@@ -1,121 +1,89 @@
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { prediccion, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation';
import { TipoCensuraCacu } from './paciente-riesgo.models';
describe('RIESGO-CACU-02: frontera del contrato DEV', () => {
it('conserva todos los campos del ejemplo externo y copia los objetos', () => {
const recurso = (v: any) => v.entry[0].resource;
describe('RIESGO-CACU-02: frontera del contrato FHIR RiskAssessment (DEV)', () => {
it('lee el Bundle searchset en la vista de la ficha y no comparte objetos con la entrada', () => {
const entrada = riesgoCacuEjemplo();
const salida = riesgoPacienteResponse(entrada);
expect(salida).toEqual(entrada);
salida.riesgo!.horizontes[0].probabilidad = 0;
salida.cohorte!.c = -999;
const salida = riesgoPacienteResponse(entrada, '42')!;
expect(salida).toEqual(riesgoCacuVista());
salida.riesgo.horizontes[0].probabilidad = 0;
expect(entrada).toEqual(riesgoCacuEjemplo());
});
it('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
it('un Bundle vacío es una paciente sin riesgo confirmado, con o sin `entry`', () => {
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0 })).toBeNull();
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0, entry: [] })).toBeNull();
});
it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])(
'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => {
const entrada = riesgoCacuEjemplo();
entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null;
expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo);
},
);
it('preserva los nulos independientes y el sentinel basal del contrato', () => {
it('el horizonte sale del whenPeriod; el inmediato es un periodo de un día', () => {
const entrada = riesgoCacuEjemplo();
entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null };
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
entrada.riesgo = null;
entrada.cohorte.c = null;
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
entrada.cohorte = null;
expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null });
recurso(entrada).prediction = [prediccion(0.02, '2026-06-01', '2026-06-01'), prediccion(0.4, '2026-06-01', '2034-06-01')];
expect(riesgoPacienteResponse(entrada)!.riesgo.horizontes.map(h => h.horizonte_anios)).toEqual([0, 8]);
});
it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
it('ordena las predicciones por horizonte y admite campos aditivos de FHIR', () => {
const entrada = riesgoCacuEjemplo();
entrada.cohorte = null;
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
recurso(entrada).prediction.reverse();
recurso(entrada).note = [{ text: 'simulado' }];
expect(riesgoPacienteResponse(entrada)).toEqual(riesgoCacuVista());
});
it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
it.each([[undefined], [[]], [[{ url: 'otra', valueString: 'x' }]]])('sin extensión de intervalo no fabrica límites (%j)', ext => {
const entrada = riesgoCacuEjemplo();
entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({
horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final',
}));
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
});
it.each([
{}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null },
{ ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 },
])('conserva IC incompletos sin generar límites: %j', limites => {
const entrada = riesgoCacuEjemplo();
entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }];
const salida = riesgoPacienteResponse(entrada);
expect(salida).toEqual(entrada);
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false);
const p = recurso(entrada).prediction[0];
if (ext === undefined) delete p.extension; else p.extension = ext;
const h = riesgoPacienteResponse(entrada)!.riesgo.horizontes[0];
expect([h.ic_bajo, h.ic_alto]).toEqual([null, null]);
expect(tieneIntervalo(h)).toBe(false);
});
it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => {
const entrada = riesgoCacuEjemplo();
entrada.riesgo!.estado_lote = 'preliminary';
entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }];
const salida = riesgoPacienteResponse(entrada);
expect(salida).toEqual(entrada);
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true);
recurso(entrada).status = 'preliminary';
recurso(entrada).prediction = [prediccion(p, '2026-06-01', '2030-06-01', [p, p])];
const salida = riesgoPacienteResponse(entrada)!;
expect(salida.riesgo.estado_lote).toBe('preliminary');
expect(salida.riesgo.horizontes[0]).toEqual({ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p });
expect(tieneIntervalo(salida.riesgo.horizontes[0])).toBe(true);
});
const invalidos: [string, (v: any) => void][] = [
['no simulado', v => v.simulado = false],
['simulado string', v => v.simulado = 'true'],
['sin simulado', v => delete v.simulado],
['sin cohorte', v => delete v.cohorte],
['sin riesgo', v => delete v.riesgo],
['cohorte lista', v => v.cohorte = []],
['URL ajena', v => v.cohorte.url = 'otra'],
['versión ausente', v => delete v.cohorte.version],
['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'],
['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'],
['basal string', v => v.cohorte.c = '0'],
['variable no finita', v => v.cohorte.l = Infinity],
['variable omitida', v => delete v.cohorte.r],
['pap no textual', v => v.cohorte.pap_0 = 5],
['hpv no textual', v => v.cohorte.hpv_0 = false],
['lote fraccionario', v => v.riesgo.lote_id = 1.5],
['lote string', v => v.riesgo.lote_id = '12'],
['modelo omitido', v => delete v.riesgo.modelo_nombre],
['versión no textual', v => v.riesgo.modelo_version = 2],
['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'],
['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'],
['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'],
['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'],
['sin horizontes', v => delete v.riesgo.horizontes],
['horizontes nulos', v => v.riesgo.horizontes = null],
['horizonte nulo', v => v.riesgo.horizontes[0] = null],
['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'],
['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN],
['horizontes desordenados', v => v.riesgo.horizontes.reverse()],
['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1],
['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01],
['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01],
['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'],
['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null],
['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN],
['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'],
['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01],
['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01],
['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'],
['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })],
['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07],
['no es Bundle', v => v.resourceType = 'RiskAssessment'],
['Bundle no searchset', v => v.type = 'collection'],
['sin total', v => delete v.total],
['entry no lista', v => v.entry = {}],
['recurso ajeno', v => recurso(v).resourceType = 'Observation'],
['no simulado', v => delete recurso(v).meta],
['etiqueta ajena', v => recurso(v).meta.tag[0].code = 'real'],
['sin id', v => delete recurso(v).id],
['estado desconocido', v => recurso(v).status = 'amended'],
['estado anulado', v => recurso(v).status = 'entered-in-error'],
['otra paciente', v => recurso(v).subject.reference = 'Patient/43'],
['sujeto no paciente', v => recurso(v).subject.reference = 'Group/42'],
['evaluación sin UTC', v => recurso(v).occurrenceDateTime = '2026-10-01T00:00:00-06:00'],
['evaluación fecha imposible', v => recurso(v).occurrenceDateTime = '2026-02-30T00:00:00Z'],
['sin modelo', v => delete recurso(v).method],
['modelo sin versión', v => delete recurso(v).method.coding[0].version],
['sin predicciones', v => recurso(v).prediction = []],
['predicción nula', v => recurso(v).prediction[0] = null],
['sin desenlace', v => delete recurso(v).prediction[0].outcome],
['probabilidad string', v => recurso(v).prediction[0].probabilityDecimal = '0.08'],
['probabilidad mayor a uno', v => recurso(v).prediction[0].probabilityDecimal = 1.01],
['probabilidad negativa', v => recurso(v).prediction[0].probabilityDecimal = -0.01],
['sin periodo', v => delete recurso(v).prediction[0].whenPeriod],
['periodo con fecha imposible', v => recurso(v).prediction[0].whenPeriod.end = '2027-02-30'],
['periodo invertido', v => recurso(v).prediction[0].whenPeriod.end = '2025-06-01'],
['dos fechas índice', v => recurso(v).prediction[1].whenPeriod.start = '2026-07-01'],
['horizontes repetidos', v => recurso(v).prediction[1].whenPeriod.end = '2027-06-01'],
['IC invertido', v => recurso(v).prediction[0].extension[0].valueRange = { low: { value: 0.12 }, high: { value: 0.05 } }],
['IC fuera de probabilidad', v => recurso(v).prediction[0].extension[0].valueRange.high.value = 0.07],
['IC string', v => recurso(v).prediction[0].extension[0].valueRange.high.value = '0.12'],
];
it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => {
const entrada = riesgoCacuEjemplo(); mutar(entrada);
expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida');
expect(() => riesgoPacienteResponse(entrada, '42')).toThrow('Respuesta de riesgo individual DEV inválida');
});
it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => {
expect(() => riesgoPacienteResponse(entrada)).toThrow();
@@ -1,54 +1,164 @@
import { isoDate } from '../cacu-seguimiento.models';
import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice, RiesgoPacienteCacu } from './paciente-riesgo.models';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const nullableNumber = (v: unknown) => v === null || finite(v);
const nullableText = (v: unknown) => v === null || typeof v === 'string';
const text = (v: unknown) => typeof v === 'string';
const estado = (v: unknown) => v === 'preliminary' || v === 'final';
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
const estado = (v: unknown): v is 'preliminary' | 'final' => v === 'preliminary' || v === 'final';
const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
const DAYS_PER_YEAR = 365.25;
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
const SIMULATED = 'simulado';
const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion';
const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice';
const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph'];
const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit'];
function utcTimestamp(v: unknown) {
function utcTimestamp(v: unknown): v is string {
return typeof v === 'string'
&& /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v)
&& isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v));
}
function cohorteValida(v: unknown) {
return v === null || record(v)
&& v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice'])
&& (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string))
&& nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r'])
&& nullableText(v['pap_0']) && nullableText(v['hpv_0']);
function invalid(): never {
throw new Error('Respuesta de riesgo individual DEV inválida');
}
function horizonteValido(v: unknown) {
if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false;
for (const key of ['ic_bajo', 'ic_alto']) {
if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false;
/** Years between two ISO dates, to two decimals: a prediction's horizon from its `whenPeriod`. */
function years(start: string, end: string): number {
const days = (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000;
return Math.round(days / DAYS_PER_YEAR * 100) / 100;
}
function interval(prediction: Record<string, unknown>): { ic_bajo: number | null; ic_alto: number | null } {
const extensions = prediction['extension'];
if (extensions === undefined) return { ic_bajo: null, ic_alto: null };
if (!Array.isArray(extensions)) invalid();
const found = extensions.find(e => record(e) && e['url'] === INTERVAL);
if (found === undefined) return { ic_bajo: null, ic_alto: null };
const range = found['valueRange'];
const low = record(range) && record(range['low']) ? range['low']['value'] : undefined;
const high = record(range) && record(range['high']) ? range['high']['value'] : undefined;
if (!probability(low) || !probability(high) || low > high) invalid();
return { ic_bajo: low, ic_alto: high };
}
/** The resource's extension `url` as its known `keys` with a text value; `null` without that extension. */
function stringExtension<K extends string>(resource: Record<string, unknown>, url: string,
keys: readonly K[]): Partial<Record<K, string>> | null {
const extensions = resource['extension'];
if (extensions === undefined) return null;
if (!Array.isArray(extensions)) invalid();
const found = extensions.find(e => record(e) && e['url'] === url);
if (found === undefined) return null;
if (!Array.isArray(found['extension'])) invalid();
const result: Partial<Record<K, string>> = {};
for (const item of found['extension']) {
if (!record(item) || !text(item['url'])) invalid();
const key = item['url'] as K;
if (keys.includes(key) && text(item['valueString'])) result[key] = item['valueString'];
}
// Missing/null endpoints are preserved. A complete interval must contain the probability.
return !(probability(v['ic_bajo']) && probability(v['ic_alto']))
|| v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto'];
return result;
}
function riesgoValido(v: unknown) {
if (v === null) return true;
if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version'])
|| !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false;
const horizontes = v['horizontes'];
return horizontes.every(horizonteValido)
&& horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']);
const estimand = (resource: Record<string, unknown>): EstimandoRiesgo | null =>
stringExtension(resource, ESTIMAND, ESTIMAND_KEYS);
/** The `sin-estimacion` extension: the outcome of a current model that didn't score her, and why; `null` without it. */
function notScoredOutcome(resource: Record<string, unknown>): { desenlace: string; motivo: string } | null {
const extensions = resource['extension'];
if (!Array.isArray(extensions)) return null;
const found = extensions.find(e => record(e) && e['url'] === NOT_SCORED);
if (found === undefined) return null;
const items = Array.isArray(found['extension']) ? found['extension'].filter(record) : invalid();
const desenlace = items.find(i => i['url'] === 'desenlace')?.['valueCode'];
const motivo = items.find(i => i['url'] === 'motivo')?.['valueString'];
if (!text(desenlace)) invalid();
return { desenlace, motivo: text(motivo) ? motivo : 'el modelo no estima a esta paciente' };
}
/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */
export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu {
if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) {
throw new Error('Respuesta de riesgo individual DEV inválida');
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
const period = prediction['whenPeriod'];
if (!record(period) || !isoDate(period['start']) || !isoDate(period['end'])) invalid();
const from = period['start'] as string, to = period['end'] as string;
if (start !== undefined && from !== start) invalid(); // one index date per patient
const h = years(from, to);
if (h < 0) invalid();
const ic = interval(prediction);
const p = prediction['probabilityDecimal'];
if (ic.ic_bajo !== null && ic.ic_alto !== null && !(ic.ic_bajo <= p && p <= ic.ic_alto)) invalid();
return { horizonte: { horizonte_anios: h, probabilidad: p, ...ic }, start: from };
}
function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
if (!record(v) || v['resourceType'] !== 'RiskAssessment' || !text(v['id']) || !estado(v['status'])
|| !utcTimestamp(v['occurrenceDateTime'])) invalid();
const subject = v['subject'];
if (!record(subject) || !text(subject['reference']) || !subject['reference'].startsWith('Patient/')
|| (pacId !== null && subject['reference'] !== `Patient/${pacId}`)) invalid();
const method = v['method'];
const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined;
if (!record(model) || !text(model['code']) || !text(model['version'])) invalid();
const notScored = notScoredOutcome(v);
if (notScored !== null && v['prediction'] === undefined) {
return {
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
fecha_indice: '', evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
desenlace: notScored.desenlace, desenlace_texto: null, horizontes: [], estimando: estimand(v),
resultados_indice: null, sin_estimacion: notScored.motivo,
};
}
return structuredClone(v) as unknown as RiesgoPacienteCacu;
const predictions = v['prediction'];
if (!Array.isArray(predictions) || predictions.length === 0) invalid();
let start: string | undefined;
const horizontes: HorizonteRiesgoCacu[] = [];
for (const prediction of predictions) {
const found = horizon(prediction, start);
start = found.start;
horizontes.push(found.horizonte);
}
horizontes.sort((a, b) => a.horizonte_anios - b.horizonte_anios);
if (horizontes.some((h, i) => i > 0 && horizontes[i - 1].horizonte_anios === h.horizonte_anios)) invalid();
const outcome = record(predictions[0]) && record(predictions[0]['outcome']) && Array.isArray(predictions[0]['outcome']['coding'])
? predictions[0]['outcome']['coding'][0] : undefined;
if (!record(outcome) || !text(outcome['code'])) invalid();
return {
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
horizontes, estimando: estimand(v), resultados_indice: stringExtension(v, INDEX_RESULTS, INDEX_RESULT_KEYS),
sin_estimacion: null,
};
}
function simulated(resource: Record<string, unknown>): boolean {
const meta = resource['meta'];
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED);
}
/** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */
export function ordenDesenlace(desenlace: string): number {
return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2;
}
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`s, one per outcome, each tagged
* `simulado` (DEV only), and one with no prediction for a current model that didn't score her. `riesgo` is the first
* that has a risk. `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and
* malformed fields. */
export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null {
if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid();
const entries = v['entry'] ?? [];
if (!Array.isArray(entries)) invalid();
if (entries.length === 0) return null;
const riesgos = entries.map(entry => {
const resource = record(entry) ? entry['resource'] : undefined;
if (!record(resource) || !simulated(resource)) invalid();
return riskAssessment(structuredClone(resource), pacId);
});
riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace));
return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos };
}
/** Presentation helper: an incomplete interval must never become a fabricated range. */
@@ -72,7 +72,13 @@ describe('Tabla de seguimiento con pac_id', () => {
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
// Opening a CaMa record asks for the patient's risk; in these tests nobody has one.
afterEach(() => {
http.match(r => r.url === '/cama/fhir/RiskAssessment').forEach(r => { if (!r.cancelled) r.flush({ resourceType: 'Bundle', type: 'searchset', total: 0 }); });
// The record asks for the two analyses of the patient (survival's menu and recurrence's); there is no model for them here.
http.match(r => r.url.startsWith('/cama/modelo/')).forEach(r => { if (!r.cancelled) r.flush({ error: 'sin modelo' }, { status: 404, statusText: 'Not Found' }); });
fixture.destroy(); http.verify();
});
const root = () => fixture.nativeElement as HTMLElement;
const cargar = (respuesta: Record<string, any>) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); };
const enlaces = () => [...root().querySelectorAll<HTMLButtonElement>('tbody button.patient-link')];
@@ -0,0 +1,131 @@
// What this module covers: the screening route chart's model and figure. The model turns the seven C3r payloads of the
// route (days from the sample and days from the previous event, per event) into one row per event for a period, and
// chains the steps one after another; the figure draws them as horizontal bars of days.
// Fixtures: `payload`, synthetic C3r /datos shaped like the WebApi's, with the values of the chart's mockup: a
// cytology result at 7.9 days, a colposcopy at 35.7, a biopsy result at 52.1 and a diagnosis after it at 64.9.
import { IndicadorDatos } from './indicadores.models';
import { C2_PALETTE } from './indicadores-c2-palette';
import { drawnRows, ROUTE_IDS, routeCellText, routeFigure, routeHasData, routeModel, RouteIncompatible } from './screening-route';
type Box = [number, number, number, number];
const row = (periodo: string, [n, q1, mediana, q3]: Box, extra: Record<string, unknown> = {}) =>
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido: 0, unidad: 'dias', ...extra });
const payload = (id: string, filas: Record<string, unknown>[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos =>
({ id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' });
const S2: Record<string, Box> = {
cacu_eu_tiempo_reporte: [4855, 4.9, 7.9, 12.2],
cacu_dias_toma_colposcopia: [864, 22.2, 35.7, 55.4],
cacu_dias_resultado_colposcopia: [864, 17, 27.8, 44],
cacu_dias_toma_biopsia: [454, 32.4, 52.1, 80.8],
cacu_dias_colposcopia_biopsia: [454, 10, 16.4, 26],
cacu_dias_toma_diagnostico: [4999, 11.4, 18.4, 28.5],
cacu_dias_biopsia_diagnostico: [454, 8, 12.8, 20],
};
function all(): Record<string, IndicadorDatos> {
return Object.fromEntries(ROUTE_IDS.map(id => [id, payload(id, [row('2025-S1', [10, 1, 2, 3]), row('2025-S2', S2[id])])]));
}
const figure = (view: 'cumulative' | 'steps', data = all(), period?: string) => routeFigure(routeModel(data, 'semestre', period), view, 'claro');
describe('Ruta del tamizaje: modelo', () => {
it('una fila por evento del periodo más reciente, con los pasos encadenados uno tras otro', () => {
// Pins down: the newest period is the default and each step starts where the previous one ends (7.9 + 27.8 = 35.7,
// + 16.4 = 52.1, + 12.8 = 64.9). Fails if the chain restarts at zero or follows another order.
const m = routeModel(all(), 'semestre');
expect(m.periods).toEqual(['2025-S2', '2025-S1']);
expect(m.period).toBe('2025-S2');
expect(m.rows.map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'biopsy', 'diagnosis']);
expect(m.rows.map(r => [r.start, r.end!.toFixed(1)])).toEqual([[0, '7.9'], [7.9, '35.7'], [35.7, '52.1'], [52.1, '64.9']]);
expect(m.rows[1].fromSample).toEqual({ estado: 'Publicado', n: 864, q1: 22.2, mediana: 35.7, q3: 55.4 });
});
it('un periodo pedido y publicado se usa; uno que no existe cae al más reciente', () => {
// Fails if a period nobody published is shown empty instead of falling back.
expect(routeModel(all(), 'semestre', '2025-S1').period).toBe('2025-S1');
expect(routeModel(all(), 'semestre', '2024-S1').period).toBe('2025-S2');
});
it('sin periodo pedido, el más reciente vacío no se elige: se usa el más reciente con cajas publicadas', () => {
// Fails if the chart opens on a semester that has just begun and shows nothing while an earlier one has data.
const vacio = (id: string) => payload(id, [row('2025-S2', S2[id]), row('2026-S1', [0, null as never, null as never, null as never], { suprimido: 1 })], ['2025-S2', '2026-S1']);
const data = Object.fromEntries(ROUTE_IDS.map(id => [id, vacio(id)]));
expect(routeModel(data, 'semestre').period).toBe('2025-S2');
expect(routeModel(data, 'semestre', '2026-S1').period).toBe('2026-S1');
});
it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => {
// Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box
// becomes a bar or leaves a gap in the chain.
const d = all();
d['cacu_dias_colposcopia_biopsia'] = payload('cacu_dias_colposcopia_biopsia', [row('2025-S2', [454, 10, 16.4, 26], { suprimido: 1 })]);
const m = routeModel(d, 'semestre');
expect(m.rows[2]).toMatchObject({ start: null, end: null });
expect(m.rows[3].start!.toFixed(1)).toBe('35.7');
expect(drawnRows(m, 'steps').map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'diagnosis']);
d['cacu_dias_toma_biopsia'] = payload('cacu_dias_toma_biopsia', []);
expect(drawnRows(routeModel(d, 'semestre'), 'cumulative').map(r => r.step.id)).toEqual(['cytology', 'colposcopy', 'diagnosis']);
});
it('rechaza datos de otro indicador, contrato, tipo de periodo o unidad, y dos totales por periodo', () => {
// Fails if a payload that doesn't belong to the route is drawn as if it did.
const con = (id: string, cambio: Partial<IndicadorDatos>) => ({ ...all(), [id]: { ...all()[id], ...cambio } });
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { id: 'otro' }), 'semestre')).toThrow(RouteIncompatible);
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { contrato: 'C1' }), 'semestre')).toThrow(RouteIncompatible);
expect(() => routeModel(all(), 'mes')).toThrow(RouteIncompatible);
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { filas: [row('2025-S2', S2['cacu_eu_tiempo_reporte'], { unidad: 'horas' })] }), 'semestre')).toThrow(RouteIncompatible);
expect(() => routeModel(con('cacu_eu_tiempo_reporte', { filas: [row('2025-S2', [1, 1, 1, 1]), row('2025-S2', [2, 2, 2, 2])] }), 'semestre')).toThrow(RouteIncompatible);
const sinUno = all(); delete sinUno['cacu_dias_toma_biopsia'];
expect(() => routeModel(sinUno, 'semestre')).toThrow(RouteIncompatible);
});
it('sin periodos publicados no hay nada que dibujar', () => {
// Fails if an empty catalog throws or draws an empty bar.
const vacio = Object.fromEntries(ROUTE_IDS.map(id => [id, payload(id, [], [])]));
const m = routeModel(vacio, 'semestre');
expect(m.period).toBeUndefined();
expect(routeHasData(m)).toBe(false);
expect(routeFigure(m, 'cumulative', 'claro')).toEqual({ data: [], layout: {} });
});
it('la celda de la tabla dice el estado si no hay caja publicada', () => {
expect(routeCellText({ estado: 'Suprimido' })).toBe('Suprimido');
expect(routeCellText(routeModel(all(), 'semestre').rows[0].fromSample)).toBe('n = 4,855, Q1 4.9, mediana 7.9, Q3 12.2 días');
});
});
describe('Ruta del tamizaje: figura', () => {
it('acumulado: barras horizontales hasta la mediana con el intervalo de Q1 a Q3 y el número de casos', () => {
// Pins down: orientation, bar lengths, the asymmetric interval, the case counts in the labels and the first
// event on top. Fails if the bars stop being horizontal or the interval stops being Q1 to Q3.
const f = figure('cumulative');
const trace = f.data[0] as Record<string, any>;
expect(trace['type']).toBe('bar');
expect(trace['orientation']).toBe('h');
expect(trace['x']).toEqual([7.9, 35.7, 52.1, 18.4]);
expect(trace['error_x'].array.map((v: number) => +v.toFixed(1))).toEqual([4.3, 19.7, 28.7, 10.1]);
expect(trace['error_x'].arrayminus.map((v: number) => +v.toFixed(1))).toEqual([3, 13.5, 19.7, 7]);
expect(trace['y'][0]).toBe('Resultado de citología<br>n = 4,855');
expect(trace['y']).toHaveLength(4);
expect((f.layout['yaxis'] as Record<string, unknown>)['autorange']).toBe('reversed');
expect(JSON.stringify(f.data)).not.toContain('null');
});
it('por pasos: cada barra flota desde donde termina la anterior y la más lenta lleva el color', () => {
// Pins down: `base` equals the chained starts, the length is the step's own median, the slowest step (colposcopy,
// 27.8 days) is the only one in colour. Fails if the steps stop floating or the emphasis moves.
const f = figure('steps');
const trace = f.data[0] as Record<string, any>;
expect(trace['base'].map((v: number) => +v.toFixed(1))).toEqual([0, 7.9, 35.7, 52.1]);
expect(trace['x']).toEqual([7.9, 27.8, 16.4, 12.8]);
expect(trace['text']).toEqual(['+7.9 d', '+27.8 d', '+16.4 d', '+12.8 d']);
expect(trace['marker'].color).toEqual([C2_PALETTE.states.noData, C2_PALETTE.series[0], C2_PALETTE.states.noData, C2_PALETTE.states.noData]);
expect(trace['y'][1]).toBe('Del resultado de citología a la colposcopía<br>n = 864');
expect(trace['hovertemplate']).toContain('Hasta el día');
});
it('un paso sin caja se omite de la figura sin dejar huecos', () => {
// Fails if an undrawn step keeps its label or leaves a null in the traces.
const d = all();
d['cacu_dias_toma_biopsia'] = payload('cacu_dias_toma_biopsia', [row('2025-S2', S2['cacu_dias_toma_biopsia'], { suprimido: 1 })]);
const trace = figure('cumulative', d).data[0] as Record<string, any>;
expect(trace['y']).toHaveLength(3);
expect(trace['x']).toEqual([7.9, 35.7, 18.4]);
});
it('el tema oscuro cambia fondo y texto, no los datos', () => {
const claro = figure('steps'), oscuro = routeFigure(routeModel(all(), 'semestre'), 'steps', 'oscuro');
expect(oscuro.layout['paper_bgcolor']).toBe('#081839');
expect(claro.layout['paper_bgcolor']).toBe('#FFFFFF');
expect(oscuro.data[0]['x']).toEqual(claro.data[0]['x']);
});
});
@@ -0,0 +1,134 @@
import { IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { Caja, caja } from './indicadores-tiempos-pareados';
/**
* The screening route as a chain of events timed from the sample: the cytology result, the colposcopy, the biopsy
* result and the diagnosis. Each event has two C3r measures: the days from the sample and the days from the previous
* event. The cytology's step is its own days from the sample.
*/
export interface RouteStep {
id: 'cytology' | 'colposcopy' | 'biopsy' | 'diagnosis';
label: string;
stepLabel: string;
sinceSample: string;
sinceStep: string;
}
export const ROUTE_STEPS: readonly RouteStep[] = [
{ id: 'cytology', label: 'Resultado de citología', stepLabel: 'Toma a resultado de citología',
sinceSample: 'cacu_eu_tiempo_reporte', sinceStep: 'cacu_eu_tiempo_reporte' },
{ id: 'colposcopy', label: 'Resultado de colposcopía', stepLabel: 'Del resultado de citología a la colposcopía',
sinceSample: 'cacu_dias_toma_colposcopia', sinceStep: 'cacu_dias_resultado_colposcopia' },
{ id: 'biopsy', label: 'Resultado de biopsia', stepLabel: 'De la colposcopía al resultado de biopsia',
sinceSample: 'cacu_dias_toma_biopsia', sinceStep: 'cacu_dias_colposcopia_biopsia' },
{ id: 'diagnosis', label: 'Diagnóstico', stepLabel: 'Del resultado de biopsia al diagnóstico',
sinceSample: 'cacu_dias_toma_diagnostico', sinceStep: 'cacu_dias_biopsia_diagnostico' },
];
/** Every measure the chart reads, once each. */
export const ROUTE_IDS: readonly string[] = [...new Set(ROUTE_STEPS.flatMap(s => [s.sinceSample, s.sinceStep]))];
/** The measures only this chart draws: the cytology's and the diagnosis' keep their own cards. */
/** CaCu's measures with no card on the page: the two times to treatment, the proportions without a figure and the risk by band. They are in the history. */
export const CACU_SIN_TARJETA: readonly string[] = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'ind1', 'cacu_eu13', 'cacu_riesgo_banda'];
export const ROUTE_ONLY_IDS: readonly string[] = ROUTE_IDS.filter(id => id !== 'cacu_eu_tiempo_reporte' && id !== 'cacu_dias_toma_diagnostico');
export type RouteView = 'cumulative' | 'steps';
export interface RouteRow {
step: RouteStep;
fromSample: Caja;
fromPrevious: Caja;
/** Where the step starts and ends on the days axis, when chained one after another; null without a published box. */
start: number | null;
end: number | null;
}
export interface RouteModel { period: string | undefined; periods: string[]; rows: RouteRow[]; }
export class RouteIncompatible extends Error {}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const fail = (message: string): never => { throw new RouteIncompatible(message); };
const NOT_AVAILABLE: Caja = { estado: 'No disponible' };
/** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo, requested?: string): RouteModel {
const boxes: Record<string, Record<string, Caja>> = {};
for (const id of ROUTE_IDS) {
const d = data[id];
if (!d || d.id !== id || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|| new Set(d.periodos).size !== d.periodos.length) {
fail('Los datos de tiempos no corresponden a los indicadores de la ruta del tamizaje.');
}
boxes[id] = {};
for (const row of d.filas) {
if (!record(row) || typeof row['periodo'] !== 'string' || !d.periodos.includes(row['periodo'])) fail('Fila C3r fuera de los periodos publicados.');
if (row['grupo'] !== 'TOTAL' || row['estrato'] != null) continue;
if (row['unidad'] !== undefined && row['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.');
const period = row['periodo'] as string;
if (boxes[id][period]) fail('Más de una fila total por periodo.');
boxes[id][period] = caja(row);
}
}
const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse();
// Without a valid request the newest period that has a published box: a semester that has just begun is empty.
const hasData = (p: string) => ROUTE_IDS.some(id => boxes[id][p]?.estado === 'Publicado');
const period = requested && periods.includes(requested) ? requested : periods.find(hasData) ?? periods[0];
let cursor = 0;
const rows = ROUTE_STEPS.map((step): RouteRow => {
const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
const fromPrevious = period ? boxes[step.sinceStep][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
if (fromPrevious.estado !== 'Publicado') return { step, fromSample, fromPrevious, start: null, end: null };
const start = cursor;
cursor += fromPrevious.mediana!;
return { step, fromSample, fromPrevious, start, end: cursor };
});
return { period, periods, rows };
}
/** The rows with a published box for the view. */
export function drawnRows(model: RouteModel, view: RouteView): RouteRow[] {
return model.rows.filter(row => (view === 'cumulative' ? row.fromSample : row.fromPrevious).estado === 'Publicado');
}
export const routeHasData = (model: RouteModel) => drawnRows(model, 'cumulative').length > 0 || drawnRows(model, 'steps').length > 0;
const days = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 });
const count = (v: number) => v.toLocaleString('es-MX');
/**
* Horizontal bars of days. Cumulative: from the sample to each event, with the Q1 to Q3 range as the interval. Steps:
* each step floats from where the previous one ends, and the slowest is the one in colour.
*/
export function routeFigure(model: RouteModel, view: RouteView, tema: Tema): PlotlyFigure {
const t = c2Theme(tema);
const rows = drawnRows(model, view);
if (!rows.length) return { data: [], layout: {} };
const base = { autosize: true, height: 360, showlegend: false, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text },
margin: { t: 24, l: 150, r: 32, b: 56 } };
const axes = {
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', gridcolor: t.grid, zeroline: false, fixedrange: true },
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true },
};
if (view === 'cumulative') {
const boxes = rows.map(row => row.fromSample);
return { data: [{
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.label}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
marker: { color: C2_PALETTE.series[0] },
error_x: { type: 'data', symmetric: false, color: t.text, thickness: 1.5, width: 6,
array: boxes.map(b => b.q3! - b.mediana!), arrayminus: boxes.map(b => b.mediana! - b.q1!) },
customdata: boxes.map(b => [count(b.n!), days(b.q1!), days(b.mediana!), days(b.q3!)]),
hovertemplate: '%{y}<br>Mediana: %{customdata[2]} días<br>Q1 a Q3: %{customdata[1]} a %{customdata[3]} días<extra></extra>',
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
}
const slowest = rows.reduce((best, row, i) => (row.fromPrevious.mediana! > rows[best].fromPrevious.mediana! ? i : best), 0);
const boxes = rows.map(row => row.fromPrevious);
return { data: [{
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.stepLabel}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
base: rows.map(row => row.start),
marker: { color: rows.map((_, i) => (i === slowest ? C2_PALETTE.series[0] : C2_PALETTE.states.noData)) },
text: boxes.map(b => `+${days(b.mediana!)} d`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
customdata: rows.map((row, i) => [count(boxes[i].n!), days(boxes[i].q1!), days(boxes[i].mediana!), days(boxes[i].q3!), days(row.end!)]),
hovertemplate: '%{y}<br>Tramo: %{customdata[2]} días (Q1 a Q3: %{customdata[1]} a %{customdata[3]})<br>Hasta el día %{customdata[4]}<extra></extra>',
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
}
export function routeCellText(box: Caja): string {
return box.estado !== 'Publicado' ? box.estado : `n = ${count(box.n!)}, Q1 ${days(box.q1!)}, mediana ${days(box.mediana!)}, Q3 ${days(box.q3!)} días`;
}
@@ -7,7 +7,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
import fixtureData from './fixtures/cama_seguimiento.json';
import finalResponse from './fixtures/cama_seguimiento-final.json';
import outsideResponse from './fixtures/cama_seguimiento-out-of-range.json';
import { PAGE_SIZE_MAX, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse, validQuery } from './seguimiento-tabla.service';
import { acotarTamano, PAGE_SIZE_MAX, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse, validQuery } from './seguimiento-tabla.service';
const clonar = () => structuredClone(fixtureData) as unknown as Record<string, any>;
const consulta: SeguimientoTablaQuery = { meses: 3, page: 1, page_size: 50 };
@@ -132,3 +132,16 @@ describe('Seguimiento genérico: petición', () => {
});
});
});
describe('acotarTamano', () => {
it('brings a typed page size into 1 to the maximum, and falls back when it is not a number', () => {
expect(acotarTamano(500)).toBe(PAGE_SIZE_MAX);
expect(acotarTamano('999')).toBe(PAGE_SIZE_MAX);
expect(acotarTamano(0)).toBe(1);
expect(acotarTamano(-7)).toBe(1);
expect(acotarTamano(25.9)).toBe(25);
expect(acotarTamano('')).toBe(1);
expect(acotarTamano('x')).toBe(50);
expect(acotarTamano(undefined, 20)).toBe(20);
});
});
@@ -44,6 +44,11 @@ export type MesesVentana = typeof MESES_VENTANA[number];
/** What the window is called on screen and in the files: the whole cohort or a number of months. */
export const etiquetaVentana = (meses: number) => meses === 0 ? 'Toda la cohorte' : `${meses} ${meses === 1 ? 'mes' : 'meses'}`;
export const PAGE_SIZE_MAX = 200;
/** A page size typed in a form, brought into 1..PAGE_SIZE_MAX: an input's `max` only flags the field, it does not stop a larger number. */
export const acotarTamano = (valor: unknown, defecto = 50) => {
const n = Math.trunc(Number(valor));
return Number.isFinite(n) ? Math.min(PAGE_SIZE_MAX, Math.max(1, n)) : defecto;
};
const RESERVADAS = ['meses', 'page', 'page_size', 'corte', ...CLAVES_CONTEXTO];
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -147,7 +152,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR
}),
};
}
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true };
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true, escenario_clinico: true };
@Injectable({ providedIn: 'root' })
export class SeguimientoTablaService {
+26 -2
View File
@@ -6,10 +6,13 @@ import {
Experiment,
ExperimentDetail,
ExperimentRequest,
NotebookTemplate,
ModelLineage,
ModelVersion,
PromotionCheck,
ReportField,
TrainableScenario,
TrainingJob,
OcrJob,
OcrRowStatus,
OcrRowsResponse,
@@ -39,6 +42,20 @@ export class GovernanceApi {
return this.http.post<{ output: string }>(`/governance/model-versions/${domain}/${scenario}/train`, {});
}
/** The scenarios that can be trained from here. */
trainableScenarios(): Observable<{ scenarios: TrainableScenario[] }> {
return this.http.get<{ scenarios: TrainableScenario[] }>('/governance/scenarios');
}
/** Starts the training in the background: 202 with the job, 409 with the running one, 503 with no dbt manifest. */
startTrainingJob(domain: string, scenario: string): Observable<{ job: TrainingJob }> {
return this.http.post<{ job: TrainingJob }>(`/governance/model-versions/${domain}/${scenario}/train-jobs`, {});
}
trainingJobs(): Observable<{ jobs: TrainingJob[] }> {
return this.http.get<{ jobs: TrainingJob[] }>('/governance/training-jobs');
}
retireModelVersion(domain: string, scenario: string, version: string): Observable<ModelVersion> {
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {});
}
@@ -69,10 +86,17 @@ export class GovernanceApi {
return this.http.get<{ experiments: Experiment[] }>('/governance/experiments', { params: toParams(filters) });
}
/** Starts the notebook on the build in the background; answers with the run while it is still `en_curso`. */
/** The domain's notebooks kept in the code, each with the scenarios it can run for. */
notebookTemplates(domain: string): Observable<{ templates: NotebookTemplate[] }> {
return this.http.get<{ templates: NotebookTemplate[] }>('/governance/notebook-templates', { params: toParams({ domain }) });
}
/** Starts the notebook (an upload, or a template the API reads from the code) on the build in the background;
* answers with the run while it is still `en_curso`. */
runExperiment(request: ExperimentRequest): Observable<ExperimentDetail> {
const form = new FormData();
form.append('file', request.file);
if (request.template) form.append('template', request.template);
else if (request.file) form.append('file', request.file);
form.append('domain', request.domain);
form.append('scenario', request.scenario);
form.append('url', request.build.url);
+38 -1
View File
@@ -79,8 +79,20 @@ export interface ExperimentDetail extends Experiment {
error: string | null;
}
/** A notebook kept in the code (`models/<domain>/<scenario>/notebooks/`), and the scenarios it can run for. */
export interface NotebookTemplate {
id: string;
domain: Domain;
scenario: string;
name: string;
scenarios: string[];
title: string;
}
/** One of `file` (an upload) or `template` (a notebook kept in the code, by its id). */
export interface ExperimentRequest {
file: File;
file?: File | null;
template?: string | null;
domain: Domain;
scenario: string;
build: CohortBuildFile;
@@ -136,3 +148,28 @@ export interface OcrRunSummary {
failed: number;
needs_review: number;
}
/** A scenario governance can train (`GET /governance/scenarios`); `produccion` is its version in production, if any. */
export interface TrainableScenario {
domain: string;
scenario: string;
cohort: string | null;
outcome: string | null;
description: string;
kind: 'cohorte' | 'referencia';
produccion: string | null;
}
export type TrainingJobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido';
/** A training in the background (`/governance/training-jobs`), with the tail of its outputs. */
export interface TrainingJob {
id: string;
domain: string;
scenario: string;
iniciado: string;
estado: TrainingJobState;
codigo: number | null;
salida: string;
error: string;
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { Observable } from 'rxjs';
import { PendingRiskBatch } from './risk-batches.types';
/** `/<domain>/riesgos/lotes`: risk batches a model produced and nobody has reviewed yet (ADR-MD-008). Only `cacu`
* is served today. */
* and `cama` are served. */
@Injectable({ providedIn: 'root' })
export class RiskBatchesApi {
private readonly http = inject(HttpClient);
@@ -83,24 +83,25 @@
<section aria-labelledby="routines-title">
<h3 id="routines-title">Rutinas del entrenamiento</h3>
<p class="muted">Lo que cada rutina hizo, registrado por la corrida mientras entrenaba (ML-01a).</p>
<ul class="artifacts">
@for (routine of routineKinds; track routine.kind) {
@let record = l.routines[routine.kind];
<li [class.checks__fail]="!record">
<mat-icon aria-hidden="true">{{ record ? 'check_circle' : 'cancel' }}</mat-icon>
<span class="artifacts__kind">{{ routine.label }}</span>
@if (record) {
<p class="muted">Lo que cada rutina hizo, registrado por la corrida mientras entrenaba. No todos los modelos
tienen cada rutina; no se piden para promover (ML-01a lo cumple la corrida misma).</p>
@let recorded = recordedRoutines(l.routines);
@if (recorded.length) {
<ul class="artifacts">
@for (routine of recorded; track routine.kind) {
<li>
<mat-icon aria-hidden="true">check_circle</mat-icon>
<span class="artifacts__kind">{{ routine.label }}</span>
<details class="routine">
<summary>{{ record['method'] ?? 'Ver registro' }}</summary>
<pre>{{ record | json }}</pre>
<summary>{{ routine.record['method'] ?? 'Ver registro' }}</summary>
<pre>{{ routine.record | json }}</pre>
</details>
} @else {
<span class="muted">La corrida no la registró.</span>
}
</li>
}
</ul>
</li>
}
</ul>
} @else {
<p class="muted">La corrida no guardó registros de rutina.</p>
}
</section>
<section aria-labelledby="artifacts-title">
@@ -55,7 +55,10 @@ export class ModelVersionDialog {
private readonly version = inject<ModelVersion>(MAT_DIALOG_DATA);
private readonly dialog = inject(MatDialog);
readonly routineKinds = ROUTINES;
/** The routines the run recorded, in `ROUTINES`' order; the others aren't listed. */
recordedRoutines(routines: ModelLineage['routines']) {
return ROUTINES.filter((r) => routines[r.kind]).map((r) => ({ ...r, record: routines[r.kind]! }));
}
readonly lineage = signal<ModelLineage | null>(null);
readonly busy = signal(false);
readonly error = signal<string | null>(null);
@@ -6,22 +6,51 @@
}
</mat-button-toggle-group>
<span class="models__spacer"></span>
<button mat-stroked-button type="button" [disabled]="training()" (click)="train()"
matTooltip="Entrena el modelo cacu/cin2_logistic con la cohorte de vigilancia vigente y lo pone en producción">
<mat-icon aria-hidden="true">model_training</mat-icon>Entrenar cacu/cin2_logistic
</button>
@if (offered().length) {
<mat-form-field class="models__scenario" subscriptSizing="dynamic">
<mat-label>Modelo a entrenar</mat-label>
<mat-select [value]="selected() ?? (offered().length === 1 ? keyOf(offered()[0]) : null)" (selectionChange)="selected.set($event.value)">
@for (s of offered(); track keyOf(s)) {
<mat-option [value]="keyOf(s)">{{ keyOf(s) }}{{ s.produccion ? ' · en producción v' + s.produccion : '' }}</mat-option>
}
</mat-select>
</mat-form-field>
<button mat-stroked-button type="button" [disabled]="starting() || !(selected() || offered().length === 1)" (click)="train()"
matTooltip="Exporta la cohorte vigente de dbt, entrena una versión y la promueve si ya tiene sus informes">
<mat-icon aria-hidden="true">model_training</mat-icon>Entrenar
</button>
}
<button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar">
<mat-icon aria-hidden="true">refresh</mat-icon>
</button>
</div>
@if (loading() || training()) {
@if (loading() || starting() || running()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (loadError(); as error) {
<p class="models__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
@if (jobs().length) {
<section class="models__jobs" aria-label="Entrenamientos recientes">
<h3>Entrenamientos recientes</h3>
<ul>
@for (job of jobs(); track job.id) {
<li [class.models__job--failed]="job.estado === 'fallido' || job.estado === 'interrumpido'">
<strong>{{ job.domain }}/{{ job.scenario }}</strong> · {{ job.iniciado | date: 'short' }} · {{ estados[job.estado] }}
@if (job.salida || job.error) {
<details>
<summary>Salida</summary>
<pre>{{ job.error || job.salida }}</pre>
</details>
}
</li>
}
</ul>
</section>
}
<table mat-table [dataSource]="versions()" class="models__table">
<ng-container matColumnDef="version">
<th mat-header-cell *matHeaderCellDef>Versión</th>
@@ -70,3 +70,29 @@
gap: var(--space-2);
margin: 0;
}
.models__scenario {
min-width: 18rem;
}
.models__jobs ul {
list-style: none;
margin: 0;
padding: 0;
}
.models__jobs li {
padding: var(--space-1) 0;
}
.models__job--failed {
color: var(--mat-sys-error);
}
.models__jobs pre {
font-size: 0.8rem;
margin: var(--space-1) 0;
max-height: 12rem;
overflow: auto;
white-space: pre-wrap;
}
@@ -0,0 +1,83 @@
// Covers the model versions panel's training: the scenarios the account can train are offered, a training starts in the
// background and its state is shown while it runs, and the versions are read again when it ends. Fixtures: a stub of
// `GovernanceApi` with the scenarios, the versions and the jobs the test sets, and an account that reaches every domain.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { vi } from 'vitest';
import { AuthService } from '../../../auth/auth.service';
import { GovernanceApi } from '../../api/governance.api';
import { TrainingJob } from '../../api/governance.types';
import { ModelVersionsPanel } from './model-versions-panel';
const SCENARIOS = [
{ domain: 'cacu', scenario: 'cin2_logistic', cohort: 'cacu/x', outcome: 'cin2', description: '', kind: 'cohorte', produccion: null },
{ domain: 'cama', scenario: 'survival', cohort: 'cama/cohorte_total', outcome: 'muerte', description: '', kind: 'cohorte', produccion: '2' },
];
const job = (estado: TrainingJob['estado']): TrainingJob => ({
id: 'j1', domain: 'cama', scenario: 'survival', iniciado: '2026-01-01T00:00:00+00:00', estado, codigo: null, salida: 'trained: version 3', error: '',
});
describe('ModelVersionsPanel training', () => {
let api: Record<string, ReturnType<typeof vi.fn>>;
let jobs: TrainingJob[];
beforeEach(() => {
jobs = [];
api = {
listModelVersions: vi.fn(() => of({ model_versions: [] })),
trainableScenarios: vi.fn(() => of({ scenarios: SCENARIOS })),
trainingJobs: vi.fn(() => of({ jobs })),
startTrainingJob: vi.fn(() => of({ job: job('en_curso') })),
};
TestBed.configureTestingModule({
providers: [
{ provide: GovernanceApi, useValue: api },
{ provide: AuthService, useValue: { puedeVer: () => true, dominios: () => ['cacu', 'cama', 'tea'], esAdministrador: () => true, usuario: () => ({ dominios: ['cacu', 'cama', 'tea'] }) } },
],
});
});
// Fails if the panel goes back to offering one hardcoded scenario, or hides a scenario the account can train.
it('offers every trainable scenario of the domains shown', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
f.detectChanges();
const panel = f.componentInstance;
panel.domain.set(null);
expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cacu/cin2_logistic', 'cama/survival']);
panel.domain.set('cama');
expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cama/survival']);
});
// Fails if the button trains another scenario than the selected one, or waits for the training to end.
it('starts the selected scenario in the background and reads the jobs again', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
f.detectChanges();
const panel = f.componentInstance;
panel.domain.set(null);
panel.selected.set('cama/survival');
panel.train();
expect(api['startTrainingJob']).toHaveBeenCalledExactlyOnceWith('cama', 'survival');
expect(api['trainingJobs']).toHaveBeenCalledTimes(2);
});
// Fails if the running state is lost or the versions are not read again when the running training ends.
it('knows a training is running and reads the versions when it ends', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
jobs = [job('en_curso')];
f.detectChanges();
const panel = f.componentInstance;
expect(panel.running()).toBe(true);
const reads = api['listModelVersions'].mock.calls.length;
jobs = [job('completado')];
panel.refreshJobs();
expect(panel.running()).toBe(false);
expect(api['listModelVersions'].mock.calls.length).toBe(reads + 1);
f.detectChanges();
expect((f.nativeElement as HTMLElement).textContent).toContain('Entrenado y promovido');
});
});
@@ -1,11 +1,14 @@
import { DatePipe } from '@angular/common';
import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
import { timer } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
@@ -15,18 +18,27 @@ import { AuthService } from '../../../auth/auth.service';
import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { GovernanceApi } from '../../api/governance.api';
import { ModelVersion } from '../../api/governance.types';
import { ModelVersion, TrainableScenario, TrainingJob } from '../../api/governance.types';
import { ModelStatusChip } from '../model-status-chip/model-status-chip';
import { ModelVersionDialog } from '../model-version-dialog/model-version-dialog';
/** The only scenario with a trainer today (ML-cin2_logistic, CaCu): `entrenar`'s own domain and scenario. */
const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
/** Milliseconds between asking for the state of a training that is still running. */
export const SONDEO_MS = 3000;
export const ESTADOS: Record<TrainingJob['estado'], string> = {
en_curso: 'En curso',
completado: 'Entrenado y promovido',
entrenado_sin_promover: 'Entrenado; faltan sus informes para promoverlo',
fallido: 'Falló',
interrumpido: 'Interrumpido',
};
/**
* Every registered model version with its status (desarrollo, candidata,
* en producción, retirada). The detail dialog holds the promotion
* checklist, lineage, artifacts and reports. The toolbar also offers
* training the one scenario with a trainer, over HTTP instead of a shell.
* checklist, lineage, artifacts and reports. The toolbar trains any scenario
* that has a trainer, in the background, and lists the latest trainings with
* their state while they run.
*/
@Component({
selector: 'app-model-versions-panel',
@@ -37,6 +49,8 @@ const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
MatChipsModule,
MatIconModule,
MatProgressBarModule,
MatSelectModule,
MatFormFieldModule,
MatSnackBarModule,
MatTableModule,
MatTooltipModule,
@@ -61,12 +75,28 @@ export class ModelVersionsPanel implements OnInit {
readonly versions = signal<ModelVersion[]>([]);
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly training = signal(false);
readonly scenarios = signal<TrainableScenario[]>([]);
readonly selected = signal<string | null>(null);
readonly jobs = signal<TrainingJob[]>([]);
readonly starting = signal(false);
readonly estados = ESTADOS;
/** The scenarios of the domain being shown, and only of the account's domains. */
readonly offered = computed(() =>
this.scenarios().filter((s) => this.auth.puedeVer(s.domain) && (this.domain() === null || s.domain === this.domain())));
readonly running = computed(() => this.jobs().some((j) => j.estado === 'en_curso'));
readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones'];
ngOnInit(): void {
this.reload();
this.api.trainableScenarios().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: ({ scenarios }) => this.scenarios.set(scenarios),
error: () => this.scenarios.set([]),
});
this.refreshJobs();
timer(SONDEO_MS, SONDEO_MS).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
if (this.running()) this.refreshJobs();
});
}
setDomain(domain: string | null): void {
@@ -108,22 +138,41 @@ export class ModelVersionsPanel implements OnInit {
return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value }));
}
/** Asks for the latest trainings; when one that was running has ended, the versions are read again. */
refreshJobs(): void {
const before = this.running();
this.api.trainingJobs().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: ({ jobs }) => {
this.jobs.set(jobs.slice(0, 8));
if (before && !this.running()) this.reload();
},
error: () => undefined,
});
}
train(): void {
this.training.set(true);
const key = this.selected() ?? (this.offered().length === 1 ? this.keyOf(this.offered()[0]) : null);
const scenario = this.offered().find((s) => this.keyOf(s) === key);
if (!scenario) return;
this.starting.set(true);
this.api
.trainModelVersion(TRAINABLE.domain, TRAINABLE.scenario)
.startTrainingJob(scenario.domain, scenario.scenario)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: () => {
this.training.set(false);
this.snackBar.open(`El modelo ${TRAINABLE.domain}/${TRAINABLE.scenario} se entrenó correctamente.`, 'OK', { duration: 3000 });
this.reload();
this.starting.set(false);
this.snackBar.open(`Entrenamiento de ${key} iniciado.`, 'OK', { duration: 3000 });
this.refreshJobs();
},
error: (error) => {
this.training.set(false);
this.snackBar.open(apiErrorMessage(error, 'No se pudo entrenar el modelo.'), 'OK', { duration: 5000 });
if (error?.status === 409) this.reload();
this.starting.set(false);
this.snackBar.open(apiErrorMessage(error, 'No se pudo iniciar el entrenamiento.'), 'OK', { duration: 5000 });
if (error?.status === 409) this.refreshJobs();
},
});
}
keyOf(s: { domain: string; scenario: string }): string {
return `${s.domain}/${s.scenario}`;
}
}
@@ -2,19 +2,39 @@
<mat-dialog-content class="content">
<p class="hint">
El notebook corre aislado en el servidor, sin red y con los datos de la cohorte que elija como única información: no
Elija un notebook del código (<code>models/&lt;dominio&gt;/&lt;escenario&gt;/notebooks/</code>) o suba uno. Corre
aislado en el servidor, sin red y con los datos de la cohorte que elija como única información: no
ve las bases de datos ni los demás archivos. Dentro usa <code>from models.notebook import experiment</code> para leer
la cohorte, cargar la versión elegida o entrenar; lo que entrene se registra como versión de desarrollo al terminar.
La corrida guarda el notebook, la página con sus resultados y con qué datos se corrió.
</p>
<div class="file">
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>Elegir notebook
</button>
<span class="file__name">{{ file()?.name ?? 'Ningún archivo (.ipynb)' }}</span>
<input #fileInput type="file" accept=".ipynb,application/x-ipynb+json" hidden (change)="pick($event)" />
</div>
<mat-button-toggle-group [value]="source()" (change)="source.set($event.value)" aria-label="Origen del notebook">
<mat-button-toggle value="plantilla" [disabled]="!templates().length">Del código</mat-button-toggle>
<mat-button-toggle value="archivo">Subir archivo</mat-button-toggle>
</mat-button-toggle-group>
@if (source() === 'plantilla') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Notebook del código</mat-label>
<mat-select [ngModel]="template()" (ngModelChange)="setTemplate($event)" [compareWith]="sameTemplate">
@for (option of templates(); track option.id) {
<mat-option [value]="option">{{ templateLabel(option) }}</mat-option>
}
</mat-select>
@if (template(); as chosen) {
<mat-hint>Corre para: {{ chosen.scenarios.join(', ') }}</mat-hint>
}
</mat-form-field>
} @else {
<div class="file">
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>Elegir notebook
</button>
<span class="file__name">{{ file()?.name ?? 'Ningún archivo (.ipynb)' }}</span>
<input #fileInput type="file" accept=".ipynb,application/x-ipynb+json" hidden (change)="pick($event)" />
</div>
}
<div class="grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -31,6 +51,8 @@
<input matInput [ngModel]="scenario()" (ngModelChange)="setScenario($event)" placeholder="cin2_logistic" />
@if (scenario() && !scenarioValid()) {
<mat-error>Solo letras, números, guion y guion bajo.</mat-error>
} @else if (source() === 'plantilla' && template() && !notebookReady()) {
<mat-hint>Esta plantilla no corre para ese escenario.</mat-hint>
} @else {
<mat-hint>El de un modelo existente o uno nuevo para el experimento.</mat-hint>
}
@@ -2,18 +2,28 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotebookTemplate } from '../../api/governance.types';
import { NotebookRunDialog } from './notebook-run-dialog';
/**
* The dialog that uploads a notebook and runs it on a cohort build: it starts
* from a version's defaults, offers the domain's exported builds, and sends
* the build the person chose. The API is `HttpTestingController`; the dialog
* The dialog that runs a notebook on a cohort build, one kept in the code or an
* upload: it starts from a version's defaults, offers the domain's templates and
* exported builds, and sends the notebook and build the person chose. The API is `HttpTestingController`; the dialog
* reference is a stub that records how it closed.
*/
describe('NotebookRunDialog', () => {
let http: HttpTestingController;
const close = vi.fn();
const build = { url: 'cacu/cohorte_vigilancia', source: 'dbt', build: 4, datos_as_of: '2025-12-31', n_members: '10' };
const pim: NotebookTemplate = {
id: 'cacu/cin2_pim/reporte_subgrupos', domain: 'cacu', scenario: 'cin2_pim', name: 'reporte_subgrupos',
scenarios: ['cin2_pim', 'cin2_pim_post_colposcopy'], title: 'Riesgo acumulado de CIN2+ por combinación',
};
function templates(found: object[] = []) {
http.expectOne((r) => r.url === '/governance/notebook-templates' && r.params.get('domain') === 'cacu')
.flush({ templates: found });
}
function open(data: object) {
TestBed.configureTestingModule({
@@ -39,10 +49,12 @@ describe('NotebookRunDialog', () => {
it('sends the chosen build and version with the notebook, and closes with the run', () => {
// Fails if the form stops carrying the build's url, source and number, or drops the version it was opened with.
const fixture = open({ domain: 'cacu', scenario: 'cin2_logistic', version: '3' });
templates();
http.expectOne((r) => r.url === '/governance/cohort-files' && r.params.get('domain') === 'cacu').flush({ builds: [build] });
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
const dialog = fixture.componentInstance;
expect(dialog.ready()).toBe(false);
expect(dialog.source()).toBe('archivo'); // no templates in the domain: the upload is the only source
dialog.file.set(new File(['{}'], 'analisis.ipynb'));
expect(dialog.ready()).toBe(true);
@@ -60,6 +72,7 @@ describe('NotebookRunDialog', () => {
it('refuses a scenario that the API would reject', () => {
// Fails if `ready` stops checking the scenario's characters before uploading.
const fixture = open({});
templates();
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
const dialog = fixture.componentInstance;
dialog.file.set(new File(['{}'], 'a.ipynb'));
@@ -69,4 +82,33 @@ describe('NotebookRunDialog', () => {
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.ready()).toBe(true);
});
it('runs a template from the code for a scenario it serves, sending its id and no file', () => {
// Fails if choosing a template stops filling its scenario, the form sends a file with it, or a scenario the
// template doesn't serve is let through.
const fixture = open({});
templates([pim]);
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
const dialog = fixture.componentInstance;
expect(dialog.source()).toBe('plantilla');
dialog.setTemplate(pim);
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.scenario()).toBe('cin2_pim');
expect(dialog.ready()).toBe(true);
dialog.setScenario('survival');
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.ready()).toBe(false);
dialog.setScenario('cin2_pim_post_colposcopy');
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
dialog.run();
const request = http.expectOne('/governance/experiments');
const form = request.request.body as FormData;
expect([form.get('template'), form.get('file'), form.get('scenario')]).toEqual([
'cacu/cin2_pim/reporte_subgrupos', null, 'cin2_pim_post_colposcopy',
]);
request.flush({ run_id: 'r2', status: 'en_curso' });
expect(close).toHaveBeenCalledWith(expect.objectContaining({ run_id: 'r2' }));
});
});
@@ -1,6 +1,7 @@
import { Component, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
@@ -10,7 +11,7 @@ import { MatSelectModule } from '@angular/material/select';
import { Domain, apiErrorMessage } from '../../../connect/api/api.types';
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
import { GovernanceApi } from '../../api/governance.api';
import { CohortBuildFile, ExperimentDetail, ModelVersion } from '../../api/governance.types';
import { CohortBuildFile, ExperimentDetail, ModelVersion, NotebookTemplate } from '../../api/governance.types';
/** What the dialog starts with: a version's dialog passes its own domain, scenario and version. */
export interface NotebookRunDefaults {
@@ -21,15 +22,20 @@ export interface NotebookRunDefaults {
const SCENARIO = /^[\w-]{1,100}$/;
/** Where the notebook comes from: one kept in the code (a template) or an upload. */
export type NotebookSource = 'plantilla' | 'archivo';
/**
* Uploads a Jupyter notebook and runs it on a cohort build's file, optionally
* with a registered version to try. Closes with the run once it has started.
* Runs a Jupyter notebook on a cohort build's file, optionally with a registered
* version to try: one kept in the code (`models/<domain>/<scenario>/notebooks/`,
* for the scenarios it serves) or an upload. Closes with the run once it has started.
*/
@Component({
selector: 'app-notebook-run-dialog',
imports: [
FormsModule,
MatButtonModule,
MatButtonToggleModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
@@ -49,7 +55,10 @@ export class NotebookRunDialog {
readonly domain = signal<Domain>(this.defaults.domain ?? 'cacu');
readonly scenario = signal(this.defaults.scenario ?? '');
readonly version = signal<string>(this.defaults.version ?? '');
readonly source = signal<NotebookSource>('plantilla');
readonly file = signal<File | null>(null);
readonly templates = signal<NotebookTemplate[]>([]);
readonly template = signal<NotebookTemplate | null>(null);
readonly builds = signal<CohortBuildFile[]>([]);
readonly build = signal<CohortBuildFile | null>(null);
readonly versions = signal<ModelVersion[]>([]);
@@ -57,13 +66,34 @@ export class NotebookRunDialog {
readonly error = signal<string | null>(null);
readonly scenarioValid = computed(() => SCENARIO.test(this.scenario()));
readonly ready = computed(() => !!this.file() && !!this.build() && this.scenarioValid() && !this.busy());
/** The template serves the scenario typed, or the upload is chosen. */
readonly notebookReady = computed(() => {
if (this.source() === 'archivo') return !!this.file();
const template = this.template();
return !!template && template.scenarios.includes(this.scenario());
});
readonly ready = computed(() => this.notebookReady() && !!this.build() && this.scenarioValid() && !this.busy());
constructor() {
this.loadTemplates();
this.loadBuilds();
this.loadVersions();
}
templateLabel(template: NotebookTemplate): string {
return `${template.scenario}/${template.name} · ${template.title}`;
}
sameTemplate(a: NotebookTemplate | null, b: NotebookTemplate | null): boolean {
return !!a && !!b && a.id === b.id;
}
/** Choosing a template puts its scenario when the one typed isn't one it serves. */
setTemplate(template: NotebookTemplate | null): void {
this.template.set(template);
if (template && !template.scenarios.includes(this.scenario())) this.setScenario(template.scenario);
}
buildLabel(build: CohortBuildFile): string {
const members = build.n_members ? ` · ${build.n_members} miembros` : '';
const asOf = build.datos_as_of ? ` · datos al ${build.datos_as_of}` : '';
@@ -77,6 +107,7 @@ export class NotebookRunDialog {
setDomain(domain: Domain): void {
this.domain.set(domain);
this.version.set('');
this.loadTemplates();
this.loadBuilds();
this.loadVersions();
}
@@ -94,13 +125,13 @@ export class NotebookRunDialog {
}
run(): void {
const file = this.file();
const build = this.build();
if (!file || !build || !this.ready()) return;
if (!build || !this.ready()) return;
const notebook = this.source() === 'plantilla' ? { template: this.template()!.id } : { file: this.file() };
this.busy.set(true);
this.error.set(null);
this.api
.runExperiment({ file, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.runExperiment({ ...notebook, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.subscribe({
next: (run) => this.dialogRef.close(run),
error: (error) => {
@@ -110,6 +141,18 @@ export class NotebookRunDialog {
});
}
private loadTemplates(): void {
this.templates.set([]);
this.template.set(null);
this.api.notebookTemplates(this.domain()).subscribe({
next: ({ templates }) => {
this.templates.set(templates);
if (!templates.length) this.source.set('archivo');
},
error: () => this.templates.set([]),
});
}
private loadBuilds(): void {
this.builds.set([]);
this.build.set(null);

Some files were not shown because too many files have changed in this diff Show More