Compare commits

...

16 Commits

Author SHA1 Message Date
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
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
AlbertoPMDM 04795a09cc feat(tea): read the EEG analysis's verdict, quality checks and age baselines 2026-11-19 15:43:27 -06:00
Angel Capetillo Zavala baf5edca42 test(indicadores): follow the published CAM-03 title and the Análisis tab
The history names CAM-03 «Resultado histopatológico»; the CAM-03 expectation in the F4C spec
now uses that title.

The CaMa page does not offer the Análisis tab while CAMA_ANALYSIS_ENABLED is off. The journey
specs that open it run only while the flag is on and are reported as skipped otherwise. The
domain-change spec selects patients through the page instead of through that tab, so it keeps
checking that the selection is cleared and that CaCu and TEA keep their sections.
2026-11-18 23:41:41 -06:00
Manuel Aurrecoechea Castillo 58ff3870be 20261118 colorfix front
Cambio de los colores de las graficas para tener una mejor armonía de colores y evitar el uso de la unión de colores que interpreten ideas falsas
2026-11-18 15:16:13 -06:00
Angel Capetillo Zavala 439a039ff4 fix(cama): recuperar el tamaño responsivo de la dona BI-RADS 2026-11-18 14:58:54 -06:00
Angel Capetillo Zavala 049a9ca43c fix(cama): ocultar temporalmente la pestaña Análisis 2026-11-18 14:15:49 -06:00
Angel Capetillo Zavala f128f2e13a fix(cama): mostrar solo el conteo al pasar sobre la dona 2026-11-18 13:15:54 -06:00
Angel Capetillo Zavala 20b8c80aaf fix(cama): equilibrar centro y anillo de la dona 2026-11-18 12:56:27 -06:00
Angel Capetillo Zavala 8e85c91f15 fix(cama): completar ajustes visuales de indicadores 2026-11-18 12:23:17 -06:00
Angel Capetillo Zavala 1ac8d5c258 fix(cama): ajustar resumen y ocultar análisis 2026-11-18 09:25:38 -06:00
Angel Capetillo Zavala 23cd89e882 Adjust CaMa indicator labels 2026-11-17 12:44:25 -06:00
Angel Capetillo Zavala 47a0ab5f1b Connect CaMa dashboard to follow-up, analysis and L3 FHIR measures
Preserve dev governance and risk-batch UI. Validate cohort navigation, API contracts and shared summary/history measures. Production build passes; 1785 tests pass with the six known Node 26 localStorage failures.
2026-11-17 10:44:08 -06:00
Roberto Treviño Cervantes dc37c54938 wording fixes 2026-11-17 02:17:24 -06:00
roberto 2834fac85c Merge pull request 'Kit exit: TEA over FHIR, dashboard-test presentation merged in' (#9) from feature/kit-exit-integration into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/9
2026-11-16 21:09:07 -06:00
96 changed files with 18179 additions and 338 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()
+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 },
]
};
@@ -100,8 +100,8 @@
type="button"
class="saved-connection__forget"
(click)="forgetSaved(saved, $event)"
aria-label="Olvidar esta conexión guardada"
matTooltip="Olvidar"
aria-label="Eliminar esta conexión guardada"
matTooltip="Eliminar"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
@@ -134,7 +134,7 @@
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Recordar servidor, usuario y base de datos (nunca la contraseña)
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
</mat-checkbox>
}
@@ -1,6 +1,6 @@
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
const EDADES: Readonly<Record<string, string>> = {
MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
MENOR_40: 'Menores de 40 años', '<40': 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
};
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
const HISTOLOGIA: Readonly<Record<string, string>> = {
+2 -2
View File
@@ -30,9 +30,9 @@ export function code(concept: Concept | undefined): string | undefined {
export function display(concept: Concept | undefined): string | undefined {
return concept?.coding?.[0]?.display ?? concept?.text;
}
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URI such as a URN).
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
const url = system.includes('://') ? system : CODE_SYSTEM + system;
const url = system.includes(':') ? system : CODE_SYSTEM + system;
return concept?.coding?.find(c => c.system === url)?.code;
}
// The extensions named `name` (the last segment of their URL).
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "dimensiones": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}], "horizontes_dias": [30, 90, 180, 365], "tipos_periodo": ["mes", "semestre"], "secciones": [{"clave": "resumen", "titulo": "Indicadores de la cohorte", "estado": "disponible", "motivo": null}, {"clave": "distribucion", "titulo": "Distribución de pacientes", "estado": "disponible", "motivo": null}, {"clave": "comparacion", "titulo": "Comparación entre grupos", "estado": "disponible", "motivo": null}, {"clave": "mapa", "titulo": "Mapa entre variables", "estado": "disponible", "motivo": null}, {"clave": "tendencia", "titulo": "Tendencia en el tiempo", "estado": "disponible", "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "medida": "maligno", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "seleccion": {"birads": "BIRADS_4"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "seleccion": {"birads": "BIRADS_4A"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "seleccion": {"birads": "BIRADS_4B"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "seleccion": {"birads": "BIRADS_4C"}}, {"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "seleccion": {"birads": "BIRADS_5"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "seleccion": {"birads": "BIRADS_6"}}], "prueba": {"valida": false, "motivo": "Hacen falta al menos dos grupos con datos publicados.", "nombre": "Chi cuadrada de homogeneidad"}}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "medida": "invasor", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "<40", "etiqueta": "<40", "seleccion": {"grupo_edad": "<40"}}, {"estado": "disponible", "casos": 5, "total": 12, "valor": 41.67, "ic_bajo": 19.33, "ic_alto": 68.05, "codigo": "40-49", "etiqueta": "40-49", "seleccion": {"grupo_edad": "40-49"}}, {"estado": "disponible", "casos": 6, "total": 13, "valor": 46.15, "ic_bajo": 23.21, "ic_alto": 70.86, "codigo": "50-59", "etiqueta": "50-59", "seleccion": {"grupo_edad": "50-59"}}, {"estado": "disponible", "casos": 8, "total": 17, "valor": 47.06, "ic_bajo": 26.17, "ic_alto": 69.04, "codigo": "60-69", "etiqueta": "60-69", "seleccion": {"grupo_edad": "60-69"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "70+", "etiqueta": "70+", "seleccion": {"grupo_edad": "70+"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "SIN_DATO", "etiqueta": "Sin dato", "seleccion": {"grupo_edad": "SIN_DATO"}}], "prueba": {"valida": true, "estadistico": 0.0889, "gl": 2, "p": 0.9565070599102384, "nombre": "Chi cuadrada de homogeneidad"}}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "biopsia", "total": 61, "items": [{"codigo": "BENIGNO", "etiqueta": "Benigno", "suprimido": false, "n": 21, "porcentaje": 34.43, "ic_bajo": 23.75, "ic_alto": 46.95, "seleccion": {"biopsia": "BENIGNO"}}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_IN_SITU"}}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_INVASOR"}}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"biopsia": "SIN_DATO"}}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"biopsia": "SIN_BIOPSIA"}}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "total": 61, "items": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "suprimido": false, "n": 33, "porcentaje": 54.1, "ic_bajo": 41.72, "ic_alto": 65.99, "seleccion": {"birads": "BIRADS_4"}}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4A"}}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4B"}}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4C"}}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_5"}}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_6"}}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "total": 61, "items": [{"codigo": "<40", "etiqueta": "<40", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "<40"}}, {"codigo": "40-49", "etiqueta": "40-49", "suprimido": false, "n": 16, "porcentaje": 26.23, "ic_bajo": 16.84, "ic_alto": 38.44, "seleccion": {"grupo_edad": "40-49"}}, {"codigo": "50-59", "etiqueta": "50-59", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"grupo_edad": "50-59"}}, {"codigo": "60-69", "etiqueta": "60-69", "suprimido": false, "n": 26, "porcentaje": 42.62, "ic_bajo": 31.02, "ic_alto": 55.1, "seleccion": {"grupo_edad": "60-69"}}, {"codigo": "70+", "etiqueta": "70+", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "70+"}}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "SIN_DATO"}}]}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "escenario": "diagnostico", "corte": "2026-11-16", "umbral_supresion": 5, "unidad": "paciente", "denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6", "grupos": [{"codigo": "BIRADS_4", "n": 33, "suprimido": false}, {"codigo": "BIRADS_4A", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4B", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4C", "n": 0, "suprimido": false}, {"codigo": "BIRADS_5", "n": null, "suprimido": true}, {"codigo": "BIRADS_6", "n": null, "suprimido": true}], "horizonte_dias": 0, "indicadores": []}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "horizonte_dias": 90, "indicadores": [{"clave": "cohorte", "titulo": "Pacientes en la cohorte BI-RADS 4 a 6", "descripcion": "Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "unidad": "pacientes", "estado": "disponible", "valor": 61, "ic_bajo": null, "ic_alto": null, "n": 61, "denominador": null, "q1": null, "q3": null, "motivo": null}, {"clave": "con_biopsia", "titulo": "Con biopsia reportada", "descripcion": "Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.", "unidad": "%", "estado": "disponible", "valor": 68.85, "ic_bajo": 56.41, "ic_alto": 79.06, "n": 42, "denominador": 61, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_conocido", "titulo": "Resultado maligno entre las biopsias con resultado", "descripcion": "Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. No es incidencia: el denominador son pacientes ya biopsiadas.", "unidad": "%", "estado": "disponible", "valor": 50.0, "ic_bajo": 35.53, "ic_alto": 64.47, "n": 21, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "invasor_conocido", "titulo": "Carcinoma invasor entre las biopsias con resultado", "descripcion": "Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.", "unidad": "%", "estado": "disponible", "valor": 45.24, "ic_bajo": 31.22, "ic_alto": 60.05, "n": 19, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "biopsia_90d", "titulo": "Biopsia reportada en 90 días", "descripcion": "Pacientes cuya biopsia se reportó dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte.", "unidad": "%", "estado": "disponible", "valor": 75.56, "ic_bajo": 61.33, "ic_alto": 85.76, "n": 34, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_90d", "titulo": "Cáncer confirmado en 90 días", "descripcion": "Pacientes con un reporte de biopsia maligna dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte. No es incidencia acumulada: no hay seguimiento de quien no tuvo biopsia.", "unidad": "%", "estado": "disponible", "valor": 40.0, "ic_bajo": 27.02, "ic_alto": 54.55, "n": 18, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "dias_a_biopsia", "titulo": "Días de la mastografía al reporte de biopsia", "descripcion": "Mediana y cuartiles entre las pacientes con biopsia reportada.", "unidad": "días", "estado": "disponible", "valor": 27.5, "ic_bajo": null, "ic_alto": null, "n": 42, "denominador": null, "q1": 19.25, "q3": 30.75, "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"corte": "2026-11-16", "umbral_supresion": 5, "tipo_periodo": "semestre", "unidad": "reportes", "poblacion": "Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, de todas las pacientes; no la cohorte de Seguimiento", "alcance_biopsias": "Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); una biopsia sin mastografía ligada no se cuenta", "denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": [{"periodo": "2025-S1", "inicio": "2025-01-01", "fin": "2025-06-30", "incompleto": false, "reportes_mastografia": {"total": 96, "por_categoria": {"4_a_6": {"n": 31, "suprimido": false}, "otras": {"n": 65, "suprimido": false}}}, "reportes_biopsia": {"total": 24, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 15, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 16, "total": 24, "valor": 66.67, "ic_bajo": 46.71, "ic_alto": 82.03}}, {"periodo": "2025-S2", "inicio": "2025-07-01", "fin": "2025-12-31", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 37, "suprimido": false}, "otras": {"n": 60, "suprimido": false}}}, "reportes_biopsia": {"total": 25, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 13, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 14, "total": 25, "valor": 56.0, "ic_bajo": 37.07, "ic_alto": 73.33}}, {"periodo": "2026-S1", "inicio": "2026-01-01", "fin": "2026-06-30", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 25, "suprimido": false}, "otras": {"n": 72, "suprimido": false}}}, "reportes_biopsia": {"total": 18, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 11, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 13, "total": 18, "valor": 72.22, "ic_bajo": 49.13, "ic_alto": 87.5}}, {"periodo": "2026-S2", "inicio": "2026-07-01", "fin": "2026-12-31", "incompleto": true, "reportes_mastografia": {"total": 72, "por_categoria": {"4_a_6": {"n": 27, "suprimido": false}, "otras": {"n": 45, "suprimido": false}}}, "reportes_biopsia": {"total": 19, "por_grado": {"BENIGNO": {"n": 9, "suprimido": false}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": null, "suprimido": true}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 10, "total": 19, "valor": 52.63, "ic_bajo": 31.71, "ic_alto": 72.67}}]}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,842 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 8,
"link": [
{
"relation": "self",
"url": "http://127.0.0.1:28091/cama/fhir/Measure?_count=50&_offset=0"
}
],
"entry": [
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIOPSIAS",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIOPSIAS",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIOPSIAS",
"version": "0.2.0",
"name": "cama_biopsias",
"title": "Distribución de resultados de biopsia",
"status": "active",
"description": "Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada paciente. «Sin dato»: el reporte no trae grado.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_biopsias"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "grado"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS",
"version": "0.2.0",
"name": "cama_birads",
"title": "Distribución de BI-RADS",
"status": "active",
"description": "Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías. «Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS-CANCER-INVASOR",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
"version": "0.1.0",
"name": "cama_birads_cancer_invasor",
"title": "BI-RADS de los cánceres invasores",
"status": "active",
"description": "De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico, etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_cancer_invasor"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "grupo_edad"
}
],
"text": "grupo_edad"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "estadio"
}
],
"text": "Estadio clínico"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "etapa"
}
],
"text": "Etapa"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "clasificacion"
}
],
"text": "Subtipo molecular"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "tamano"
}
],
"text": "Tamaño tumoral (T)"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS456-MASTOGRAFIA",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
"version": "0.2.0",
"name": "cama_birads_456_mastografia",
"title": "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6",
"status": "active",
"description": "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_456_mastografia"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-PACIENTE",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS456-PACIENTE",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE",
"version": "0.2.0",
"name": "cama_birads_456_paciente",
"title": "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
"status": "active",
"description": "Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus mastografías.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_456_paciente"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
"resource": {
"resourceType": "Measure",
"id": "CAMA-CONFIRMACION-BIRADS45",
"url": "https://isssteleon.org/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
"version": "0.2.0",
"name": "cama_confirmacion_birads45",
"title": "Tasa de confirmación histopatológica",
"status": "active",
"description": "De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si la biopsia confirmó cáncer.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C1"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "proportion"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "principal"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_denominador"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"description": "Denominador",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_denominador"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"description": "Numerador",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_numerador"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "episodio"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "increase"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
"resource": {
"resourceType": "Measure",
"id": "CAMA-DIAS-TOMA-DIAGNOSTICO",
"url": "https://isssteleon.org/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
"version": "0.2.2",
"name": "cama_dias_toma_diagnostico",
"title": "Tiempo de tamizaje a diagnóstico",
"status": "active",
"description": "Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C3r"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "continuous-variable"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"description": "Unidades con valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-population-exclusion"
}
]
},
"description": "Unidades sin valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-EU38A",
"resource": {
"resourceType": "Measure",
"id": "CAMA-EU38A",
"url": "https://isssteleon.org/fhir/Measure/CAMA-EU38A",
"version": "0.2.1",
"name": "cama_eu38a",
"title": "Días de la toma de la mastografía a su resultado",
"status": "active",
"description": "Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C3r"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "continuous-variable"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"description": "Unidades con valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-population-exclusion"
}
]
},
"description": "Unidades sin valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
},
"search": {
"mode": "match"
}
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 6, "desde": "2026-05-18", "hasta": "2026-11-17"}, "filtros": {"birads": "BIRADS_5", "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "254", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-11", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-09-16"}, {"pac_id": "129", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-22", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-20"}, {"pac_id": "117", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-09"}, {"pac_id": "101", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-03", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-31"}, {"pac_id": "225", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-02", "biopsia": "CARCINOMA_IN_SITU", "biopsia_fecha": "2026-07-31"}, {"pac_id": "287", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-14", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-13"}, {"pac_id": "55", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-09", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-30"}, {"pac_id": "7", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-02", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "260", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-05-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-07"}]}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 3, "desde": "2026-08-18", "hasta": "2026-11-17"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "54", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "255", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-21", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "4", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-10", "biopsia": "BENIGNO", "biopsia_fecha": "2026-11-06"}, {"pac_id": "256", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-08", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "239", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-14", "biopsia": "BENIGNO", "biopsia_fecha": "2026-10-06"}, {"pac_id": "245", "grupo_edad": "40-49", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-09", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "186", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-31", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "282", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-29", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-10"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "31", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}]}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -34,7 +34,7 @@
<div class="figures">
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
@if (total) {
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
</section>
@@ -14,6 +14,8 @@ h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
app-plotly-chart { --plot-height: 400px; }
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
.donut-chart { --plot-min-width: 230px; }
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; }
@@ -38,10 +38,7 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
private subscription?: Subscription;
private key = '';
private loaded = false;
// On a narrow screen the donut's long label gives way to a legend under it.
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
private anchoDona = 390;
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
get total() { return this.model ? totalExamenes(this.model) : null; }
@@ -108,12 +105,18 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.draw();
}
ajustarAnchoDona(ancho: number) {
if (ancho === this.anchoDona) return;
this.anchoDona = ancho;
const m = this.model;
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
}
private draw() {
const m = this.model;
if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false);
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
this.barsFigure = barrasConteos(m, this.par, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
ngOnDestroy() { this.subscription?.unsubscribe(); }
}
@@ -37,7 +37,7 @@
:host(.methodology-expanded) .figure-card { grid-row: auto; }
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; }
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
@@ -30,22 +30,8 @@
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
@for (c of m.categorias; track c.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
</div>
</div>
<div class="figures">
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
@if (ratesFigure) {
@@ -61,7 +47,21 @@
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
</section>
</div>
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
@for (c of m.categorias; track c.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
</div>
</div>
}
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
@@ -0,0 +1,109 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis, TendenciaAnalisis } from './indicadores-analisis.service';
// The figures of the descriptive analysis. They draw what the answer publishes and nothing else: a suppressed or missing
// value is left out of the drawing (a gap, never a zero) and named in the table beside it.
const miles = (v: number) => v.toLocaleString('es-MX');
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' %';
const base = (tema: Tema, alto: number, margen: Record<string, number>) => {
const t = c2Theme(tema);
return { autosize: true, height: alto, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text }, margin: margen, showlegend: false };
};
const config = { displayModeBar: false };
/** Share of the selection by category, with the Wilson interval of each published share as a horizontal bar. */
export function distribucionFigura(d: DistribucionAnalisis, tema: Tema): PlotlyFigure {
const t = c2Theme(tema);
const items = d.items.filter(i => !i.suprimido && (i.n ?? 0) > 0 && i.porcentaje !== null);
return {
data: [{
type: 'bar', orientation: 'h', y: items.map(i => i.etiqueta), x: items.map(i => i.porcentaje), customdata: items.map(i => i.codigo),
marker: { color: C2_PALETTE.series[0] },
error_x: { type: 'data', symmetric: false, array: items.map(i => i.ic_alto! - i.porcentaje!), arrayminus: items.map(i => i.porcentaje! - i.ic_bajo!), color: t.text },
text: items.map(i => `${miles(i.n!)} (${pct(i.porcentaje!)})`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
hovertemplate: items.map(i => `<b>${i.etiqueta}</b><br>${miles(i.n!)} pacientes<br>${pct(i.porcentaje!)} (IC 95 %: ${pct(i.ic_bajo!)} a ${pct(i.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, Math.max(220, 60 + 44 * items.length), { t: 24, l: 150, r: 90, b: 52 }),
xaxis: { title: { text: 'Porcentaje de la selección' }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
yaxis: { autorange: 'reversed', automargin: true, fixedrange: true } },
config,
};
}
/** The share of cases per group as a point with its interval: groups that aren't published have no point. */
export function comparacionFigura(c: ComparacionAnalisis, tema: Tema, medida: string): PlotlyFigure {
const t = c2Theme(tema);
const grupos = c.grupos.filter(g => g.estado === 'disponible');
return {
data: [{
type: 'scatter', mode: 'markers', y: grupos.map(g => g.etiqueta), x: grupos.map(g => g.valor), customdata: grupos.map(g => g.codigo),
marker: { color: C2_PALETTE.series[1], size: 11 },
error_x: { type: 'data', symmetric: false, array: grupos.map(g => g.ic_alto! - g.valor!), arrayminus: grupos.map(g => g.valor! - g.ic_bajo!), color: t.text, thickness: 2, width: 6 },
hovertemplate: grupos.map(g => `<b>${g.etiqueta}</b><br>${g.casos} de ${g.total} pacientes con resultado<br>${pct(g.valor!)} (IC 95 %: ${pct(g.ic_bajo!)} a ${pct(g.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, Math.max(220, 80 + 46 * grupos.length), { t: 24, l: 150, r: 28, b: 56 }),
xaxis: { title: { text: `${medida} entre pacientes con resultado de biopsia` }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
config,
};
}
const textoCelda = (c: CeldaMapa, medida: string) => c.suprimido ? 'No publicado'
: medida === 'pacientes' ? `${miles(c.n!)} pacientes` : c.resultado.estado === 'disponible' ? `${pct(c.resultado.valor!)}<br>${c.resultado.casos} de ${c.resultado.total}` : c.resultado.estado === 'suprimido' ? 'No publicado' : 'Sin pacientes con resultado';
/** BI-RADS by age group: the number of patients or the share of cases in each cell; hidden cells are blank. */
export function mapaFigura(m: MapaAnalisis, tema: Tema, medida: 'pacientes' | 'resultado'): PlotlyFigure {
const t = c2Theme(tema);
const celdas = new Map(m.celdas.map(c => [c.fila + '\u0000' + c.columna, c]));
const valor = (c: CeldaMapa | undefined) => !c || c.suprimido ? null : medida === 'pacientes' ? c.n : c.resultado.estado === 'disponible' ? c.resultado.valor : null;
const z = m.filas.categorias.map(f => m.columnas.categorias.map(c => valor(celdas.get(f.codigo + '\u0000' + c.codigo))));
return {
data: [{
type: 'heatmap', x: m.columnas.categorias.map(c => c.etiqueta), y: m.filas.categorias.map(f => f.etiqueta), z,
customdata: m.filas.categorias.map(f => m.columnas.categorias.map(c => [f.codigo, c.codigo])),
text: m.filas.categorias.map(f => m.columnas.categorias.map(c => textoCelda(celdas.get(f.codigo + '\u0000' + c.codigo)!, medida === 'pacientes' ? 'pacientes' : 'resultado'))),
hovertemplate: '%{y}, %{x}<br>%{text}<extra></extra>', hoverongaps: false, xgap: 2, ygap: 2,
colorscale: [[0, '#E4EEC0'], [1, '#6A8000']], zmin: 0, zmax: medida === 'resultado' ? 100 : undefined,
colorbar: { title: { text: medida === 'resultado' ? '% de casos' : 'Pacientes' } },
}],
layout: { ...base(tema, Math.max(280, 90 + 40 * m.filas.categorias.length), { t: 24, l: 130, r: 28, b: 60 }),
xaxis: { automargin: true, fixedrange: true, type: 'category' }, yaxis: { autorange: 'reversed', automargin: true, fixedrange: true, type: 'category' },
plot_bgcolor: t.grid },
config,
};
}
export interface FigurasTendencia { actividad: PlotlyFigure; proporcion: PlotlyFigure; }
/** Reports per period (bars; a hidden total is a gap) and the share of malignant results with its interval. */
export function tendenciaFiguras(r: TendenciaAnalisis, tema: Tema, medida: string): FigurasTendencia {
const t = c2Theme(tema);
const x = r.periodos.map(p => p.periodo + (p.incompleto ? ' (en curso)' : ''));
const disponibles = r.periodos.map((p, i) => ({ p, x: x[i] })).filter(({ p }) => p.maligno.estado === 'disponible');
return {
actividad: {
data: [
{ type: 'bar', name: 'Reportes de mastografía', x, y: r.periodos.map(p => p.reportes_mastografia.total), marker: { color: C2_PALETTE.series[2] },
hovertemplate: '%{x}<br>%{y} reportes de mastografía<extra></extra>' },
{ type: 'bar', name: 'Reportes de biopsia', x, y: r.periodos.map(p => p.reportes_biopsia.total), marker: { color: C2_PALETTE.series[3] },
hovertemplate: '%{x}<br>%{y} reportes de biopsia<extra></extra>' },
],
layout: { ...base(tema, 340, { t: 24, l: 56, r: 16, b: 80 }), showlegend: true, legend: { orientation: 'h', y: -0.28 }, barmode: 'group',
xaxis: { type: 'category', automargin: true, fixedrange: true }, yaxis: { title: { text: 'Reportes' }, gridcolor: t.grid, rangemode: 'tozero', fixedrange: true } },
config,
},
proporcion: {
data: [{
type: 'scatter', mode: 'lines+markers', x: disponibles.map(d => d.x), y: disponibles.map(d => d.p.maligno.valor), connectgaps: false,
line: { color: C2_PALETTE.series[1] }, marker: { color: C2_PALETTE.series[1], size: 9 },
error_y: { type: 'data', symmetric: false, array: disponibles.map(d => d.p.maligno.ic_alto! - d.p.maligno.valor!), arrayminus: disponibles.map(d => d.p.maligno.valor! - d.p.maligno.ic_bajo!), color: t.text },
hovertemplate: disponibles.map(d => `${d.x}<br>${d.p.maligno.casos} de ${d.p.maligno.total} reportes de biopsia con resultado<br>${pct(d.p.maligno.valor!)} (IC 95 %: ${pct(d.p.maligno.ic_bajo!)} a ${pct(d.p.maligno.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, 340, { t: 24, l: 64, r: 16, b: 64 }),
xaxis: { type: 'category', categoryorder: 'array', categoryarray: x, automargin: true, fixedrange: true },
yaxis: { title: { text: medida }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true } },
config,
},
};
}
@@ -0,0 +1,298 @@
// What this module covers: CaMa's descriptive analysis in the Analysis tab: the answers' validation, the cards, the
// figures built from them, the sections the component draws, the way from a figure to Seguimiento and the states
// without data, suppressed or not published.
// Fixtures (`fixtures/cama_analisis_real_*.json`): answers of the WebApi's `/cama/analisis` endpoints over the local
// installation's synthetic CaMa data at 2026-11-16, whole cohort: catalog, indicators (90 days), distribution by BI-RADS, by
// age group and by biopsy result, comparison by age group, map, trend by semester and by month, and the 403 body.
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresAnalisisDescriptivo, detalleTarjeta, valorTarjeta } from './indicadores-analisis-descriptivo';
import {
catalogoDescriptivo, comparacionDescriptiva, distribucionDescriptiva, mapaDescriptivo, resumenDescriptivo, tendenciaDescriptiva,
} from './indicadores-analisis.service';
import { comparacionFigura, distribucionFigura, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
import catalogoData from './fixtures/cama_analisis_real_catalogo.json';
import resumenData from './fixtures/cama_analisis_real_resumen90.json';
import distBirads from './fixtures/cama_analisis_real_dist_birads.json';
import distEdad from './fixtures/cama_analisis_real_dist_edad.json';
import distBiopsia from './fixtures/cama_analisis_real_dist_biopsia.json';
import compBirads from './fixtures/cama_analisis_real_comp_birads.json';
import compEdad from './fixtures/cama_analisis_real_comp_edad.json';
import mapaData from './fixtures/cama_analisis_real_mapa.json';
import tendSem from './fixtures/cama_analisis_real_tend_sem.json';
import tendMes from './fixtures/cama_analisis_real_tend_mes.json';
import pequenoData from './fixtures/cama_analisis_real_pequeno.json';
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
const CORTE = '2026-11-16';
describe('Respuestas del análisis descriptivo', () => {
it('las respuestas reales cumplen su contrato y nombran la cohorte que describen', () => {
// Pins down: every answer is accepted as the server sends it, names the cohort, scenario, revision and cut-off, and
// carries no `simulado` field. Fails if the contract drifts from what the client validates.
const todas = [catalogoDescriptivo(copia(catalogoData)), resumenDescriptivo(copia(resumenData)), distribucionDescriptiva(copia(distBirads)),
comparacionDescriptiva(copia(compEdad)), mapaDescriptivo(copia(mapaData))];
for (const r of todas) { expect(r.cohorte).toBe('cama_birads_v1'); expect(r.revision).toMatch(/^[0-9a-f]{64}$/); expect(r.corte).toBe(CORTE); expect('simulado' in r).toBe(false); }
expect(new Set(todas.map(r => r.revision)).size).toBe(1);
// The trend is activity, not the cohort: it names its cut-off, unit, population and biopsy scope, and no cohort, filters or test.
for (const t of [tendenciaDescriptiva(copia(tendSem)), tendenciaDescriptiva(copia(tendMes))]) {
expect(t.corte).toBe(CORTE); expect(t.unidad).toBe('reportes'); expect(t.poblacion).toBeTruthy(); expect(t.alcance_biopsias).toBeTruthy();
expect(Object.keys(t)).not.toEqual(expect.arrayContaining(['cohorte']));
for (const k of ['cohorte', 'revision', 'ventana', 'filtros', 'prueba', 'simulado']) expect(k in t).toBe(false);
}
});
it('una respuesta con un conteo publicado y suprimido a la vez, o sin cohorte, se rechaza', () => {
// Pins down: a suppressed item can't carry a count and a published one must; an answer without cohort context isn't read.
// Fails if the client draws figures from an answer that contradicts itself.
const d = copia(distBirads); d['items'][0].suprimido = true;
expect(() => distribucionDescriptiva(d)).toThrow();
const sin = copia(distBirads); delete sin['revision'];
expect(() => distribucionDescriptiva(sin)).toThrow();
const r = copia(resumenData); r['indicadores'][1].estado = 'suprimido';
expect(() => resumenDescriptivo(r)).toThrow();
});
it('las tarjetas escriben el valor, su intervalo y su denominador, o dicen por qué no hay cifra', () => {
// Pins down: a proportion reads «68.9»-style with its Wilson interval and `k de n pacientes`; a median reads its quartiles;
// a suppressed card has no value and says why. Fails if a card shows a number the answer doesn't publish.
const r = resumenDescriptivo(copia(resumenData));
const t = Object.fromEntries(r.indicadores.map(i => [i.clave, i]));
expect(valorTarjeta(t['cohorte'])).toBe('61');
expect(valorTarjeta(t['con_biopsia'])).toBe('68.9');
expect(detalleTarjeta(t['con_biopsia'])).toContain('IC 95 %: 56.4 a 79.1 %. 42 de 61 pacientes.');
expect(detalleTarjeta(t['dias_a_biopsia'])).toContain('Q1 a Q3: 19.3 a 30.8 días. 42 pacientes.');
const oculta = { ...t['con_biopsia'], estado: 'suprimido' as const, valor: null, ic_bajo: null, ic_alto: null };
expect(valorTarjeta(oculta)).toBeNull();
expect(detalleTarjeta(oculta)).toContain('Muy pocos pacientes');
});
});
describe('Figuras del análisis descriptivo', () => {
it('la distribución dibuja solo las categorías publicadas, con su intervalo, y deja las suprimidas fuera', () => {
// Pins down: BI-RADS 5 and 6 are suppressed in the real answer, so only BI-RADS 4 is drawn, at its share with its Wilson
// interval as asymmetric error bars; a hidden category is a gap, not a zero bar. Fails if a suppressed group is drawn.
const d = distribucionDescriptiva(copia(distBirads));
const [traza] = distribucionFigura(d, 'claro').data as Record<string, any>[];
expect(traza['y']).toEqual(['BI-RADS 4']);
expect(traza['x']).toEqual([54.1]);
expect(traza['error_x']['array'][0] + traza['x'][0]).toBeCloseTo(d.items[0].ic_alto!, 5);
});
it('la comparación dibuja un punto por grupo publicado con su intervalo', () => {
// Pins down: by age group three groups have enough patients with a result; each point is its share and the interval is
// asymmetric. Fails if a group without data or a hidden one gets a point.
const c = comparacionDescriptiva(copia(compEdad));
const [traza] = comparacionFigura(c, 'claro', 'Carcinoma invasor').data as Record<string, any>[];
expect(traza['y']).toEqual(['40 a 49 años', '50 a 59 años', '60 a 69 años'].map(e => expect.stringContaining(e.split(' ')[0])));
expect(traza['x']).toHaveLength(3);
expect(c.grupos.filter(g => g.estado === 'disponible').map(g => g.casos)).toEqual([5, 6, 8]);
});
it('el mapa deja en blanco las celdas que no se publican y conserva la posición de cada celda publicada', () => {
// Pins down: a hidden cell is `null` in the matrix (blank), never zero; published cells keep their row and column and carry
// the key that opens their patients. Fails if suppression turns into a zero or shifts a cell.
const m = mapaDescriptivo(copia(mapaData));
const [traza] = mapaFigura(m, 'claro', 'pacientes').data as Record<string, any>[];
const iFila = m.filas.categorias.findIndex(f => f.codigo === 'BIRADS_4'), iCol = m.columnas.categorias.findIndex(c => c.codigo === '50-59');
expect(traza['z'][iFila][iCol]).toBeNull();
const publicada = m.celdas.find(c => !c.suprimido && (c.n ?? 0) > 0)!;
const f = m.filas.categorias.findIndex(x => x.codigo === publicada.fila), c = m.columnas.categorias.findIndex(x => x.codigo === publicada.columna);
expect(traza['z'][f][c]).toBe(publicada.n);
expect(traza['customdata'][f][c]).toEqual([publicada.fila, publicada.columna]);
});
it('la tendencia dibuja los periodos y el porcentaje solo donde se publica, y marca el periodo en curso', () => {
// Pins down: by semester four periods carry a share with an interval; by month the months with fewer than five biopsies
// have no point; the period the cut-off cuts is labelled. Fails if an unpublished period gets a point.
const sem = tendenciaFiguras(tendenciaDescriptiva(copia(tendSem)), 'claro', 'x');
expect((sem.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(4);
const mes = tendenciaDescriptiva(copia(tendMes));
const figuras = tendenciaFiguras(mes, 'claro', 'x');
const publicados = mes.periodos.filter(p => p.maligno.estado === 'disponible').length;
expect((figuras.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(publicados);
expect((figuras.actividad.data[0] as Record<string, any>)['x'].at(-1)).toContain('(en curso)');
});
});
describe('Análisis descriptivo de CaMa (componente)', () => {
let fixture: ComponentFixture<IndicadoresAnalisisDescriptivo>, http: HttpTestingController;
let emitidas: { seleccion: any; origen: HTMLElement | null }[];
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresAnalisisDescriptivo], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresAnalisisDescriptivo); http = TestBed.inject(HttpTestingController);
emitidas = []; fixture.componentInstance.verPacientes.subscribe(e => emitidas.push(e));
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('corte', CORTE);
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const pide = (ruta: string) => http.expectOne(r => r.url === `/cama/analisis${ruta}`);
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
async function abrir() {
fixture.componentRef.setInput('active', true); fixture.detectChanges();
pide('').flush(catalogoData); pide('/resumen').flush(resumenData); pide('/distribucion').flush(distBirads);
pide('/comparacion').flush(compBirads); pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
await asentar();
}
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
it('no pide nada hasta que la pestaña se abre y entonces pide sus seis respuestas con el corte y la selección', async () => {
// Pins down: nothing before the tab is open; then the catalog, indicators (90-day horizon), distribution by BI-RADS,
// comparison by age group, map and semester trend, all at the cut-off and the whole cohort. Fails if a section is
// asked early or without the selection.
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const parametros = (ruta: string) => { const r = pide(ruta); const p = Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); r.flush({}, { status: 404, statusText: 'x' }); return p; };
expect(parametros('')).toEqual({ corte: CORTE, meses: '0' });
expect(parametros('/resumen')).toEqual({ corte: CORTE, meses: '0', horizonte: '90' });
expect(parametros('/distribucion')).toEqual({ corte: CORTE, meses: '0', por: 'birads' });
expect(parametros('/comparacion')).toEqual({ corte: CORTE, meses: '0', por: 'grupo_edad', medida: 'maligno' });
expect(parametros('/mapa')).toEqual({ corte: CORTE, meses: '0', filas: 'birads', columnas: 'grupo_edad', medida: 'maligno' });
expect(parametros('/tendencia')).toEqual({ corte: CORTE, tipo: 'semestre', periodos: '6' });
});
it('dibuja las tarjetas, las tablas y la lista de lo que no se puede calcular, con las mismas 61 pacientes en todas partes', async () => {
// Pins down: the cohort card, the distribution's total and its caption agree on 61 patients; the unavailable analyses
// are listed with their reasons; nothing says the data is simulated, provisional or a test. Fails if two parts of the tab
// count different patients or a banner of that kind appears.
await abrir();
const texto = root().textContent!;
expect(root().querySelectorAll('app-indicador-kpi-card')).toHaveLength(7);
expect(root().querySelector('app-indicador-kpi-card .value')?.textContent).toContain('61');
expect(root().querySelector('#desc-dist ~ div table caption, section[aria-labelledby="desc-dist"] caption')?.textContent).toContain('61 pacientes');
expect(texto).toContain('No disponible con las fuentes actuales');
for (const titulo of ['Supervivencia', 'Recaída', 'Adherencia al tratamiento']) expect(texto).toContain(titulo);
expect(texto).toContain('No hay estado vital');
expect(texto).not.toMatch(/simulad|demostraci|provisional|prueba de concepto|modo de desarrollo|datos de prueba/i);
});
it('una categoría suprimida dice «No publicado» sin botón y una publicada abre sus pacientes con la selección completa', async () => {
// Pins down: BI-RADS 5 (suppressed) has no «Ver pacientes» button; BI-RADS 4 has one and its click emits the filter, the
// label, the cut-off, the patients counted and the cohort context to quote back. Fails if a hidden group can be opened or
// the list would open another selection.
await abrir();
const fila = (codigo: string) => root().querySelector<HTMLElement>(`tr[data-codigo="${codigo}"]`)!;
expect(fila('BIRADS_5').textContent).toContain('No publicado'); expect(fila('BIRADS_5').querySelector('button')).toBeNull();
fila('BIRADS_4').querySelector<HTMLButtonElement>('button.ver')!.click();
expect(emitidas).toHaveLength(1);
expect(emitidas[0].seleccion).toMatchObject({ filtros: { birads: 'BIRADS_4' }, etiqueta: 'BI-RADS 4', corte: CORTE, esperados: 33,
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
});
it('cambiar la dimensión de la distribución vuelve a pedir solo esa sección', async () => {
// Pins down: choosing «Grupo de edad» asks `distribucion?por=grupo_edad` and nothing else, and its answer replaces the
// table. Fails if a choice in one section reloads the rest.
await abrir();
boton('Grupo de edad').click(); fixture.detectChanges();
const r = pide('/distribucion'); expect(r.request.params.get('por')).toBe('grupo_edad'); r.flush(distEdad); await asentar();
expect([...root().querySelectorAll('tr[data-codigo]')].map(tr => tr.getAttribute('data-codigo'))).toEqual(['<40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']);
http.expectNone(() => true);
boton('Resultado de la biopsia').click(); fixture.detectChanges(); pide('/distribucion').flush(distBiopsia); await asentar();
expect(root().querySelector('tr[data-codigo="SIN_BIOPSIA"]')?.textContent).toContain('19');
});
it('un grupo sin suficientes pacientes dice por qué, un 503 lo dice y un 404 queda pendiente, sin pantalla vacía', async () => {
// Pins down: a 403 on the distribution shows the fixed message; the indicators' 503 says the cohort isn't available and
// offers a retry; a 404 is «pendiente», not an error. Fails if a failure leaves the section empty or shows the body.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
pide('').flush(catalogoData);
pide('/resumen').flush({}, { status: 503, statusText: 'x' });
pide('/distribucion').flush(pequenoData, { status: 403, statusText: 'x' });
pide('/comparacion').flush({}, { status: 404, statusText: 'x' });
pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
await asentar();
expect(root().textContent).toContain('La cohorte no está disponible en este momento.');
expect(root().querySelector('#desc-dist')!.parentElement!.querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
expect(root().querySelector('#desc-dist')!.parentElement!.textContent).not.toContain('menos de 5 pacientes: su lista');
expect(root().querySelector('[aria-labelledby="desc-comp"] table')).toBeNull();
});
it('la comparación sin prueba válida lo dice; con prueba válida da el estadístico y su p', async () => {
// Pins down: by BI-RADS no table supports the test and the page says «No disponible» with the reason; by age group it
// gives chi-square, degrees of freedom and p. Fails if a p-value appears on a table the server called invalid.
await abrir();
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toContain('No disponible. Hacen falta al menos dos grupos');
const c = fixture.componentInstance;
c.cambiarComparacion('grupo_edad', 'invasor'); fixture.detectChanges();
pide('/comparacion').flush(compEdad); await asentar();
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toMatch(/χ² 0.089, 2 gl, p 0.957/);
});
it('la tendencia marca el periodo en curso y deja sin cifra el porcentaje que no se publica', async () => {
// Pins down: by month the table says «No publicado» where a month has too few biopsies and labels the current month.
// Fails if a hidden share is written as a number or the partial period looks whole.
await abrir();
fixture.componentInstance.cambiarTendencia('mes', 12); fixture.detectChanges(); pide('/tendencia').flush(tendMes); await asentar();
const tabla = root().querySelector('[aria-labelledby="desc-tend"] table')!;
expect(tabla.textContent).toContain('(en curso)');
expect(tabla.textContent).toContain('No publicado');
expect(new Set([...tabla.querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.trim())).has('No publicado')).toBe(true);
});
it('la actividad de reportes conserva su definición: solo cambia con el corte, nunca con la ventana ni los filtros', async () => {
// Pins down: «Aplicar» with another window and filters reloads the cohort sections with them but not the trend, and a new
// cut-off reloads the trend with only that cut-off, the period type and the count. Fails if the trend takes a filter or
// window it doesn't apply, or isn't refreshed when the cut-off changes.
await abrir();
const c = fixture.componentInstance;
c.meses = 3; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
const d = pide('/distribucion'); expect(d.request.params.get('meses')).toBe('3'); expect(d.request.params.get('grupo_edad')).toBe('50-59');
d.flush({}, { status: 404, statusText: 'x' });
for (const ruta of ['', '/resumen', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
http.expectNone(r => r.url.endsWith('/tendencia'));
fixture.componentRef.setInput('corte', '2026-10-31'); await asentar();
const t = http.expectOne(r => r.url === '/cama/analisis/tendencia');
expect(Object.fromEntries(t.request.params.keys().map(k => [k, t.request.params.get(k)]))).toEqual({ corte: '2026-10-31', tipo: 'semestre', periodos: '6' });
t.flush({}, { status: 404, statusText: 'x' });
for (const ruta of ['', '/resumen', '/distribucion', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
});
it('la actividad de reportes se presenta con su población, la unidad y el alcance de las biopsias, y sin prueba estadística', async () => {
// Pins down: the section names what it counts (reports, not patients), over whom, the scope of the biopsies and that the
// cohort selection doesn't apply; it has no chi-square paragraph. Fails if the text attributes the filters or implies a test.
await abrir();
const seccion = root().querySelector('[aria-labelledby="desc-tend"]')!.textContent!;
expect(seccion).toContain('Actividad de reportes en el tiempo');
expect(seccion).toContain('no depende de la cohorte, la ventana ni los filtros');
expect(seccion).toContain('Cuenta reportes, no pacientes');
expect(seccion).toContain((tendSem as any).alcance_biopsias);
expect(seccion).toContain('Reportes de biopsia');
expect(seccion).not.toMatch(/χ²|p-valor|prueba de homogeneidad/i);
});
it.each([0, 1, 3, 6, 12])('una barra de la distribución con la ventana de %i meses y filtros abre la lista con esa misma ventana', async (m) => {
// Pins down: the selection a published bar emits carries the window the analysis was computed over, the filters applied,
// the cut-off and the cohort context. Fails if a window turns into the whole cohort when the patients are opened.
await abrir();
const c = fixture.componentInstance;
c.meses = m; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
pide('').flush({}, { status: 404, statusText: 'x' }); pide('/resumen').flush({}, { status: 404, statusText: 'x' });
pide('/distribucion').flush({ ...(distBirads as any), ventana: { ...(distBirads as any).ventana, meses: m }, filtros: { birads: null, grupo_edad: '50-59', biopsia: null } });
pide('/comparacion').flush({}, { status: 404, statusText: 'x' }); pide('/mapa').flush({}, { status: 404, statusText: 'x' });
await asentar();
root().querySelector<HTMLButtonElement>('tr[data-codigo="BIRADS_4"] button.ver')!.click();
expect(emitidas.at(-1)!.seleccion).toMatchObject({ filtros: { grupo_edad: '50-59', birads: 'BIRADS_4' }, corte: CORTE, meses: m, esperados: 33,
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
});
it('«No disponible con las fuentes actuales» es una sección plegable, cerrada al inicio, con todo su contenido al abrirla', async () => {
// Pins down: the unavailable analyses sit in a native disclosure (keyboard and screen reader for free), closed at first,
// with its heading as the summary and every title and reason in the list inside it; opening it shows the same text as
// before. Fails if it starts open, loses an entry or stops being reachable from the keyboard.
await abrir();
const plegable = root().querySelector<HTMLDetailsElement>('details[data-plegable="no-disponibles"]')!;
const resumen = plegable.querySelector('summary')!;
expect(plegable.open).toBe(false);
expect(resumen.querySelector('h2')!.textContent).toBe('No disponible con las fuentes actuales');
expect(root().querySelector('section[aria-labelledby="desc-no"] h2')!.id).toBe('desc-no');
expect(resumen.tabIndex).toBeGreaterThanOrEqual(0);
const entradas = [...plegable.querySelectorAll('li')].map(li => li.textContent);
expect(entradas.length).toBe((resumenData as any).no_disponibles.length);
for (const n of (resumenData as any).no_disponibles) expect(entradas.some(t => t!.includes(n.titulo) && t!.includes('No disponible. ' + n.motivo))).toBe(true);
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
expect(plegable.open).toBe(true);
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
expect(plegable.open).toBe(false);
});
});
@@ -0,0 +1,368 @@
import { Component, DestroyRef, effect, inject, input, output, signal, untracked, WritableSignal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { Observable, Subscription } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import {
AnalisisCatalogoDescriptivo, AnalisisDescriptivoService, AnalisisSeleccion, CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis,
PedidoDescriptivo, ResumenAnalisis, TarjetaAnalisis, TendenciaAnalisis,
} from './indicadores-analisis.service';
import { comparacionFigura, distribucionFigura, FigurasTendencia, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
import { Dominio, PlotlyFigure, Tema } from './indicadores.models';
import type { SeleccionPacientes } from './indicadores-analisis';
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
const VACIA = { data: [], layout: {} } as PlotlyFigure;
const miles = (v: number) => v.toLocaleString('es-MX');
const decimal = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
/** The card's value as the page writes it: a share with its interval, a median with its quartiles, or a count. */
export function valorTarjeta(t: TarjetaAnalisis): string | null {
if (t.estado !== 'disponible' || t.valor === null) return null;
return t.unidad === '%' ? decimal(t.valor) : t.unidad === 'días' ? decimal(t.valor) : miles(t.valor);
}
export function detalleTarjeta(t: TarjetaAnalisis): string {
if (t.estado === 'suprimido') return 'Muy pocos pacientes para publicar esta cifra. ' + t.descripcion;
if (t.estado === 'sin_datos') return 'No hay pacientes en esta base para calcularla. ' + t.descripcion;
const partes: string[] = [];
if (t.unidad === '%' && t.ic_bajo !== null && t.ic_alto !== null) partes.push(`IC 95 %: ${decimal(t.ic_bajo)} a ${decimal(t.ic_alto)} %. ${miles(t.n ?? 0)} de ${miles(t.denominador ?? 0)} pacientes.`);
if (t.unidad === 'días' && t.q1 !== null && t.q3 !== null) partes.push(`Q1 a Q3: ${decimal(t.q1)} a ${decimal(t.q3)} días. ${miles(t.n ?? 0)} pacientes.`);
partes.push(t.descripcion);
return partes.join(' ');
}
// Descriptive analysis of the BI-RADS cohort: its indicators, its distribution, a comparison between groups, the map
// between two variables and the trend over time. Every figure is drawn from the endpoint's answer; what the data cannot
// hold is listed as not available, with its reason. Nothing is requested until the tab is first opened.
@Component({
selector: 'app-indicadores-analisis-descriptivo',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
template: `
<section class="bloque" aria-labelledby="desc-resumen">
<h2 id="desc-resumen">Indicadores de la cohorte</h2>
<p class="nota">Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6. Descriptivos: describen a estas pacientes, no la incidencia en una población.</p>
<form class="controles" (ngSubmit)="aplicar()">
<label>Ventana
<select name="meses" [(ngModel)]="meses">
<option [ngValue]="0">Toda la cohorte</option><option [ngValue]="1">Último mes</option><option [ngValue]="3">Últimos 3 meses</option>
<option [ngValue]="6">Últimos 6 meses</option><option [ngValue]="12">Últimos 12 meses</option>
</select></label>
<label>Categoría BI-RADS
<select name="birads" [(ngModel)]="filtros['birads']"><option [ngValue]="undefined">Todas</option>
@for (o of opciones('birads'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
<label>Grupo de edad
<select name="grupo_edad" [(ngModel)]="filtros['grupo_edad']"><option [ngValue]="undefined">Todos</option>
@for (o of opciones('grupo_edad'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
<label>Horizonte del seguimiento diagnóstico
<select name="horizonte" [(ngModel)]="horizonte">
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} días</option> }</select></label>
<button type="submit" mat-stroked-button [disabled]="cargando()">Aplicar</button>
</form>
@switch (resumen().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores" /> }
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
@case ('no-disponible') { <p role="status">La cohorte no está disponible en este momento.</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button> }
@case ('error') { <div role="alert"><p>{{ $any(resumen()).mensaje }}</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button></div> }
}
@if (r(); as res) {
<p class="contexto">Fecha de corte: {{ res.corte }}. Ventana: {{ res.ventana.meses === 0 ? 'toda la cohorte' : res.ventana.desde + ' al ' + res.ventana.hasta }}.</p>
<div class="tarjetas">
@for (t of res.indicadores; track t.clave) {
<app-indicador-kpi-card [title]="t.titulo" [value]="valor(t)" [unit]="t.unidad === 'pacientes' ? '' : t.unidad === 'días' ? 'días (mediana)' : '%'"
[state]="t.estado === 'disponible' ? 'Disponible' : t.estado === 'suprimido' ? 'Dato oculto por tamaño' : 'Sin valor disponible'"
[quietWhenAvailable]="true" [additionalInfo]="detalle(t)" />
}
</div>
}
</section>
<section class="bloque" aria-labelledby="desc-dist">
<h2 id="desc-dist">Distribución de pacientes</h2>
<div class="selector" role="group" aria-label="Distribuir por">
@for (d of dimensionesDist; track d.clave) {
<button type="button" mat-stroked-button [class.activo]="por() === d.clave" [attr.aria-pressed]="por() === d.clave" (click)="cambiarPor(d.clave)">{{ d.etiqueta }}</button>
}
</div>
@switch (distribucion().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la distribución" /> }
@case ('error') { <div role="alert"><p>{{ $any(distribucion()).mensaje }}</p></div> }
}
@if (dist(); as d) {
@if (d.total === 0) { <p role="status">No hay pacientes en esta cohorte para el corte seleccionado.</p> }
@else {
<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>
<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>
}</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> }
}
}
</section>
<section class="bloque" aria-labelledby="desc-comp">
<h2 id="desc-comp">Comparación entre grupos</h2>
<p class="nota">Porcentaje de pacientes con el resultado elegido entre las que tienen resultado de biopsia conocido, por grupo. Es una comparación descriptiva dentro de la cohorte.</p>
<div class="controles">
<label>Comparar por
<select name="comp-por" [ngModel]="compPor()" (ngModelChange)="cambiarComparacion($event, compMedida())">
<option value="birads">Categoría BI-RADS</option><option value="grupo_edad">Grupo de edad</option></select></label>
<label>Resultado
<select name="comp-medida" [ngModel]="compMedida()" (ngModelChange)="cambiarComparacion(compPor(), $event)">
<option value="maligno">Carcinoma in situ o invasor</option><option value="invasor">Carcinoma invasor</option></select></label>
</div>
@switch (comparacion().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la comparación" /> }
@case ('error') { <div role="alert"><p>{{ $any(comparacion()).mensaje }}</p></div> }
}
@if (comp(); as c) {
@if (hayComparables()) { <app-plotly-chart [showNotes]="false" [figure]="figuraComp()" label="Comparación entre grupos" /> }
@else { <p role="status">Ningún grupo tiene suficientes pacientes con resultado de biopsia para publicar su porcentaje.</p> }
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Comparación entre grupos, tabla">
<table><caption>{{ c.denominador }}</caption>
<thead><tr><th scope="col">Grupo</th><th scope="col">Con el resultado</th><th scope="col">Con resultado conocido</th><th scope="col">Porcentaje (IC 95 %)</th></tr></thead>
<tbody>@for (g of c.grupos; track g.codigo) {
<tr><th scope="row">{{ g.etiqueta }}</th>
<td>{{ g.estado === 'disponible' ? miles(g.casos!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
<td>{{ g.estado === 'disponible' ? miles(g.total!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
<td>{{ g.estado === 'disponible' ? decimal(g.valor!) + ' % (' + decimal(g.ic_bajo!) + ' a ' + decimal(g.ic_alto!) + ')' : 'No disponible' }}</td></tr>
}</tbody></table>
</div>
<p class="nota" role="status">{{ textoPrueba(c.prueba) }}</p>
}
</section>
<section class="bloque" aria-labelledby="desc-mapa">
<h2 id="desc-mapa">Mapa entre variables: categoría BI-RADS y grupo de edad</h2>
<div class="selector" role="group" aria-label="Medida del mapa">
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'pacientes'" [attr.aria-pressed]="mapaMedida() === 'pacientes'" (click)="cambiarMapa('pacientes')">Pacientes</button>
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'resultado'" [attr.aria-pressed]="mapaMedida() === 'resultado'" (click)="cambiarMapa('resultado')">Porcentaje con carcinoma</button>
</div>
@switch (mapa().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa" /> }
@case ('error') { <div role="alert"><p>{{ $any(mapa()).mensaje }}</p></div> }
}
@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>
<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>
<tbody>@for (c of celdasPublicadas(mm); track c.fila + c.columna) {
<tr><th scope="row">{{ etiqueta(mm.filas.categorias, c.fila) }}</th><td>{{ etiqueta(mm.columnas.categorias, c.columna) }}</td><td>{{ miles(c.n!) }}</td>
<td>{{ c.resultado.estado === 'disponible' ? c.resultado.casos + ' de ' + c.resultado.total + ' (' + decimal(c.resultado.valor!) + ' %)' : 'No disponible' }}</td></tr>
}</tbody></table>
</div>
</details>
}
</section>
<section class="bloque" aria-labelledby="desc-tend">
<h2 id="desc-tend">Actividad de reportes en el tiempo</h2>
<p class="nota">Reportes de mastografía con BI-RADS y de biopsia ligada a esas mastografías en cada periodo, de todas las pacientes, y el porcentaje de resultados con carcinoma entre los reportes de biopsia con resultado. Es la actividad general: no depende de la cohorte, la ventana ni los filtros de arriba. Cuenta reportes, no pacientes; una paciente con varios reportes se cuenta varias veces.</p>
<div class="controles">
<label>Periodo
<select name="tend-tipo" [ngModel]="tendTipo()" (ngModelChange)="cambiarTendencia($event, tendPeriodos())"><option value="semestre">Semestral</option><option value="mes">Mensual</option></select></label>
<label>Periodos a mostrar
<select name="tend-n" [ngModel]="tendPeriodos()" (ngModelChange)="cambiarTendencia(tendTipo(), $event)"><option [ngValue]="4">4</option><option [ngValue]="6">6</option><option [ngValue]="12">12</option><option [ngValue]="24">24</option></select></label>
</div>
@switch (tendencia().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la tendencia" /> }
@case ('error') { <div role="alert"><p>{{ $any(tendencia()).mensaje }}</p></div> }
}
@if (t(); as tt) {
<div class="par">
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().actividad" label="Reportes de mastografía y de biopsia por periodo" />
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().proporcion" label="Porcentaje de resultados con carcinoma por periodo" />
</div>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Tendencia, tabla">
<table><thead><tr><th scope="col">Periodo</th><th scope="col">Reportes de mastografía</th><th scope="col">Reportes de biopsia</th><th scope="col">Con carcinoma (IC 95 %)</th></tr></thead>
<tbody>@for (p of tt.periodos; track p.periodo) {
<tr><th scope="row">{{ p.periodo }}@if (p.incompleto) { <span class="nota"> (en curso)</span> }</th>
<td>{{ p.reportes_mastografia.total === null ? 'No publicado' : miles(p.reportes_mastografia.total) }}</td>
<td>{{ p.reportes_biopsia.total === null ? 'No publicado' : miles(p.reportes_biopsia.total) }}</td>
<td>{{ p.maligno.estado === 'disponible' ? p.maligno.casos + ' de ' + p.maligno.total + ' (' + decimal(p.maligno.valor!) + ' %; ' + decimal(p.maligno.ic_bajo!) + ' a ' + decimal(p.maligno.ic_alto!) + ')' : p.maligno.estado === 'suprimido' ? 'No publicado' : 'Sin reportes de biopsia con resultado' }}</td></tr>
}</tbody></table>
</div>
<p class="nota" role="status">{{ tt.alcance_biopsias }}. Los periodos en curso están incompletos y se marcan.</p>
}
</section>
@if (r(); as res) {
<section class="bloque" aria-labelledby="desc-no">
<!-- Closed at first; the native disclosure gives the keyboard (Enter and Space) and the screen reader its state. -->
<details class="plegable" data-plegable="no-disponibles">
<summary><h2 id="desc-no">No disponible con las fuentes actuales</h2></summary>
<ul class="no-disponibles">
@for (n of res.no_disponibles; track n.clave) { <li><strong>{{ n.titulo }}</strong>: No disponible. {{ n.motivo }}</li> }
</ul>
</details>
</section>
}
`,
styles: `
:host { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
.bloque { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p, ul { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.nota, .contexto { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-4); }
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (min-width: 1100px) { .tarjetas { grid-template-columns: repeat(4, minmax(0, 1fr)); } .par { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.par { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
.selector { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin-top: var(--issste-space-3); }
.selector .activo { background: var(--issste-accent, #A8C243); color: #081839; }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
select { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; font: inherit; }
select:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
app-plotly-chart { margin-top: var(--issste-space-3); }
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
td { font-variant-numeric: tabular-nums; }
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
.ver:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
details { margin-top: var(--issste-space-3); } summary { cursor: pointer; }
.no-disponibles { padding-left: 1.2rem; color: var(--issste-text-secondary); }
.plegable > summary { display: list-item; list-style-position: inside; cursor: pointer; border-radius: var(--issste-radius); }
.plegable > summary h2 { display: inline; }
.plegable > summary:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
`,
})
export class IndicadoresAnalisisDescriptivo {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly corte = input.required<string>();
readonly active = input(false);
readonly verPacientes = output<{ seleccion: SeleccionPacientes; origen: HTMLElement | null }>();
readonly miles = miles; readonly decimal = decimal;
readonly valor = valorTarjeta; readonly detalle = detalleTarjeta;
readonly dimensionesDist = [{ clave: 'birads', etiqueta: 'Categoría BI-RADS' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, { clave: 'biopsia', etiqueta: 'Resultado de la biopsia' }];
meses = 0; horizonte = 90; filtros: Record<string, string | undefined> = {};
readonly por = signal('birads');
readonly compPor = signal('grupo_edad'); readonly compMedida = signal('maligno');
readonly mapaMedida = signal<'pacientes' | 'resultado'>('pacientes');
readonly tendTipo = signal('semestre'); readonly tendPeriodos = signal(6);
readonly catalogo = signal<Carga<AnalisisCatalogoDescriptivo>>({ estado: 'cargando' });
readonly resumen = signal<Carga<ResumenAnalisis>>({ estado: 'cargando' });
readonly distribucion = signal<Carga<DistribucionAnalisis>>({ estado: 'cargando' });
readonly comparacion = signal<Carga<ComparacionAnalisis>>({ estado: 'cargando' });
readonly mapa = signal<Carga<MapaAnalisis>>({ estado: 'cargando' });
readonly tendencia = signal<Carga<TendenciaAnalisis>>({ estado: 'cargando' });
readonly figuraDist = signal<PlotlyFigure>(VACIA); readonly figuraComp = signal<PlotlyFigure>(VACIA);
readonly figuraMapa = signal<PlotlyFigure>(VACIA);
readonly figurasTend = signal<FigurasTendencia>({ actividad: VACIA, proporcion: VACIA });
private readonly service = inject(AnalisisDescriptivoService);
private readonly destroy = inject(DestroyRef);
private readonly suscripciones = new Map<string, Subscription>();
private abierto = false; private corteCargado = ''; private tendCorte = '';
// The filters and window the sections were last asked with: one selection for all of them.
private pedidoVigente: PedidoDescriptivo = { corte: '', meses: 0, filtros: {} };
constructor() {
effect(() => {
const activa = this.active(), corte = this.corte();
if (!activa) return;
untracked(() => { if (!this.abierto || corte !== this.corteCargado) { this.abierto = true; this.corteCargado = corte; this.aplicar(); } });
});
}
// Each accessor gives the loaded data or nothing: the template draws only what the endpoint answered.
r() { const c = this.resumen(); return c.estado === 'listo' ? c.datos : undefined; }
dist() { const c = this.distribucion(); return c.estado === 'listo' ? c.datos : undefined; }
comp() { const c = this.comparacion(); return c.estado === 'listo' ? c.datos : undefined; }
m() { const c = this.mapa(); return c.estado === 'listo' ? c.datos : undefined; }
t() { const c = this.tendencia(); return c.estado === 'listo' ? c.datos : undefined; }
cargando() { return [this.resumen(), this.distribucion(), this.comparacion(), this.mapa(), this.tendencia()].some(c => c.estado === 'cargando'); }
opciones(clave: string) { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.dimensiones.find(d => d.clave === clave)?.opciones ?? [] : []; }
horizontes() { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.horizontes_dias : [90]; }
hayComparables() { return !!this.comp()?.grupos.some(g => g.estado === 'disponible'); }
celdasPublicadas(m: MapaAnalisis): CeldaMapa[] { return m.celdas.filter(c => !c.suprimido && (c.n ?? 0) > 0); }
etiqueta(categorias: { codigo: string; etiqueta: string }[], codigo: string) { return categorias.find(c => c.codigo === codigo)?.etiqueta ?? codigo; }
textoPrueba(p: { valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; nombre: string }) {
if (!p.valida) return `${p.nombre}: No disponible. ${p.motivo ?? ''}`.trim();
const valor = p.p! < 0.001 ? '< 0.001' : p.p!.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
return `${p.nombre}: χ² ${p.estadistico!.toLocaleString('es-MX')}, ${p.gl} gl, p ${valor}. Describe diferencias en estas pacientes; no es una estimación causal.`;
}
private pedido(): PedidoDescriptivo {
return { corte: this.corte(), meses: this.meses, filtros: { ...this.filtros } };
}
/** Asks every section for the selection in the form: the first time, on a new cut-off and on «Aplicar». */
aplicar() {
this.pedidoVigente = this.pedido();
const p = this.pedidoVigente;
this.cargar('catalogo', this.catalogo, this.service.catalogo(this.dominio(), p));
this.cargar('resumen', this.resumen, this.service.resumen(this.dominio(), p, this.horizonte));
this.recargarDist(); this.recargarComp(); this.recargarMapa();
// The trend depends only on the cut-off: «Aplicar» with other filters or window leaves it as it is.
if (this.corte() !== this.tendCorte) { this.tendCorte = this.corte(); this.recargarTend(); }
}
private recargarDist() { this.cargar('dist', this.distribucion, this.service.distribucion(this.dominio(), this.pedidoVigente, this.por()), d => this.figuraDist.set(distribucionFigura(d, this.tema()))); }
private recargarComp() { this.cargar('comp', this.comparacion, this.service.comparacion(this.dominio(), this.pedidoVigente, this.compPor(), this.compMedida()), c => this.figuraComp.set(comparacionFigura(c, this.tema(), this.compMedida() === 'invasor' ? 'Carcinoma invasor' : 'Carcinoma in situ o invasor'))); }
private recargarMapa() { this.cargar('mapa', this.mapa, this.service.mapa(this.dominio(), this.pedidoVigente, 'birads', 'grupo_edad', 'maligno'), m => this.figuraMapa.set(mapaFigura(m, this.tema(), this.mapaMedida()))); }
private recargarTend() { this.cargar('tend', this.tendencia, this.service.tendencia(this.dominio(), this.corte(), this.tendTipo(), this.tendPeriodos()), t => this.figurasTend.set(tendenciaFiguras(t, this.tema(), 'Con carcinoma entre biopsias con resultado'))); }
cambiarPor(clave: string) { this.por.set(clave); this.recargarDist(); }
cambiarComparacion(por: string, medida: string) { this.compPor.set(por); this.compMedida.set(medida); this.recargarComp(); }
cambiarMapa(medida: 'pacientes' | 'resultado') { this.mapaMedida.set(medida); const m = this.m(); if (m) this.figuraMapa.set(mapaFigura(m, this.tema(), medida)); }
cambiarTendencia(tipo: string, periodos: number) { this.tendTipo.set(tipo); this.tendPeriodos.set(periodos); this.recargarTend(); }
private cargar<T>(clave: string, destino: WritableSignal<Carga<T>>, fuente: Observable<T>, alListo?: (d: T) => void) {
this.suscripciones.get(clave)?.unsubscribe();
destino.set({ estado: 'cargando' });
this.suscripciones.set(clave, fuente.pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: datos => { destino.set({ estado: 'listo', datos }); alListo?.(datos); },
error: error => destino.set(this.fallo(error)),
}));
}
private fallo(error: unknown): Carga<never> {
if (error instanceof HttpErrorResponse) {
if (error.status === 404) return { estado: 'pendiente' };
if (error.status === 503) return { estado: 'no-disponible' };
if (error.status === 403) return { estado: 'error', mensaje: 'La selección tiene muy pocos pacientes para publicar sus resultados.' };
if (error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió. Consulta de nuevo.' };
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la selección. Revisa la ventana y los filtros.' };
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
}
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
}
/** The patients of a published group or cell, for the page to open them in Seguimiento. */
abrir(seleccion: Record<string, string>, etiqueta: string, n: number | null, base: AnalisisSeleccion, origen?: EventTarget | null) {
if (!n) return;
const activos = Object.fromEntries(Object.entries(base.filtros).filter(([, v]) => v !== null)) as Record<string, string>;
this.verPacientes.emit({
origen: origen instanceof HTMLElement ? origen : null,
seleccion: { filtros: { ...activos, ...seleccion }, etiqueta, corte: base.corte, meses: base.ventana.meses, esperados: n, contexto: { cohorte: base.cohorte, escenario: base.escenario, revision: base.revision } },
});
}
clicDist(evento: unknown) {
const codigo = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0]?.customdata;
const d = this.dist(), item = d?.items.find(i => i.codigo === codigo && !i.suprimido);
if (d && item) this.abrir(item.seleccion, item.etiqueta, item.n, d);
}
clicMapa(evento: unknown) {
const c = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
const [fila, columna] = Array.isArray(c?.customdata) ? c.customdata as string[] : [];
const mm = this.m(), celda = mm?.celdas.find(x => x.fila === fila && x.columna === columna && !x.suprimido);
if (mm && celda) this.abrir(celda.seleccion, `${this.etiqueta(mm.filas.categorias, celda.fila)}, ${this.etiqueta(mm.columnas.categorias, celda.columna)}`, celda.n, mm);
}
}
@@ -55,3 +55,119 @@ export class AnalisisService {
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
}
}
// The descriptive analysis (`/<dominio>/analisis/...`): counts and proportions of the cohort at a cut-off, with the
// window and filters of the follow-up list. Every answer names the cohort it describes, so a figure can open its patients.
export interface AnalisisSeleccion {
cohorte: string; escenario: string; revision: string; corte: string; umbral_supresion: number;
ventana: { meses: number; desde: string; hasta: string };
filtros: Record<string, string | null>;
}
export type EstadoDato = 'disponible' | 'suprimido' | 'sin_datos';
export interface Proporcion { estado: EstadoDato; casos: number | null; total: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; }
export interface DimensionAnalisis { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
export interface NoDisponible { clave: string; titulo: string; motivo: string; }
export interface AnalisisCatalogoDescriptivo extends AnalisisSeleccion {
dimensiones: DimensionAnalisis[]; medidas: { clave: string; etiqueta: string }[]; horizontes_dias: number[]; tipos_periodo: string[];
secciones: { clave: string; titulo: string; estado: string; motivo: string | null }[]; no_disponibles: NoDisponible[];
}
export interface TarjetaAnalisis {
clave: string; titulo: string; descripcion: string; unidad: string; estado: EstadoDato; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
n: number | null; denominador: number | null; q1: number | null; q3: number | null; motivo: string | null;
}
export interface ResumenAnalisis extends AnalisisSeleccion { horizonte_dias: number; indicadores: TarjetaAnalisis[]; no_disponibles: NoDisponible[]; }
export interface ItemDistribucion { codigo: string; etiqueta: string; suprimido: boolean; n: number | null; porcentaje: number | null; ic_bajo: number | null; ic_alto: number | null; seleccion: Record<string, string>; }
export interface DistribucionAnalisis extends AnalisisSeleccion { por: string; total: number; items: ItemDistribucion[]; }
export interface Prueba { nombre: string; valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; }
export interface GrupoComparacion extends Proporcion { codigo: string; etiqueta: string; seleccion: Record<string, string>; }
export interface ComparacionAnalisis extends AnalisisSeleccion { por: string; medida: string; denominador: string; grupos: GrupoComparacion[]; prueba: Prueba; }
export interface CeldaMapa { fila: string; columna: string; suprimido: boolean; n: number | null; seleccion: Record<string, string>; resultado: Proporcion; }
export interface EjeMapa { por: string; categorias: { codigo: string; etiqueta: string }[]; }
export interface MapaAnalisis extends AnalisisSeleccion { filas: EjeMapa; columnas: EjeMapa; medida: string; celdas: CeldaMapa[]; }
export interface ConteoPeriodo { n: number | null; suprimido: boolean; }
export interface PeriodoTendencia {
periodo: string; inicio: string; fin: string; incompleto: boolean;
reportes_mastografia: { total: number | null; por_categoria: Record<string, ConteoPeriodo> };
reportes_biopsia: { total: number | null; por_grado: Record<string, ConteoPeriodo> };
maligno: Proporcion;
}
// The trend is general activity, not the cohort: it carries no cohort, window or filters, only what it counts and over whom.
export interface TendenciaAnalisis {
corte: string; umbral_supresion: number; tipo_periodo: string; unidad: string; poblacion: string; alcance_biopsias: string;
denominador: string; periodos: PeriodoTendencia[];
}
export interface PedidoDescriptivo { corte: string; meses: number; filtros: Record<string, string | undefined>; contexto?: { cohorte: string; escenario: string; revision: string }; }
const numOnulo = (v: unknown) => v === null || (typeof v === 'number' && Number.isFinite(v));
const estadoOk = (v: unknown) => v === 'disponible' || v === 'suprimido' || v === 'sin_datos';
const proporcionOk = (v: unknown) => record(v) && estadoOk(v['estado']) && numOnulo(v['valor']) && numOnulo(v['ic_bajo']) && numOnulo(v['ic_alto'])
&& numOnulo(v['casos']) && numOnulo(v['total']) && (v['estado'] === 'disponible' ? v['valor'] !== null && v['casos'] !== null : v['valor'] === null);
const seleccionOk = (v: unknown): v is Record<string, unknown> => record(v) && text(v['cohorte']) && text(v['escenario']) && text(v['revision']) && text(v['corte'])
&& typeof v['umbral_supresion'] === 'number' && record(v['ventana']) && record(v['filtros']);
const invalidoDescriptivo = (): never => { throw new Error('Respuesta de análisis inválida'); };
export function catalogoDescriptivo(v: unknown): AnalisisCatalogoDescriptivo {
if (!seleccionOk(v) || !Array.isArray(v['dimensiones']) || !v['dimensiones'].every(d => record(d) && text(d['clave']) && Array.isArray(d['opciones']))
|| !Array.isArray(v['no_disponibles']) || !Array.isArray(v['horizontes_dias']) || !Array.isArray(v['tipos_periodo'])) invalidoDescriptivo();
return v as unknown as AnalisisCatalogoDescriptivo;
}
export function resumenDescriptivo(v: unknown): ResumenAnalisis {
if (!seleccionOk(v) || !Array.isArray(v['indicadores']) || !v['indicadores'].every(t => record(t) && text(t['clave']) && text(t['titulo']) && estadoOk(t['estado'])
&& numOnulo(t['valor']) && (t['estado'] === 'disponible' ? t['valor'] !== null : t['valor'] === null))) invalidoDescriptivo();
return v as unknown as ResumenAnalisis;
}
export function distribucionDescriptiva(v: unknown): DistribucionAnalisis {
if (!seleccionOk(v) || typeof v['total'] !== 'number' || !Array.isArray(v['items'])
|| !v['items'].every(i => record(i) && text(i['codigo']) && typeof i['suprimido'] === 'boolean' && numOnulo(i['n']) && (i['suprimido'] ? i['n'] === null : i['n'] !== null)
&& record(i['seleccion']))) invalidoDescriptivo();
return v as unknown as DistribucionAnalisis;
}
export function comparacionDescriptiva(v: unknown): ComparacionAnalisis {
if (!seleccionOk(v) || !Array.isArray(v['grupos']) || !v['grupos'].every(g => record(g) && text(g['codigo']) && proporcionOk(g))
|| !record(v['prueba']) || typeof v['prueba']['valida'] !== 'boolean') invalidoDescriptivo();
return v as unknown as ComparacionAnalisis;
}
export function mapaDescriptivo(v: unknown): MapaAnalisis {
if (!seleccionOk(v) || !record(v['filas']) || !record(v['columnas']) || !Array.isArray(v['celdas'])
|| !v['celdas'].every(c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean' && numOnulo(c['n'])
&& (c['suprimido'] ? c['n'] === null : c['n'] !== null) && record(c['resultado']) && estadoOk(c['resultado']['estado']))) invalidoDescriptivo();
return v as unknown as MapaAnalisis;
}
export function tendenciaDescriptiva(v: unknown): TendenciaAnalisis {
if (!record(v) || !text(v['corte']) || v['unidad'] !== 'reportes' || !text(v['poblacion']) || !text(v['alcance_biopsias']) || !text(v['tipo_periodo'])
|| !Array.isArray(v['periodos']) || !v['periodos'].every(p => record(p) && text(p['periodo']) && typeof p['incompleto'] === 'boolean'
&& record(p['reportes_mastografia']) && record(p['reportes_biopsia']) && proporcionOk(p['maligno']))) invalidoDescriptivo();
return v as unknown as TendenciaAnalisis;
}
function paramsDe(pedido: PedidoDescriptivo, extra: Record<string, string | number | undefined> = {}) {
let params = new HttpParams().set('corte', pedido.corte).set('meses', pedido.meses);
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
if (pedido.contexto) for (const [k, v] of Object.entries(pedido.contexto)) params = params.set(k, v);
for (const [k, v] of Object.entries(extra)) if (v !== undefined) params = params.set(k, v);
return params;
}
@Injectable({ providedIn: 'root' })
export class AnalisisDescriptivoService {
private readonly http = inject(HttpClient);
private url(dominio: Dominio, ruta: string) { return `/${requireDominio(dominio)}/analisis${ruta}`; }
catalogo(d: Dominio, p: PedidoDescriptivo) { return this.http.get<unknown>(this.url(d, ''), { params: paramsDe(p) }).pipe(map(catalogoDescriptivo)); }
resumen(d: Dominio, p: PedidoDescriptivo, horizonte: number) {
return this.http.get<unknown>(this.url(d, '/resumen'), { params: paramsDe(p, { horizonte }) }).pipe(map(resumenDescriptivo));
}
distribucion(d: Dominio, p: PedidoDescriptivo, por: string) {
return this.http.get<unknown>(this.url(d, '/distribucion'), { params: paramsDe(p, { por }) }).pipe(map(distribucionDescriptiva));
}
comparacion(d: Dominio, p: PedidoDescriptivo, por: string, medida: string) {
return this.http.get<unknown>(this.url(d, '/comparacion'), { params: paramsDe(p, { por, medida }) }).pipe(map(comparacionDescriptiva));
}
mapa(d: Dominio, p: PedidoDescriptivo, filas: string, columnas: string, medida: string) {
return this.http.get<unknown>(this.url(d, '/mapa'), { params: paramsDe(p, { filas, columnas, medida }) }).pipe(map(mapaDescriptivo));
}
/** The trend takes only the cut-off, the period type and the number of periods: never the window, filters or context. */
tendencia(d: Dominio, corte: string, tipo: string, periodos: number) {
const params = new HttpParams().set('corte', corte).set('tipo', tipo).set('periodos', periodos);
return this.http.get<unknown>(this.url(d, '/tendencia'), { params }).pipe(map(tendenciaDescriptiva));
}
}
@@ -1,12 +1,12 @@
import { Component, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { analisisAgregado } from './indicadores-analisis.service';
import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing';
import { agregado, agregadoJson, CONTEXTO, CORTE, sinAnalisisDescriptivo } from './indicadores-analisis.testing';
// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
@@ -80,7 +80,7 @@ class ChartStub { readonly plotClick = output<unknown>(); }
describe('Pestaña Análisis epidemiológico', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
@@ -1,5 +1,7 @@
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { throwError } from 'rxjs';
import { AnalisisAgregado } from './indicadores-analisis.service';
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
@@ -45,3 +47,12 @@ export function listaCohorte(o: { corte?: string; filtros?: Record<string, strin
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
/**
* For specs of the analysis tab that are about its BI-RADS aggregate and its way to Seguimiento: the descriptive sections
* below it (catalog, indicators, distribution, comparison, map, trend) answer «not published» and never reach the test
* backend, so those specs keep counting only the requests they are about.
*/
export const sinAnalisisDescriptivo: HttpInterceptorFn = (req, next) =>
/^\/[a-z]+\/analisis(\/(resumen|distribucion|comparacion|mapa|tendencia))?$/.test(req.url)
? throwError(() => new HttpErrorResponse({ status: 404, url: req.url })) : next(req);
@@ -7,6 +7,7 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { IndicadoresAnalisisDescriptivo } from './indicadores-analisis-descriptivo';
import { isoDate } from './cacu-seguimiento.models';
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { etiquetaBirads } from './etiquetas-cohorte';
@@ -20,7 +21,7 @@ type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estad
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
* patients the analysis counts there.
*/
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; esperados: number | null; contexto: ContextoCohorte; }
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; meses?: number; esperados: number | null; contexto: ContextoCohorte; }
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
@@ -54,7 +55,7 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
@Component({
selector: 'app-indicadores-analisis',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard, IndicadoresAnalisisDescriptivo],
template: `
<section class="analisis" aria-labelledby="analisis-titulo">
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
@@ -112,6 +113,7 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
}
</article>
</section>
<app-indicadores-analisis-descriptivo [dominio]="dominio()" [tema]="tema()" [corte]="corteConsultado()" [active]="active()" (verPacientes)="abrirDescriptivo($event)" />
`,
styles: `
:host { display: block; min-width: 0; }
@@ -166,6 +168,8 @@ export class IndicadoresAnalisis {
private ultimo?: string;
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
corte = this.hoy;
// The cut-off of the last query: the descriptive sections follow it.
readonly corteConsultado = signal(this.hoy);
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
// Why the last click on a bar opened nothing.
readonly aviso = signal('');
@@ -206,6 +210,7 @@ export class IndicadoresAnalisis {
consultar() {
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
this.ultimo = this.corte;
this.corteConsultado.set(this.corte);
this.pedidos.next(this.corte);
}
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
@@ -229,6 +234,12 @@ export class IndicadoresAnalisis {
this.retorno = { origen: el, area, arriba: area.scrollTop };
this.verPacientes.emit(seleccion);
}
// The patients of a figure of the descriptive sections: the same way back as a bar of the BI-RADS table.
abrirDescriptivo(evento: { seleccion: SeleccionPacientes; origen: HTMLElement | null }) {
const area = contenedorDeScroll(this.host.nativeElement);
this.retorno = { origen: evento.origen, area, arriba: area.scrollTop };
this.verPacientes.emit(evento.seleccion);
}
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
restaurar() {
const r = this.retorno;
@@ -18,7 +18,7 @@ export function c1AlterationCapability(contract: string, representation: string)
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The any-alteration bar keeps the red of the event; each alteration takes its own colour.
// The any-alteration bar uses the second series colour; each alteration takes its own colour.
const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]];
const color = (i: number) => COLORS[i % COLORS.length];
@@ -21,7 +21,7 @@ const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'],
M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'],
};
// Green for the event, red for its complement; age groups get lighter shades.
// Olive for the event, the next series colour for its complement; age groups keep their own colours.
const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const;
// One colour per age group, the same in the donut (M21) and the bars (M22).
const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length];
@@ -1,5 +1,5 @@
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
import { c2Color, C2_PALETTE } from './indicadores-c2-palette';
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
import { c2Fixture } from './indicadores-c2-adapter.testing';
import { FigureSelection } from './indicadores.models';
import { donutFixture } from './indicadores-donut-drilldown.testing';
@@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
const legend = donutLegend(final), view = donutSimpleView(final);
expect(legend).toEqual([
{ label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' },
{ label: 'A', color: C2_PALETTE.series[0] }, { label: 'B', color: C2_PALETTE.series[1] }, { label: 'C', color: C2_PALETTE.series[2] },
]);
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
@@ -158,15 +158,18 @@ describe('C2: datos publicados a Plotly', () => {
});
describe('paleta C2 institucional y semántica', () => {
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => {
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
const figure = supported(data, { ...selection, tema }).figure;
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']);
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A');
expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778');
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
expect(c2Color('#D98E4A', 0)).toBe('#D98E4A');
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
});
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
@@ -1,6 +1,6 @@
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
import { DonutHierarchy } from './indicadores-donut-drilldown';
import { c2Color, c2Theme } from './indicadores-c2-palette';
import { c2Theme, groupBase, seriesColors } from './indicadores-c2-palette';
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
// Normalized presentation nodes and a selection path are independent of Plotly.
@@ -81,7 +81,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))];
const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] };
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
const colors = categories.map((c, i) => c2Color(c.color, i));
const colors = seriesColors(categories.map(c => c.color));
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
@@ -109,7 +109,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
marker: { colors: parents.map((_, i) => c2Color(undefined, i)), line: { color: theme.outline, width: 0.7 } },
marker: { colors: parents.map((_, i) => groupBase(i)), line: { color: theme.outline, width: 0.7 } },
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
}
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
@@ -19,7 +19,9 @@ describe('selección local segura de barras generales C2', () => {
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
const view = c2GeneralSelection(source, data, selection, local)!;
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } });
const marker = source.data[0]['marker'] as { color: string[] }, labels = source.data[0]['y'] as string[];
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'],
marker: { color: ['B', 'C'].map(label => marker.color[labels.indexOf(label)]) } });
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
expect(view.context).toContain('G2, 2025-S2');
@@ -0,0 +1,53 @@
import { C2_PALETTE, groupBase, institutionalize, isHarmoniousColor, paintByGroup, recolorFigure } from './indicadores-c2-palette';
describe('paleta del logo ISSSTELEON', () => {
it('combina varios matices del logo y del verde azulado, sin repetir el mismo color', () => {
expect(new Set(C2_PALETTE.series).size).toBe(C2_PALETTE.series.length);
for (const color of C2_PALETTE.series) expect(isHarmoniousColor(color)).toBe(true);
expect(institutionalize(['#a8c243'])).toEqual(['#a8c243']);
expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]);
});
it('reemplaza mezclas de partido por entradas distintas y conserva el gris de sin dato', () => {
const [azul, rojo, naranja, amarillo, guinda, sinDato, edad] = institutionalize([
'#0044CC', '#C41E3A', '#FF6B00', '#FFD100', '#7A2E0E', '#C9CDD2', '#2F6DB3',
]);
expect([azul, rojo, naranja, amarillo, guinda]).toEqual(C2_PALETTE.series.slice(0, 5));
expect(edad).toBe('#2F6DB3');
expect(sinDato).toBe('#C9CDD2');
});
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
expect(new Set(colors.slice(0, 3)).size).toBe(3);
expect(colors[3]).toBe(groupBase(1));
expect(colors[0]).not.toBe(colors[3]);
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
});
it('pinta la tinta categórica, deja una escala continua y no toca texto ni fondo', () => {
const figure = recolorFigure({
data: [{
type: 'scatter', marker: { color: '#B55A1F' }, error_x: { color: 'rgba(0,68,204,0.4)' }, line: { color: '#C9CDD2' },
colorscale: [[0, '#0d0887'], [0.5, '#ed7953'], [1, '#f0f921']],
}],
layout: { font: { color: '#081839' }, paper_bgcolor: '#FFFFFF', colorway: ['#EF553B', '#636efa'] },
});
expect((figure.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]);
expect(figure.data[0]['error_x']).toMatchObject({ color: expect.stringMatching(/^rgba\(\d+,\d+,\d+,0\.4\)$/) });
expect((figure.data[0]['error_x'] as { color: string }).color).not.toContain('0,68,204');
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
const scale = figure.data[0]['colorscale'] as [number, string][];
expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]);
expect(scale[0][1]).not.toBe('#0d0887');
expect(scale[0][1]).not.toBe(scale[1][1]);
expect(figure.layout['font']).toEqual({ color: '#081839' });
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
expect(figure.layout['colorway']).toEqual(C2_PALETTE.series.slice(2, 4));
expect(new Set([
(figure.data[0]['marker'] as { color: string }).color,
...(figure.layout['colorway'] as string[]),
]).size).toBe(3);
expect(recolorFigure(figure)).toBe(figure);
});
});
@@ -1,11 +1,16 @@
import { Tema } from './indicadores.models';
import { PlotlyFigure, Tema } from './indicadores.models';
// Matches src/styles.scss: interface tokens are the source of these candidates,
// not a certified brand guide. Published semantic colours always take priority.
// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0).
// Neighboring entries differ in hue so series stay distinct, and none is a party colour:
// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral.
// Sequential fills (heatmaps) use SCALE, from pale lime to deep teal.
export const C2_PALETTE = Object.freeze({
// ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness.
series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']),
// Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest.
series: Object.freeze([
'#5c7014', '#0e7568', '#6a6448', '#3d6b38',
'#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38',
]),
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
@@ -13,6 +18,206 @@ export const C2_PALETTE = Object.freeze({
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }),
});
export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; }
export function c2Color(published: string | undefined, index: number): string {
return published ?? C2_PALETTE.series[index % C2_PALETTE.series.length];
const ageKeys = new Set(C2_PALETTE.edades.map(color => parseColor(color)?.key).filter((key): key is string => !!key));
export function isAgeColor(color: string): boolean {
const key = parseColor(color)?.key;
return !!key && ageKeys.has(key);
}
export function c2Color(published: string | undefined, index: number): string {
// A published swatch stays. The series only fills a category that arrived without one.
if (published && (/^#[0-9a-f]{6}$/i.test(published) || isAgeColor(published))) return published;
return C2_PALETTE.series[index % C2_PALETTE.series.length];
}
/** One base hue per group, then lighter and darker steps so siblings stay related but distinct. */
export function paintByGroup(groups: readonly string[]): string[] {
const order = [...new Set(groups)];
const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length]));
const stairs = new Map(order.map((id, i) => [id, steps(C2_PALETTE.series[i % C2_PALETTE.series.length], counts.get(id)!)]));
const cursor = new Map<string, number>();
return groups.map(id => {
const index = cursor.get(id) ?? 0;
cursor.set(id, index + 1);
return stairs.get(id)![index];
});
}
export function groupBase(index: number): string {
return C2_PALETTE.series[index % C2_PALETTE.series.length];
}
/** Replace inharmonious hues. Same source colour keeps the same slot; grays and palette hues stay. */
export function institutionalize(colors: readonly string[]): string[] {
const parsed = colors.map(parseColor);
const foreign: string[] = [];
const seen = new Set<string>();
for (const item of parsed) {
if (!item || item.kind !== 'foreign' || ageKeys.has(item.key) || seen.has(item.key)) continue;
seen.add(item.key);
foreign.push(item.key);
}
const assigned = new Map(foreign.map((key, i) => [key, C2_PALETTE.series[i % C2_PALETTE.series.length]]));
return colors.map((color, i) => {
const item = parsed[i];
const next = item && assigned.get(item.key);
return item && next ? formatAs(item, next) : color;
});
}
/** Keep a published colour; only a missing one takes the next series entry. */
export function seriesColors(published: readonly (string | undefined)[]): string[] {
return published.map((color, index) => c2Color(color, index));
}
const NAMED: Record<string, [number, number, number]> = {
black: [0, 0, 0], white: [255, 255, 255], gray: [128, 128, 128], grey: [128, 128, 128], silver: [192, 192, 192],
red: [255, 0, 0], blue: [0, 0, 255], green: [0, 128, 0], orange: [255, 165, 0], yellow: [255, 255, 0],
purple: [128, 0, 128], brown: [165, 42, 42], pink: [255, 192, 203], cyan: [0, 255, 255], magenta: [255, 0, 255],
gold: [255, 215, 0], navy: [0, 0, 128], teal: [0, 128, 128], maroon: [128, 0, 0], lime: [0, 255, 0], olive: [128, 128, 0],
};
interface Parsed { r: number; g: number; b: number; a: number; key: string; hue: number; sat: number; lum: number; kind: 'neutral' | 'harmonious' | 'foreign'; explicitAlpha: boolean; }
function parseColor(input: string): Parsed | undefined {
const text = input.trim();
let r = 0, g = 0, b = 0, a = 1, explicitAlpha = false;
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text);
const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(text);
if (hex) {
const raw = hex[1].length === 3 ? hex[1].split('').map(c => c + c).join('') : hex[1];
r = parseInt(raw.slice(0, 2), 16); g = parseInt(raw.slice(2, 4), 16); b = parseInt(raw.slice(4, 6), 16);
} else if (rgb) {
r = Number(rgb[1]); g = Number(rgb[2]); b = Number(rgb[3]);
if (rgb[4] !== undefined) { a = Number(rgb[4]); explicitAlpha = true; }
if ([r, g, b].some(v => v > 255) || !Number.isFinite(a)) return undefined;
} else if (NAMED[text.toLowerCase()]) {
[r, g, b] = NAMED[text.toLowerCase()];
} else return undefined;
const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min;
const sat = max === 0 ? 0 : d / max;
let hue = 0;
if (d !== 0) {
if (max === r) hue = ((g - b) / d) % 6;
else if (max === g) hue = (b - r) / d + 2;
else hue = (r - g) / d + 4;
hue *= 60; if (hue < 0) hue += 360;
}
const lum = luminance({ r, g, b });
const neutral = sat < 0.18;
const harmonious = !neutral && (
(hue >= 64 && hue <= 188 && sat >= 0.22)
|| (hue > 188 && hue <= 230 && sat <= 0.5)
|| (hue >= 40 && hue < 64 && sat <= 0.42));
return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' };
}
function steps(base: string, count: number): string[] {
if (count <= 1) return [base];
return Array.from({ length: count }, (_, i) => {
const t = i / (count - 1);
if (t < 0.5) return mixHex(base, [0, 0, 0], (0.5 - t) * 0.5);
return mixHex(base, [255, 255, 255], (t - 0.5) * 0.22);
});
}
function mixHex(base: string, toward: [number, number, number], amount: number): string {
const item = parseColor(base)!;
const channel = (from: number, to: number) => Math.round(from + (to - from) * amount);
return '#' + [channel(item.r, toward[0]), channel(item.g, toward[1]), channel(item.b, toward[2])]
.map(v => v.toString(16).padStart(2, '0')).join('');
}
function sampleScale(t: number): string {
const stops = C2_PALETTE.scale;
const scaled = Math.min(1, Math.max(0, t)) * (stops.length - 1);
const index = Math.min(stops.length - 2, Math.floor(scaled));
const item = parseColor(stops[index])!, next = parseColor(stops[index + 1])!;
return mixHex(stops[index], [next.r, next.g, next.b], scaled - index);
}
function luminance(input: { r: number; g: number; b: number } | Parsed): number {
const c = [input.r, input.g, input.b].map(v => v / 255).map(v => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
return c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722;
}
function formatAs(original: Parsed, hex: string): string {
if (!original.explicitAlpha) return hex;
const item = parseColor(hex)!;
const alpha = Number(original.a.toFixed(3));
return `rgba(${item.r},${item.g},${item.b},${alpha})`;
}
export function isNeutralColor(color: string): boolean { return parseColor(color)?.kind === 'neutral'; }
export function isHarmoniousColor(color: string): boolean { return parseColor(color)?.kind === 'harmonious'; }
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function collectStrings(value: unknown, into: string[]) {
if (typeof value === 'string') into.push(value);
else if (Array.isArray(value)) {
if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') into.push(value[1]);
else value.forEach(item => collectStrings(item, into));
}
}
function mapColors(value: unknown, lookup: Map<string, string>): unknown {
if (typeof value === 'string') return lookup.get(value) ?? value;
if (Array.isArray(value)) {
if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') return [value[0], lookup.get(value[1]) ?? value[1]];
return value.map(item => mapColors(item, lookup));
}
return value;
}
function paintTrace(trace: Record<string, unknown>, lookup: Map<string, string>) {
if (record(trace['marker'])) {
const marker = { ...trace['marker'] };
if ('color' in marker) marker['color'] = mapColors(marker['color'], lookup);
if ('colors' in marker) marker['colors'] = mapColors(marker['colors'], lookup);
if (record(marker['line']) && 'color' in marker['line']) marker['line'] = { ...marker['line'], color: mapColors(marker['line']['color'], lookup) };
trace['marker'] = marker;
}
if (record(trace['line']) && 'color' in trace['line']) trace['line'] = { ...trace['line'], color: mapColors(trace['line']['color'], lookup) };
if (typeof trace['fillcolor'] === 'string') trace['fillcolor'] = lookup.get(trace['fillcolor']) ?? trace['fillcolor'];
for (const key of ['error_x', 'error_y']) {
if (record(trace[key]) && 'color' in (trace[key] as Record<string, unknown>)) {
trace[key] = { ...(trace[key] as Record<string, unknown>), color: mapColors((trace[key] as Record<string, unknown>)['color'], lookup) };
}
}
if (Array.isArray(trace['colorscale'])) trace['colorscale'] = sequentialScale(trace['colorscale']);
}
function sequentialScale(stops: unknown[]): unknown[] {
return stops.map(stop => {
if (!Array.isArray(stop) || typeof stop[0] !== 'number' || typeof stop[1] !== 'string') return stop;
return [stop[0], sampleScale(stop[0])];
});
}
function scalePending(figure: PlotlyFigure): boolean {
return traceList(figure).some(trace => Array.isArray(trace['colorscale'])
&& JSON.stringify(sequentialScale(trace['colorscale'] as unknown[])) !== JSON.stringify(trace['colorscale']));
}
function traceList(host: { data?: unknown; frames?: unknown }): Record<string, unknown>[] {
const traces = Array.isArray(host.data) ? host.data.filter(record) : [];
if (Array.isArray(host.frames)) {
for (const frame of host.frames) {
if (record(frame) && Array.isArray(frame['data'])) traces.push(...frame['data'].filter(record));
}
}
return traces;
}
function gather(figure: PlotlyFigure): string[] {
const found: string[] = [];
for (const trace of traceList(figure)) {
const marker = record(trace['marker']) ? trace['marker'] : undefined;
collectStrings(marker?.['color'], found); collectStrings(marker?.['colors'], found);
collectStrings(record(marker?.['line']) ? marker['line']['color'] : undefined, found);
collectStrings(record(trace['line']) ? trace['line']['color'] : undefined, found);
collectStrings(trace['fillcolor'], found);
collectStrings(record(trace['error_x']) ? trace['error_x']['color'] : undefined, found);
collectStrings(record(trace['error_y']) ? trace['error_y']['color'] : undefined, found);
}
if (Array.isArray(figure.layout['colorway'])) collectStrings(figure.layout['colorway'], found);
return found;
}
/** Data ink of a published figure, without touching text, grid or background. */
export function recolorFigure<T extends PlotlyFigure>(figure: T): T {
const collected = gather(figure);
const painted = institutionalize(collected);
if (painted.every((color, i) => color === collected[i]) && !scalePending(figure)) return figure;
const lookup = new Map(collected.map((color, i) => [color, painted[i]]));
const copy = structuredClone(figure);
for (const trace of traceList(copy)) paintTrace(trace, lookup);
if (Array.isArray(copy.layout['colorway'])) copy.layout['colorway'] = mapColors(copy.layout['colorway'], lookup);
return copy;
}
@@ -138,8 +138,8 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1',
'/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
expect(titulos.filter(([t]) => ['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
.toEqual([['Resultado histopatológico por categoría BI-RADS', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
expect(titulos.filter(([t]) => ['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
expect(graficas()).toHaveLength(3);
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2, 2]);
});
@@ -0,0 +1,310 @@
// What this module covers: CaMa's eight FHIR measures as the page reads them: their ids, catalog entries, category
// metadata, the rows of each contract (C1, C2, C3r) and what the summary's cards and figures make of them, for periods
// with data and for periods that legitimately have none.
// Fixtures (`fixtures/cama_fhir_*.json`): `reportes` are real `GET /cama/fhir/MeasureReport` answers of the local
// installation, cut to three semesters (2021-S1 without units, 2024-S2 and 2025-S2 with them) and two months;
// `measures` is the Measure bundle the WebApi serves from the current dbt definitions; `measures_instalada` is the one
// the installation served before the category metadata existed.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir';
import { cajaDeDatos, categorias, datosDeReportes, FhirIndicadoresService, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
import { c2Figure } from './indicadores-c2-adapter';
import { modelosConteos, parConteos, totalExamenes } from './indicadores-conteos-pareados';
import { CAMA_CONFIRMACION_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TOMA_DIAGNOSTICO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
import { datosValidos } from './indicadores.service';
import measuresData from './fixtures/cama_fhir_measures.json';
import installedData from './fixtures/cama_fhir_measures_instalada.json';
import reportsData from './fixtures/cama_fhir_reportes.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const installed = resources(installedData as unknown as Bundle, 'Measure') as Measure[];
const answers = reportsData.reports as unknown as Record<string, { semestre: Bundle; mes?: Bundle }>;
const measure = (fhirId: string, from = measures) => from.find(m => m.id === fhirId)!;
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start: string) =>
(resources(answers[fhirId][tipo]!, 'MeasureReport') as Report[]).filter(r => r.period?.start === start);
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', from = measures): IndicadorDatos {
return datosValidos(datosDeReportes(measure(fhirId, from), reportsOf(fhirId, tipo, start), tipo), indicadorId(fhirId), tipo, [periodo]);
}
const SEMESTRE_VACIO = ['2021-01-01', '2021-S1'] as const;
const SEMESTRE_CON_DATOS = ['2025-07-01', '2025-S2'] as const;
describe('Identificadores de CaMa entre FHIR y la página', () => {
it('cada Measure publicada tiene un id de la página y ninguno se repite', () => {
// Pins down: the explicit table covers the eight measures the WebApi publishes and the page ids stay unique
// (`BIRADS456` is `birads_456`, which no rule derives). Fails if a measure is published without a
// correspondence, or two measures collapse into one page id.
const ids = measures.map(m => indicadorId(m.id!));
expect(ids.sort()).toEqual(['cama_biopsias', 'cama_birads', 'cama_birads_456_mastografia', 'cama_birads_456_paciente',
'cama_birads_cancer_invasor', 'cama_confirmacion_birads45', 'cama_dias_resultado_diagnostico', 'cama_dias_toma_diagnostico',
'cama_eu38a', 'cama_histopatologia_birads', 'cama_tasa_deteccion_histopatologica']);
expect(new Set(ids).size).toBe(measures.length);
expect(measures.every(m => Object.hasOwn(CAMA_MEASURE_IDS, m.id!))).toBe(true);
});
it('el id de una medida de otro dominio sigue la regla general', () => {
// Pins down: only CaMa's measures use the table; TEA's and CaCu's keep `-` to `_`. Fails if the table captures
// ids of other domains or the generic rule changes.
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
expect(indicadorId('CACU-EU7')).toBe('CACU_EU7');
});
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
// Pins down: the contract, the figures and the period types each CaMa measure publishes: a distribution offers
// the donut and the bars, a duration its box plot, a proportion none (its history is drawn from the data rows).
// Fails if the dbt definitions stop declaring them or the mapper drops them.
const catalog = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
expect(catalog['cama_birads_456_paciente']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre', 'mes'], estratos: [] });
expect(catalog['cama_biopsias']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'] });
expect(catalog['cama_confirmacion_birads45']).toMatchObject({ contrato: 'C1', figuras: [], sentido: 'mayor_mejor' });
expect(catalog['cama_eu38a']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
expect(catalog['cama_dias_toma_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'] });
expect(catalog['cama_birads_cancer_invasor']).toMatchObject({ contrato: 'C2', estratos: ['grupo_edad', 'estadio', 'etapa', 'clasificacion', 'tamano'] });
});
});
describe('Ficha técnica de CaMa', () => {
it('cada medida tiene su propio código y sus poblaciones con la métrica que las cuenta', () => {
// Pins down: the sheet's code is the measure's name without the domain (not `CAMA` for all eight) and each
// population names the dbt metric that counts it. Fails if the sheets of different measures read alike.
const codes = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
expect(new Set(codes).size).toBe(measures.length);
expect(metadatosDeMeasure(measure('CAMA-EU38A')).ficha!.codigo).toBe('EU38A');
expect(metadatosDeMeasure(measure('CAMA-BIRADS456-PACIENTE')).ficha!.codigo).toBe('BIRADS456-PACIENTE');
expect(metadatosDeMeasure(measure('CAMA-CONFIRMACION-BIRADS45')).poblaciones!.map(p => p.grupo)).toEqual(['poblacion', 'denominador', 'numerador']);
});
});
describe('Categorías de las composiciones de CaMa', () => {
it('BI-RADS 4 a 6 declara solo sus subcategorías y BI-RADS completo añade «Sin dato»', () => {
// Pins down: the labels and colours come from the Measure's extensions, in the order of the catalog, and the
// exams' and patients' measures declare the same categories. Fails if the dbt labels drift or one measure loses them.
expect(Object.keys(categorias(measure('CAMA-BIRADS456-PACIENTE')))).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6']);
expect(categorias(measure('CAMA-BIRADS456-MASTOGRAFIA'))).toEqual(categorias(measure('CAMA-BIRADS456-PACIENTE')));
expect(Object.keys(categorias(measure('CAMA-BIRADS')))).toEqual(['B0', 'B1', 'B2', 'B3', 'B4A', 'B4B', 'B4C', 'B5', 'B6', 'SIN_DATO']);
expect(categorias(measure('CAMA-BIRADS'))['B5']).toEqual({ etiqueta: 'BI-RADS 5', color: '#B55A1F', grupo: null });
expect(Object.keys(categorias(measure('CAMA-BIOPSIAS')))).toEqual(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'SIN_DATO']);
});
it('un BI-RADS 4 sin subcategoría se muestra después de las categorías declaradas y no se pierde', () => {
// Pins down: the real 2025-S2 report counts patients in `B4`, which no Measure declares. The rows add it after the
// declared categories under the Core catalog's caption, and the total is still the report's units. Fails if
// undeclared categories are dropped (the card would show fewer patients than the report counts).
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6', 'B4']);
expect((periodo['categorias'] as Record<string, { etiqueta: string }>)['B4'].etiqueta).toBe('BI-RADS 4 (sin subcategoría)');
const total = periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0);
expect(total).toBe(36);
expect(periodo.filas.map(row => [row['categoria'], row['orden']])).toEqual([['B4A', 0], ['B4B', 1], ['B4C', 2], ['B5', 3], ['B6', 4], ['B4', 5]]);
});
it('una Measure sin metadatos de categoría deja ver las categorías con su código, sin perder unidades', () => {
// Pins down: against the Measure the installation served before the labels existed (no category extensions),
// every counted category is still listed (by its code) and the figure still draws the whole partition. Fails if a
// Measure without metadata makes the distribution empty or undercounts it.
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS, 'semestre', installed);
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4', 'B5', 'B6']);
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.model.total).toBe(36);
});
});
describe('Composiciones (C2): BI-RADS y biopsias', () => {
it.each(['CAMA-BIRADS456-PACIENTE', 'CAMA-BIRADS456-MASTOGRAFIA', 'CAMA-BIRADS', 'CAMA-BIOPSIAS'])('%s se dibuja como dona y como barras con el total de sus unidades', fhirId => {
// Pins down: for a period with units, both published figures are supported and the total equals the report's
// `initial-population`. Fails if a category, a label or the unit total is lost between the report and the figure.
const periodo = datos(fhirId, ...SEMESTRE_CON_DATOS);
const units = reportsOf(fhirId, 'semestre', SEMESTRE_CON_DATOS[0])[0].group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
const result = c2Figure(periodo, { dominio: 'cama', indicador: indicadorId(fhirId), figura, tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(`${fhirId} ${figura}: ${result.reason}`);
expect(result.model.total).toBe(units);
expect(result.model.total).toBeGreaterThan(0);
}
});
it('todas las composiciones de CaMa de los reportes reales suman las unidades de su periodo', () => {
// Pins down: for every C2 measure and every real period in the fixtures (semesters and months), the categories the
// mapper lists add up to the report's units, so none is dropped. Fails if a report counts a category the rows lose.
// The three measures of L3 have their own fixture (`indicadores-cama-l3.spec.ts`).
for (const m of measures.filter(item => indicadorDeMeasure(item).contrato === 'C2' && Object.hasOwn(answers, item.id!))) {
for (const tipo of ['semestre', 'mes'] as const) {
const bundle = answers[m.id!][tipo];
if (!bundle) continue;
const reports = resources(bundle, 'MeasureReport') as Report[];
const rows = datosDeReportes(m, reports, tipo).filas;
for (const report of reports) {
const units = report.group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
const label = report.period!.start;
const total = rows.filter(row => row['periodo'] === (tipo === 'mes' ? label.slice(0, 7) : label.slice(0, 4) + (label.slice(5, 7) < '07' ? '-S1' : '-S2'))).reduce((sum, row) => sum + (row['n'] as number), 0);
expect(total, `${m.id} ${label}`).toBe(units);
}
}
}
});
it('un periodo sin unidades da una distribución vacía, no un error', () => {
// Pins down: a semester without mammograms (legitimate absence of data) is a supported figure with the
// «conteos en cero» message and every category at zero. Fails if an empty period turns into an unsupported figure.
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_VACIO);
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2021-S1'] });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.model.total).toBe(0);
expect(result.emptyMessage).toContain('cero');
expect(periodo.filas.every(row => row['n'] === 0)).toBe(true);
});
it('la tarjeta de pacientes BI-RADS 4, 5 y 6 suma las categorías del periodo', () => {
// Pins down: the opportunity card reads the patients' distribution: its value is the sum of the categories
// (including the undeclared B4) and the card says «Disponible». Fails if the card still sees the catalog without B4.
const result = kpiResult(datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS), KPI_BY_DOMAIN.cama[0], 'cama', apply('2025-S2'));
expect(result).toMatchObject({ state: 'Disponible', value: 36 });
expect(Object.values(result.categorias!).reduce((a, b) => a + b, 0)).toBe(36);
});
it('un mes con datos se lee igual que un semestre', () => {
// Pins down: the monthly search answers by `periodo` labels like `2025-12`, and the rows carry that label. Fails
// if the month's period is read as a semester or the categories are lost.
const periodo = datos('CAMA-BIRADS456-PACIENTE', '2025-12-01', '2025-12', 'mes');
expect(periodo.tipo_periodo).toBe('mes');
expect(periodo.periodos).toEqual(['2025-12']);
expect(periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0)).toBeGreaterThan(0);
});
it('las biopsias suman por grado histológico con los rótulos del catálogo', () => {
// Pins down: the grades arrive as `BENIGNO`, `CARCINOMA_IN_SITU` and `CARCINOMA_INVASOR` and are drawn with the
// catalog's captions. Fails if a grade loses its caption or is merged into another.
const periodo = datos('CAMA-BIOPSIAS', ...SEMESTRE_CON_DATOS);
const labels = Object.fromEntries(Object.entries(periodo['categorias'] as Record<string, { etiqueta: string }>).map(([k, v]) => [k, v.etiqueta]));
expect(labels).toEqual({ BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', CARCINOMA_INVASOR: 'Carcinoma invasor', SIN_DATO: 'Sin dato' });
expect(Object.fromEntries(periodo.filas.map(row => [row['categoria'], row['n']]))).toEqual({ BENIGNO: 11, CARCINOMA_IN_SITU: 1, CARCINOMA_INVASOR: 13, SIN_DATO: 0 });
});
});
describe('Proporción (C1): confirmación histopatológica', () => {
it('el grupo principal llega a la página como `total` con numerador, denominador y porcentaje', () => {
// Pins down: the WebApi's `principal` group is the page's `total`, and the score becomes a percentage next to
// its numerator and denominator. Fails if the group keeps its FHIR name (the card would find no rows).
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_CON_DATOS);
expect(periodo['grupos']).toEqual({ total: 'Total' });
expect(periodo.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador: 28, denominador: 37, valor: 75.7, suprimido: 0 })]);
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: '75.7',
info: '28 de 37 mastografías BI-RADS 4 y 5 con reporte de biopsia.' });
});
it('un periodo sin mastografías de sospecha no muestra un porcentaje', () => {
// Pins down: denominator zero and no score is «Sin valor disponible», never 0 %. Fails if an empty period is
// drawn as a measured zero.
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_VACIO);
expect(periodo.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 0, valor: null });
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
});
});
describe('Duraciones (C3r): tiempos de CaMa', () => {
it('toma a resultado da mediana, cuartiles y número de mastografías', () => {
// Pins down: median 8 days with Q1 4 and Q3 12 over 101 mammograms for 2025-S2, and the card shows them. Fails if the
// quartiles or the observation count stop coming from the report's extensions and populations.
const periodo = datos('CAMA-EU38A', ...SEMESTRE_CON_DATOS);
expect(periodo.filas[0]).toMatchObject({ grupo: 'TOTAL', n: 101, mediana: 8, q1: 4, q3: 12, n_sin_evento: 0, unidad: 'dias' });
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 8,
info: '101 mastografías; Q1 a Q3: 4 a 12 días.' });
});
it('tamizaje a diagnóstico separa las mastografías medidas de las que no tienen diagnóstico', () => {
// Pins down: 55 measured and 43 without a diagnosis by the cut-off (FHIR's population exclusion), median 60 days.
// Fails if the unmeasured units are counted as observations or lost.
const periodo = datos('CAMA-DIAS-TOMA-DIAGNOSTICO', ...SEMESTRE_CON_DATOS);
expect(periodo.filas[0]).toMatchObject({ n: 55, n_sin_evento: 43, mediana: 60, q1: 41.5, q3: 131.5 });
expect(kpiResult(periodo, CAMA_TOMA_DIAGNOSTICO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 60 });
});
it('un periodo sin mastografías no tiene mediana', () => {
// Pins down: zero observations and no score is «Sin valor disponible», not a median of 0 days. Fails if an empty
// period is shown as an instant result.
const periodo = datos('CAMA-EU38A', ...SEMESTRE_VACIO);
expect(periodo.filas[0]).toMatchObject({ n: 0, mediana: null });
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
});
it('la caja de cuartiles se dibuja con los semestres que tienen mediana', () => {
// Pins down: the box plot keeps the periods with a median and leaves out the empty one. Fails if an empty
// period becomes a box at zero.
const reports = ['2021-01-01', '2024-07-01', '2025-07-01'].flatMap(start => reportsOf('CAMA-EU38A', 'semestre', start));
const figure = cajaDeDatos(datosValidos(datosDeReportes(measure('CAMA-EU38A'), reports, 'semestre'), 'cama_eu38a', 'semestre'));
expect((figure.data[0] as Record<string, unknown>)['x']).toEqual(['2024-S2', '2025-S2']);
expect((figure.data[0] as Record<string, unknown>)['median']).toEqual([7.5, 8]);
});
});
describe('Servicio FHIR sobre CaMa', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('pide por el id de la página y consulta la medida por su canónico', async () => {
// Pins down: the page asks for `cama_birads_456_paciente` and the WebApi receives the canonical of
// `CAMA-BIRADS456-PACIENTE` with the periods asked for. Fails if the page id is sent as the measure or the table is bypassed.
const service = TestBed.inject(FhirIndicadoresService);
const answer = firstValueFrom(service.datos('cama', 'cama_birads_456_paciente', 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
const request = http.expectOne(r => r.url === '/cama/fhir/MeasureReport');
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE');
expect(request.request.params.get('periodo')).toBe('2025-S2');
request.flush({ ...answers['CAMA-BIRADS456-PACIENTE'].semestre, entry: reportsOf('CAMA-BIRADS456-PACIENTE', 'semestre', '2025-07-01').map(resource => ({ resource })) });
expect((await answer).id).toBe('cama_birads_456_paciente');
});
it('el catálogo de CaMa publica los ocho ids de la página', async () => {
// Pins down: the catalog the page receives lists the correspondence ids, so its filters and cards find them.
// Fails if a measure reaches the page under its FHIR id.
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).catalogo('cama'));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
expect((await answer).map(item => item.id).sort()).toEqual(Object.values(CAMA_MEASURE_IDS).sort());
});
});
describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () => {
const models = (examenes: IndicadorDatos, pacientes: IndicadorDatos) => modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, examenes, pacientes, 'semestre');
it('con datos reales del semestre da los conteos por categoría de ambas medidas', () => {
// Pins down: the page's pair reads the two real C2 answers (units `examen` and `paciente`, version 0.2.0 of the
// patients' measure) and gives the exams by category and the patients by BI-RADS family. Fails if an id, a unit or
// a category of either measure stops matching what the pair checks.
const [model] = models(datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS), datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS));
expect(model.pacientesVerificados).toBe(true);
expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
});
it('un periodo sin BI-RADS 4 sin subcategoría cuenta cero en esa categoría y no rompe la tarjeta', () => {
// Pins down: `B4` is published only when some report counts it; a period set without it leaves the card
// working, with zero exams in that category. The reports are the real 2025-S2 ones with the `B4` stratum removed
// and the units reduced by its count. Fails if the card turns «categorías no coinciden» whenever no 4 arrives unqualified.
const without = (fhirId: string) => {
const [report] = reportsOf(fhirId, 'semestre', '2025-07-01');
const group = report.group![0];
const removed = group.stratifier![0].stratum!.find(s => s.value?.coding?.[0].code === 'B4')!.population![0].count!;
const units = group.population!.map(p => p.code?.coding?.[0].code === 'initial-population' ? { ...p, count: p.count! - removed } : p);
const stratifier = [{ ...group.stratifier![0], stratum: group.stratifier![0].stratum!.filter(s => s.value?.coding?.[0].code !== 'B4') }];
const copy = { ...report, group: [{ ...group, population: units, stratifier }] } as Report;
return datosValidos(datosDeReportes(measure(fhirId), [copy], 'semestre'), indicadorId(fhirId), 'semestre', ['2025-S2']);
};
const [model] = models(without('CAMA-BIRADS456-MASTOGRAFIA'), without('CAMA-BIRADS456-PACIENTE'));
expect(model.examenes.find(c => c.id === 'B4')!.n).toBe(0);
expect(model.filas.map(f => f.examenes)).toEqual([0, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
});
});
@@ -0,0 +1,47 @@
// How CaMa's FHIR measures map onto what the indicator page reads: the page's id of each measure, the name of a
// proportion's primary group and the categories a composition publishes beyond its declared ones.
//
// The WebApi names a measure `CAMA-BIRADS456-PACIENTE`; the page, its history and its cards use
// `cama_birads_456_paciente`. A rule can't derive one from the other (`BIRADS456` splits into `birads_456`), so the
// correspondence is explicit and a measure outside it keeps the generic rule.
export const CAMA_MEASURE_IDS: Readonly<Record<string, string>> = {
'CAMA-BIOPSIAS': 'cama_biopsias',
'CAMA-BIRADS': 'cama_birads',
'CAMA-BIRADS-CANCER-INVASOR': 'cama_birads_cancer_invasor',
'CAMA-BIRADS456-MASTOGRAFIA': 'cama_birads_456_mastografia',
'CAMA-BIRADS456-PACIENTE': 'cama_birads_456_paciente',
'CAMA-CONFIRMACION-BIRADS45': 'cama_confirmacion_birads45',
'CAMA-DIAS-RESULTADO-DIAGNOSTICO': 'cama_dias_resultado_diagnostico',
'CAMA-DIAS-TOMA-DIAGNOSTICO': 'cama_dias_toma_diagnostico',
'CAMA-EU38A': 'cama_eu38a',
'CAMA-HISTOPATOLOGIA-BIRADS': 'cama_histopatologia_birads',
'CAMA-TASA-DETECCION-HISTOPATOLOGICA': 'cama_tasa_deteccion_histopatologica',
};
export const esMedidaCama = (measureId: string | undefined): boolean =>
measureId !== undefined && Object.hasOwn(CAMA_MEASURE_IDS, measureId);
// A proportion's primary group is `principal` in the WebApi; CaMa's page names it `total`.
export const GRUPO_PRINCIPAL_PAGINA = 'total';
export const GRUPO_PRINCIPAL_FHIR = 'principal';
// A category a report counts that its Measure doesn't declare (a BI-RADS 4 without subcategory arrives as `B4`) is
// shown after the declared ones under the caption the Core catalog gives it.
export const ETIQUETA_CATEGORIA_NO_DECLARADA: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
// The histopathological result by BI-RADS (`CAMA-HISTOPATOLOGIA-BIRADS`) publishes the cross of two stratifiers, the
// BI-RADS of the mammogram and the grade of its biopsy, as FHIR codes (`B4A`, `CARCINOMA_IN_SITU`); the view that
// draws it reads the page's codes. The correspondence is explicit, one table per axis, so a code outside it is an error
// and never a silent zero. A grade is benign or malignant as the parameter `cama.biopsia_cancer` says; no biopsy and
// no grade belong to no group.
export const ESTRATO_BIRADS_PAGINA: Readonly<Record<string, string>> = {
B4: 'BIRADS_4', B4A: 'BIRADS_4A', B4B: 'BIRADS_4B', B4C: 'BIRADS_4C', B5: 'BIRADS_5', B6: 'BIRADS_6',
};
export const CATEGORIA_HISTOPATOLOGIA_PAGINA: Readonly<Record<string, { id: string; grupo: string | null; gravedad: number | null }>> = {
BENIGNO: { id: 'BENIGNO', grupo: 'NO_MALIGNO', gravedad: 1 },
CARCINOMA_IN_SITU: { id: 'IN_SITU', grupo: 'MALIGNO', gravedad: 3 },
CARCINOMA_INVASOR: { id: 'INVASOR', grupo: 'MALIGNO', gravedad: 4 },
SIN_BIOPSIA: { id: 'SIN_BIOPSIA', grupo: null, gravedad: null },
SIN_DATO: { id: 'SIN_DATO', grupo: 'SIN_DATO', gravedad: null },
};
export const GRUPOS_HISTOPATOLOGIA_PAGINA: Readonly<Record<string, string>> = { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' };
@@ -0,0 +1,242 @@
// What this module covers: the three CaMa measures of L3 as the page reads them from FHIR: the detection rate (C1), the
// time from the mammogram's result to the diagnosis (C3r) and the histopathological result by BI-RADS (C2 stratified by
// BI-RADS): their ids, catalog entries, numerators and denominators, medians, the BI-RADS by result matrix, the periods
// with no data and the reports that don't add up.
// Fixtures: `fixtures/cama_fhir_measures.json` (the Measure bundle the WebApi serves from the current dbt definitions) and
// `fixtures/cama_fhir_l3_reportes.json` (real `GET /cama/fhir/MeasureReport` answers over a read-only copy of the data of
// the 18092 installation, with L3's views applied on the copy), cut to six semesters and three months. The semesters:
// 2021-S1 (no data), 2024-S2, 2025-S1, 2025-S2, 2026-S1 and 2026-S2 (the one the cut-off cuts).
import { Bundle, resources } from './fhir';
import { datosDeReportes, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
import { CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TASA_DETECCION_KPI, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
import { datosValidos } from './indicadores.service';
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
import { ESTRATOS_BIRADS, modeloHistopatologia, periodosHistopatologia, seleccionBase, tasas } from './indicadores-histopatologia-cama';
import measuresData from './fixtures/cama_fhir_measures.json';
import l3Data from './fixtures/cama_fhir_l3_reportes.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const answers = l3Data.reports as unknown as Record<string, { semestre: Bundle; mes: Bundle }>;
const TASA = 'CAMA-TASA-DETECCION-HISTOPATOLOGICA', DIAS = 'CAMA-DIAS-RESULTADO-DIAGNOSTICO', HISTO = 'CAMA-HISTOPATOLOGIA-BIRADS';
const measure = (fhirId: string) => measures.find(m => m.id === fhirId)!;
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start?: string) =>
(resources(answers[fhirId][tipo], 'MeasureReport') as Report[]).filter(r => !start || r.period?.start === start);
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', scope = {}): IndicadorDatos {
return datosDeReportes(measure(fhirId), reportsOf(fhirId, tipo, start), tipo, scope);
}
const SEMESTRES = [['2025-01-01', '2025-S1'], ['2025-07-01', '2025-S2'], ['2026-01-01', '2026-S1'], ['2026-07-01', '2026-S2']] as const;
const BIRADS_PACIENTES_2025_S2 = 36;
describe('Las tres medidas de L3 en el catálogo', () => {
it('cada una tiene su id de página, su contrato y su sentido', () => {
// Pins down: the explicit table names the three, none collides with another, and the catalog gives each its contract
// (a proportion, a duration with its box plot, a composition stratified by BI-RADS). Fails if a measure is published
// without a correspondence or its contract drifts.
expect(indicadorId(TASA)).toBe('cama_tasa_deteccion_histopatologica');
expect(indicadorId(DIAS)).toBe('cama_dias_resultado_diagnostico');
expect(indicadorId(HISTO)).toBe('cama_histopatologia_birads');
expect([TASA, DIAS, HISTO].every(id => Object.hasOwn(CAMA_MEASURE_IDS, id))).toBe(true);
const catalogo = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
expect(catalogo['cama_tasa_deteccion_histopatologica']).toMatchObject({ contrato: 'C1', figuras: [], unidad: 'examen', tipos_periodo: ['semestre', 'mes'] });
expect(catalogo['cama_dias_resultado_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
expect(catalogo['cama_histopatologia_birads']).toMatchObject({ contrato: 'C2', estratos: ['birads'], unidad: 'paciente' });
expect(new Set(measures.map(m => indicadorId(m.id!))).size).toBe(measures.length);
});
it('la ficha de cada una dice qué cuenta y qué no es', () => {
// Pins down: the description is the measure's definition: the detection rate is of biopsy reports and says it is not a
// rate over screened women nor the confirmation proportion; the time says its note isn't linked to the mammogram nor is
// the biopsy's date. Fails if the sheet is lost or reads like another indicator.
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/reporte de biopsia, no la\s+paciente/);
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/no es una tasa\s+sobre las mujeres tamizadas/);
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no está ligada a la mastografía/);
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no es la fecha de la biopsia/);
expect(metadatosDeMeasure(measure(HISTO)).descripcion).toMatch(/la misma regla de CAMA_BIRADS456_PACIENTE/);
const codigos = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
expect(new Set(codigos).size).toBe(measures.length);
expect(metadatosDeMeasure(measure(TASA)).ficha!.codigo).toBe('TASA-DETECCION-HISTOPATOLOGICA');
});
});
describe('Tasa de detección histopatológica (C1)', () => {
it.each([['2025-01-01', '2025-S1', 16, 24, 66.7], ['2025-07-01', '2025-S2', 14, 25, 56], ['2026-01-01', '2026-S1', 13, 18, 72.2], ['2026-07-01', '2026-S2', 10, 19, 52.6]] as const)(
'en %s el numerador y el denominador son los reportes de biopsia malignos y con resultado conocido', (inicio, periodo, numerador, denominador, valor) => {
// Pins down: each semester's rows carry the report counts (malignant over known result) and the percentage the card
// shows, in the page's group `total`, and the card reads «Disponible» with its sentence. Fails if a count is lost or
// the numerator leaves its denominator.
const d = datosValidos(datos(TASA, inicio, periodo), 'cama_tasa_deteccion_histopatologica', 'semestre', [periodo]);
expect(d['grupos']).toEqual({ total: 'Total' });
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` });
});
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
// Pins down: over the real periods, malignant ≤ known result, and the four semesters add up to 56 + ... = the reports
// (16+14+13+10 malignant of 24+25+18+19 with known result). Fails if a report is counted in two periods or one is dropped.
const filas = SEMESTRES.flatMap(([inicio, periodo]) => datos(TASA, inicio, periodo).filas);
expect(filas.every(f => (f['numerador'] as number) <= (f['denominador'] as number))).toBe(true);
expect(filas.reduce((s, f) => s + (f['numerador'] as number), 0)).toBe(53);
expect(filas.reduce((s, f) => s + (f['denominador'] as number), 0)).toBe(86);
});
it('un semestre sin reportes de biopsia no da una tasa: 0 de 0 es sin datos, no 0 %', () => {
// Pins down: 2021-S1 has no biopsy reports; the rows say 0 of 0 with no value and the card doesn't claim a rate.
// Fails if an empty period is shown as 0 % or as an error.
const d = datos(TASA, '2021-01-01', '2021-S1');
expect(d.filas).toEqual([expect.objectContaining({ numerador: 0, denominador: 0, valor: null })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
});
});
describe('Tiempo de resultado a diagnóstico (C3r)', () => {
it.each([['2025-01-01', '2025-S1', 56, 41, 65], ['2025-07-01', '2025-S2', 59, 41, 49], ['2026-01-01', '2026-S1', 61, 21, 58], ['2026-07-01', '2026-S2', 18, 0, 40]] as const)(
'en %s mide las mastografías con nota diagnóstica y deja fuera, contadas, las que no la tienen', (inicio, periodo, n, sinEvento, mediana) => {
// Pins down: the observations (mammograms with a diagnosing note in the horizon), those without one and the median in
// days, as the report publishes them, with the card reading the median. Fails if an unmeasured mammogram is dropped
// without being counted or a median is read as zero.
const d = datosValidos(datos(DIAS, inicio, periodo), 'cama_dias_resultado_diagnostico', 'semestre', [periodo]);
expect(d.filas).toEqual([expect.objectContaining({ n, mediana, n_sin_evento: sinEvento, unidad: 'dias' })]);
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(periodo))).toMatchObject({ state: 'Disponible', value: mediana });
});
it('las mastografías del periodo son las observadas más las que no tienen nota', () => {
// Pins down: initial population = observations + exclusions in every real semester, so no mammogram is lost between
// the population and the box plot. Fails if the report's counts don't close.
for (const [inicio] of SEMESTRES) {
const grupo = reportsOf(DIAS, 'semestre', inicio)[0].group![0];
const n = (c: string) => grupo.population!.find(p => p.code?.coding?.[0].code === c)!.count!;
expect(n('measure-observation') + n('measure-population-exclusion'), inicio).toBe(n('initial-population'));
}
});
it('un semestre sin mastografías no da una mediana', () => {
// Pins down: with no observations the card has no value (a median over zero observations is no value, not zero days).
// Fails if an empty period reads as 0 days.
const d = datos(DIAS, '2021-01-01', '2021-S1');
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
});
});
describe('Resultado histopatológico por categoría BI-RADS (C2 por BI-RADS)', () => {
const matriz = (inicio: string, periodo: string, tipo: TipoPeriodo = 'semestre') =>
modeloHistopatologia(datosValidos(datos(HISTO, inicio, periodo, tipo, { estrato: 'birads' }), 'cama_histopatologia_birads', tipo, [periodo], { estrato: 'birads' }), periodo);
const celdas = (m: ReturnType<typeof matriz>) => Object.fromEntries(m.filas.map(f => [f.id,
{ ...Object.fromEntries(Object.entries(f.celdas).map(([k, c]) => [k, c.n])), ...Object.fromEntries(Object.entries(f.aparte).map(([k, c]) => [k, c.n])), total: f.total.n }]));
it('2025-S1: la matriz BI-RADS por resultado es la del reporte, con ceros publicados en las categorías sin pacientes', () => {
// Pins down: the cells of the real report (BI-RADS 4: 8 benign, 6 invasive, 6 without biopsy; BI-RADS 5: 6 invasive, 1 in
// situ, 3 without biopsy), every other stratum a published zero (never «No disponible»), each stratum's total the sum of
// its cells and the matrix the 30 patients of the period. Fails if a cell moves, a zero turns unavailable or a total drifts.
const m = matriz('2025-01-01', '2025-S1');
expect(m.filas.map(f => f.id)).toEqual([...ESTRATOS_BIRADS]);
expect(celdas(m)).toEqual({
BIRADS_4: { BENIGNO: 8, IN_SITU: 0, INVASOR: 6, SIN_BIOPSIA: 6, SIN_DATO: 0, total: 20 },
BIRADS_4A: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_4B: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_4C: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_5: { BENIGNO: 0, IN_SITU: 1, INVASOR: 6, SIN_BIOPSIA: 3, SIN_DATO: 0, total: 10 },
BIRADS_6: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
});
expect(m.filas.every(f => Object.values(f.celdas).every(c => c.estado === 'Publicado'))).toBe(true);
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(30);
expect(m.conResultado).toBe(21);
});
it('la lesión de riesgo (B3) no se inventa: no hay esa categoría en las fuentes y la matriz no la dibuja', () => {
// Pins down: the source grades are benign, in situ and invasive; the page's optional «Lesión de riesgo (B3)» isn't
// published, so the model lists three categories and two groups (non malignant, malignant). Fails if a category the
// source lacks appears, or the model needs it.
const m = matriz('2025-01-01', '2025-S1');
expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'IN_SITU', 'INVASOR']);
expect(m.categorias.map(c => c.etiqueta)).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor']);
expect(m.grupos.map(g => [g.id, g.categorias])).toEqual([['NO_MALIGNO', ['BENIGNO']], ['MALIGNO', ['IN_SITU', 'INVASOR']]]);
expect(m.aparte.map(a => a.id)).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
});
it('las tasas por categoría usan solo a las pacientes con resultado de biopsia y llevan su intervalo', () => {
// Pins down: for the malignant group the rate of BI-RADS 4 is 6 of 14 and BI-RADS 5 is 7 of 7 (no biopsy and no data
// never enter the denominator), and a stratum with no patients has no rate. Fails if «sin biopsia» enters a denominator.
const m = matriz('2025-01-01', '2025-S1');
const t = Object.fromEntries(tasas(m, seleccionBase(m)).map(x => [x.fila.id, x]));
expect([t['BIRADS_4'].k, t['BIRADS_4'].fila.den]).toEqual([6, 14]);
expect([t['BIRADS_5'].k, t['BIRADS_5'].fila.den]).toEqual([7, 7]);
expect(t['BIRADS_5'].valor).toBe(100);
expect(t['BIRADS_4'].bajo).toBeLessThan(t['BIRADS_4'].valor!);
expect(t['BIRADS_4'].alto).toBeGreaterThan(t['BIRADS_4'].valor!);
expect(t['BIRADS_6'].valor).toBeNull();
});
it('el total de la matriz de cada semestre es el de pacientes BI-RADS 4, 5 y 6 del periodo', () => {
// Pins down: the matrix counts the same patients as CAMA_BIRADS456_PACIENTE (36 in 2025-S2, the report of the earlier
// fixture), and in every real semester the units of the report are the matrix's cells. Fails if the two measures count
// different patients.
const total = (inicio: string, periodo: string) => matriz(inicio, periodo).filas.reduce((s, f) => s + f.total.n!, 0);
expect(total('2025-07-01', '2025-S2')).toBe(BIRADS_PACIENTES_2025_S2);
for (const [inicio, periodo] of SEMESTRES) {
expect(total(inicio, periodo), periodo).toBe(reportsOf(HISTO, 'semestre', inicio)[0].group![0].population![0].count);
}
});
it('un semestre sin pacientes es una matriz de ceros publicados, no un error', () => {
// Pins down: 2021-S1 has no mammograms: the matrix is complete with zeros and the denominators are zero (no rate).
// Fails if an empty period breaks the view or turns into «No disponible».
const m = matriz('2021-01-01', '2021-S1');
expect(m.filas.every(f => f.total.n === 0 && f.den === 0)).toBe(true);
expect(m.conResultado).toBe(0);
});
it('un mes con pacientes se lee igual que un semestre', () => {
// Pins down: the monthly answer carries the month label and the same matrix shape. Fails if the month is read as a semester.
const m = matriz('2025-12-01', '2025-12', 'mes');
expect(m.periodo).toBe('2025-12');
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(8);
});
it('el catálogo de categorías sale de la Measure y los códigos desconocidos son un error, no ceros', () => {
// Pins down: an unknown BI-RADS or grade code in a report, or cells that don't add up to the units, throw instead of
// being read as zero. Fails if the adapter hides an inconsistent report.
const clon = (): Report[] => structuredClone(reportsOf(HISTO, 'semestre', '2025-01-01'));
const conCodigo = clon();
conCodigo[0].group![0].stratifier![1]['stratum']![0].component![0].value!.coding![0].code = 'B9';
expect(() => datosDeReportes(measure(HISTO), conCodigo, 'semestre', { estrato: 'birads' })).toThrow(/no reconocido/);
const desajustado = clon();
desajustado[0].group![0].stratifier![1]['stratum']![0].population![0].count! += 1;
expect(() => datosDeReportes(measure(HISTO), desajustado, 'semestre', { estrato: 'birads' })).toThrow(/no suman/);
const sinCruce = clon();
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
expect(() => datosDeReportes(measure(HISTO), sinCruce, 'semestre', { estrato: 'birads' })).toThrow(/no admitida/);
});
it('sin pedir el estrato, la medida se lee como una distribución por resultado y suma las mismas pacientes', () => {
// Pins down: asked without the stratum the measure is a plain C2 (categories of the biopsy result); its categories add
// to the report's units. Fails if the stratified reading changes the plain one.
const d = datos(HISTO, '2025-01-01', '2025-S1');
expect(d.filas.reduce((s, f) => s + (f['n'] as number), 0)).toBe(30);
expect(periodosHistopatologia(datos(HISTO, '2025-01-01', '2025-S1', 'semestre', { estrato: 'birads' }), 'semestre')).toEqual(['2025-S1']);
});
});
describe('Resumen e Histórico leen lo mismo', () => {
type Traza = { name?: string; x: (string | null)[]; y: (number | null)[] };
const serie = (d: IndicadorDatos, nombre: string): Traza =>
((historicoFigura(d, 'claro').figure as unknown as { data: Traza[] }).data).find(t => t.name === nombre)!;
it.each([[TASA, 'Porcentaje', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(p)).value)],
[DIAS, 'Mediana', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(p)).value)]] as const)(
'%s: el valor de la tarjeta de cada semestre es el punto del Histórico en ese semestre', (fhirId, nombre, tarjeta) => {
// Pins down: the card of one semester and the history of all of them are built from the same reports, so the number on the
// card is the point of the series for that period. Fails if the two screens compute the figure differently.
const historico = datosDeReportes(measure(fhirId), SEMESTRES.map(([inicio]) => reportsOf(fhirId, 'semestre', inicio)[0]), 'semestre');
const traza = serie(historico, nombre);
for (const [inicio, periodo] of SEMESTRES) {
const i = traza.x.indexOf(etiquetaPeriodo(periodo));
expect(i, periodo).toBeGreaterThanOrEqual(0);
expect(traza.y[i], periodo).toBe(tarjeta(datos(fhirId, inicio, periodo), periodo));
}
});
});
@@ -0,0 +1,151 @@
// What this module covers: CaMa's follow-up as the WebApi's cohort endpoint answers it (`GET /cama/seguimiento`):
// the answer's validation and labels, the table the page draws from it, its states, the record of one patient and the
// rows of a file. Nothing here is a status, a priority or a figure the data doesn't hold.
// Fixtures (`fixtures/cama_seguimiento_cohorte_real*.json`): answers of the endpoint over the local installation's
// synthetic CaMa data: `_inicial` (default: today, three months), `_consulta` (six months, BI-RADS 5), the whole cohort
// at 2026-11-16 and the 403 body of a group of fewer than five patients.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { ComponentFixture } from '@angular/core/testing';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { consultaAplicada, contextoDe, seguimientoTablaResponse, SeguimientoTablaQuery } from './seguimiento-tabla.service';
import { identidadesDe } from './paciente-identidad';
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import { flatTable } from './export/tracking-export-table';
import inicialData from './fixtures/cama_seguimiento_cohorte_real_inicial.json';
import consultaData from './fixtures/cama_seguimiento_cohorte_real_consulta.json';
import cohorteData from './fixtures/cama_seguimiento_cohorte_real.json';
import pequenoData from './fixtures/cama_seguimiento_cohorte_real_403.json';
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
describe('Seguimiento de CaMa sobre la cohorte del servidor', () => {
it('la respuesta cumple el contrato, nombra la cohorte y rotula los códigos sin cambiar los valores enviados', () => {
// Pins down: the answer is accepted as is (every row names its patient by `pac_id`, a decimal text), the cohort
// context is read from it, and codes read as the clinic writes them while the code stays in `<clave>_codigo`.
// Fails if the endpoint's shape stops passing the client's validation, or a label replaces a code the requests send.
const respuesta = seguimientoTablaResponse(copia(cohorteData));
expect(respuesta.items).toHaveLength(61);
expect(identidadesDe(respuesta.items)!.every(i => i.campo === 'pac_id' && /^[1-9][0-9]*$/.test(i.id))).toBe(true);
expect(contextoDe(respuesta)).toEqual({ cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: expect.stringMatching(/^[0-9a-f]{64}$/) });
const fila = respuesta.items.find(i => i['birads_codigo'] === 'BIRADS_4')!;
expect(fila['birads']).toBe('BI-RADS 4');
expect(respuesta.filtros_disponibles.find(f => f.clave === 'birads')!.opciones.map(o => [o.codigo, o.etiqueta]))
.toContainEqual(['BIRADS_4A', 'BI-RADS 4A']);
expect(respuesta.filtros_disponibles.find(f => f.clave === 'grupo_edad')!.opciones.map(o => o.etiqueta))
.toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
expect(respuesta.columnas.map(c => c.clave)).toEqual(['pac_id', 'grupo_edad', 'birads', 'biopsia']);
});
it('una página o un archivo solo se acepta si es de la consulta, la cohorte y la revisión que se pidieron', () => {
// Pins down: the answer must repeat the window, filters and context asked for. Fails if rows of another revision
// or another selection could be shown under the title of this one.
const respuesta = seguimientoTablaResponse(copia(consultaData));
const contexto = contextoDe(respuesta)!;
const pedido: SeguimientoTablaQuery = { corte: respuesta.corte, meses: 6, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto };
expect(consultaAplicada(pedido, respuesta)).toBe(true);
expect(consultaAplicada({ ...pedido, contexto: { ...contexto, revision: 'otra' } }, respuesta)).toBe(false);
expect(consultaAplicada({ ...pedido, filtros: {} }, respuesta)).toBe(false);
expect(consultaAplicada({ ...pedido, meses: 3 }, respuesta)).toBe(false);
});
it('la ficha de una paciente muestra lo que trae la fila y deja sin dato estatus, prioridad y días', () => {
// Pins down: the record reads BI-RADS, its date, the age group and the biopsy from the row, and what the list
// doesn't carry stays `null` (shown as «No disponible»), never a value made up. Fails if the summary fills
// status, priority or the days to diagnosis from anywhere.
const r = seguimientoTablaResponse(copia(cohorteData));
const conBiopsia = r.items.find(i => i['biopsia'] !== null)!, sinBiopsia = r.items.find(i => i['biopsia'] === null)!;
const resumen = toCamaPatientSummary(conBiopsia, r.corte, r.columnas)!;
expect(resumen).toMatchObject({ patientId: String(conBiopsia['pac_id']), idField: 'pac_id', cutoff: r.corte, status: null, priority: null,
daysMammographyToDiagnosis: null, birads: conBiopsia['birads'], biopsyDate: conBiopsia['biopsia_fecha'] });
expect(resumen.biopsyDateLabel).toBe('Fecha de reporte');
expect(toCamaPatientSummary(sinBiopsia, r.corte, r.columnas)).toMatchObject({ histopathology: null, biopsyDate: null });
});
it('el archivo lleva las columnas del servidor, sin estatus, prioridad ni días de diagnóstico', () => {
// Pins down: the file's columns are the announced ones (with their date details) and no other, and a missing biopsy
// is `null`. Fails if the files add a column the cohort doesn't have.
const r = seguimientoTablaResponse(copia(cohorteData));
const tabla = flatTable({ corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items });
expect(tabla.columns.map(c => c.label)).toEqual(['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Última mastografía: Fecha',
'Resultado histopatológico', 'Resultado histopatológico: Fecha de reporte']);
expect(tabla.rows).toHaveLength(61);
expect(tabla.rows.some(fila => fila[4] === null && fila[5] === null)).toBe(true);
});
});
describe('Seguimiento de CaMa (tabla) con las respuestas del servidor', () => {
let fixture: ComponentFixture<IndicadoresSeguimientoTabla>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
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(); });
const root = () => fixture.nativeElement as HTMLElement;
const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento');
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
const filas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => [...td.childNodes]
.filter(n => n.nodeType !== Node.COMMENT_NODE).map(n => (n.textContent ?? '').trim()).filter(Boolean).join(' ')));
const elegir = (etiqueta: string, valor: string) => {
const s = campo(etiqueta).querySelector('select')!;
s.value = [...s.options].find(o => o.value.endsWith(valor))!.value; s.dispatchEvent(new Event('change'));
};
it('la primera consulta pide la ventana de 3 meses y dibuja las cuatro columnas de la cohorte con los datos que hay', async () => {
// Pins down: the table has the cohort's four columns and no status, priority or days; the first request is three
// months, page one of 50, with no cut-off (the server's today); a patient without biopsy reads «No disponible».
// Fails if the table asks for or draws a column the endpoint doesn't announce.
const r = solicitud();
expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush(inicialData); await asentar();
expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual(
['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Resultado histopatológico']);
expect(filas()).toHaveLength(16);
const sin = filas().find(f => f[3] === 'No disponible');
expect(sin).toBeDefined();
expect(sin![2]).toMatch(/^BI-RADS (4|4A|4B|4C|5|6) Fecha: 20\d\d-\d\d-\d\d$/);
expect(root().textContent).toContain(`Ventana consultada: ${(inicialData as any).ventana.desde} al ${(inicialData as any).ventana.hasta}.`);
});
it('el formulario ofrece los filtros que anuncia el servidor y Consultar envía el filtro elegido, el corte y la revisión que devolvió', async () => {
// Pins down: the filters are BI-RADS, age group and biopsy result as announced, and a second query sends the cut-off
// the first answer gave, with its cohort, scenario and revision, plus the chosen window and filter. Fails if the revision isn't quoted back or a filter the server doesn't announce appears
// (BRCA, stage, size, priority...).
solicitud().flush(inicialData); await asentar();
expect([...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim()))
.toEqual(['Fecha de corte', 'Ventana de meses', 'Categoría BI-RADS', 'Grupo de edad', 'Resultado de la biopsia', 'Registros por página']);
expect([...campo('Resultado de la biopsia').querySelectorAll('option')].map(o => o.text.trim())).toEqual(
['Todos', 'Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Biopsia reportada sin resultado', 'Sin biopsia reportada']);
elegir('Ventana de meses', '6'); elegir('Categoría BI-RADS', 'BIRADS_5'); await asentar();
boton('Consultar').click(); fixture.detectChanges();
const r = solicitud();
expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({
meses: '6', page: '1', page_size: '50', corte: (inicialData as any).corte, birads: 'BIRADS_5',
cohorte: (inicialData as any).cohorte, escenario: (inicialData as any).escenario, revision: (inicialData as any).revision });
r.flush(consultaData); await asentar();
expect(root().textContent).toContain(`Ventana consultada: ${(consultaData as any).ventana.desde} al ${(consultaData as any).ventana.hasta}.`);
expect(filas().every(f => f[2].startsWith('BI-RADS 5'))).toBe(true);
});
it('un grupo de menos de cinco pacientes se dice con su motivo y no se dibuja ninguna fila', async () => {
// Pins down: the server's 403 for a small selection is shown as a message and clears the table. Fails if rows of a
// previous selection stay on screen or the page says nothing.
solicitud().flush(inicialData); await asentar();
elegir('Categoría BI-RADS', 'BIRADS_6'); await asentar();
boton('Consultar').click(); fixture.detectChanges();
solicitud().flush(pequenoData, { status: 403, statusText: 'Forbidden' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
expect(filas()).toHaveLength(0);
});
it('si el servidor responde 404 en CaMa dice que la cohorte no está disponible, sin pantalla vacía', async () => {
// Pins down: an endpoint that isn't there leaves an informative state. Fails if the tab shows an empty table or an
// unhandled error.
solicitud().flush({}, { status: 404, statusText: 'Not Found' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('cohorte no está disponible');
});
});
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
@@ -69,10 +69,6 @@ function suma(celdas: Celda[]): number | null {
function estado(celdas: Celda[]): Celda['estado'] {
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
}
function promedio(colores: string[]): string {
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
.toString(16).padStart(2, '0')).join('');
}
function rgba(hex: string, alfa: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
@@ -101,15 +97,21 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
const c = cats[a.id];
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
});
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
});
const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO);
const colores = paintByGroup(conColor.map(g => g.grupo));
const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]]));
const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color }));
const ordenGrupos = [...new Set(conColor.map(g => g.grupo))];
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
// Off-catalogue grades share the group but not its colour.
const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
const propios = grados.filter(g => g.grupo === id);
const indice = ordenGrupos.indexOf(id);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: indice < 0 ? COLOR_RESPALDO : groupBase(indice),
grados: propios.map(g => g.id) };
});
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
@@ -87,50 +87,24 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
const dona = donaConteos(m, PAR, 'claro') as unknown as { data: { labels: string[]; values: number[] }[]; layout: { annotations: { text: string }[] } };
expect(dona.data[0].labels).toEqual(['BI-RADS 4 (sin subcategoría)', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(dona.data[0].values).toEqual([15, 2, 0, 0, 18, 0]);
expect(dona.layout.annotations[0].text).toBe('<b>35</b><br>mastografías');
expect(dona.layout.annotations.slice(0, 2).map(a => a.text)).toEqual(['<b>35</b>', 'mastografías']);
});
});
describe('Conteos pareados de CaMa: etiquetas de la dona', () => {
type Figura = { data: Record<string, any>[]; layout: { annotations: Record<string, any>[]; margin: Record<string, number>; showlegend: boolean } };
const dona = (compacta = false) => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro', compacta) as unknown as Figura;
const dona = () => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro') as unknown as Figura;
// Fails if the long label of the 4 without subcategory goes back inside the ring (where it is cut), loses its
// percentage or its guide line, or if the short labels or the centre total change.
it('2025-S2: la etiqueta larga sale del anillo, horizontal y con línea guía; las cortas y el total se conservan', () => {
const f = dona(), t = f.data[0], llamada = f.layout.annotations[1];
expect(t['text'][0]).toBe('');
expect(t['text'][1]).toBe('');
expect(t['text'][4]).toMatch(/^BI-RADS 5<br>54[.,]5 %$/);
it('mantiene las etiquetas con porcentaje fuera del sector', () => {
const f = dona(), t = f.data[0];
expect(t['textinfo']).toBe('none');
expect(t['hovertemplate']).toBe('%{value}<extra></extra>');
expect(f.layout.annotations.slice(2).map(a => a['text']).sort()).toEqual([
'BI-RADS 4<br>(sin<br>subcategoría)<br>45.5 %', 'BI-RADS 5<br>54.5 %',
]);
expect(t['values']).toEqual([15, 0, 0, 0, 18, 0]);
expect(f.layout.annotations[0]['text']).toBe('<b>33</b><br>mastografías');
expect(f.layout.annotations).toHaveLength(2);
expect(llamada['text']).toBe('BI-RADS 4<br>(sin subcategoría)<br>45.5 %');
// A guide line: an arrow without head from the label to a point inside the slice, and no text rotation.
expect(llamada['showarrow']).toBe(true);
expect(llamada['arrowhead']).toBe(0);
expect(llamada['textangle']).toBeUndefined();
});
// Fails if the label can reach the neighbouring chart: its side must keep a margin, and it sits on the side of its slice.
it('reserva espacio del lado de la etiqueta y la coloca del lado de su segmento', () => {
const f = dona(), llamada = f.layout.annotations[1];
// The slice is 45 % of a clockwise ring: its middle points right, so label and margin are on the right.
expect(llamada['xanchor']).toBe('left');
expect(llamada['ax']).toBeGreaterThan(0);
expect(f.layout.margin['r']).toBeGreaterThanOrEqual(110);
expect(f.layout.margin['l']).toBeLessThan(20);
expect(f.layout.showlegend).toBe(false);
});
// Fails if a narrow screen keeps a label that needs side room instead of moving to a legend under the donut.
it('en pantalla estrecha no hay llamada: la dona usa una leyenda debajo', () => {
const f = dona(true);
expect(f.layout.annotations).toHaveLength(1);
expect(f.layout.showlegend).toBe(true);
expect((f.layout as Record<string, any>)['legend']['orientation']).toBe('h');
expect(f.layout.margin['r']).toBeLessThan(20);
expect(f.data[0]['values']).toEqual([15, 0, 0, 0, 18, 0]);
expect(f.layout.annotations.slice(0, 2).map(a => a['text'])).toEqual(['<b>33</b>', 'mastografías']);
});
});
@@ -42,10 +42,10 @@ export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly strin
// The kit publishes a 4 without subcategory as «B4», with no colour.
const ETIQUETA_RESPALDO: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
// The categories a response lists only when some unit falls in them: a period set without any has none, not an unknown.
const OPCIONALES: ReadonlySet<string> = new Set(Object.keys(ETIQUETA_RESPALDO));
const COLOR_RESPALDO: Readonly<Record<string, string>> = { B4: '#E9C08C' };
const COLOR_NEUTRO = '#8A9199';
// Labels longer than «BI-RADS 4A» do not fit inside the ring.
const LARGO_ETIQUETA_INTERIOR = 12;
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
@@ -82,21 +82,24 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
};
const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO;
const todas = par.grupos.flatMap(g => g.categorias);
if (par.categoriasExamen.some(id => !Object.hasOwn(catExamenes, id)) || todas.some(id => !Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id))) {
if (par.categoriasExamen.some(id => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|| todas.some(id => !OPCIONALES.has(id) && (!Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id)))) {
fail('Las categorías de mastografías y pacientes no coinciden.');
}
const verificados = par.versionesPacientes.includes(String(pacientes['version'] ?? ''));
const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort();
const filasE = examenes.filas as Record<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
const de = (filas: Record<string, unknown>[], cat: Record<string, unknown>, periodo: string, id: string) =>
OPCIONALES.has(id) && !Object.hasOwn(cat, id) ? 0 : cuenta(filas, periodo, id);
return periodos.map(periodo => ({
periodo,
examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) })),
examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: de(filasE, catExamenes, periodo, id) })),
// Only the exams the response reports apart; an indicator that lists no such category has none.
sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
filas: par.grupos.map(g => ({
id: g.id, etiqueta: g.etiqueta,
pacientes: verificados ? sumar(g.categorias.map(id => cuenta(filasP, periodo, id))) : null,
examenes: sumar(g.categorias.map(id => cuenta(filasE, periodo, id))),
pacientes: verificados ? sumar(g.categorias.map(id => de(filasP, catPacientes, periodo, id))) : null,
examenes: sumar(g.categorias.map(id => de(filasE, catExamenes, periodo, id))),
})),
pacientesVerificados: verificados,
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
@@ -104,49 +107,62 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
}
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
// Geometry the callouts rely on. The ring is height-bound (a 400 px figure with a 10 px margin above and below and
// the pie over 90 % of that height), so its radius does not depend on the width of the card.
const ALTO_DONA = 400, MARGEN_VERTICAL = 10, RADIO_DONA = Math.round((ALTO_DONA - 2 * MARGEN_VERTICAL) * .9 / 2);
const MARGEN_ROTULO = 120, SALIDA_ROTULO = 28;
const ALTO_DONA = 400, MARGEN_DONA = 8;
const DIAMETRO_MAXIMO_DONA = 270;
/**
* Exams by category around their total; nothing is drawn when a cell is unknown. A long label does not fit in the
* ring: it is drawn outside, horizontal and on two lines, joined to its slice by a guide line, on the side of the
* slice with room reserved for it so it never reaches the neighbouring chart. On a narrow card (`compacta`) the
* callouts give way to a legend under the donut.
*/
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, compacta = false): PlotlyFigure {
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
const total = totalExamenes(m);
if (!total) return { data: [], layout: {} };
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
const larga = (i: number) => m.examenes[i].etiqueta.length > LARGO_ETIQUETA_INTERIOR && n[i] > 0;
const porcentaje = (i: number) => percentNumber(100 * n[i] / total) + ' %';
const dibujadas = (i: number) => !larga(i) && n[i] / total >= .05;
// Each long label is a callout whose guide line ends inside its slice.
let antes = 0;
const llamadas = n.flatMap((v, i) => {
const angulo = 2 * Math.PI * (antes + v / 2) / total;
antes += v;
if (compacta || !larga(i)) return [];
const seno = Math.sin(angulo), coseno = Math.cos(angulo), dentro = Math.round(RADIO_DONA * .8), fuera = RADIO_DONA + SALIDA_ROTULO - dentro;
const etiqueta = escapar(m.examenes[i].etiqueta), corte = etiqueta.indexOf(' (');
return [{ x: .5, y: .5, xref: 'paper', yref: 'paper', xshift: Math.round(dentro * seno), yshift: Math.round(dentro * coseno),
ax: Math.round(fuera * seno), ay: Math.round(-fuera * coseno), axref: 'pixel', ayref: 'pixel', showarrow: true, arrowhead: 0, arrowwidth: 1, arrowcolor: p.text,
text: (corte > 0 ? etiqueta.slice(0, corte) + '<br>' + etiqueta.slice(corte + 1) : etiqueta) + '<br>' + porcentaje(i),
align: seno >= 0 ? 'left' : 'right', xanchor: seno >= 0 ? 'left' : 'right', yanchor: 'middle', font: { size: 12, color: p.text }, lado: seno >= 0 ? 'r' : 'l' }];
// Fit both label columns before sizing the ring. Use the same radius for Plotly and the guide lines.
const margenEtiquetas = Math.min(90, 59 + Math.max(0, ancho - 230) * .2);
const diametro = Math.max(1, Math.min(DIAMETRO_MAXIMO_DONA, ancho - 2 * (MARGEN_DONA + margenEtiquetas)));
const radio = diametro / 2;
const fraccionVertical = radio / (ALTO_DONA - 2 * MARGEN_DONA);
const fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10);
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8;
const etiquetas = m.examenes.map(c => escapar(c.etiqueta));
const porcentajes = n.map(v => percentNumber(100 * v / total));
const centro = { x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false };
// The pie starts at noon. Keep each callout on its slice's side and order the rows vertically,
// so even several adjacent slivers get separate labels and their guide lines keep the same order.
let acumulado = 0;
const puntos = n.flatMap((valor, i) => {
const angulo = 2 * Math.PI * (acumulado + valor / 2) / total;
acumulado += valor;
if (!valor) return [];
const x = radio * Math.sin(angulo), y = radio * Math.cos(angulo);
return [{ i, x, y }];
});
const lado = (l: string) => llamadas.some(a => a.lado === l) ? MARGEN_ROTULO : 10;
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
text: n.map((_, i) => dibujadas(i) ? escapar(m.examenes[i].etiqueta) + '<br>' + porcentaje(i) : ''),
domain: { x: [0, 1], y: [.05, .95] },
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
layout: { autosize: true, height: compacta ? ALTO_DONA + 40 : ALTO_DONA, showlegend: compacta, paper_bgcolor: p.background, font: { color: p.text },
margin: { t: MARGEN_VERTICAL, b: compacta ? 70 : MARGEN_VERTICAL, l: lado('l'), r: lado('r') },
...(compacta ? { legend: { orientation: 'h', x: .5, xanchor: 'center', y: -.02, yanchor: 'top', font: { size: 12 } } } : {}),
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }, ...llamadas.map(({ lado: _lado, ...a }) => a)] }, config: { displayModeBar: false } };
const llamadas = [-1, 1].flatMap(lado => {
const columna = puntos.filter(punto => (punto.x < 0 ? -1 : 1) === lado).sort((a, b) => b.y - a.y);
return columna.map(({ i, x, y }, fila) => {
const altura = (columna.length - 1 - 2 * fila) * 24;
const texto = etiquetas[i].replace(' (sin subcategoría)', '<br>(sin<br>subcategoría)');
return {
annotation: { ...centro, xshift: lado * (radio + 10), yshift: altura,
xanchor: lado < 0 ? 'right' : 'left', align: lado < 0 ? 'right' : 'left',
font: { size: fuenteEtiqueta, color: p.text }, text: texto + '<br>' + porcentajes[i] + ' %' },
shape: { type: 'path', xref: 'paper', yref: 'paper', xsizemode: 'pixel', ysizemode: 'pixel',
xanchor: .5, yanchor: .5, line: { color: p.text, width: 1 },
path: 'M ' + Math.round(x) + ',' + Math.round(y) + ' L ' + lado * (radio + 3) + ',' + y + ' L ' + lado * (radio + 8) + ',' + altura },
};
});
});
return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas,
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] },
customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
hovertemplate: '%{value}<extra></extra>' }],
layout: { autosize: true, height: ALTO_DONA, showlegend: false, paper_bgcolor: p.background, font: { color: p.text },
margin: { t: MARGEN_DONA, b: MARGEN_DONA, l: MARGEN_DONA, r: MARGEN_DONA },
shapes: llamadas.map(({ shape }) => shape),
annotations: [
{ ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` },
{ ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: par.unidades.examenes },
...llamadas.map(({ annotation }) => annotation),
] }, config: { displayModeBar: false } };
}
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
@@ -39,10 +39,6 @@ function estado(celdas: Celda[]): Escenario['estado'] {
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido'
: celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
}
function promedio(colores: string[]): string {
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
.toString(16).padStart(2, '0')).join('');
}
function rgba(hex: string, alfa: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
@@ -128,9 +124,10 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
// Missing rows remain unavailable. Catalog order is used only for the accessible
// list of missing categories; a partial distribution is never drawn as a donut.
const categorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id],
color: promedio(categorias.filter(c => c.grupo === id).map(c => c.color)) }));
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
const colores = paintByGroup(baseCategorias.map(c => c.grupo));
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
const grupos = [...new Set(categorias.map(c => c.grupo))].map((id, i) => ({ id, etiqueta: nombres[id], color: groupBase(i) }));
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
const totals = porEscenario['totales_estrato'];
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
File diff suppressed because one or more lines are too long
@@ -173,14 +173,15 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 });
expect(response.resumen_eeg).toMatchObject({ validadas: true, con_eeg_valido: 3, normales: 2, anormales: 1, sin_eeg: 3 });
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
});
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
// Pins down: the age group from the summary's episode, ADOS-2 domains whose totals add up (the page checks it),
// the EEG analysis's checks as its report writes them (value or text, A/N, decisive), each metric's state, effects
// and median from the code system and its observation, and one map per evaluable metric from its electrodes'
// z-scores. Fails if the summary stops passing the page's checks or a map appears for a metric without electrodes.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
@@ -188,9 +189,11 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(detalle.grupo_edad).toBe('16-23 meses');
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
expect(detalle.eeg!.calidad).toBe('bueno');
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' });
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'line-noise')).toMatchObject({ valor: 3.5, unidad: 'dB', nivel: 'bueno', decisivo: false, electrodo: null });
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'clean-windows')).toMatchObject({ valor: 95, decisivo: true });
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'triage-level')?.valor).toBe('completo');
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 });
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08, referencia: { min: 4.5, max: 7, mediana: 5.75 }, sin_evaluar: null });
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
});
@@ -9,6 +9,10 @@ import {
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
import { IndicadoresRequests } from './indicadores-requests';
import {
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
} from './indicadores-cama-fhir';
// 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
@@ -27,7 +31,7 @@ export interface Measure extends Resource {
export interface Report extends Resource {
measure?: string; date?: string; period?: { start: string; end: string }; group?: Group[];
}
interface Categoria { etiqueta: string; color: string | null; grupo: null }
interface Categoria { etiqueta: string; color: string | null; grupo: string | null; gravedad?: number | null }
const MAX_COUNT = 200;
const POPULATION_GROUP: Record<string, string> = {
@@ -35,8 +39,9 @@ const POPULATION_GROUP: Record<string, string> = {
'denominator-exclusion': 'exclusion', 'measure-population-exclusion': 'exclusion', 'measure-observation': 'observacion',
};
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use.
export const indicadorId = (measureId: string) => measureId.replace(/-/g, '_');
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`).
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
// Age groups travel as `16_23`; the page names them `16-23`.
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
@@ -84,13 +89,16 @@ export function indicadorDeMeasure(measure: Measure): Indicador & Record<string,
};
}
// TEA's measures are named by their first segment (`M21`); CaMa's share the domain's, so theirs is the rest (`BIRADS456-PACIENTE`).
const codigoDeFicha = (measureId: string) => esMedidaCama(measureId) ? measureId.slice(measureId.indexOf('-') + 1) : measureId.split('-')[0];
export function metadatosDeMeasure(measure: Measure): IndicadorMetadatos {
const unidad = code(measure.subjectCodeableConcept) ?? null;
return {
id: indicadorId(measure.id ?? ''),
version: measure.version,
descripcion: measure.description ?? null,
ficha: { codigo: (measure.id ?? '').split('-')[0], unidad, definicion: measure.description ?? null },
ficha: { codigo: codigoDeFicha(measure.id ?? ''), unidad, definicion: measure.description ?? null },
unidad,
referencias: [],
poblaciones: (measure.group?.[0]?.population ?? []).map(p => ({
@@ -148,12 +156,67 @@ function stratumValue(stratum: Stratum): string | undefined {
return value === undefined ? undefined : estratoValor(value);
}
// The categories a composition's reports count that its Measure doesn't declare, in order of appearance, with their
// captions. Only CaMa's: its BI-RADS 4 without subcategory is published this way.
function categoriasNoDeclaradas(reports: Report[], declaradas: Record<string, Categoria>): Map<string, string> {
const found = new Map<string, string>();
for (const report of reports) {
for (const stratum of report.group?.flatMap(g => g.stratifier?.[0]?.stratum ?? []) ?? []) {
const categoria = code(stratum.value);
if (!categoria || Object.hasOwn(declaradas, categoria) || found.has(categoria) || !(stratum.population?.[0]?.count)) continue;
found.set(categoria, ETIQUETA_CATEGORIA_NO_DECLARADA[categoria] ?? display(stratum.value) ?? categoria);
}
}
return found;
}
// The cross of the two stratifiers of CaMa's histopathological result (BI-RADS by biopsy grade) in one report, in the
// page's codes. FHIR publishes only the cells that have patients; the report is complete, so a cell it doesn't list is
// zero. A code the correspondence tables don't know, or cells that don't add up to the report's units, is an error.
function cruceDeHistopatologia(group: Group, estrato: string): Map<string, number> {
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
const unidades = count(group.population, 'initial-population');
// A report with no units has no cell to cross: it is a published matrix of zeros, not a missing stratifier.
if (!stratifier && unidades === 0) return new Map();
if (!stratifier) throw new Error('Dimensión no admitida');
const celdas = new Map<string, number>();
for (const stratum of stratifier.stratum ?? []) {
const bi = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
const e = ESTRATO_BIRADS_PAGINA[code(bi?.value) ?? ''], c = CATEGORIA_HISTOPATOLOGIA_PAGINA[code(cat?.value) ?? ''];
if (!e || !c) throw new Error('Código de histopatología no reconocido');
const clave = `${e}|${c.id}`;
celdas.set(clave, (celdas.get(clave) ?? 0) + (stratum.population?.[0]?.count ?? 0));
}
if (unidades !== null && [...celdas.values()].reduce((sum, n) => sum + n, 0) !== unidades) {
throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
return celdas;
}
// 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), cats = categorias(measure), estrato = scope.estrato;
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
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).
const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
const cats: Record<string, Categoria> = cruzado
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
if (!m) throw new Error('Categoría de histopatología no reconocida');
return [m.id, { ...c, grupo: m.grupo, gravedad: m.gravedad }];
}))
: { ...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`.
const nombre = (codigo: string | undefined) => {
const grupo = codigo ?? 'TOTAL';
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
};
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = code(g.code) ?? 'TOTAL';
return [id, id === 'TOTAL' ? 'Total' : display(g.code) ?? id];
const id = nombre(code(g.code));
return [id, id === 'TOTAL' || id === GRUPO_PRINCIPAL_PAGINA ? 'Total' : display(g.code) ?? id];
}));
const valores = new Map<string, string>();
const filas: Record<string, unknown>[] = [];
@@ -163,9 +226,29 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
const periodo = periodLabel(report.period);
periodos.push(periodo);
for (const group of report.group ?? []) {
const grupo = code(group.code) ?? 'TOTAL';
const grupo = nombre(code(group.code));
if (cruzado) {
const celdas = cruceDeHistopatologia(group, estrato!);
Object.values(ESTRATO_BIRADS_PAGINA).forEach(e => {
let total = 0;
Object.keys(cats).forEach((categoria, orden) => {
const n = celdas.get(`${e}|${categoria}`) ?? 0;
total += n;
filas.push({ periodo, grupo, estrato: e, categoria, n, orden, suprimido: 0 });
});
totales.push({ periodo, grupo, estrato: e, n: total, suprimido: 0 });
valores.set(e, e);
});
continue;
}
if (kind === 'C2') {
const counts = new Map((group.stratifier?.[0]?.stratum ?? []).map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
const strata = group.stratifier?.[0]?.stratum ?? [];
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
// A report whose categories don't add up to its units can't be drawn as a partition; say so, don't undercount.
const units = count(group.population, 'initial-population');
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');
}
Object.keys(cats).forEach((categoria, orden) =>
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
continue;
@@ -196,10 +279,11 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
tipo_periodo: tipo,
periodos,
estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: Object.fromEntries(valores) } : { valores_estrato: [] }),
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
...(cruzado ? { totales_estrato: totales } : {}),
grupos,
categorias: cats,
grupos_de_categoria: {},
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
notas: [],
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
filas,
@@ -242,7 +242,11 @@ describe('Histopatología por BI-RADS: componente', () => {
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
expect([...f.nativeElement.querySelectorAll('.keys button')].map((b: Element) => b.textContent!.trim()))
.toEqual(['No maligno', 'Maligno', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']);
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('selección: Maligno');
const grafica = f.nativeElement.querySelector('.figures') as HTMLElement;
const seleccion = f.nativeElement.querySelector('.selection-status') as HTMLElement;
expect(grafica.nextElementSibling?.classList.contains('legend')).toBe(true);
expect(grafica.nextElementSibling?.nextElementSibling).toBe(seleccion);
expect(seleccion.textContent).toContain('selección: Maligno');
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(
['Categoría BI-RADS', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor', 'Con resultado', 'Sin biopsia reportada', 'Sin dato', 'Total de pacientes']);
@@ -21,6 +21,7 @@ const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
// The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two
// and MALIGNO the last two, as the catalog says.
export const CON_RESULTADO = ['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR'] as const;
const OBLIGATORIAS: readonly string[] = ['BENIGNO', 'IN_SITU', 'INVASOR'];
// Reported apart, outside the denominator and the donut: no biopsy reported at the cut-off, and a biopsy without grade.
export const APARTE = [
{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia reportada' },
@@ -100,10 +101,11 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de categorías incompleto.');
// A category the view does not know would change the denominator without anyone noticing.
const conocidas: readonly string[] = [...CON_RESULTADO, ...APARTE_IDS];
if (Object.keys(cats).some(id => !conocidas.includes(id)) || CON_RESULTADO.some(id => !Object.hasOwn(cats, id))) {
// The risk lesion (B3) is only published by a source that has it: the others have to be there.
if (Object.keys(cats).some(id => !conocidas.includes(id)) || OBLIGATORIAS.some(id => !Object.hasOwn(cats, id))) {
return fail('El catálogo no publica las categorías esperadas de la biopsia.');
}
const categorias: Categoria[] = CON_RESULTADO.map(id => {
const categorias: Categoria[] = CON_RESULTADO.filter(id => Object.hasOwn(cats, id)).map(id => {
const c = cats[id];
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && c['color'] !== undefined && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Categorías de biopsia incompatibles.');
@@ -111,7 +113,7 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
});
const grupos: GrupoCategorias[] = [...new Set(categorias.map(c => c.grupo))].map(id => {
const propias = categorias.filter(c => c.grupo === id);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio(propias.map(c => c.color)), categorias: propias.map(c => c.id) };
return { id, etiqueta: id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!, color: promedio(propias.map(c => c.color)), categorias: propias.map(c => c.id) };
});
if (grupos.length !== 2) return fail('Se esperaban dos grupos de resultados.');
const base = categorias.find(c => c.id === CATEGORIA_BASE)!.grupo;
@@ -46,7 +46,7 @@ describe('Histórico de CaMa', () => {
}
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
// Answers in waves, because the shared request queue runs four at a time.
function responder(fallo?: (r: TestRequest) => boolean) {
function responder(fallo?: (r: TestRequest) => boolean, sinDatos?: (periodo: string) => boolean) {
const vistos: string[] = [];
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
@@ -56,7 +56,9 @@ describe('Histórico de CaMa', () => {
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(',');
r.flush(datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos));
const d = datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos);
if (sinDatos) d.filas = d.filas.filter(fila => !sinDatos(fila.periodo));
r.flush(d);
}
}
fixture.detectChanges();
@@ -81,10 +83,32 @@ describe('Histórico de CaMa', () => {
montar(CATALOGO, true); responder();
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
expect(pendientes).toEqual(['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']);
expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']);
expect(graficas()).toHaveLength(5);
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
});
it('los periodos sin dato van en una sección plegable cerrada, con una etiqueta breve, y al abrirla salen completos', () => {
// Pins down: a chart with months without data keeps its figure and its caption and puts the list of those months in a
// closed disclosure labelled «Periodos sin dato (n)»; opening it shows every month, as the note read before. Fails if the
// list is open from the start, is cut short, or the figure changes.
montar(CATALOGO, true); responder(undefined, periodo => !['2025-01', '2025-02'].includes(periodo));
const panel = paneles()[1];
const plegable = panel.querySelector<HTMLDetailsElement>('details[data-plegable="sin-dato"]')!;
expect(plegable).not.toBeNull();
expect(plegable.open).toBe(false);
expect(plegable.querySelector('summary')!.textContent!.trim()).toBe('Periodos sin dato (5)');
expect(plegable.querySelector('p')!.textContent).toMatch(/Sin dato: .*mar 2025.*abr 2025.*may 2025.*jun 2025.*jul 2025./);
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
expect(panel.querySelector('.nota')!.textContent!.length).toBeGreaterThan(0);
plegable.querySelector('summary')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
fixture.detectChanges();
expect(plegable.open).toBe(true);
});
it('un panel sin periodos sin dato no muestra la sección', () => {
// Fails if an empty disclosure appears where every period has data.
montar(CATALOGO, true); responder();
expect(root().querySelector('details[data-plegable="sin-dato"]')).toBeNull();
});
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
montar(CATALOGO, true); responder();
expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual');
@@ -28,10 +28,15 @@ describe('Pestaña Histórico', () => {
http.match(() => true);
}
it('CaMa: Resumen, Histórico, Análisis epidemiológico, Seguimiento y Datos y definiciones, en ese orden', () => {
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 epidemiológico', 'Seguimiento', '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();
expect(fixture.componentInstance.activeSection()).toBe('resumen');
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.
@@ -26,7 +26,7 @@ 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 por categoría BI-RADS' },
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6' },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
@@ -109,7 +109,12 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
<p>Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
</details>
}
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
@if (panel.figura.sinDato.length) {
<details class="nota-pie" data-plegable="sin-dato">
<summary>Periodos sin dato ({{ panel.figura.sinDato.length }})</summary>
<p>Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p>
</details>
}
}
}
</article>
@@ -63,9 +63,9 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
],
};
// CaMa's four opportunity cards, in display order. Two of them have no indicator in the catalog yet
// (indicadores_kit defines neither `cama_tasa_deteccion_histopatologica` nor `cama_dias_resultado_diagnostico`),
// so they stay outside KPI_BY_DOMAIN: they are queried only once the catalog publishes them.
// CaMa's four opportunity cards, in display order. Two of them have no measure in the FHIR catalog yet
// (`cama_tasa_deteccion_histopatologica` and `cama_dias_resultado_diagnostico`), so they stay outside
// KPI_BY_DOMAIN: they are queried only once the catalog publishes them.
export const CAMA_OPORTUNIDAD_KPIS: KpiDefinition[] = [
KPI_BY_DOMAIN.cama[0],
CAMA_TASA_DETECCION_KPI,
@@ -83,8 +83,11 @@ export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[]
// 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.
// The two published opportunity indicators draw their KPI card only; their evolution is in Histórico.
export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a',
'cama_tasa_deteccion_histopatologica', 'cama_dias_resultado_diagnostico'];
// `cama_birads` is replaced by the exams' and patients' counts, and `cama_birads_cancer_invasor` is the
// epidemiological analysis' measure: neither has a card of its own.
export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias', 'cama_birads', 'cama_birads_cancer_invasor',
'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_tasa_deteccion_histopatologica',
'cama_dias_resultado_diagnostico'];
export const ID_HISTOPATOLOGIA_CAMA = 'cama_histopatologia_birads';
// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`.
const C1_GROUP: Record<Dominio, string> = { tea: 'TOTAL', cacu: 'total', cama: 'total' };
@@ -135,7 +135,7 @@
@if (conAnalisis) {
<section id="panel-analisis" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-analisis" tabindex="0" [hidden]="activeSection() !== 'analisis'">
<app-indicadores-analisis [dominio]="dominio" [tema]="tema" [active]="activeSection() === 'analisis'" (verPacientes)="verPacientes($event)" />
<p>En desarrollo</p>
</section>
}
@@ -42,19 +42,23 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
// TEA and CaMa have enough periods for their history to say anything; 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]];
const SECTIONS_WITH_ANALYSIS: readonly { id: DashboardSection; label: string }[] = [
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1], { id: 'analisis', label: 'Análisis epidemiológico' }, SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
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]];
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, IndicadoresAnalisis, TeaResumenPeriodo],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conAnalisis ? SECTIONS_WITH_ANALYSIS : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
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 conAnalisis() { return this.dominio === 'cama'; }
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
private readonly analisis = viewChild(IndicadoresAnalisis);
@@ -2,19 +2,21 @@
// «Volver al análisis», with the analysis as it was and the focus on the control that opened the list; the selection going
// with the domain; CaCu and TEA keeping their three sections; and the wording of every screen of the journey.
// Fixtures: indicadores-analisis.testing.ts (the aggregate) and fixtures/cama_seguimiento.json (the list).
// The journey through the Análisis tab only runs while the page offers that tab (CAMA_ANALYSIS_ENABLED); with it
// withdrawn those tests are reported as skipped, and the selection and sections tests keep running without it.
import { Component, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from '../../app.routes';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import fixtureData from './fixtures/cama_seguimiento.json';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresAnalisis, hoyIso } from './indicadores-analisis';
import { CAMA_ANALYSIS_ENABLED, IndicadoresPage } from './indicadores-page';
import { IndicadoresAnalisis, hoyIso, seleccionDeGrupo } from './indicadores-analisis';
import { IndicadorFigureCard } from './indicador-figure-card';
import { agregadoJson, CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { agregadoJson, CONTEXTO, listaCohorte, sinAnalisisDescriptivo } from './indicadores-analisis.testing';
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
import { Indicador } from './indicadores.models';
@@ -22,6 +24,7 @@ import { Indicador } from './indicadores.models';
class ChartStub { readonly plotClick = output<unknown>(); }
const catalogoCama: Indicador[] = [{ id: 'published', titulo: 'Nombre publicado', contrato: 'C2', figuras: ['fig_c2_barras'], tipos_periodo: ['mes'] }];
const conAnalisis = CAMA_ANALYSIS_ENABLED ? it : it.skip;
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
// What the cohort's list answers to the group BI-RADS 5: the whole cohort, the cut-off asked for, the filter applied and the cohort quoted back.
const cohorte = (corte: string) => ({ ...base(), ...CONTEXTO, corte, ventana: { meses: 0, desde: '2025-01-01', hasta: corte },
@@ -39,7 +42,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
const corte = hoyIso();
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
@@ -63,7 +66,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
const lista = () => http.expectOne(q => q.url === '/cama/seguimiento');
const parametros = (r: ReturnType<typeof lista>) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
it('Ver pacientes abre la lista de ese grupo; la ficha y el regreso conservan la lista, el análisis y el foco', async () => {
conAnalisis('Ver pacientes abre la lista de ese grupo; la ficha y el regreso conservan la lista, el análisis y el foco', async () => {
// Fails if any step of the journey drops the selection, repeats a request, loses the focus or the answer already loaded.
const e = await entrar();
await abrirAnalisis(e);
@@ -105,7 +108,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
http.expectNone(q => q.url === '/cama/seguimiento');
expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5');
});
it('el corte que el usuario elige llega al agregado, al listado, a la ficha y al archivo descargado', async () => {
conAnalisis('el corte que el usuario elige llega al agregado, al listado, a la ficha y al archivo descargado', async () => {
// Fails if any step of the journey is read at another cut-off than the chosen one, or the file does not say it.
const ELEGIDO = '2026-09-01';
const descargas: string[] = [];
@@ -135,7 +138,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
expect(descargas).toHaveLength(1);
expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-09-01_/);
});
it('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => {
conAnalisis('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => {
// Fails if a stale revision shows rows, or the way back to the analysis is lost with the error.
const e = await entrar();
await abrirAnalisis(e);
@@ -150,8 +153,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
it('al cambiar de dominio la selección se limpia; CaCu y TEA no tienen Análisis y conservan sus secciones', async () => {
// Fails if a selection survives into another domain, or the analysis tab leaks into CaCu or TEA.
const e = await entrar();
await abrirAnalisis(e);
e.root.querySelector<HTMLButtonElement>('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges();
e.page.verPacientes(seleccionDeGrupo(agregadoJson({ corte }), 'BIRADS_5')!); e.harness.detectChanges();
lista().flush(cohorte(corte)); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeDefined();
for (const dominio of ['cacu', 'tea'] as const) {
@@ -167,7 +169,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(e.root.querySelector('.seleccion')).toBeNull();
});
it('la pestaña Análisis sin endpoint publicado dice que está pendiente, sin ocultarlo ni mostrarlo como error', async () => {
conAnalisis('la pestaña Análisis sin endpoint publicado dice que está pendiente, sin ocultarlo ni mostrarlo como error', async () => {
// Fails if the missing endpoint is hidden or shown as a broken page, or the wording leaks the environment.
const e = await entrar();
e.tab('analisis').click(); e.harness.detectChanges();
@@ -0,0 +1,20 @@
// What this module covers: that the FHIR mapping shared by all domains gives CaCu and TEA what it gave them before CaMa's
// measures got their own correspondences, categories and groups.
// Fixtures: `fixtures/regresion_cacu_tea_fhir.json` (real Measure bundles and two semesters of reports of every CaCu and
// TEA measure, from the local installation) and `fixtures/regresion_cacu_tea_mapeo.json` (what the mapper returned for
// them before the CaMa changes: ids, catalog entries, sheets and data rows, without and with each stratum).
import { datosDeReportes, indicadorDeMeasure, indicadorId, metadatosDeMeasure } from './indicadores-fhir';
import { mapeoDeCacuYTea } from './indicadores-regresion-fhir.testing';
import esperado from './fixtures/regresion_cacu_tea_mapeo.json';
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,
// 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));
for (const clave of Object.keys(esperado)) expect(actual[clave], clave).toEqual((esperado as Record<string, unknown>)[clave]);
});
});
@@ -0,0 +1,32 @@
// The FHIR mapping of every CaCu and TEA measure over real answers, as one comparable object: what the page reads of
// each Measure (id, catalog entry, technical sheet) and its data rows without and with each stratum the catalog offers.
// A mapper that changes for another domain shows up as a difference here.
import { Bundle, resources } from './fhir';
import type { Measure, Report } from './indicadores-fhir';
import { DimensionEstrato, IndicadorDatos, TipoPeriodo } from './indicadores.models';
import data from './fixtures/regresion_cacu_tea_fhir.json';
export interface Mapeador {
indicadorId: (measureId: string) => string;
indicadorDeMeasure: (measure: Measure) => unknown;
metadatosDeMeasure: (measure: Measure) => unknown;
datosDeReportes: (measure: Measure, reports: Report[], tipo: TipoPeriodo, scope?: { estrato?: DimensionEstrato }) => IndicadorDatos;
}
export function mapeoDeCacuYTea(mapeador: Mapeador): Record<string, unknown> {
const salida: Record<string, unknown> = {};
for (const dominio of ['cacu', 'tea'] as const) {
const measures = resources(data.measures[dominio] as unknown as Bundle, 'Measure') as Measure[];
for (const measure of measures) {
const reports = resources((data.reports[dominio] as Record<string, unknown>)[measure.id!] as Bundle, 'MeasureReport') as Report[];
const indicador = mapeador.indicadorDeMeasure(measure) as { estratos: DimensionEstrato[] };
const datos: Record<string, unknown> = {};
for (const estrato of [undefined, ...indicador.estratos]) {
try { datos[estrato ?? 'total'] = mapeador.datosDeReportes(measure, reports, 'semestre', estrato ? { estrato } : {}); }
catch (error) { datos[estrato ?? 'total'] = { error: (error as Error).message }; }
}
salida[`${dominio}/${measure.id}`] = { id: mapeador.indicadorId(measure.id!), indicador, metadatos: mapeador.metadatosDeMeasure(measure), datos };
}
}
return JSON.parse(JSON.stringify(salida));
}
@@ -37,8 +37,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 adds Análisis epidemiológico before Seguimiento; CaCu keeps its three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']
// 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'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
@@ -66,6 +66,16 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => {
expect(fixture.componentInstance.etiquetaDatos()).toBe('Categoría BI-RADS: BI-RADS 5');
expect(exportar()).not.toBeNull();
});
it.each([1, 3, 6, 12])('una selección calculada con la ventana de %i meses pide esa misma ventana, con el corte, el filtro y la cohorte, y no avisa de diferencia si los pacientes coinciden', async (m) => {
// Fails if a bar computed over a window opens the whole cohort (or another window), so the list shows other patients than counted.
abrirCon(seleccion(m, { meses: m, filtros: { birads: 'BIRADS_5', grupo_edad: '50-59' } }));
const r = solicitud();
expect(parametros(r)).toEqual({ ...PARAMS, meses: String(m), grupo_edad: '50-59' });
r.flush(cohorte({ birads: 'BIRADS_5', grupo_edad: '50-59' }, 1, 50, { ventana: { meses: m, desde: '2026-01-01', hasta: CORTE } })); await asentar();
expect(root().querySelector('.diferencia')).toBeNull();
expect(fixture.componentInstance.draft.meses).toBe(m);
expect([...exportar()!.querySelectorAll('button')].some(b => !b.disabled)).toBe(true);
});
it('sin una selección la ventana no ofrece «Toda la cohorte» y la consulta no cita ninguna cohorte', async () => {
// Fails if the whole cohort becomes a plain window of the list, or a plain query quotes a revision.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
@@ -18,9 +18,10 @@ type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: str
/** A request with the name of the selection it belongs to, so the answer and its name can never be told apart. */
type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string };
// What the analysis sends: the whole published group, the cut-off it was computed at, the cohort (and its revision) the
// list must quote back, how to name it, how many patients the analysis counts there and an id that changes with each click.
// list must quote back, the window of months it was computed over (0: the whole cohort), how to name it, how many patients the
// analysis counts there and an id that changes with each click.
export interface SeleccionSeguimiento {
filtros: Record<string, string>; etiqueta: string; corte?: string; esperados?: number | null; contexto?: ContextoLista; id: number;
filtros: Record<string, string>; etiqueta: string; corte?: string; meses?: number; esperados?: number | null; contexto?: ContextoLista; id: number;
}
const ETIQUETA_COHORTE = 'Cohorte del análisis epidemiológico';
/** The answer does not apply the cut-off, window or filters that were asked for: it is neither shown nor exported. */
@@ -260,7 +261,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
// Whatever was on screen belongs to another query: it goes before the selection is asked for.
this.data.set(undefined); this.etiquetaDatos.set(undefined);
if (this.ficha()) { this.ficha.set(undefined); this.controlFicha = undefined; this.fichaAbierta.emit(false); }
this.draft = { ...this.draft, meses: 0, corte: sel.corte ?? this.draft.corte, filtros: { ...sel.filtros } };
this.draft = { ...this.draft, meses: (sel.meses ?? 0) as MesesVentana, corte: sel.corte ?? this.draft.corte, filtros: { ...sel.filtros } };
this.aplicar(sel.etiqueta);
return;
}
@@ -303,7 +304,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
aplicar(seleccion?: string) {
const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record<string, string>;
const activa = this.activa, contexto = this.contextoActivo;
const exacta = !!seleccion || (!!activa && this.draft.meses === 0 && mismosFiltros(filtros, activa.filtros) && (!activa.corte || this.draft.corte === activa.corte));
const exacta = !!seleccion || (!!activa && this.draft.meses === (activa.meses ?? 0) && mismosFiltros(filtros, activa.filtros) && (!activa.corte || this.draft.corte === activa.corte));
// In the cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months.
// The banner names the analysis' selection, or the cohort of the analysis once the user has refined it.
const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto && activa ? ETIQUETA_COHORTE : undefined);
@@ -1,6 +1,6 @@
import { DimensionEstrato, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { DonutSelection } from './indicadores-donut-drilldown';
import { c2Color, c2Theme } from './indicadores-c2-palette';
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;');
@@ -43,6 +43,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
const cells: StratifiedCell[] = [];
const theme = c2Theme(tema);
const palette = seriesColors(categories.map(([, c]) => c.color));
const figure: PlotlyFigure = { data: strata.map((s, series) => {
const selected = categories.map(([id, c]) => {
const row = rows.get(JSON.stringify([id, s]));
@@ -52,7 +53,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
return value;
});
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
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,
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
@@ -61,15 +61,23 @@
@if (teaData; as response) {
<section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo">
<h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3>
<dl>
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
}
</dl>
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
@if (response.resumen_eeg.validadas) {
<dl>
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
}
</dl>
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
} @else {
<dl>
<div><dt>Con EEG válido</dt><dd>{{ response.resumen_eeg.con_eeg_valido }}</dd></div>
<div><dt>Sin EEG válido</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
</dl>
<p>Las alteraciones del EEG se muestran cuando se validen sus curvas de referencia.</p>
}
</section>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table>
@@ -12,7 +12,7 @@ import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'
import { Dominio } from './indicadores.models';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { IndicadoresService } from './indicadores.service';
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { ALTERACIONES_EEG, EEG_VALIDO, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { TeaPacienteResumen } from './tea-paciente-resumen';
@Component({
@@ -98,6 +98,8 @@ export class IndicadoresTracking implements OnChanges {
if (result.data) {
const data = result.data;
this.tiposAlteracion = data.tipos_alteracion;
// Until the alterations are validated, the EEG filter can only tell a valid EEG from none.
this.statuses = data.resumen_eeg.validadas ? ALTERACIONES_EEG : EEG_VALIDO;
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
this.draft = { ...this.applied };
}
@@ -11,7 +11,7 @@
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
<div class="headline">
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacion[a.clasificacion] }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacionDe(a) }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
</div>
@for (dom of a.dominios; track dom.codigo) {
<div class="dominio">
@@ -37,39 +37,45 @@
</section>
<section class="panel calidad" aria-label="Calidad del EEG">
<h3>Calidad del EEG @if (d.eeg) { <span class="mock">Datos de ejemplo</span> }</h3>
<h3>Calidad del EEG</h3>
@if (d.eeg; as e) {
<p class="meta">{{ e.fecha }} · {{ e.duracion_min }} min · {{ e.canales }} canales</p>
<p class="meta">{{ e.fecha }}@if (e.duracion_min !== null) { · {{ e.duracion_min }} min }@if (e.canales !== null) { · {{ e.canales }} canales }</p>
<div class="headline">
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
<small>La calificación general es la peor de sus criterios.</small>
<small>{{ e.calidad === 'sin_analizar' ? 'El análisis del EEG aún no lo revisa.' : 'Veredicto del análisis del EEG, según las reglas siguientes.' }}</small>
</div>
<dl>
@for (c of e.criterios_calidad; track c.codigo) {
<dt>{{ c.etiqueta }}</dt><dd [attr.data-calidad]="c.nivel">{{ c.valor }} {{ c.unidad === 'canales' ? 'de ' + e.canales : c.unidad }}</dd>
@for (c of delEstudio(e); track c.codigo) {
<dt>{{ c.etiqueta }}@if (c.decisivo) {<small> (decisiva)</small>}</dt><dd [attr.data-calidad]="c.nivel">{{ valorDe(c) }}</dd>
}
</dl>
@if (canalesMalos(e).length) {
<p class="efectos-titulo">Canales descartados</p>
<ul class="canales-malos">
@for (c of canalesMalos(e); track $index) { <li><strong>{{ c.electrodo }}</strong> · {{ c.etiqueta }}</li> }
</ul>
}
} @else { <p>Sin EEG registrado.</p> }
</section>
@if (d.eeg; as e) {
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
<div class="alteraciones-zona" [class.abierta]="abierto(e)">
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
<p class="meta">Referencia neurotípica para {{ d.grupo_edad }} y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p>
<p class="meta">Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.</p>
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
<ul class="metricas">
@for (m of e.alteraciones; track m.codigo) {
<li [attr.data-estado]="m.estado">
<div class="metrica">
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === m.codigo"
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : abierto(e) && mapaElegido === m.codigo"
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
<span class="estado">{{ estado[m.estado] }}</span>
</div>
@if (m.valor !== null) {
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p>
@if (m.referencia; as r) {
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ r.min }}–{{ r.max }}@if (r.mediana !== null) { (mediana {{ r.mediana }}) } · z = {{ m.valor_z }}</p>
} @else {
<p class="valor">Sin registro de sueño en el estudio.</p>
<p class="valor">@if (m.valor !== null) { {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</p>
}
@if (m.efectos.length) {
<p class="efectos-titulo">Posibles efectos asociados</p>
@@ -82,8 +88,24 @@
</ul>
</section>
@if (mapaActual(e); as mapa) {
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas">
@if (abierto(e)) {
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
@if (mapaActual(e) && normaActual(e)) {
<div class="vistas" role="group" aria-label="Qué mostrar">
<button type="button" [attr.aria-pressed]="vista === 'zonas'" (click)="verVista('zonas')">Zonas de la cabeza</button>
<button type="button" [attr.aria-pressed]="vista === 'norma'" (click)="verVista('norma')">Norma por edad</button>
</div>
}
@if (vista === 'norma' && normaActual(e); as m) {
<h3>Norma por edad</h3>
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}</p>
@if (figuraNorma) {
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
}
<p class="leyenda-norma">La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura).
El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).</p>
} @else if (mapaActual(e); as mapa) {
<h3>Zonas más afectadas</h3>
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
@@ -96,9 +118,54 @@
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
}
</ol>
}
</section></div>
}
</div>
}
@if (d.relacion_ados2; as rel) {
<section class="panel relacion" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
<p class="meta">Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se
asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2.
No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}</p>
@if (!filasRelacion(rel).length) {
<p class="sin-alteraciones">Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara con el ADOS-2 en la cohorte.</p>
} @else {
<div class="tabla-relacion" role="region" aria-label="Asociaciones por zona" tabindex="0">
<table>
<thead>
<tr>
<th scope="col">Zona del EEG</th><th scope="col">Aspecto del ADOS-2</th><th scope="col">Asociación en la cohorte</th>
<th scope="col">Probabilidad para este paciente</th><th scope="col">Lo que muestra su ADOS-2</th>
</tr>
</thead>
<tbody>
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
<tr [class.alterada]="zonaAlterada(f)">
<td><strong>{{ biomarcador[f.biomarcador] ?? f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
<td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
<td>
<span class="prob">{{ porcentaje(f.probabilidad) }} %</span>
<span class="barra" aria-hidden="true">
<span class="paciente" [style.width.%]="porcentaje(f.probabilidad)"></span>
<span class="referencia" [style.left.%]="porcentaje(f.probabilidad_referencia)"></span>
</span>
<small>{{ f.evento }} · con z = 0: {{ porcentaje(f.probabilidad_referencia) }} %</small>
</td>
<td>{{ observado(f) }}@if (coincide(f) !== null) { <small>{{ coincide(f) ? 'Coincide con lo que el modelo esperaba' : 'No coincide con lo que el modelo esperaba' }}</small> }</td>
</tr>
}
</tbody>
</table>
</div>
<p class="nota">OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La
probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0.
Solo se muestran las zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q &lt; 0.05). Versión del modelo: {{ rel.version }}.</p>
}
</section>
}
</div>
}
@@ -9,7 +9,7 @@ h3 { margin: 0 0 .15rem; font-size: 1rem; }
border: 2px solid var(--issste-border); border-radius: var(--issste-radius); font-size: 1.1rem; font-weight: 700; }
.css small { margin: 0; font-size: .7rem; font-weight: 400; }
.css[data-nivel=alto], .css[data-calidad=malo] { border-color: #B3261E; color: #B3261E; }
.css[data-nivel=moderado], .css[data-calidad=aceptable] { border-color: #B26A00; color: #B26A00; }
.css[data-nivel=moderado], .css[data-calidad=sin_analizar] { border-color: #B26A00; color: #B26A00; }
.css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=bueno] { border-color: var(--issste-accent); }
.css[data-calidad] { flex: none; white-space: nowrap; }
dd[data-calidad=malo] { color: #B3261E; }
@@ -23,7 +23,6 @@ button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outl
.leyenda-mapa span { width: .8rem; height: .8rem; border-radius: 2px; }
.leyenda-mapa .azul { background: #2166AC; }
.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; }
dd[data-calidad=aceptable] { color: #B26A00; }
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; }
.bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; }
.bar span { display: block; height: 100%; background: var(--issste-text); }
@@ -72,3 +71,26 @@ li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font
.efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; }
.efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .8rem; }
button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; }
.canales-malos { margin: .25rem 0 0; padding-inline-start: 1.1rem; font-size: .85rem; }
// Relation with the ADOS-2 (association model): full width, a scrollable table on narrow screens.
.relacion { grid-column: 1 / -1; }
.tabla-relacion { overflow-x: auto; }
.tabla-relacion table { width: 100%; min-width: 44rem; border-collapse: collapse; font-size: .85rem; }
.tabla-relacion th, .tabla-relacion td { padding: .45rem .5rem; border-top: 1px solid var(--issste-border); text-align: start; vertical-align: top; }
.tabla-relacion thead th { font-size: .8rem; color: var(--issste-text-secondary); font-weight: 600; }
.tabla-relacion small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); font-size: .75rem; }
.tabla-relacion tr.alterada td:first-child { box-shadow: inset 4px 0 0 #B3261E; }
.tabla-relacion .marca { color: #B3261E; font-weight: 600; }
.or, .prob { font-weight: 700; font-variant-numeric: tabular-nums; }
.barra { position: relative; display: block; height: .45rem; margin-top: .25rem; border-radius: 999px; background: var(--issste-border); }
.barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); }
.barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); }
.nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); }
// The switch between the head map and the age norm, when the metric has both.
.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; }
.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; }
.vistas button + button { border-inline-start: 1px solid var(--issste-border); }
.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; }
.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); }
@@ -2,12 +2,20 @@ import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PlotlyFigure } from './indicadores.models';
import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaEegMapa, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service';
import {
CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle,
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
} from './tea-seguimiento.service';
const BIOMARCADOR: Record<string, string> = {
picos: 'Picos paroxísticos', husos: 'Husos de sueño', ritmo_posterior: 'Ritmo posterior', gradiente: 'Gradiente anteroposterior',
};
// A zone counts as altered from |z| ≥ 2, as the alteration cards do.
const Z_ALTERADO = 2;
const CLASIFICACION: Record<TeaAdos2['clasificacion'], string> = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' };
// ADOS-2 calibrated severity score ranges.
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Bueno', aceptable: 'Aceptable', malo: 'Malo' };
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Válido', malo: 'No válido', sin_analizar: 'Sin analizar' };
const ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' };
const INK = '#081839';
@@ -43,6 +51,36 @@ export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): Pl
};
}
// The age norm around the patient: the 5–95 and 25–75 percentile bands, the median line and the patient as a point.
const BANDA_EXTERIOR = 'rgba(49,130,189,.16)', BANDA_INTERIOR = 'rgba(49,130,189,.32)', MEDIANA = '#2C6FA6', ALTERADO = '#B3261E';
export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure {
const c = m.curva_referencia!, x = c.edad_meses, atras = [...x].reverse();
const banda = (bajo: number[], alto: number[], color: string, nombre: string) => ({
type: 'scatter', mode: 'lines', x: [...x, ...atras], y: [...alto, ...[...bajo].reverse()], fill: 'toself', fillcolor: color,
line: { width: 0 }, name: nombre, hoverinfo: 'skip',
});
const unidad = m.unidad ? ` ${m.unidad}` : '';
const alterado = m.estado === 'aumentado' || m.estado === 'disminuido';
return {
data: [
banda(c.p5, c.p95, BANDA_EXTERIOR, 'Del 5 al 95 %'),
banda(c.p25, c.p75, BANDA_INTERIOR, 'Del 25 al 75 %'),
{ type: 'scatter', mode: 'lines', x, y: c.mediana, name: 'Mediana', line: { color: MEDIANA, width: 2 },
hovertemplate: `%{x} meses: mediana %{y:.2f}${unidad}<extra></extra>` },
{ type: 'scatter', mode: 'markers', x: [edad], y: [m.valor], name: 'Este paciente',
marker: { size: 11, color: alterado ? ALTERADO : INK, line: { color: '#FFFFFF', width: 2 } },
hovertemplate: `Este paciente: %{y:.2f}${unidad} a los %{x:.1f} meses (z = ${m.valor_z})<extra></extra>` },
],
layout: {
margin: { l: 52, r: 12, t: 8, b: 44 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
showlegend: true, legend: { orientation: 'h', y: -0.28, font: { size: 11 } }, font: { color: INK },
xaxis: { title: { text: 'Edad (meses)' }, range: [x[0], x[x.length - 1]], dtick: 6, gridcolor: 'rgba(8,24,57,.08)', fixedrange: true },
yaxis: { title: { text: m.unidad || m.etiqueta }, gridcolor: 'rgba(8,24,57,.08)', zeroline: false, fixedrange: true },
},
config: { displayModeBar: false },
};
}
@Component({
selector: 'app-tea-paciente-resumen',
imports: [PlotlyChart],
@@ -56,7 +94,7 @@ export class TeaPacienteResumen implements OnInit {
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
figura?: PlotlyFigure;
private mapaElegido?: string;
mapaElegido?: string;
private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef);
// The first solid background around this component: the map has no box of its own.
private fondo() {
@@ -66,14 +104,30 @@ export class TeaPacienteResumen implements OnInit {
}
return '#FFFFFF';
}
// The side panel shows the chosen metric's head map, its age norm, or both with a switch between them.
vista: 'zonas' | 'norma' = 'zonas';
figuraNorma?: PlotlyFigure;
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
elegirMapa(eeg: TeaEeg, codigo: string) {
// The chosen card closes the map again, and the cards take the whole space back.
const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo);
this.mapaElegido = mapa?.codigo;
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
// The age norm can only be drawn with the curve, the patient's value and their age.
private conNorma(eeg: TeaEeg, codigo?: string) {
const m = eeg.alteraciones.find(a => a.codigo === codigo);
return m && m.curva_referencia && m.valor !== null && typeof eeg.edad_meses === 'number' ? m : undefined;
}
readonly clasificacion = CLASIFICACION;
normaActual(eeg: TeaEeg) { return this.conNorma(eeg, this.mapaElegido); }
abierto(eeg: TeaEeg) { return !!this.mapaActual(eeg) || !!this.normaActual(eeg); }
private mostrar(eeg: TeaEeg, codigo: string | undefined) {
const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo);
this.mapaElegido = mapa || norma ? codigo : undefined;
this.vista = mapa ? 'zonas' : 'norma';
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number);
}
elegirMapa(eeg: TeaEeg, codigo: string) {
// The chosen card closes the panel again, and the cards take the whole space back.
this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo);
}
verVista(vista: 'zonas' | 'norma') { this.vista = vista; }
readonly clasificacion = CLASIFICACIONES_ADOS2;
readonly nivelCss = NIVEL_CSS;
readonly calidad = CALIDAD;
readonly estado = ESTADO;
@@ -82,15 +136,49 @@ export class TeaPacienteResumen implements OnInit {
this.status.set('loading');
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: d => {
// Opens on the first altered metric, or on the first one if none is altered.
const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0];
this.mapaElegido = inicial?.codigo;
this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined;
// Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered.
const e = d.eeg;
if (e) {
const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo));
this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo);
} else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; }
this.detalle.set(d); this.status.set('ready');
},
error: () => this.status.set('error'),
});
}
// The study-wide checks, then each bad channel.
delEstudio(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo === null); }
canalesMalos(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo !== null); }
valorDe(c: TeaCriterioCalidad) {
return c.valor === null ? '' : typeof c.valor === 'number' ? `${Math.round(c.valor * 100) / 100}${c.unidad ? ' ' + c.unidad : ''}` : c.valor;
}
// Why a metric couldn't be evaluated, in the reader's terms.
sinEvaluar(m: TeaEegAlteracion) {
return m.sin_evaluar === 'sin_valor' ? 'No se pudo medir en el estudio.' : 'Sin referencia para la edad del niño.';
}
clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; }
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); }
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
// Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first.
readonly biomarcador = BIOMARCADOR;
zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; }
filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); }
direccion(f: TeaRelacionAdos2) {
return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad';
}
porcentaje(p: number) { return Math.round(100 * p); }
qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; }
observado(f: TeaRelacionAdos2) {
if (f.observado === null) return 'Sin dato';
if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)';
return `CSS ${f.observado}`;
}
// Whether what the patient shows matches what the model leans to (above or below one half).
coincide(f: TeaRelacionAdos2) {
if (f.observado === null) return null;
const presente = f.tipo === 'item' ? f.observado >= 1 : f.observado >= 8;
return presente === (f.probabilidad >= .5);
}
}
@@ -6,8 +6,9 @@ import { estratoValor } from './indicadores-fhir';
import { SeguimientoQuery } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service';
import {
RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad,
teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg,
TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse,
TeaSeguimientoService,
} from './tea-seguimiento.service';
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
@@ -19,7 +20,7 @@ interface Observation extends Resource {
valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept;
interpretation?: Concept[]; dataAbsentReason?: Concept;
referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[];
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueBoolean?: boolean; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
}
interface Report extends Resource {
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
@@ -28,6 +29,9 @@ interface Metric { code?: string; display?: string; property?: { code: string; v
const MAX_COUNT = 200;
const METRICAS = 'tea-eeg-metrica';
// The EEG analysis's quality checks, under the code system of its own validation report.
const CRITERIOS = 'urn:tea:validation';
const FILTRO_EEG: Record<string, string> = { sin_eeg_valido: 'sin-eeg-valido' };
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { H: 'aumentado', L: 'disminuido', N: 'normal' };
// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average.
@@ -77,10 +81,16 @@ export function mapaDeElectrodos(codigo: string, etiqueta: string, valores: Reco
return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones };
}
// The module as the page writes it: `MODULO_1` is 1, the toddler module is T.
function moduloAdos2(codigo: string | undefined): string | undefined {
const modulo = codigo?.replace(/^ados2\.modulo\./, '');
return modulo === 'TODDLER' ? 'T' : modulo?.replace(/^MODULO_/, '');
}
export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null {
const css = component(o, 'ados2.css')?.valueInteger;
if (!o?.effectiveDateTime || typeof css !== 'number') return null;
const modulo = code(component(o, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '') ?? '';
const modulo = moduloAdos2(code(component(o, 'ados2.modulo')?.valueCodeableConcept)) ?? '';
const clasificacion = code(component(o, 'ados2.clasificacion')?.valueCodeableConcept)?.replace('ados2.clasificacion.', '').toLowerCase();
const items = (o.component ?? []).filter(c => extension(c, 'dominio'));
const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => {
@@ -96,34 +106,52 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
return {
fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '',
dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0),
clasificacion: (clasificacion ?? 'no_espectro') as TeaAdos2['clasificacion'], css,
clasificacion: clasificacion && Object.hasOwn(CLASIFICACIONES_ADOS2, clasificacion) ? clasificacion as TeaAdos2['clasificacion'] : null, css,
nivel_css: (RANGOS_CSS.find(r => css >= r.min && css <= r.max)?.codigo ?? 'minimo') as TeaAdos2['nivel_css'],
};
}
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
// cover the child's age (or none is in production yet).
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
const codigo = code(o.code) ?? '';
const metrica = metricas.find(m => m.code === codigo);
const evaluable = !o.dataAbsentReason && typeof o.valueQuantity?.value === 'number';
const valor = o.valueQuantity?.value ?? null;
const z = component(o, 'z')?.valueQuantity?.value;
const evaluable = valor !== null && typeof z === 'number';
const estado = evaluable ? INTERPRETACION[code(o.interpretation?.[0]) ?? ''] ?? 'normal' : 'no_evaluable';
const range = o.referenceRange?.[0];
const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value;
const referencia = typeof low === 'number' && typeof high === 'number'
? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null;
return {
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
referencia: { min: range?.low?.value ?? 0, max: range?.high?.value ?? 0 },
valor: evaluable ? o.valueQuantity!.value! : null,
valor_z: evaluable ? component(o, 'z')?.valueQuantity?.value ?? null : null,
estado,
referencia: evaluable ? referencia : null,
valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
};
}
// One quality check as the EEG analysis reports it: its value or reason, A/N, the bad channel's electrode, whether it
// alone invalidates the EEG.
function criterio(o: Observation): TeaCriterioCalidad {
const parte = (nombre: string) => o.component?.find(c => c.code?.text === nombre);
return {
codigo: codeIn(o.code, CRITERIOS)!, etiqueta: display(o.code) ?? codeIn(o.code, CRITERIOS)!,
valor: o.valueQuantity?.value ?? o.valueString ?? null, unidad: o.valueQuantity?.unit ?? '',
nivel: code(o.interpretation?.[0]) === 'A' ? 'malo' : 'bueno',
electrodo: parte('electrode')?.valueString ?? null, decisivo: parte('decisive')?.valueBoolean === true,
};
}
// The study EEG of `report`, with the observations it lists and the electrode maps of its metrics.
export function eegDeReporte(report: Report | undefined, observations: Observation[], metricas: Metric[]): TeaEeg | null {
if (!report?.effectiveDateTime) return null;
const ids = new Set((report.result ?? []).map(r => referenceId(r)));
const listed = observations.filter(o => ids.has(o.id));
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'MALO').toLowerCase() as TeaNivelCalidad;
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
const duracion = extension(report, 'duracion-min')?.valueDecimal;
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS)).map(o => alteracion(o, metricas));
// A metric's electrode values are `electrodos-<the metric observation's id>`.
const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length)))
@@ -135,14 +163,10 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
.filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable'));
return {
fecha: report.effectiveDateTime.slice(0, 10),
duracion_min: Math.round(extension(report, 'duracion-min')?.valueDecimal ?? 0),
canales: extension(report, 'canales')?.valueInteger ?? 0,
duracion_min: duracion === undefined ? null : Math.round(duracion),
canales: extension(report, 'canales')?.valueInteger ?? null,
calidad: calidad(report.conclusionCode?.[0]),
criterios_calidad: listed.filter(o => code(o.code)?.startsWith('eeg.calidad_')).map(o => ({
codigo: code(o.code)!.replace('eeg.calidad_', ''), etiqueta: display(o.code) ?? '',
valor: o.valueInteger ?? o.valueQuantity?.value ?? 0, unidad: typeof o.valueInteger === 'number' ? 'canales' : o.valueQuantity?.unit ?? '',
nivel: calidad(o.interpretation?.[0]),
})),
criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
alteraciones, mapas,
ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) },
};
@@ -166,7 +190,7 @@ export function pacienteDeEpisodio(episode: Resource, included: Resource[], vali
const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined;
const ados2 = byCode(observations, 'ados2');
const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined;
const modulo = code(component(ados2, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '');
const modulo = moduloAdos2(code(component(ados2, 'ados2.modulo')?.valueCodeableConcept));
return {
id_seudonimo: id,
grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code),
@@ -221,7 +245,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
const corte = query.corte ?? isoDay(this.today());
const { desde, hasta } = ventana(corte, query.meses);
let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta);
if (query.estatus) params = params.set('resultado-eeg', query.estatus);
if (query.estatus) params = params.set('resultado-eeg', FILTRO_EEG[query.estatus] ?? query.estatus);
if (query.grupo_edad) params = params.set('grupo-edad', grupoCodigo(query.grupo_edad));
const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css);
if (mchat) params = params.append('mchat', 'ge' + mchat.min).append('mchat', 'le' + mchat.max);
@@ -248,6 +272,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)),
tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [],
resumen_eeg: {
validadas, con_eeg_valido: validadas ? parameter(resumen, 'normales') + parameter(resumen, 'anormales') : parameter(resumen, 'con_eeg_valido'),
normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'),
por_alteracion: porAlteracion(resumen, metricas),
},
@@ -261,12 +286,11 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
}).pipe(map(({ bundle, metricas }) => {
const all = resources(bundle);
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
const metric = observations.find(o => codeIn(o.code, METRICAS) && o.referenceRange?.[0]?.text);
const edad = metric?.referenceRange?.[0]?.text?.split(': ').pop();
const episode = resources(bundle, 'EpisodeOfCare')[0];
return teaPacienteDetalle({
simulado: all.length > 0 && all.every(isSimulated),
id_seudonimo: id,
grupo_edad: grupoEdad(edad),
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
}, id);
@@ -4,7 +4,8 @@ import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service';
export type AlteracionesEeg = 'normal' | 'anormal';
// The EEG filter: by alteration once the domain expert has validated them, otherwise only by a valid EEG or none.
export type AlteracionesEeg = 'normal' | 'anormal' | 'valido' | 'sin_eeg_valido';
export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo';
export interface TeaSeguimientoPaciente {
id_seudonimo: string;
@@ -12,7 +13,7 @@ export interface TeaSeguimientoPaciente {
ultimo_eeg: string | null;
mchat: number | null;
css_ados2: number | null;
alteraciones_eeg: AlteracionesEeg | null;
alteraciones_eeg: 'normal' | 'anormal' | null;
modulo_ados2: string | null;
estado_caso: EstadoCaso;
// What a case in process still lacks.
@@ -21,6 +22,9 @@ export interface TeaSeguimientoPaciente {
alteraciones: string[];
}
export interface TeaResumenEeg {
// Without validated alterations only the split by a valid EEG is known: `normales`, `anormales` and `por_alteracion`
// stay empty.
validadas: boolean; con_eeg_valido: number;
normales: number; anormales: number; sin_eeg: number;
por_alteracion: { codigo: string; etiqueta: string; n: number }[];
}
@@ -35,28 +39,60 @@ export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: nu
export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] }
export interface TeaAdos2 {
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
clasificacion: ClasificacionAdos2 | null; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
}
export type ClasificacionAdos2 = 'autismo' | 'espectro_autista' | 'no_espectro' | 'preocupacion_leve_moderada' | 'preocupacion_severa';
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
// Mock: EEG metrics with placeholder reference ranges and associated effects, pending medical review.
export type TeaNivelCalidad = 'bueno' | 'aceptable' | 'malo';
// EEG metrics against age baselines and their associated effects, both pending medical validation.
export type TeaNivelCalidad = 'bueno' | 'malo' | 'sin_analizar';
// One quality check of the EEG analysis: a study-wide rule, or a bad channel with its electrode and reason.
export interface TeaCriterioCalidad {
codigo: string; etiqueta: string; valor: number | string | null; unidad: string; nivel: 'bueno' | 'malo';
electrodo: string | null; decisivo: boolean;
}
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
export interface TeaEegAlteracion {
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number };
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number; mediana: number | null } | null;
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
// Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age.
sin_evaluar: 'sin_valor' | 'sin_referencia' | null;
// The age norm the reference comes from (percentiles by month), when the analysis sends it.
curva_referencia?: TeaCurvaReferencia | null;
}
export interface TeaCurvaReferencia {
fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[];
}
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
export interface TeaEeg {
fecha: string; duracion_min: number; canales: number;
// The overall rating is in words, like Automagic, and is the worst of its criteria, which report numbers.
calidad: TeaNivelCalidad; criterios_calidad: { codigo: string; etiqueta: string; valor: number; unidad: string; nivel: TeaNivelCalidad }[];
fecha: string; duracion_min: number | null; canales: number | null;
// Age at the EEG, to place the patient on the age norms.
edad_meses?: number | null;
// The overall rating is the EEG analysis's verdict; its checks say why.
calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[];
alteraciones: TeaEegAlteracion[];
// One map per alteration that could be evaluated, on shared axes.
mapas: TeaEegMapa[];
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
}
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null }
// The association model (OR) of each EEG alteration by zone with an ADOS-2 item or domain, fitted on the cohort; for
// this patient, their z, the probability the model gives them and what their ADOS-2 shows. Pending medical validation.
export interface TeaRelacionAdos2 {
biomarcador: string; zona: string; zona_etiqueta: string; valor_z: number;
tipo: 'item' | 'dominio'; resultado: string; resultado_etiqueta: string; evento: string;
or: number; ic_inf: number; ic_sup: number; q: number;
probabilidad: number; probabilidad_referencia: number; observado: number | null;
}
export interface TeaRelacionModelo { validado: boolean; nivel: 'item' | 'dominio'; n_cohorte: number; version: string; filas: TeaRelacionAdos2[] }
export interface TeaPacienteDetalle {
simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null;
// Absent until the WebApi serves the model.
relacion_ados2?: TeaRelacionModelo | null;
}
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
export const CLASIFICACIONES_ADOS2: Record<ClasificacionAdos2, string> = {
autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro',
preocupacion_leve_moderada: 'Preocupación leve a moderada', preocupacion_severa: 'Preocupación de moderada a severa',
};
export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' };
export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses'];
// M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary.
@@ -71,15 +107,22 @@ export const RANGOS_CSS = [
{ codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 },
{ codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 },
];
export const ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }];
export const ALTERACIONES_EEG: SeguimientoStatus[] = [
{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' },
];
export const EEG_VALIDO: SeguimientoStatus[] = [{ codigo: 'valido', etiqueta: 'Con EEG válido' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' }];
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
const filtroEeg = (v: unknown) => v === null || ['normal', 'anormal', 'valido', 'sin_eeg_valido'].includes(v as string);
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
// ADOS-2 item codes: 0 to 3, and 7 to 9 for an item that doesn't apply or wasn't scored.
const CODIGOS_REACTIVO = [0, 1, 2, 3, 7, 8, 9];
const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string');
function validResumenEeg(r: unknown): boolean {
return record(r) && integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
return record(r) && typeof r['validadas'] === 'boolean' && integer(r['con_eeg_valido'])
&& integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
&& r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n']));
}
export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
@@ -88,7 +131,7 @@ export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !record(filters) || !eeg(filters['alteraciones_eeg'])
|| !record(filters) || !filtroEeg(filters['alteraciones_eeg'])
|| !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'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
@@ -106,33 +149,52 @@ const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
const text = (v: unknown) => typeof v === 'string' && v.length > 0;
function validAdos(a: unknown): boolean {
if (a === null) return true;
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || !text(a['algoritmo']) || !score(a['css'], 1, 10)
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string)
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || typeof a['algoritmo'] !== 'string' || !score(a['css'], 1, 10)
|| !(a['clasificacion'] === null || Object.hasOwn(CLASIFICACIONES_ADOS2, a['clasificacion'] as string))
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
// Items score 0–3 (algorithm 0–2); each domain and the total must be the sum of their parts.
// Items carry an ADOS-2 code (algorithm 0–2); each domain and the total must be the sum of their parts.
const dominios = a['dominios'] as unknown[];
const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos'])
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && score(r['puntaje'], 0, 3) && score(r['puntaje_algoritmo'], 0, 2))
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && CODIGOS_REACTIVO.includes(r['puntaje'] as number) && score(r['puntaje_algoritmo'], 0, 2))
&& d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0)
&& d['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
}
// A metric without a value cannot be evaluated; one with a value is out of range exactly when it is altered.
// An age norm: ages in increasing order and, at each one, percentiles that never cross.
const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const;
function validCurva(c: unknown): boolean {
if (c === undefined || c === null) return true;
if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false;
const edades = c['edad_meses'] as unknown[], n = edades.length;
if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false;
const series = PERCENTILES.map(k => c[k]);
return series.every(s => Array.isArray(s) && s.length === n && s.every(finite))
&& edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i]));
}
// A metric that can't be evaluated says why and has no z; one that can has its value, z and reference.
function validAlteracion(a: unknown): boolean {
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !record(a['referencia'])
|| !finite(a['referencia']['min']) || !finite(a['referencia']['max']) || (a['referencia']['min'] as number) > (a['referencia']['max'] as number)
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false;
const ref = a !== null && record(a) ? a['referencia'] : undefined;
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string'
|| !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number)
&& (ref['mediana'] === null || finite(ref['mediana'])))
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false;
const estado = a['estado'];
if (estado === 'no_evaluable') return a['valor'] === null && a['valor_z'] === null;
return finite(a['valor']) && finite(a['valor_z']) && ['normal', 'aumentado', 'disminuido'].includes(estado as string);
if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string)
&& (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null);
return finite(a['valor']) && finite(a['valor_z']) && ref !== null && a['sin_evaluar'] === null
&& ['normal', 'aumentado', 'disminuido'].includes(estado as string);
}
function validEeg(e: unknown): boolean {
if (e === null) return true;
const nivel = (v: unknown) => ['bueno', 'aceptable', 'malo'].includes(v as string);
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad'])
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad'])
&& (c['unidad'] === 'canales' ? integer(c['valor']) && (c['valor'] as number) <= (e['canales'] as number) : finite(c['valor']) && (c['valor'] as number) >= 0))) return false;
const optional = (v: unknown) => v === null || integer(v);
const edad = record(e) ? e['edad_meses'] : undefined;
if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales'])
|| !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0)
|| !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string)
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta'])
&& ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean'
&& (c['electrodo'] === null || text(c['electrodo'])) && (c['valor'] === null || finite(c['valor']) || text(c['valor'])))) return false;
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
const ejes = e['ejes_mapa'];
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
@@ -143,9 +205,21 @@ function validEeg(e: unknown): boolean {
&& m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
&& Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z'])));
}
const probability = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 1;
function validRelacion(r: unknown): boolean {
if (r === undefined || r === null) return true;
return record(r) && typeof r['validado'] === 'boolean' && ['item', 'dominio'].includes(r['nivel'] as string)
&& integer(r['n_cohorte'], 1) && text(r['version']) && Array.isArray(r['filas'])
&& r['filas'].every(f => record(f) && text(f['biomarcador']) && text(f['zona_etiqueta']) && finite(f['valor_z'])
&& ['item', 'dominio'].includes(f['tipo'] as string) && text(f['resultado_etiqueta']) && text(f['evento'])
&& finite(f['or']) && finite(f['ic_inf']) && finite(f['ic_sup']) && (f['ic_inf'] as number) <= (f['ic_sup'] as number)
&& probability(f['q']) && probability(f['probabilidad']) && probability(f['probabilidad_referencia'])
&& (f['observado'] === null || finite(f['observado'])));
}
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']))
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])
|| !validRelacion(v['relacion_ados2']))
throw new Error('Resumen del paciente inválido');
return v as unknown as TeaPacienteDetalle;
}
@@ -13,13 +13,14 @@ const data = {
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
items: [item, { ...item, id_seudonimo: 'T-0002', ultimo_eeg: null, mchat: null, css_ados2: null, alteraciones_eeg: null, modulo_ados2: null, estado_caso: 'fuera_protocolo', pendientes: [], alteraciones: [] }],
tipos_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior' }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos' }],
resumen_eeg: { normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] },
resumen_eeg: { validadas: true, con_eeg_valido: 4, normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] },
};
const reactivo = (codigo: string, puntaje: number) => ({ codigo, etiqueta: 'Reactivo ' + codigo, puntaje, puntaje_algoritmo: Math.min(puntaje, 2) });
const metrica = (codigo: string, etiqueta: string, extra: object) => ({ codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2 }, efectos: [], ...extra });
const metrica = (codigo: string, etiqueta: string, extra: object) => ({
codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2, mediana: 1.5 }, efectos: [], sin_evaluar: null, ...extra });
const alteraciones = [
metrica('ritmo_posterior', 'Ritmo posterior', { valor: 0.9, valor_z: -2.4, estado: 'disminuido', efectos: ['Ritmo más lento de lo esperado para la edad.'] }),
metrica('husos_sueno_n2', 'Husos de sueño N2', { valor: null, valor_z: null, estado: 'no_evaluable' }),
metrica('husos_sueno_n2', 'Husos de sueño N2', { valor: null, valor_z: null, estado: 'no_evaluable', referencia: null, sin_evaluar: 'sin_valor' }),
metrica('husos_sueno_n3', 'Husos de sueño N3', { valor: 1.4, valor_z: 0.2, estado: 'normal' }),
metrica('picos_paroxisticos', 'Picos paroxísticos', { valor: 1.5, valor_z: 0.3, estado: 'normal' }),
metrica('gradiente_anteroposterior', 'Gradiente anteroposterior', { valor: 1.2, valor_z: -0.4, estado: 'normal' }),
@@ -30,8 +31,12 @@ const detalle = {
ados2: { fecha: '2026-08-23', modulo: '1', algoritmo: 'Pocas o ninguna palabra', total: 5, total_maximo: 8, clasificacion: 'no_espectro', css: 3, nivel_css: 'bajo',
dominios: [{ codigo: 'AS', etiqueta: 'Afecto social', puntaje: 4, maximo: 4, reactivos: [reactivo('A2', 3), reactivo('B1', 2)] },
{ codigo: 'CRR', etiqueta: 'Comportamiento restringido y repetitivo', puntaje: 1, maximo: 4, reactivos: [reactivo('D1', 1), reactivo('D2', 0)] }] },
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'aceptable',
criterios_calidad: [{ codigo: 'amplitud', etiqueta: 'Canales con amplitud extrema', valor: 1, unidad: 'canales', nivel: 'bueno' }, { codigo: 'linea', etiqueta: 'Ruido de la línea eléctrica', valor: 8, unidad: 'dB', nivel: 'aceptable' }],
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'bueno',
criterios_calidad: [
{ codigo: 'clean-windows', etiqueta: 'Ventanas limpias', valor: 95, unidad: '%', nivel: 'bueno', electrodo: null, decisivo: true },
{ codigo: 'line-noise', etiqueta: 'Ruido de la línea eléctrica', valor: 48, unidad: 'dB', nivel: 'malo', electrodo: null, decisivo: false },
{ codigo: 'dead-channel', etiqueta: 'Canal muerto', valor: 'dead channel', unidad: '', nivel: 'malo', electrodo: 'T3', decisivo: false },
],
alteraciones,
mapas: [mapa('ritmo_posterior', 'Ritmo posterior (puntuación z)', 'Central'), mapa('picos_paroxisticos', 'Picos paroxísticos (puntuación z)', 'Occipital')],
ejes_mapa: { x: [-1, 0, 1], y: [-1, 0, 1], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } },
@@ -75,7 +80,7 @@ describe('Seguimiento TEA', () => {
expect(root.querySelector('input[type=date]')).not.toBeNull();
const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!;
expect(select.closest('label')?.textContent).toContain('Alteraciones EEG');
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal']);
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal', 'Sin EEG válido']);
fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 };
fixture.componentInstance.apply();
const filtered = request();
@@ -167,6 +172,41 @@ describe('Seguimiento TEA', () => {
expect(root.querySelector('section.mapa')).not.toBeNull();
http.verify();
});
it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => {
const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48],
p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] };
const conCurva = detalle.eeg.alteraciones.map(m =>
m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m);
const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } };
const fixture = open();
request().flush(data); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges();
const panel = () => root.querySelector('section.mapa')!;
const vistas = () => panel().querySelectorAll<HTMLButtonElement>('.vistas button');
// Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age.
expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']);
expect(panel().textContent).toContain('Zonas más afectadas');
vistas()[1].click(); fixture.detectChanges();
expect(vistas()[1].getAttribute('aria-pressed')).toBe('true');
expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad');
expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)');
expect(panel().querySelector('.regiones')).toBeNull();
// Gradiente has no map: its card opens the norm alone, without the switch.
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
tarjetas[4].click(); fixture.detectChanges();
expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true');
expect(vistas().length).toBe(0);
expect(panel().textContent).toContain('Gradiente anteroposterior');
const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance;
const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[];
expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']);
expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]);
const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m);
expect(() => teaPacienteDetalle({ ...conNorma, eeg: { ...conNorma.eeg, alteraciones: cruzada } }, 'T-0001')).toThrow();
http.verify();
});
it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => {
const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo);
const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor;
@@ -218,7 +258,7 @@ describe('Seguimiento TEA', () => {
const panel = root.querySelector('#tea-detalle-T-0002')!;
expect(panel.textContent).toContain('CSS 3');
expect(panel.textContent).toContain('Afecto social (AS)');
expect(panel.textContent).toContain('Aceptable');
expect(panel.textContent).toContain('Válido');
// Opens with the map of the first altered metric.
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
// Item scores start collapsed.
@@ -228,7 +268,7 @@ describe('Seguimiento TEA', () => {
expect(metricas.textContent).toContain('Disminuido');
expect(metricas.textContent).toContain('Posibles efectos asociados');
expect(metricas.textContent).toContain('Ritmo más lento de lo esperado para la edad.');
expect(metricas.textContent).toContain('Sin registro de sueño en el estudio.');
expect(metricas.textContent).toContain('No se pudo medir en el estudio.');
expect(Array.from(metricas.querySelectorAll('.nombre')).map(n => n.textContent)).toEqual(
['Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', 'Gradiente anteroposterior']);
expect(metricas.textContent).not.toContain('Sin alteraciones en las métricas evaluadas.');
@@ -269,6 +309,29 @@ describe('Seguimiento TEA', () => {
expect(root.querySelector('#tea-detalle-T-0002')?.textContent).toContain('No se pudo cargar el resumen del paciente.');
http.verify();
});
it('admite las clasificaciones del módulo T, una sin clasificar y los códigos de reactivo que no aplican', () => {
const ados2 = detalle.ados2;
for (const clasificacion of ['preocupacion_leve_moderada', 'preocupacion_severa', null]) {
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...ados2, clasificacion } }, 'T-0001')).not.toThrow();
}
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...ados2, clasificacion: 'dudoso' } }, 'T-0001')).toThrow();
const [as, crr] = ados2.dominios;
const noAplica = { ...ados2, dominios: [{ ...as, reactivos: [{ ...as.reactivos[0], puntaje: 8, puntaje_algoritmo: 2 }, as.reactivos[1]] }, crr] };
expect(() => teaPacienteDetalle({ ...detalle, ados2: noAplica }, 'T-0001')).not.toThrow();
});
it('sin alteraciones validadas resume y filtra solo por EEG válido', () => {
const fixture = open();
const sinValidar = { ...data, resumen_eeg: { validadas: false, con_eeg_valido: 2, normales: 0, anormales: 0, sin_eeg: 1, por_alteracion: [] } };
request().flush(sinValidar); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const resumen = root.querySelector('.resumen-eeg')!;
expect(Array.from(resumen.querySelectorAll('dt')).map(d => d.textContent)).toEqual(['Con EEG válido', 'Sin EEG válido']);
expect(Array.from(resumen.querySelectorAll('dd')).map(d => d.textContent)).toEqual(['2', '1']);
const opciones = Array.from(root.querySelectorAll<HTMLOptionElement>('select[name="estatus"] option')).map(o => o.textContent!.trim());
expect(opciones).toContain('Con EEG válido');
expect(opciones).not.toContain('Anormal');
http.verify();
});
it('valida que los puntajes ADOS-2 sumen y que el mapa sea rectangular', () => {
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle({ ...detalle, simulado: false }, 'T-0001')).toThrow();
@@ -279,25 +342,27 @@ describe('Seguimiento TEA', () => {
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapas: [{ ...detalle.eeg.mapas[0], z: [[0, 0]] }] } }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow();
});
it('la calidad general es una palabra, sus criterios son números y se validan', () => {
it('la calidad es el veredicto del análisis, con sus reglas y los canales descartados, y se valida', () => {
const fixture = open();
request().flush(tres); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
const panel = root.querySelector('section.calidad')!;
expect(panel.querySelector('.css')!.textContent!.trim()).toBe('Aceptable');
expect(Array.from(panel.querySelectorAll('dt, dd')).map(n => n.textContent)).toEqual(['Canales con amplitud extrema', '1 de 19', 'Ruido de la línea eléctrica', '8 dB']);
expect(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('aceptable');
expect(panel.textContent).not.toMatch(/Impedancia|Artefactos|de 100/);
const texto = (n: Element) => n.textContent!.replace(/\s+/g, ' ').trim();
expect(texto(panel.querySelector('.css')!)).toBe('Válido');
expect(Array.from(panel.querySelectorAll('dt, dd')).map(texto)).toEqual(['Ventanas limpias (decisiva)', '95 %', 'Ruido de la línea eléctrica', '48 dB']);
expect(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('malo');
expect(Array.from(panel.querySelectorAll('.canales-malos li')).map(texto)).toEqual(['T3 · Canal muerto']);
const conCriterios = (criterios_calidad: unknown) => ({ ...detalle, eeg: { ...detalle.eeg, criterios_calidad } });
expect(() => teaPacienteDetalle(conCriterios(undefined), 'T-0001')).toThrow();
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: 'canales', nivel: 'bueno' };
expect(() => teaPacienteDetalle(conCriterios([criterio]), 'T-0001')).not.toThrow();
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: '', nivel: 'bueno', electrodo: null, decisivo: false };
expect(() => teaPacienteDetalle(conCriterios([criterio, { ...criterio, valor: 'completo' }, { ...criterio, valor: null }]), 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, nivel: 'regular' }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: null }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: 20 }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, decisivo: 'si' }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, electrodo: '' }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'buena' } }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'sin_analizar', duracion_min: null, canales: null } }, 'T-0001')).not.toThrow();
http.verify();
});
it('valida las alteraciones del EEG', () => {
@@ -306,8 +371,35 @@ describe('Seguimiento TEA', () => {
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], estado: 'alto' }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], valor: null }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3 }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3, sin_evaluar: 'sin_referencia' }), 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], sin_evaluar: 'sin_valor' }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], referencia: { min: 3, max: 1 } }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow();
});
// The association model's panel (prototype, simulated data): the field is optional and checked when present.
it('valida la relación con el ADOS-2 y solo muestra las zonas alteradas del paciente', () => {
const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa',
resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002,
probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 };
const otra = { ...fila, zona: 'parietal', zona_etiqueta: 'Parietal', valor_z: 0.4, q: 0.01 };
const rel = (filas: object[]) => ({ ...detalle, relacion_ados2: { validado: false, nivel: 'item', n_cohorte: 46, version: 'v', filas } });
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle({ ...detalle, relacion_ados2: null }, 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle(rel([fila]), 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle(rel([{ ...fila, probabilidad: 1.2 }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(rel([{ ...fila, ic_inf: 0.5 }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(rel([{ ...fila, tipo: 'zona' }]), 'T-0001')).toThrow();
const fixture = open();
request().flush(tres); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges();
const filas = Array.from(root.querySelectorAll('section.relacion tbody tr'));
expect(filas.length).toBe(1);
expect(filas[0].classList.contains('alterada')).toBe(true);
expect(filas[0].textContent).toContain('q < 0.001');
expect(filas[0].textContent).toContain('93 %');
http.verify();
});
});
@@ -61,7 +61,7 @@
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
@if (patientState() === 'listo') {
<article class="card"><h3>ADOS-2</h3>@if (ados(); as ados) { <p>Fecha: {{ ados.effectiveDateTime }}</p><dl>@for (c of ados.component; track $index) { <div><dt>{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}</dt><dd>{{ componentValue(c) }}</dd></div> }</dl> } @else { <p>Sin información de ADOS-2.</p> }</article>
<article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article>
<article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}@if (electrode(o); as e) { · {{ e }} }</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article>
@if (alterationsAvailable() && alterations().length) { <article class="card"><h3>Métricas del EEG</h3><dl>@for (o of alterations(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }}</dd></div> }</dl></article> }
}
</section>
@@ -174,12 +174,14 @@ export class TeaStatusPage implements OnDestroy {
}
ados() { return this.patientResources().find(r => r.resourceType === 'Observation' && code(r.code) === 'ados2'); }
eeg() { return this.patientResources().find(r => r.resourceType === 'DiagnosticReport' && code(r.code) === 'eeg'); }
eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : 'Sin dato'; }
eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : quality === 'SIN_ANALIZAR' ? 'Sin analizar' : 'Sin dato'; }
eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; }
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'BUENO' ? 'buena' : value === 'MALO' ? 'mala' : 'sin dato'; }
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && code(r.code).startsWith('eeg.calidad_')); }
// The EEG analysis's checks: A is out of range, N within.
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'N' ? 'dentro de rango' : value === 'A' ? 'fuera de rango' : 'sin dato'; }
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && r.code?.coding?.[0]?.system === 'urn:tea:validation'); }
electrode(o: Resource): string | undefined { return o.component?.find((c: Resource) => c.code?.text === 'electrode')?.valueString; }
alterationsAvailable() { return this.measures().some(m => m.id.startsWith('M30-')); }
alterations() { return this.patientResources().filter(r => r.resourceType === 'Observation' && r.code?.coding?.[0]?.system?.endsWith('/tea-eeg-metrica') && !r.id?.startsWith('electrodos-')); }
componentValue(c: Resource) { return c.valueInteger ?? c.valueString ?? (text(c.valueCodeableConcept) || 'Sin dato'); }
observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}` : 'Sin dato'); }
observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim() : o.valueString ?? 'Sin dato'); }
}
+7
View File
@@ -32,6 +32,13 @@ export class GovernanceApi {
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/promote`, {});
}
/** Exports the scenario's latest dbt cohort build, trains a PROD version and tries to promote it, the same
* one-shot pipeline the `entrenar` compose profile runs. 409 when it trained but needs its reports attached
* before it can be promoted; 503 with no dbt manifest configured or an operational failure. */
trainModelVersion(domain: string, scenario: string): Observable<{ output: string }> {
return this.http.post<{ output: string }>(`/governance/model-versions/${domain}/${scenario}/train`, {});
}
retireModelVersion(domain: string, scenario: string, version: string): Observable<ModelVersion> {
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {});
}
@@ -0,0 +1,29 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
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. */
@Injectable({ providedIn: 'root' })
export class RiskBatchesApi {
private readonly http = inject(HttpClient);
listPending(domain: string): Observable<PendingRiskBatch[]> {
return this.http.get<PendingRiskBatch[]>(`/${domain}/riesgos/lotes`);
}
/** Moves every current evaluation of the batch to `final`: it becomes the one patient records read. */
confirm(domain: string, loteId: number, reason: string): Observable<{ lote_id: number; evaluaciones_cambiadas: number }> {
return this.http.post<{ lote_id: number; evaluaciones_cambiadas: number }>(
`/${domain}/riesgos/lotes/${loteId}/confirmar`, { reason },
);
}
/** Moves every current evaluation of the batch to `entered-in-error` instead. */
void(domain: string, loteId: number, reason: string): Observable<{ lote_id: number; evaluaciones_cambiadas: number }> {
return this.http.post<{ lote_id: number; evaluaciones_cambiadas: number }>(
`/${domain}/riesgos/lotes/${loteId}/anular`, { reason },
);
}
}
@@ -0,0 +1,9 @@
/** A risk batch waiting for someone to confirm or void it (ADR-MD-008); invisible to patient records until
* confirmed. */
export interface PendingRiskBatch {
lote_id: number;
modelo_nombre: string;
modelo_version: string;
evaluado_en: string;
n_evaluaciones: number;
}
@@ -22,5 +22,10 @@
<app-ocr-review-panel></app-ocr-review-panel>
</div>
</mat-tab>
<mat-tab label="Lotes de riesgo">
<div class="governance__panel">
<app-risk-batches-panel></app-risk-batches-panel>
</div>
</mat-tab>
</mat-tab-group>
</div>
@@ -4,15 +4,16 @@ import { MatToolbarModule } from '@angular/material/toolbar';
import { ExperimentsPanel } from '../experiments-panel/experiments-panel';
import { ModelVersionsPanel } from '../model-versions-panel/model-versions-panel';
import { OcrReviewPanel } from '../ocr-review-panel/ocr-review-panel';
import { RiskBatchesPanel } from '../risk-batches-panel/risk-batches-panel';
/**
* The "Gobernanza de modelos" page (route `/gobernanza`): model versions,
* notebooks run on cohort builds and the OCR review queue, one tab each. Every tab is a
* notebooks run on cohort builds, the OCR review queue and pending risk batches, one tab each. Every tab is a
* self-contained panel that loads its own data.
*/
@Component({
selector: 'app-governance-page',
imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel],
imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel, RiskBatchesPanel],
templateUrl: './governance-page.html',
styleUrl: './governance-page.scss',
})
@@ -6,12 +6,16 @@
}
</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>
<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()) {
@if (loading() || training()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (loadError(); as error) {
@@ -17,10 +17,14 @@ import { ModelVersion } 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' };
/**
* Every registered model version with its status (desarrollo, candidata,
* en producción, retirada). The detail dialog holds the promotion
* checklist, lineage, artifacts and reports.
* checklist, lineage, artifacts and reports. The toolbar also offers
* training the one scenario with a trainer, over HTTP instead of a shell.
*/
@Component({
selector: 'app-model-versions-panel',
@@ -50,6 +54,7 @@ export class ModelVersionsPanel implements OnInit {
readonly versions = signal<ModelVersion[]>([]);
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly training = signal(false);
readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones'];
@@ -94,4 +99,23 @@ export class ModelVersionsPanel implements OnInit {
metrics(version: ModelVersion): { key: string; value: unknown }[] {
return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value }));
}
train(): void {
this.training.set(true);
this.api
.trainModelVersion(TRAINABLE.domain, TRAINABLE.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();
},
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();
},
});
}
}
@@ -0,0 +1,62 @@
<div class="batches">
<div class="batches__toolbar">
<span class="batches__spacer"></span>
<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()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (loadError(); as error) {
<p class="batches__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
<table mat-table [dataSource]="batches()" class="batches__table">
<ng-container matColumnDef="modelo">
<th mat-header-cell *matHeaderCellDef>Modelo</th>
<td mat-cell *matCellDef="let b">{{ b.modelo_nombre }}:{{ b.modelo_version }}</td>
</ng-container>
<ng-container matColumnDef="evaluado_en">
<th mat-header-cell *matHeaderCellDef>Calculado</th>
<td mat-cell *matCellDef="let b">{{ b.evaluado_en | date: 'short' }}</td>
</ng-container>
<ng-container matColumnDef="n_evaluaciones">
<th mat-header-cell *matHeaderCellDef>Pacientes</th>
<td mat-cell *matCellDef="let b">{{ b.n_evaluaciones }}</td>
</ng-container>
<ng-container matColumnDef="motivo">
<th mat-header-cell *matHeaderCellDef>Motivo</th>
<td mat-cell *matCellDef="let b">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="batches__reason">
<input matInput [formControl]="reasonFor(b)" placeholder="Motivo de la confirmación o anulación" />
</mat-form-field>
</td>
</ng-container>
<ng-container matColumnDef="acciones">
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let b">
<button mat-button type="button" color="primary" [disabled]="!reasonFor(b).value.trim() || deciding() === b.lote_id"
(click)="confirm(b)">
<mat-icon aria-hidden="true">check_circle</mat-icon>Confirmar
</button>
<button mat-button type="button" color="warn" [disabled]="!reasonFor(b).value.trim() || deciding() === b.lote_id"
(click)="void(b)">
<mat-icon aria-hidden="true">block</mat-icon>Anular
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
@if (!loading() && batches().length === 0) {
<p class="batches__empty"><mat-icon aria-hidden="true">task_alt</mat-icon>No hay lotes de riesgo pendientes de revisión.</p>
}
</div>
@@ -0,0 +1,43 @@
.batches {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.batches__toolbar {
align-items: center;
display: flex;
gap: var(--space-2);
}
.batches__spacer {
flex: 1;
}
.batches__alert {
align-items: center;
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
display: flex;
gap: var(--space-2);
margin: 0;
padding: var(--space-2) var(--space-3);
}
.batches__table {
width: 100%;
}
.batches__reason {
min-width: 220px;
width: 100%;
}
.batches__empty {
align-items: center;
color: var(--mat-sys-on-surface-variant);
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-2);
margin: 0;
}
@@ -0,0 +1,113 @@
import { DatePipe } from '@angular/common';
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { RiskBatchesApi } from '../../api/risk-batches.api';
import { PendingRiskBatch } from '../../api/risk-batches.types';
const DOMAIN = 'cacu';
/**
* Risk batches a model produced that nobody has confirmed or voided yet (ADR-MD-008): invisible to patient
* records until someone decides, with a reason. Only CaCu has a model estimating risks today.
*/
@Component({
selector: 'app-risk-batches-panel',
imports: [
DatePipe,
MatButtonModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSnackBarModule,
MatTableModule,
MatTooltipModule,
ReactiveFormsModule,
],
templateUrl: './risk-batches-panel.html',
styleUrl: './risk-batches-panel.scss',
})
export class RiskBatchesPanel implements OnInit {
private readonly api = inject(RiskBatchesApi);
private readonly snackBar = inject(MatSnackBar);
private readonly destroyRef = inject(DestroyRef);
readonly batches = signal<PendingRiskBatch[]>([]);
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly deciding = signal<number | null>(null);
readonly displayedColumns = ['modelo', 'evaluado_en', 'n_evaluaciones', 'motivo', 'acciones'];
private readonly reasons = new Map<number, FormControl<string>>();
ngOnInit(): void {
this.reload();
}
reload(): void {
this.loading.set(true);
this.loadError.set(null);
this.api
.listPending(DOMAIN)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: (batches) => {
this.loading.set(false);
this.batches.set(batches);
},
error: (error) => {
this.loading.set(false);
this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar los lotes de riesgo.'));
},
});
}
reasonFor(batch: PendingRiskBatch): FormControl<string> {
let control = this.reasons.get(batch.lote_id);
if (!control) {
control = new FormControl('', { nonNullable: true });
this.reasons.set(batch.lote_id, control);
}
return control;
}
confirm(batch: PendingRiskBatch): void {
this.decide(batch, (reason) => this.api.confirm(DOMAIN, batch.lote_id, reason), 'confirmado');
}
void(batch: PendingRiskBatch): void {
this.decide(batch, (reason) => this.api.void(DOMAIN, batch.lote_id, reason), 'anulado');
}
private decide(
batch: PendingRiskBatch,
request: (reason: string) => ReturnType<RiskBatchesApi['confirm']>,
verb: string,
): void {
const reason = this.reasonFor(batch).value.trim();
if (!reason) return;
this.deciding.set(batch.lote_id);
request(reason).subscribe({
next: () => {
this.deciding.set(null);
this.reasons.delete(batch.lote_id);
this.snackBar.open(`El lote ${batch.lote_id} quedó ${verb}.`, 'OK', { duration: 3000 });
this.reload();
},
error: (error) => {
this.deciding.set(null);
this.snackBar.open(apiErrorMessage(error, 'La operación no se pudo completar.'), 'OK', { duration: 5000 });
},
});
}
}