Compare commits
121 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bfcba8ad1f | |||
| f04c40b1e1 | |||
| bd3f63b20a | |||
| 860c66ba5c | |||
| 5c8e2866ef | |||
| 29d021b347 | |||
| 98e9b60e83 | |||
| 5061350dd8 | |||
| eb887be447 | |||
| 0b22b3c309 | |||
| 6ade415f63 | |||
| 5791928976 | |||
| f4d1829cd3 | |||
| 069cc459a4 | |||
| 881c613744 | |||
| be46429627 | |||
| 25f584c864 | |||
| 561a5dde36 | |||
| bf89099ce8 | |||
| ff1f6758ba | |||
| f38a2c6bb4 | |||
| 40c19a6a1f | |||
| 329c0891ae | |||
| 34c6f2af3a | |||
| 7ab2567dc9 | |||
| 14d6875d9b | |||
| f82ce8cc38 | |||
| 61867ff973 | |||
| 8bca0fbcdf | |||
| ec8542de9f | |||
| 29c9e6853b | |||
| b1ff6cadb2 | |||
| 26285a87fa | |||
| f058f1f476 | |||
| 7f1e43bdc5 | |||
| 5bf6af8ecf | |||
| 253290ed6a | |||
| ec5b8fde6b | |||
| 2a36397fac | |||
| eada50d2ff | |||
| 396902541d | |||
| 68b5e927e7 | |||
| 990cab0e37 | |||
| 39e1e3e094 | |||
| 4e08bb8c4b | |||
| 686580af81 | |||
| 60c71bfc3d | |||
| ad4edbe2a1 | |||
| 1af0c21291 | |||
| dd356efb6b | |||
| 01271621b7 | |||
| 4c181af291 | |||
| b8bf57e235 | |||
| 17cef51d90 | |||
| 7692952ec9 | |||
| feaed5ff0e | |||
| 999bc4ecf5 | |||
| 6ed87ff3d8 | |||
| ff4ad2c964 | |||
| b5f8e5bfc2 | |||
| f04478e600 | |||
| 6a0c3c9e92 | |||
| e3c9849e29 | |||
| 10773edcc1 | |||
| 8b80e1d26c | |||
| 2a48c28245 | |||
| e1a8127c22 | |||
| 6de193f44e | |||
| 0059427179 | |||
| 8192f92be9 | |||
| 1fef7812b4 | |||
| 6465165e34 | |||
| a26df55214 | |||
| 72e5f9bf93 | |||
| 08f1d812ac | |||
| ce207a72a5 | |||
| 5094880622 | |||
| 093ceffa36 | |||
| 6a7c1d0cbd | |||
| fb5a4ed5cc | |||
| e8ce7a487b | |||
| a3a552ad0e | |||
| fb54cfb188 | |||
| 7adceb86bf | |||
| 4e9b25bd8f | |||
| a7b5f4c50b | |||
| 4d159ae0d0 | |||
| 4fba4fa861 | |||
| db4d743413 | |||
| d6c52c8536 | |||
| 1969ffdb5f | |||
| 699d4b13e1 | |||
| c5cbaaab13 | |||
| cc802cbb57 | |||
| e7a6398168 | |||
| 62027f2216 | |||
| 88dc7537c2 | |||
| 0cb9395cd6 | |||
| e74e3d8fd4 | |||
| 0fc80bd29a | |||
| dae8bc517e | |||
| 68e2930e65 | |||
| bb957ec6a4 | |||
| 02e28e624b | |||
| 08161db1c4 | |||
| fa029d69b8 | |||
| 67ae7f482f | |||
| 304c563845 | |||
| efe4404c4e | |||
| 7d180417d8 | |||
| 00f773dd75 | |||
| 3bb1c8dd84 | |||
| ef4f606648 | |||
| 54b3e50ca5 | |||
| 680cc0adc6 | |||
| b53322ed72 | |||
| c32d2b6012 | |||
| 7aa3d2c6e6 | |||
| c2c6d9ef47 | |||
| d4d3ea3837 | |||
| 04795a09cc |
@@ -14,3 +14,25 @@ npx ng build # compilación de producción en dist/WebApp
|
|||||||
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
||||||
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
||||||
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
||||||
|
|
||||||
|
## CaCu en Windows con la instalación del puerto 5210
|
||||||
|
|
||||||
|
En `feature/cacu-update`, desde la carpeta de WebApp:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npm ci
|
||||||
|
npm run start:cacu
|
||||||
|
```
|
||||||
|
|
||||||
|
Abre [Indicadores CaCu](http://127.0.0.1:4300/indicadores/cacu) e inicia sesión
|
||||||
|
con la cuenta de CaCu de la aplicación. La sesión se valida en el navegador.
|
||||||
|
Detén Angular con `Ctrl+C` en la misma terminal.
|
||||||
|
|
||||||
|
El lockfile de Angular admite Node.js `^22.22.3`, `^24.15.0` o `>=26.0.0`.
|
||||||
|
`package.json` declara npm `11.17.0`. El arranque se probó con Node.js
|
||||||
|
`26.13.0` y npm `11.20.0`.
|
||||||
|
|
||||||
|
`start:cacu` escucha en `127.0.0.1:4300`. El proxy de Angular reenvía
|
||||||
|
solicitudes GET de CaCu a `http://10.0.10.41:5210`, incluida la lista
|
||||||
|
`/cacu/seguimiento` y los recursos FHIR `Measure`, `MeasureReport` y
|
||||||
|
`RiskAssessment`. La ruta `/indicadores/cacu` la sirve Angular.
|
||||||
|
|||||||
@@ -62,6 +62,17 @@
|
|||||||
"optimization": false,
|
"optimization": false,
|
||||||
"extractLicenses": false,
|
"extractLicenses": false,
|
||||||
"sourceMap": true
|
"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"
|
"defaultConfiguration": "production"
|
||||||
@@ -77,6 +88,10 @@
|
|||||||
},
|
},
|
||||||
"development": {
|
"development": {
|
||||||
"buildTarget": "WebApp:build:development"
|
"buildTarget": "WebApp:build:development"
|
||||||
|
},
|
||||||
|
"simulado": {
|
||||||
|
"buildTarget": "WebApp:build:simulado",
|
||||||
|
"proxyConfig": "simulado/proxy.simulado.json"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"defaultConfiguration": "development"
|
"defaultConfiguration": "development"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"ng": "ng",
|
"ng": "ng",
|
||||||
"start": "ng serve",
|
"start": "ng serve",
|
||||||
|
"start:cacu": "ng serve --host 127.0.0.1 --port 4300 --proxy-config proxy.cacu-readonly.cjs",
|
||||||
"build": "ng build",
|
"build": "ng build",
|
||||||
"watch": "ng build --watch --configuration development",
|
"watch": "ng build --watch --configuration development",
|
||||||
"test": "ng test"
|
"test": "ng test"
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// Keep the installed API read-only for local CaCu development.
|
||||||
|
module.exports = {
|
||||||
|
'^/(?:health|cacu/(?:seguimiento|fhir/(?:Measure|MeasureReport|RiskAssessment|metadata)))(?:\\?|$)': {
|
||||||
|
target: 'http://10.0.10.41:5210',
|
||||||
|
changeOrigin: true,
|
||||||
|
bypass(request, response) {
|
||||||
|
if (request.method === 'GET') return;
|
||||||
|
if (!response) return false;
|
||||||
|
response.writeHead(405, { Allow: 'GET' });
|
||||||
|
response.end();
|
||||||
|
return request.url;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
@@ -41,7 +41,7 @@ describe('Encabezado del marco', () => {
|
|||||||
const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.path)]);
|
const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.path)]);
|
||||||
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
|
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
|
||||||
});
|
});
|
||||||
it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
|
it.each([['tea', 'Trastorno del espectro autista'], ['cacu', 'Cáncer cervicouterino'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
|
||||||
await ir('/indicadores/' + dominio);
|
await ir('/indicadores/' + dominio);
|
||||||
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
|
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
|
||||||
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
|
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
|
||||||
@@ -60,7 +60,7 @@ describe('Encabezado del marco', () => {
|
|||||||
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
|
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
|
||||||
await ir('/indicadores/cama');
|
await ir('/indicadores/cama');
|
||||||
const items = await abrirMenu();
|
const items = await abrirMenu();
|
||||||
expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']);
|
expect(items.map(a => a.textContent?.trim())).toEqual(['Trastorno del espectro autista', 'Cáncer cervicouterino']);
|
||||||
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
|
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
|
||||||
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
|
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
|
||||||
});
|
});
|
||||||
@@ -69,7 +69,7 @@ describe('Encabezado del marco', () => {
|
|||||||
const items = await abrirMenu();
|
const items = await abrirMenu();
|
||||||
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
|
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
|
||||||
expect(router.url).toBe('/indicadores/cacu');
|
expect(router.url).toBe('/indicadores/cacu');
|
||||||
expect(selector()!.textContent).toContain('CaCu');
|
expect(selector()!.textContent).toContain('Cáncer cervicouterino');
|
||||||
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
|
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
|
||||||
const ubicacion = TestBed.inject(Location);
|
const ubicacion = TestBed.inject(Location);
|
||||||
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
|
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
|
||||||
@@ -80,7 +80,8 @@ describe('Encabezado del marco', () => {
|
|||||||
await ir(url);
|
await ir(url);
|
||||||
expect(selector()).toBeNull();
|
expect(selector()).toBeNull();
|
||||||
expect(root().querySelector('.platform-title')).toBeNull();
|
expect(root().querySelector('.platform-title')).toBeNull();
|
||||||
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
|
expect(root().querySelector('.site-header__section')).toBeNull();
|
||||||
|
expect(root().querySelector('.site-header__nav')?.textContent).not.toContain('Análisis de información');
|
||||||
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
|
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
|
||||||
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
|
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { routes } from './app.routes';
|
||||||
|
import { IndicadoresService } from './features/indicadores/indicadores.service';
|
||||||
|
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
|
||||||
|
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
|
||||||
|
|
||||||
|
// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento
|
||||||
|
// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`).
|
||||||
|
export const appConfig: ApplicationConfig = {
|
||||||
|
providers: [
|
||||||
|
provideBrowserGlobalErrorListeners(),
|
||||||
|
provideRouter(routes),
|
||||||
|
provideHttpClient(),
|
||||||
|
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
||||||
|
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
||||||
|
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
|
||||||
|
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
|
||||||
|
]
|
||||||
|
};
|
||||||
+1
-2
@@ -20,9 +20,8 @@
|
|||||||
}
|
}
|
||||||
} @else {
|
} @else {
|
||||||
<nav class="site-header__nav" aria-label="Secciones">
|
<nav class="site-header__nav" aria-label="Secciones">
|
||||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
|
||||||
@if (breadcrumb(); as crumb) {
|
@if (breadcrumb(); as crumb) {
|
||||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
<span class="site-header__crumb" aria-current="page">{{ crumb }}</span>
|
||||||
}
|
}
|
||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
|
|||||||
+29
-19
@@ -41,14 +41,6 @@
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
.site-header__section {
|
|
||||||
text-decoration: none;
|
|
||||||
color: var(--color-text);
|
|
||||||
font-size: 15px;
|
|
||||||
font-weight: 500;
|
|
||||||
letter-spacing: 0.01em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.app-main {
|
.app-main {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
@@ -89,11 +81,6 @@
|
|||||||
width: clamp(132px, 42vw, 170px);
|
width: clamp(132px, 42vw, 170px);
|
||||||
}
|
}
|
||||||
|
|
||||||
.site-header__section {
|
|
||||||
font-size: 13px;
|
|
||||||
text-align: right;
|
|
||||||
}
|
|
||||||
|
|
||||||
.site-footer__content {
|
.site-footer__content {
|
||||||
min-height: 76px;
|
min-height: 76px;
|
||||||
padding: 0 20px;
|
padding: 0 20px;
|
||||||
@@ -117,7 +104,8 @@
|
|||||||
|
|
||||||
.domain-selector--espera {
|
.domain-selector--espera {
|
||||||
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
|
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
|
||||||
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
|
max-width: 100%; background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; line-height: 1.2;
|
||||||
|
min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Session exit: the same action look as the home buttons, in header size. */
|
/* Session exit: the same action look as the home buttons, in header size. */
|
||||||
@@ -160,9 +148,31 @@
|
|||||||
width: 18px;
|
width: 18px;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
// Full domain names need their own track. On a wide header they sit beside the title;
|
||||||
@media (max-width: 599px) {
|
// below 900px the name takes a row of its own so the logo and the exit stay together.
|
||||||
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
.app-shell--indicadores .site-header__content {
|
||||||
.app-shell--indicadores .brand { margin-inline-end: auto; }
|
display: grid;
|
||||||
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
|
grid-template-columns: auto minmax(0, 1fr) auto auto;
|
||||||
|
grid-template-areas: "brand title domain salir";
|
||||||
|
align-items: center;
|
||||||
|
column-gap: 16px;
|
||||||
|
row-gap: 8px;
|
||||||
|
padding-block: 8px;
|
||||||
|
}
|
||||||
|
.app-shell--indicadores .brand { grid-area: brand; }
|
||||||
|
.app-shell--indicadores .platform-title { grid-area: title; margin: 0; overflow-wrap: normal; }
|
||||||
|
.app-shell--indicadores .domain-selector,
|
||||||
|
.app-shell--indicadores .domain-selector--espera { grid-area: domain; justify-self: end; }
|
||||||
|
.app-shell--indicadores .site-header__salir { grid-area: salir; margin-inline-start: 0; }
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.app-shell--indicadores .site-header__content {
|
||||||
|
grid-template-columns: auto minmax(0, 1fr);
|
||||||
|
grid-template-areas:
|
||||||
|
"brand salir"
|
||||||
|
"domain domain"
|
||||||
|
"title title";
|
||||||
|
}
|
||||||
|
.app-shell--indicadores .domain-selector,
|
||||||
|
.app-shell--indicadores .domain-selector--espera { justify-self: start; white-space: normal; }
|
||||||
|
.app-shell--indicadores .platform-title { font-size: 1.125rem; }
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-1
@@ -60,6 +60,15 @@ describe('App', () => {
|
|||||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('home shows only the brand name as eyebrow and names the risk models action', async () => {
|
||||||
|
// Fails if the eyebrow regains the section text or the action goes back to «Indicadores».
|
||||||
|
const page = await render('/');
|
||||||
|
expect(page.querySelector('.home__eyebrow')?.textContent?.trim()).toBe('ISSSTELEON');
|
||||||
|
const acciones = Array.from(page.querySelectorAll('.home__action')).map(a => a.textContent?.replace(/\s+/g, ' ').trim());
|
||||||
|
expect(acciones.some(t => t?.endsWith('Modelos predictivos de riesgo'))).toBe(true);
|
||||||
|
expect(acciones.some(t => t?.endsWith('Indicadores'))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||||
const page = await render('/conectar');
|
const page = await render('/conectar');
|
||||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||||
@@ -93,7 +102,7 @@ describe('App', () => {
|
|||||||
it('el encabezado no ofrece los otros dominios', async () => {
|
it('el encabezado no ofrece los otros dominios', async () => {
|
||||||
const page = await render('/indicadores/cacu');
|
const page = await render('/indicadores/cacu');
|
||||||
expect(page.querySelector('app-domain-selector')).toBeNull();
|
expect(page.querySelector('app-domain-selector')).toBeNull();
|
||||||
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('CaCu');
|
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('Cáncer cervicouterino');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -38,7 +38,9 @@ export class App {
|
|||||||
|
|
||||||
protected readonly usuario = this.auth.usuario;
|
protected readonly usuario = this.auth.usuario;
|
||||||
protected readonly title = 'Plataforma de Indicadores';
|
protected readonly title = 'Plataforma de Indicadores';
|
||||||
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
|
protected readonly domainLabels: Record<Dominio, string> = {
|
||||||
|
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
|
||||||
|
};
|
||||||
private readonly url = toSignal(this.router.events.pipe(
|
private readonly url = toSignal(this.router.events.pipe(
|
||||||
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
|
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
|
||||||
/** On an indicators page the header names its domain and switches to the others. */
|
/** On an indicators page the header names its domain and switches to the others. */
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ import { DataConnection, SourceTable } from '../domain/data-source';
|
|||||||
import { ImportFlow } from '../domain/import-flow';
|
import { ImportFlow } from '../domain/import-flow';
|
||||||
|
|
||||||
export const DOMAINS: { id: Domain; label: string; description: string }[] = [
|
export const DOMAINS: { id: Domain; label: string; description: string }[] = [
|
||||||
{ id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' },
|
{ id: 'cacu', label: 'Cáncer cervicouterino', description: 'Cáncer cervicouterino' },
|
||||||
{ id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' },
|
{ id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' },
|
||||||
{ id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' },
|
{ id: 'tea', label: 'Trastorno del espectro autista', description: 'Trastorno del espectro autista' },
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
:host { display: contents; }
|
:host { display: contents; }
|
||||||
.domain-selector {
|
.domain-selector {
|
||||||
flex: 0 0 auto;
|
flex: 0 0 auto;
|
||||||
|
max-width: 100%;
|
||||||
|
height: auto;
|
||||||
|
min-height: 40px;
|
||||||
background-color: var(--issste-accent);
|
background-color: var(--issste-accent);
|
||||||
color: var(--issste-text);
|
color: var(--issste-text);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
|
line-height: 1.2;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.domain-selector { white-space: normal; text-align: start; padding-block: 8px; }
|
||||||
|
}
|
||||||
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
|
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
|
||||||
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { BarrasHorizontales } from './barras-horizontales';
|
||||||
|
import { ConjuntoBarras, FilaBarra, limiteEscala, maximoDelConjunto, sumaActivas } from './indicadores-barras';
|
||||||
|
|
||||||
|
const fila = (id: string, etiqueta: string, n: number | null, estado: FilaBarra['estado'] = 'Publicado'): FilaBarra => ({ id, etiqueta, n, estado, color: '#438B53' });
|
||||||
|
const suma = (fs: FilaBarra[]) => fs.some(f => f.n === null) ? null : fs.reduce((s, f) => s + f.n!, 0);
|
||||||
|
// Cytology with more than 95 % normal results: the others are small counts, one of them a single record.
|
||||||
|
const normales = [fila('NORMAL', 'Normal', 912)];
|
||||||
|
const anormales = [fila('ASC-US', 'ASC-US', 14), fila('LIEBG', 'LIEBG', 9), fila('ASC-H', 'ASC-H', 3), fila('LIEAG', 'LIEAG', 5), fila('CIS', 'Carcinoma in situ', 1)];
|
||||||
|
const citologia = (activas: string[] | null = null): ConjuntoBarras => ({ den: 944, unidad: 'pacientes con resultado', activas: activas ? new Set(activas) : null, grupos: [
|
||||||
|
{ id: 'SIN', etiqueta: 'Sin anomalía', color: '#247A71', subtotal: 912, filas: normales }, { id: 'ANORMAL', etiqueta: 'Anormal', color: '#656677', subtotal: suma(anormales), filas: anormales }] });
|
||||||
|
const plano = (filas: FilaBarra[], den: number | null): ConjuntoBarras => ({ den, unidad: 'reportes de VPH elegibles', activas: null, grupos: [{ id: null, etiqueta: null, color: '#8A9199', subtotal: den, filas }] });
|
||||||
|
|
||||||
|
describe('Barras horizontales: escala', () => {
|
||||||
|
it('el límite es un número redondo y par que contiene la barra o el subtotal más largo', () => {
|
||||||
|
expect([0, 1, 5, 44, 63, 912, 946, 1892].map(limiteEscala)).toEqual([2, 2, 6, 50, 80, 1000, 1000, 2000]);
|
||||||
|
expect(maximoDelConjunto(citologia())).toBe(912);
|
||||||
|
// A group's subtotal can exceed its categories: the scale holds it.
|
||||||
|
expect(maximoDelConjunto({ den: 108, unidad: 'x', activas: null, grupos: [{ id: 'g', etiqueta: 'g', color: '#000', subtotal: 63, filas: [fila('a', 'a', 44), fila('b', 'b', 13), fila('c', 'c', 6)] }] })).toBe(63);
|
||||||
|
});
|
||||||
|
it('la suma de lo seleccionado es nula sin selección o con una celda desconocida', () => {
|
||||||
|
expect(sumaActivas(citologia())).toBeNull(); expect(sumaActivas(citologia(['ASC-US', 'CIS']))).toBe(15);
|
||||||
|
expect(sumaActivas({ ...plano([fila('a', 'a', null, 'Suprimido'), fila('b', 'b', 2)], 2), activas: new Set(['a', 'b']) })).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Barras horizontales: componente', () => {
|
||||||
|
beforeEach(() => TestBed.configureTestingModule({}));
|
||||||
|
function montar(conjunto: ConjuntoBarras) {
|
||||||
|
const f = TestBed.createComponent(BarrasHorizontales);
|
||||||
|
f.componentRef.setInput('conjunto', conjunto); f.componentRef.setInput('titulo', 'Resultados'); f.detectChanges();
|
||||||
|
return f.nativeElement as HTMLElement;
|
||||||
|
}
|
||||||
|
const texto = (e: Element | null) => (e?.textContent ?? '').replace(/\s+/g, ' ').trim();
|
||||||
|
const filas = (r: HTMLElement) => [...r.querySelectorAll('.filas .fila')];
|
||||||
|
|
||||||
|
it('denominador y unidad, escala absoluta rotulada y sin barra de longitud artificial', () => {
|
||||||
|
const r = montar(citologia());
|
||||||
|
expect(texto(r.querySelector('.den'))).toContain('Total: 944 pacientes con resultado'); expect(texto(r.querySelector('.titulo-eje'))).toBe('Escala: cantidad de pacientes con resultado (de 0 a 1,000)');
|
||||||
|
expect([...r.querySelectorAll('.marcas span')].map(x => x.textContent)).toEqual(['0', '500', '1,000']);
|
||||||
|
const ancho = (etiqueta: string) => (filas(r).find(x => texto(x).startsWith(etiqueta))!.querySelector('.pista i') as HTMLElement).style.width;
|
||||||
|
expect(ancho('Normal')).toBe('91.2%'); expect(ancho('ASC-US')).toBe('1.4%'); expect(ancho('Carcinoma in situ')).toBe('0.1%');
|
||||||
|
// The count and the percentage are always written, whatever the bar length.
|
||||||
|
expect(filas(r).map(x => texto(x))).toEqual(['Normal 912 96.6 %', 'ASC-US 14 1.5 %', 'LIEBG 9 1.0 %', 'ASC-H 3 0.3 %', 'LIEAG 5 0.5 %', 'Carcinoma in situ 1 0.1 %']);
|
||||||
|
});
|
||||||
|
it('un valor demasiado corto para verse lleva un marcador hueco en su posición, sin alargar la barra', () => {
|
||||||
|
const r = montar(citologia());
|
||||||
|
const ci = filas(r).find(x => texto(x).startsWith('Carcinoma'))!;
|
||||||
|
expect((ci.querySelector('.minima') as HTMLElement).style.left).toBe('0.1%');
|
||||||
|
expect(filas(r).find(x => texto(x).startsWith('Normal'))!.querySelector('.minima')).toBeNull();
|
||||||
|
expect(filas(r).find(x => texto(x).startsWith('ASC-US'))!.querySelector('.minima')).not.toBeNull();
|
||||||
|
});
|
||||||
|
it('los grupos son encabezados con su subtotal y no cuentan como categorías de la distribución', () => {
|
||||||
|
const r = montar(citologia());
|
||||||
|
const grupos = [...r.querySelectorAll('.grupo')];
|
||||||
|
expect(grupos.map(g => g.getAttribute('aria-label'))).toEqual(['Sin anomalía', 'Anormal']);
|
||||||
|
expect(grupos.map(g => texto(g.querySelector('.cabecera')))).toEqual(['Grupo Sin anomalía 912 96.6 %', 'Grupo Anormal 32 3.4 %']);
|
||||||
|
expect(filas(r)).toHaveLength(6); expect(r.querySelectorAll('.cabecera')).toHaveLength(2);
|
||||||
|
// The subtotals add up to the total once, never together with their categories.
|
||||||
|
expect(912 + 32).toBe(944);
|
||||||
|
});
|
||||||
|
it('un cero publicado tiene marca punteada y ninguna barra; lo no disponible se rotula y no es cero', () => {
|
||||||
|
const r = montar(plano([fila('a', 'Negativo', 5), fila('b', 'Positivo 16 y 18', 0), fila('c', 'Indeterminado', null, 'No disponible'), fila('d', 'Otro', null, 'Suprimido')], 5));
|
||||||
|
const [a, b, c, d] = filas(r);
|
||||||
|
expect(b.querySelector('.pista i')).toBeNull(); expect(b.querySelector('.cero-marca')).not.toBeNull(); expect(texto(b)).toBe('Positivo 16 y 18 0 0.0 %');
|
||||||
|
expect(c.classList.contains('nd')).toBe(true); expect(c.querySelector('.pista i')).toBeNull(); expect(texto(c)).toBe('Indeterminado No disponible'); expect(texto(d)).toBe('Otro Suprimido');
|
||||||
|
expect(a.querySelector('.cero-marca')).toBeNull(); expect(c.querySelector('.cero-marca')).toBeNull();
|
||||||
|
});
|
||||||
|
it('sin denominador se muestran las cantidades y se dice que el porcentaje no está disponible', () => {
|
||||||
|
const r = montar(plano([fila('a', 'Negativo', 5)], null));
|
||||||
|
expect(texto(r.querySelector('.den'))).toContain('no disponible'); expect(texto(filas(r)[0])).toBe('Negativo 5 % no disponible');
|
||||||
|
});
|
||||||
|
it('la selección atenúa lo no seleccionado y dice cuánto suma; sin selección nada se atenúa', () => {
|
||||||
|
const r = montar(citologia(['ASC-US', 'CIS']));
|
||||||
|
expect(filas(r).filter(x => x.classList.contains('atenuada')).map(x => texto(x).split(' ')[0])).toEqual(['Normal', 'LIEBG', 'ASC-H', 'LIEAG']);
|
||||||
|
expect(r.querySelectorAll('.cabecera.atenuada')).toHaveLength(1); expect(texto(r.querySelector('.seleccion'))).toBe('Selección: 15 de 944 (1.6 %)');
|
||||||
|
const s = montar(citologia()); expect(s.querySelectorAll('.atenuada')).toHaveLength(0); expect(s.querySelector('.seleccion')).toBeNull();
|
||||||
|
});
|
||||||
|
it('accesibilidad: el nombre del conjunto, barras decorativas y cada dato leído una sola vez', () => {
|
||||||
|
const r = montar(citologia());
|
||||||
|
expect(r.querySelector('[role=group]')!.getAttribute('aria-label')).toBe('Resultados');
|
||||||
|
expect([...r.querySelectorAll('.pista, .eje')].every(e => e.getAttribute('aria-hidden') === 'true')).toBe(true);
|
||||||
|
expect(r.querySelectorAll('[role=img]')).toHaveLength(0); expect(r.querySelectorAll('[aria-label]:not(.barras):not(.grupo)')).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { Component, computed, input } from '@angular/core';
|
||||||
|
import { NgTemplateOutlet } from '@angular/common';
|
||||||
|
import { shareText } from './indicadores-format';
|
||||||
|
import { ConjuntoBarras, FilaBarra, GrupoBarras, limiteEscala, maximoDelConjunto, sumaActivas } from './indicadores-barras';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Horizontal bars of one indicator: a bar per category with its name at the left and «count · % of the total» at the
|
||||||
|
* right, clinical groups as headers with their subtotal. The scale is the absolute count, from 0 to a rounded upper
|
||||||
|
* limit that is written under the bars; the bar of a value is exactly its share of that limit (no minimum length).
|
||||||
|
* A value too short to see keeps its figure and gets a hollow marker at its position; a published zero has a dotted
|
||||||
|
* tick and no bar; an unavailable value has a hatched track and says so.
|
||||||
|
*/
|
||||||
|
@Component({
|
||||||
|
selector: 'app-barras-horizontales',
|
||||||
|
imports: [NgTemplateOutlet],
|
||||||
|
template: `
|
||||||
|
@let c = conjunto();
|
||||||
|
<div class="barras" role="group" [attr.aria-label]="titulo()">
|
||||||
|
<p class="den">@if (c.den !== null) { Total: <strong>{{ c.den.toLocaleString('es-MX') }}</strong> {{ c.unidad }}. Barras en cantidades; porcentaje del total. } @else { Total de {{ c.unidad }} no disponible: se muestran las cantidades publicadas, sin porcentaje. }</p>
|
||||||
|
@if (seleccionado(); as s) { <p class="seleccion" role="status">Selección: <strong>{{ s.toLocaleString('es-MX') }}</strong>@if (c.den !== null) { de {{ c.den.toLocaleString('es-MX') }} ({{ pct(s) }}) } </p> }
|
||||||
|
@for (g of c.grupos; track g.id ?? $index) {
|
||||||
|
@if (g.etiqueta) {
|
||||||
|
<div class="grupo" role="group" [attr.aria-label]="g.etiqueta" [style.--c]="g.color">
|
||||||
|
<div class="fila cabecera" [class.atenuada]="atenuado(g)">
|
||||||
|
<span class="et"><span class="marca-grupo">Grupo</span> {{ g.etiqueta }}</span>{{ ' ' }}
|
||||||
|
{{ ' ' }}<span class="pista" aria-hidden="true">@if (g.subtotal !== null && g.subtotal > 0) { <i [style.width.%]="ancho(g.subtotal)"></i> }</span>
|
||||||
|
<span class="v">@if (g.subtotal !== null) { <strong>{{ g.subtotal.toLocaleString('es-MX') }}</strong>{{ ' ' }}@if (c.den !== null) { <small>{{ pct(g.subtotal) }}</small> } } @else { <strong>No disponible</strong> }</span>
|
||||||
|
</div>
|
||||||
|
<ul class="filas hijas">@for (f of g.filas; track f.id) { <ng-container [ngTemplateOutlet]="fila" [ngTemplateOutletContext]="{ f: f }" /> }</ul>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<ul class="filas">@for (f of g.filas; track f.id) { <ng-container [ngTemplateOutlet]="fila" [ngTemplateOutletContext]="{ f: f }" /> }</ul>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<div class="eje" aria-hidden="true"><span></span><div class="marcas"><span>0</span><span>{{ (limite() / 2).toLocaleString('es-MX') }}</span><span>{{ limite().toLocaleString('es-MX') }}</span></div><span></span></div>
|
||||||
|
<p class="titulo-eje">Escala: cantidad de {{ c.unidad }} (de 0 a {{ limite().toLocaleString('es-MX') }})</p>
|
||||||
|
</div>
|
||||||
|
<ng-template #fila let-f="f">
|
||||||
|
<li class="fila" [class.atenuada]="atenuado(f)" [class.nd]="f.n === null" [class.cero]="f.n === 0" [style.--c]="f.color">
|
||||||
|
<span class="et">{{ f.etiqueta }}</span>{{ ' ' }}
|
||||||
|
<span class="pista" aria-hidden="true">
|
||||||
|
@if (f.n !== null && f.n > 0) { <i [style.width.%]="ancho(f.n)"></i> @if (ancho(f.n) < 2) { <b class="minima" [style.left.%]="ancho(f.n)"></b> } }
|
||||||
|
@if (f.n === 0) { <u class="cero-marca"></u> }
|
||||||
|
</span>
|
||||||
|
<span class="v">@if (f.n === null) { <strong>{{ f.estado === 'Suprimido' ? 'Suprimido' : 'No disponible' }}</strong> }
|
||||||
|
@else { <strong>{{ f.n.toLocaleString('es-MX') }}</strong>{{ ' ' }}@if (c.den !== null) { <small>{{ pct(f.n) }}</small> } @else { <small>% no disponible</small> } }</span>
|
||||||
|
</li>
|
||||||
|
</ng-template>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
:host { display: block; min-width: 0; container-type: inline-size; }
|
||||||
|
.den, .seleccion, .titulo-eje { margin: 0 0 .4rem; font-size: .85rem; color: var(--issste-text-secondary); }
|
||||||
|
.den strong, .seleccion strong { color: var(--issste-text); }
|
||||||
|
.titulo-eje { margin: .15rem 0 0; font-size: .75rem; }
|
||||||
|
ul { margin: 0; padding: 0; list-style: none; }
|
||||||
|
.filas { display: grid; gap: .3rem; }
|
||||||
|
.fila { display: grid; grid-template-columns: minmax(0, min(17rem, 35%)) minmax(0, 1fr) 7.6rem; align-items: center; gap: .5rem; transition: opacity .15s; }
|
||||||
|
.fila.atenuada { opacity: .45; }
|
||||||
|
.et { font-size: .85rem; line-height: 1.2; overflow-wrap: anywhere; }
|
||||||
|
.pista { position: relative; height: 1rem; background: linear-gradient(90deg, var(--issste-border) 1px, transparent 1px) 0 0 / 50% 100% repeat-x, linear-gradient(270deg, var(--issste-border) 1px, transparent 1px); }
|
||||||
|
.pista i { position: absolute; inset: 0 auto 0 0; background: var(--c); border-radius: 0 2px 2px 0; }
|
||||||
|
.minima { position: absolute; top: 50%; width: .5rem; height: .5rem; box-sizing: border-box; border: 2px solid var(--c); border-radius: 50%; background: var(--issste-surface); transform: translate(-50%, -50%); }
|
||||||
|
.cero-marca { position: absolute; inset: .15rem auto .15rem 0; border-left: 2px dotted var(--c); }
|
||||||
|
.nd .pista { background: repeating-linear-gradient(45deg, var(--issste-border) 0 4px, var(--issste-surface) 4px 8px); }
|
||||||
|
.v { text-align: end; font-variant-numeric: tabular-nums; font-size: .85rem; white-space: nowrap; }
|
||||||
|
.v small { margin-inline-start: .3rem; color: var(--issste-text-secondary); font-size: .8rem; }
|
||||||
|
.grupo { margin-top: .5rem; }
|
||||||
|
.cabecera { font-weight: 600; }
|
||||||
|
.cabecera .pista { height: .4rem; background: var(--issste-border); }
|
||||||
|
.cabecera .pista i { opacity: .45; border-radius: 0; }
|
||||||
|
.marca-grupo { display: inline-block; margin-inline-end: .25rem; padding: 0 .3rem; border: 1px solid currentColor; border-radius: 3px; font-size: .65rem; font-weight: 500; color: var(--issste-text-secondary); text-transform: uppercase; }
|
||||||
|
.hijas { margin: .25rem 0 0; padding-inline-start: .75rem; border-inline-start: 3px solid var(--c); }
|
||||||
|
.eje { display: grid; grid-template-columns: minmax(0, min(17rem, 35%)) minmax(0, 1fr) 7.6rem; gap: .5rem; margin-top: .25rem; font-size: .7rem; color: var(--issste-text-secondary); }
|
||||||
|
.marcas { display: flex; justify-content: space-between; }
|
||||||
|
@container (max-width: 25rem) {
|
||||||
|
.fila, .eje { grid-template-columns: minmax(0, 1fr) auto; row-gap: .1rem; }
|
||||||
|
.fila .pista { grid-column: 1 / -1; grid-row: 2; }
|
||||||
|
.eje > span:first-child, .eje > span:last-child { display: none; }
|
||||||
|
.eje { grid-template-columns: 1fr; }
|
||||||
|
.hijas { padding-inline-start: .5rem; }
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class BarrasHorizontales {
|
||||||
|
readonly conjunto = input.required<ConjuntoBarras>();
|
||||||
|
/** Accessible name of the whole chart. */
|
||||||
|
readonly titulo = input.required<string>();
|
||||||
|
readonly limite = computed(() => limiteEscala(maximoDelConjunto(this.conjunto())));
|
||||||
|
readonly seleccionado = computed(() => sumaActivas(this.conjunto()));
|
||||||
|
ancho(n: number) { return 100 * n / this.limite(); }
|
||||||
|
pct(n: number) { const d = this.conjunto().den; return d ? shareText(n, d) : ''; }
|
||||||
|
/** With a selection, what is not selected is dimmed, as the donut did. */
|
||||||
|
atenuado(x: FilaBarra | GrupoBarras) {
|
||||||
|
const a = this.conjunto().activas;
|
||||||
|
if (!a) return false;
|
||||||
|
return 'filas' in x ? !x.filas.some(f => a.has(f.id)) : !a.has(x.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,43 @@
|
|||||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
import { RutaResumen } from './ruta-tamizaje/ruta-tamizaje';
|
||||||
|
export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia';
|
||||||
|
export type OrdenSeguimiento = 'reciente' | ProbabilidadClave;
|
||||||
|
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string;
|
||||||
|
/** CaCu: partial identifier search, applied by the server before it counts and paginates. */
|
||||||
|
q?: string;
|
||||||
|
/** CaCu: asks for the screening route block of each row. */
|
||||||
|
incluir?: 'ruta_tamizaje';
|
||||||
|
/** CaCu: inclusive age range at the cut-off date, applied by the server. */
|
||||||
|
edad_min?: number; edad_max?: number;
|
||||||
|
page: number; page_size: number; }
|
||||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||||
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||||
export interface SeguimientoPaciente {
|
export interface SeguimientoPaciente {
|
||||||
pac_id?: string;
|
pac_id?: string;
|
||||||
id_seudonimo?: string;
|
id_seudonimo?: string;
|
||||||
grupo_edad: string;
|
grupo_edad: string;
|
||||||
|
/** CaCu: her age in whole years at the cut-off date (`edad_al_corte`), when the service gives it. */
|
||||||
|
edad_al_corte?: number | null;
|
||||||
estatus: SeguimientoStatus;
|
estatus: SeguimientoStatus;
|
||||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||||
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
||||||
dias_toma_diagnostico: number | null;
|
dias_toma_diagnostico: number | null;
|
||||||
|
/** CaCu: her latest biopsy reported by the cut-off, with its grade. */
|
||||||
|
ultima_biopsia?: { fecha: string; grado: string | null } | null;
|
||||||
|
/** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */
|
||||||
|
probabilidades?: Partial<Record<ProbabilidadClave, ProbabilidadHorizonte[]>> | null;
|
||||||
prioridad: SeguimientoStatus | null;
|
prioridad: SeguimientoStatus | null;
|
||||||
|
/** CaCu: present only when the list was asked `incluir=ruta_tamizaje`; null when the row has no selected cytology. */
|
||||||
|
ruta_tamizaje?: RutaResumen | null;
|
||||||
}
|
}
|
||||||
|
export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; }
|
||||||
export interface SeguimientoResponse {
|
export interface SeguimientoResponse {
|
||||||
simulado: boolean;
|
simulado: boolean;
|
||||||
corte: string;
|
corte: string;
|
||||||
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
||||||
filtros: { estatus: string | null };
|
/** `q`, `edad_min` and `edad_max` are the parameters the server applied (null: none); older servers omit them. */
|
||||||
|
filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number; q?: string | null; edad_min?: number | null; edad_max?: number | null };
|
||||||
|
/** The horizons the models give, in years, for ordering and showing the probabilities. */
|
||||||
|
horizontes_disponibles?: number[];
|
||||||
estatus_disponibles: SeguimientoStatus[];
|
estatus_disponibles: SeguimientoStatus[];
|
||||||
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
|
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
|
||||||
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
||||||
@@ -26,6 +48,50 @@ export function isoDate(value: unknown): value is string {
|
|||||||
const date = new Date(value + 'T00:00:00Z');
|
const date = new Date(value + 'T00:00:00Z');
|
||||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||||
}
|
}
|
||||||
|
/** Her exact age in whole years; null when the service does not give one. It is never derived from the age group. */
|
||||||
|
export function edadAnios(item: Pick<SeguimientoPaciente, 'edad_al_corte'>): number | null {
|
||||||
|
const edad = item.edad_al_corte;
|
||||||
|
return typeof edad === 'number' && Number.isInteger(edad) && edad >= 0 ? edad : null;
|
||||||
|
}
|
||||||
|
export function edadTexto(item: Pick<SeguimientoPaciente, 'edad_al_corte'>): string {
|
||||||
|
const edad = edadAnios(item);
|
||||||
|
return edad === null ? 'No disponible' : `${edad} ${edad === 1 ? 'año' : 'años'}`;
|
||||||
|
}
|
||||||
|
/** The search text as sent: trimmed, inner whitespace collapsed; empty means no search. */
|
||||||
|
export function normalizarConsulta(texto: string | undefined): string { return (texto ?? '').trim().replace(/\s+/g, ' '); }
|
||||||
|
/** The search text WebApi admits, in characters, once normalized. */
|
||||||
|
export const CONSULTA_MAXIMA = 100;
|
||||||
|
/** A bound is a whole number of years, 0 or more (as WebApi admits); the range needs min <= max. */
|
||||||
|
export function rangoEdadValido(min: number | undefined, max: number | undefined): boolean {
|
||||||
|
const entero = (n: number | undefined) => n === undefined || (Number.isInteger(n) && n >= 0);
|
||||||
|
return entero(min) && entero(max) && (min === undefined || max === undefined || min <= max);
|
||||||
|
}
|
||||||
|
/** True when a returned row breaks the query it answers: the server did not apply the search or the age range. */
|
||||||
|
export function incumpleConsulta(q: Pick<SeguimientoQuery, 'q' | 'edad_min' | 'edad_max'>, id: string, item: Pick<SeguimientoPaciente, 'edad_al_corte'>): boolean {
|
||||||
|
const texto = normalizarConsulta(q.q).normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
|
||||||
|
if (texto && !id.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().includes(texto)) return true;
|
||||||
|
const edad = edadAnios(item);
|
||||||
|
// Under an age range a row with no age is outside the contract: WebApi leaves those out.
|
||||||
|
if (q.edad_min === undefined && q.edad_max === undefined) return false;
|
||||||
|
return edad === null || (q.edad_min !== undefined && edad < q.edad_min) || (q.edad_max !== undefined && edad > q.edad_max);
|
||||||
|
}
|
||||||
|
/** The search and age range the server says it applied, against the ones asked: every active parameter must come back equal. */
|
||||||
|
export function filtrosConfirmados(q: Pick<SeguimientoQuery, 'q' | 'edad_min' | 'edad_max'>, filtros: SeguimientoResponse['filtros']): boolean {
|
||||||
|
const texto = normalizarConsulta(q.q);
|
||||||
|
return (!texto || filtros.q === texto) && (q.edad_min === undefined || filtros.edad_min === q.edad_min) && (q.edad_max === undefined || filtros.edad_max === q.edad_max);
|
||||||
|
}
|
||||||
export function latestStudy(item: SeguimientoPaciente): string | null {
|
export function latestStudy(item: SeguimientoPaciente): string | null {
|
||||||
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
|
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
|
||||||
}
|
}
|
||||||
|
/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */
|
||||||
|
export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined {
|
||||||
|
return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte);
|
||||||
|
}
|
||||||
|
/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival).
|
||||||
|
* Every patient or an unknown status shows none: each scenario has its own models. */
|
||||||
|
export const COLUMNAS_DE_PROBABILIDAD: Readonly<Record<string, readonly ProbabilidadClave[]>> = {
|
||||||
|
CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'],
|
||||||
|
};
|
||||||
|
export const ETIQUETA_PROBABILIDAD: Readonly<Record<ProbabilidadClave, string>> = {
|
||||||
|
lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia',
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,41 +1,70 @@
|
|||||||
import { inject, Injectable } from '@angular/core';
|
import { inject, Injectable } from '@angular/core';
|
||||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
import { map } from 'rxjs';
|
import { map } from 'rxjs';
|
||||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
import { CONSULTA_MAXIMA, isoDate, normalizarConsulta, rangoEdadValido, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||||
import { identidadDe, identidadesDe } from './paciente-identidad';
|
import { identidadDe, identidadesDe } from './paciente-identidad';
|
||||||
|
import { RutaDetalle, rutaDetalleValida, rutaResumenValida, urlDetalleValida } from './ruta-tamizaje/ruta-tamizaje';
|
||||||
|
import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||||
|
const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia'];
|
||||||
|
// The exact age is optional: an API that does not give it still validates, and the table says so.
|
||||||
|
const edad = (v: unknown) => v === undefined || v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= 130;
|
||||||
|
const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
|
||||||
|
const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
|
||||||
|
// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates.
|
||||||
|
const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string');
|
||||||
|
const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) =>
|
||||||
|
['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad'])
|
||||||
|
&& (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto']))));
|
||||||
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
||||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= 200;
|
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX
|
||||||
|
&& rangoEdadValido(q.edad_min, q.edad_max) && normalizarConsulta(q.q).length <= CONSULTA_MAXIMA;
|
||||||
}
|
}
|
||||||
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||||
// The current authorization covers demonstration records only. Validate this
|
if (!record(v) || typeof v['simulado'] !== 'boolean') throw new Error('Respuesta de seguimiento inválida');
|
||||||
// before passing any item to the component; real-patient activation is separate.
|
|
||||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
|
||||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||||
|
|| (filters['q'] !== undefined && filters['q'] !== null && typeof filters['q'] !== 'string')
|
||||||
|
|| !edad(filters['edad_min']) || !edad(filters['edad_max'])
|
||||||
|
|| (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string))
|
||||||
|
|| (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios)))
|
||||||
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
||||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||||
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !edad(item['edad_al_corte']) || !status(item['estatus'])) return false;
|
||||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']))
|
||||||
|
&& biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades'])
|
||||||
|
&& (item['ruta_tamizaje'] === undefined || item['ruta_tamizaje'] === null || rutaResumenValida(item['ruta_tamizaje']));
|
||||||
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
|
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
|
||||||
return v as unknown as SeguimientoResponse;
|
return v as unknown as SeguimientoResponse;
|
||||||
}
|
}
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
export class CacuSeguimientoService {
|
export class CacuSeguimientoService {
|
||||||
private readonly http = inject(HttpClient);
|
private readonly http = inject(HttpClient);
|
||||||
|
/** The detail of one route, from the `detalle_url` of the list; only a path of this service's own routes is requested. */
|
||||||
|
detalleRuta(url: string) {
|
||||||
|
if (!urlDetalleValida(url)) throw new Error('Ruta de detalle inválida');
|
||||||
|
return this.http.get<unknown>(url).pipe(map((v): RutaDetalle => { if (!rutaDetalleValida(v)) throw new Error('Detalle de ruta inválido'); return v; }));
|
||||||
|
}
|
||||||
consultar(query: SeguimientoQuery) {
|
consultar(query: SeguimientoQuery) {
|
||||||
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
|
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
|
||||||
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
||||||
if (query.corte) params = params.set('corte', query.corte);
|
if (query.corte) params = params.set('corte', query.corte);
|
||||||
if (query.estatus) params = params.set('estatus', query.estatus);
|
if (query.estatus) params = params.set('estatus', query.estatus);
|
||||||
|
if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden);
|
||||||
|
if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte);
|
||||||
|
const q = normalizarConsulta(query.q);
|
||||||
|
if (q) params = params.set('q', q);
|
||||||
|
if (query.edad_min !== undefined) params = params.set('edad_min', query.edad_min);
|
||||||
|
if (query.edad_max !== undefined) params = params.set('edad_max', query.edad_max);
|
||||||
|
if (query.incluir) params = params.set('incluir', query.incluir);
|
||||||
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
|||||||
import fixtureData from './fixtures/cacu_seguimiento.json';
|
import fixtureData from './fixtures/cacu_seguimiento.json';
|
||||||
import { CacuSeguimientoService, seguimientoResponse } from './cacu-seguimiento.service';
|
import { CacuSeguimientoService, seguimientoResponse } from './cacu-seguimiento.service';
|
||||||
import { latestStudy } from './cacu-seguimiento.models';
|
import { latestStudy } from './cacu-seguimiento.models';
|
||||||
|
import { tablaExportacionCaCu } from './export/cacu-tracking-export';
|
||||||
import { IndicadoresTracking } from './indicadores-tracking';
|
import { IndicadoresTracking } from './indicadores-tracking';
|
||||||
|
|
||||||
describe('Seguimiento CaCu con contrato de demostración', () => {
|
describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||||
@@ -24,10 +25,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
||||||
fixture.componentInstance.apply();
|
fixture.componentInstance.apply();
|
||||||
let req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
let req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
expect(req.request.params.keys().sort()).toEqual(['corte', 'incluir', 'meses', 'page', 'page_size']);
|
||||||
req.flush(fixtureData); fixture.detectChanges();
|
req.flush(fixtureData); fixture.detectChanges();
|
||||||
fixture.componentInstance.navigate(2); req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
fixture.componentInstance.navigate(2); req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
expect(req.request.params.keys().sort()).toEqual(['corte', 'incluir', 'meses', 'page', 'page_size']);
|
||||||
expect(req.request.params.get('page')).toBe('2');
|
expect(req.request.params.get('page')).toBe('2');
|
||||||
req.flush({ ...fixtureData, paginacion: { ...fixtureData.paginacion, page: 2 } });
|
req.flush({ ...fixtureData, paginacion: { ...fixtureData.paginacion, page: 2 } });
|
||||||
});
|
});
|
||||||
@@ -36,12 +37,13 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
const root:HTMLElement=fixture.nativeElement;
|
const root:HTMLElement=fixture.nativeElement;
|
||||||
expect(root.textContent).not.toContain('Datos simulados — uso de demostración');
|
expect(root.textContent).not.toContain('Datos simulados — uso de demostración');
|
||||||
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
|
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
|
||||||
|
expect(root.querySelector('h2')?.textContent).toBe('Modelos de riesgo asociados a cáncer cervicouterino');
|
||||||
expect(root.textContent).toContain('Ventana consultada:');
|
expect(root.textContent).toContain('Ventana consultada:');
|
||||||
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
|
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
|
||||||
expect(root.textContent).toContain('Insatisfactoria');
|
expect(root.textContent).toContain('Insatisfactoria');
|
||||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
|
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
|
||||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
|
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
|
||||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
|
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9);
|
||||||
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
||||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||||
@@ -77,6 +79,243 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
fixture.componentRef.setInput('active',false); fixture.detectChanges(); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
fixture.componentRef.setInput('active',false); fixture.detectChanges(); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||||
expect(fixture.componentInstance.data?.paginacion.page).toBe(2);
|
expect(fixture.componentInstance.data?.paginacion.page).toBe(2);
|
||||||
});
|
});
|
||||||
|
// API-01: the search and the age range are the server's; WebApp sends them, shows what comes back and nothing else.
|
||||||
|
describe('búsqueda global y rango de edad', () => {
|
||||||
|
const consultas = () => http.match(r => r.url === '/cacu/seguimiento');
|
||||||
|
const escribir = (texto: string) => {
|
||||||
|
const input = fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement;
|
||||||
|
input.value = texto; input.dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges();
|
||||||
|
};
|
||||||
|
const filas = () => [...fixture.nativeElement.querySelectorAll('tr[data-paciente]')].map((tr: Element) => tr.getAttribute('data-paciente'));
|
||||||
|
const respuesta = (ids: string[], extra: object = {}) => ({ ...fixtureData, ...extra,
|
||||||
|
items: ids.map((id, i) => ({ ...fixtureData.items[i], id_seudonimo: id, edad_al_corte: 45 })), paginacion: { ...fixtureData.paginacion, total_items: ids.length, total_pages: 1, ...((extra as { paginacion?: object }).paginacion ?? {}) } });
|
||||||
|
// The server echoes the parameters it applied in `filtros`, as WebApi does.
|
||||||
|
const eco = (req: { request: { params: { get(k: string): string | null } } }) => { const n = (k: string) => req.request.params.get(k) === null ? null : Number(req.request.params.get(k)); return { q: req.request.params.get('q'), edad_min: n('edad_min'), edad_max: n('edad_max') }; };
|
||||||
|
const responder = (req: { request: { params: { get(k: string): string | null } }; flush(b: unknown): void }, ids: string[], extra: Record<string, unknown> = {}) =>
|
||||||
|
req.flush(respuesta(ids, { ...extra, filtros: { ...((extra['filtros'] as object) ?? fixtureData.filtros), ...eco(req) } }));
|
||||||
|
beforeEach(() => { vi.useFakeTimers(); });
|
||||||
|
afterEach(() => { vi.useRealTimers(); });
|
||||||
|
|
||||||
|
it('espera tras la última tecla, pide la página 1 con q normalizada y muestra solo lo que devuelve el servidor', () => {
|
||||||
|
respond();
|
||||||
|
escribir('a'); escribir(' a4 2 ');
|
||||||
|
vi.advanceTimersByTime(399); expect(consultas()).toHaveLength(0);
|
||||||
|
vi.advanceTimersByTime(2);
|
||||||
|
const [req] = consultas(); expect(consultas()).toHaveLength(0);
|
||||||
|
expect(req.request.params.get('q')).toBe('a4 2'); expect(req.request.params.get('page')).toBe('1');
|
||||||
|
fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Cargando seguimiento');
|
||||||
|
responder(req, ['PRUEBA-A4 2', 'PRUEBA-A4 25']); fixture.detectChanges();
|
||||||
|
expect(filas()).toEqual(['PRUEBA-A4 2', 'PRUEBA-A4 25']);
|
||||||
|
expect(fixture.nativeElement.querySelector('#alcance-busqueda-cacu').textContent).toContain('2 registros coinciden');
|
||||||
|
// The input keeps its text and focus target while the list reloads.
|
||||||
|
expect((fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement).value).toBe(' a4 2 ');
|
||||||
|
});
|
||||||
|
it('conserva la búsqueda al paginar, reinicia a la página 1 al cambiarla y se puede limpiar', () => {
|
||||||
|
respond(); escribir('P'); vi.advanceTimersByTime(401);
|
||||||
|
responder(consultas()[0], ['P-1'], { paginacion: { total_items: 120, total_pages: 3 } }); fixture.detectChanges();
|
||||||
|
fixture.componentInstance.navigate(2);
|
||||||
|
let [req] = consultas(); expect(req.request.params.get('q')).toBe('P'); expect(req.request.params.get('page')).toBe('2');
|
||||||
|
responder(req, ['P-2'], { paginacion: { page: 2, total_items: 120, total_pages: 3 } }); fixture.detectChanges();
|
||||||
|
expect(fixture.nativeElement.querySelector('nav').textContent).toContain('120 registros');
|
||||||
|
escribir('PR'); vi.advanceTimersByTime(401);
|
||||||
|
[req] = consultas(); expect(req.request.params.get('page')).toBe('1'); expect(req.request.params.get('q')).toBe('PR');
|
||||||
|
responder(req, ['PR-1']); fixture.detectChanges();
|
||||||
|
([...fixture.nativeElement.querySelectorAll('button')] as HTMLButtonElement[]).find(b => b.textContent === 'Limpiar búsqueda')!.click();
|
||||||
|
[req] = consultas(); expect(req.request.params.has('q')).toBe(false); expect(req.request.params.get('page')).toBe('1');
|
||||||
|
responder(req, ['X-1']); fixture.detectChanges();
|
||||||
|
expect((fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement).value).toBe('');
|
||||||
|
});
|
||||||
|
// Why: a slow answer to an old search must never replace the answer to the current one.
|
||||||
|
it('una respuesta obsoleta se cancela y no sustituye a la vigente', () => {
|
||||||
|
respond(); escribir('ab'); vi.advanceTimersByTime(401);
|
||||||
|
const [vieja] = consultas();
|
||||||
|
escribir('abc'); vi.advanceTimersByTime(401);
|
||||||
|
const [nueva] = consultas();
|
||||||
|
expect(vieja.cancelled).toBe(true);
|
||||||
|
responder(nueva, ['ABC-1']); fixture.detectChanges();
|
||||||
|
expect(filas()).toEqual(['ABC-1']);
|
||||||
|
});
|
||||||
|
it('sin coincidencias lo dice y no cae en la lista local', () => {
|
||||||
|
respond(); escribir('zzz'); vi.advanceTimersByTime(401);
|
||||||
|
const [vacia] = consultas(); vacia.flush({ ...respuesta([]), filtros: { ...fixtureData.filtros, ...eco(vacia) }, paginacion: { ...fixtureData.paginacion, total_items: 0, total_pages: 0 } }); fixture.detectChanges();
|
||||||
|
expect(filas()).toEqual([]); expect(fixture.nativeElement.textContent).toContain('No hay coincidencias para la búsqueda y el rango de edad.');
|
||||||
|
});
|
||||||
|
it('el rango de edad se envía con uno o ambos límites, se limpia y no pide nada si es inválido', () => {
|
||||||
|
respond();
|
||||||
|
const c = fixture.componentInstance;
|
||||||
|
c.draft.edad_min = 40; c.apply();
|
||||||
|
let [req] = consultas(); expect(req.request.params.get('edad_min')).toBe('40'); expect(req.request.params.has('edad_max')).toBe(false);
|
||||||
|
responder(req, ['E-1']); fixture.detectChanges();
|
||||||
|
c.draft.edad_max = 49; c.apply();
|
||||||
|
[req] = consultas(); expect([req.request.params.get('edad_min'), req.request.params.get('edad_max')]).toEqual(['40', '49']);
|
||||||
|
responder(req, ['E-2']); fixture.detectChanges();
|
||||||
|
c.draft.edad_min = 60; c.apply(); fixture.detectChanges();
|
||||||
|
expect(consultas()).toHaveLength(0); expect(fixture.nativeElement.querySelector('#error-edad').textContent).toContain('desde 0');
|
||||||
|
for (const malo of [-1, 40.5]) { c.draft.edad_min = malo; c.draft.edad_max = undefined; c.apply(); expect(consultas()).toHaveLength(0); }
|
||||||
|
c.limpiarRangoEdad();
|
||||||
|
[req] = consultas(); expect(req.request.params.has('edad_min') || req.request.params.has('edad_max')).toBe(false);
|
||||||
|
responder(req, ['E-3']); fixture.detectChanges();
|
||||||
|
expect(fixture.nativeElement.querySelector('#error-edad')).toBeNull();
|
||||||
|
});
|
||||||
|
it('el rango de edad se combina con la búsqueda y con los filtros existentes sin cambiar el orden ni el horizonte', () => {
|
||||||
|
respond(); escribir('P'); vi.advanceTimersByTime(401);
|
||||||
|
responder(consultas()[0], ['P-1'], { filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'lieag', horizonte: 3 }, horizontes_disponibles: [1, 3, 5] }); fixture.detectChanges();
|
||||||
|
const c = fixture.componentInstance; c.draft.edad_max = 50; c.apply();
|
||||||
|
const [req] = consultas();
|
||||||
|
expect(['q', 'edad_max', 'estatus', 'orden', 'horizonte', 'page'].map(k => req.request.params.get(k))).toEqual(['P', '50', 'PRE_COLPOSCOPIA', 'lieag', '3', '1']);
|
||||||
|
});
|
||||||
|
// Why: an older server ignores the new parameters; a partial local result must not pass as a global search.
|
||||||
|
it('si el servidor no aplica la búsqueda o la edad, no presenta resultados parciales', () => {
|
||||||
|
respond(); escribir('a42'); vi.advanceTimersByTime(401);
|
||||||
|
consultas()[0].flush(respuesta(['OTRO-1', 'A42-2'])); fixture.detectChanges();
|
||||||
|
expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó la búsqueda');
|
||||||
|
([...fixture.nativeElement.querySelectorAll('button')] as HTMLButtonElement[]).find(b => b.textContent === 'Limpiar búsqueda')!.click();
|
||||||
|
responder(consultas()[0], ['OTRO-1']); fixture.detectChanges();
|
||||||
|
const c = fixture.componentInstance; c.draft.edad_min = 40; c.apply();
|
||||||
|
responder(consultas()[0], ['OTRO-1'], {}); fixture.detectChanges();
|
||||||
|
expect(filas()).toEqual(['OTRO-1']);
|
||||||
|
c.draft.edad_min = 40; c.apply();
|
||||||
|
const conEdad = respuesta(['E-1']); (conEdad.items[0] as { edad_al_corte?: number }).edad_al_corte = 30;
|
||||||
|
{ const [r] = consultas(); r.flush({ ...conEdad, filtros: { ...conEdad.filtros, ...eco(r) } }); } fixture.detectChanges();
|
||||||
|
expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó');
|
||||||
|
// A row without age under an age range is outside the contract too.
|
||||||
|
c.draft.edad_min = 40; c.apply(); const sinEdad = respuesta(['E-2']); (sinEdad.items[0] as { edad_al_corte?: number | null }).edad_al_corte = null;
|
||||||
|
{ const [r] = consultas(); r.flush({ ...sinEdad, filtros: { ...sinEdad.filtros, ...eco(r) } }); } fixture.detectChanges();
|
||||||
|
expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó');
|
||||||
|
});
|
||||||
|
// Why: WebApi answers 400 over 100 characters; WebApp does not send it, and a backend 400 shows its message and no rows.
|
||||||
|
it('q admite 100 caracteres: más no se envía; un 400 del servidor se anuncia sin filas', () => {
|
||||||
|
respond(); escribir('1'.repeat(101)); vi.advanceTimersByTime(401);
|
||||||
|
expect(consultas()).toHaveLength(0); fixture.detectChanges();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('hasta 100 caracteres');
|
||||||
|
escribir('1'.repeat(100)); vi.advanceTimersByTime(401);
|
||||||
|
const [req] = consultas(); expect(req.request.params.get('q')).toHaveLength(100);
|
||||||
|
req.flush({ error: 'x' }, { status: 400, statusText: 'Bad Request' }); fixture.detectChanges();
|
||||||
|
expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('Revisa');
|
||||||
|
});
|
||||||
|
// Why: the file must hold the query the server confirms, not the one WebApp hoped for.
|
||||||
|
it('la exportación valida y usa los filtros efectivos que el servidor confirma', () => {
|
||||||
|
respond();
|
||||||
|
const pedir = (filtros: Record<string, string>) => {
|
||||||
|
let tabla: { filtros: Record<string, string | null> } | undefined, error: unknown;
|
||||||
|
fixture.componentInstance.origenExportacionCaCu.consultar('cacu', { corte: fixtureData.corte, meses: 12, page: 1, page_size: 200, filtros } as never).subscribe({ next: t => tabla = t as never, error: e => error = e });
|
||||||
|
return { req: http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200'), get tabla() { return tabla; }, get error() { return error; } };
|
||||||
|
};
|
||||||
|
const sinEco = pedir({ q: 'P', edad_min: '30' });
|
||||||
|
expect(sinEco.req.request.params.get('incluir')).toBeNull();
|
||||||
|
sinEco.req.flush(respuesta(['P-1']));
|
||||||
|
expect(sinEco.error).toBeInstanceOf(Error); expect(sinEco.tabla).toBeUndefined();
|
||||||
|
const conEco = pedir({ q: 'P', edad_min: '30' });
|
||||||
|
responder(conEco.req, ['P-1']);
|
||||||
|
expect(conEco.tabla!.filtros).toMatchObject({ q: 'P', edad_min: '30', edad_max: null });
|
||||||
|
const sinFiltros = pedir({}); sinFiltros.req.flush(respuesta(['X-1']));
|
||||||
|
expect(sinFiltros.tabla).toBeDefined();
|
||||||
|
});
|
||||||
|
it('la exportación lleva la consulta completa: q, edad_min, edad_max y los demás filtros, y dice qué se aplicó', () => {
|
||||||
|
respond(); escribir('P'); vi.advanceTimersByTime(401);
|
||||||
|
responder(consultas()[0], ['P-1'], { paginacion: { total_items: 201, total_pages: 5 } }); fixture.detectChanges();
|
||||||
|
const c = fixture.componentInstance; c.draft.edad_min = 30; c.draft.edad_max = 60; c.apply();
|
||||||
|
responder(consultas()[0], ['P-1'], { paginacion: { total_items: 201, total_pages: 5 } }); fixture.detectChanges();
|
||||||
|
const tabla = c.exportacionCaCu!;
|
||||||
|
expect(tabla.filtros).toMatchObject({ q: 'P', edad_min: '30', edad_max: '60' });
|
||||||
|
expect(tabla.filtros_disponibles.filter(f => ['q', 'edad_min', 'edad_max'].includes(f.clave)).map(f => f.opciones[0].etiqueta)).toEqual(['P', '30', '60']);
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
([...root.querySelectorAll('app-seguimiento-exportar button')] as HTMLButtonElement[]).find(x => x.textContent!.includes('Excel'))!.click();
|
||||||
|
const exportacion = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200');
|
||||||
|
expect(['q', 'edad_min', 'edad_max', 'page'].map(k => exportacion.request.params.get(k))).toEqual(['P', '30', '60', '1']);
|
||||||
|
responder(exportacion, ['P-1'], { paginacion: { total_items: 1, total_pages: 1 } });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('sin edad exacta ni identificador demográfico muestra los estados correspondientes', () => {
|
||||||
|
respond();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
const fila = root.querySelector<HTMLElement>('tr[data-paciente]')!;
|
||||||
|
expect(root.querySelector('thead th:nth-child(2)')?.textContent).toBe('Edad');
|
||||||
|
expect(fila.querySelector('td:nth-child(2)')?.textContent).toContain('No disponible');
|
||||||
|
expect(fila.querySelector('td:nth-child(2)')?.textContent?.trim()).toBe('No disponible');
|
||||||
|
expect(root.textContent).not.toContain('Grupo de edad');
|
||||||
|
fila.querySelector('button')!.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
const nacimiento = [...root.querySelectorAll('app-paciente-detalle dt')].find(dt => dt.textContent === 'Fecha de nacimiento');
|
||||||
|
expect(nacimiento?.nextElementSibling?.textContent?.trim()).toBe('No se pudo cargar');
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('muestra en la ficha la fecha recuperada para el paciente seleccionado', () => {
|
||||||
|
open().flush({ ...fixtureData, items: [{ ...fixtureData.items[0], pac_id: '42' }] });
|
||||||
|
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
|
||||||
|
fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
root.querySelector<HTMLElement>('tr[data-paciente] button')!.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
http.expectOne(r => r.url === '/cacu/fhir/RiskAssessment').flush({}, { status: 404, statusText: 'Not Found' });
|
||||||
|
const nacimiento = [...root.querySelectorAll('app-paciente-detalle dt')].find(dt => dt.textContent === 'Fecha de nacimiento')!;
|
||||||
|
expect(nacimiento.nextElementSibling?.textContent).toContain('Cargando');
|
||||||
|
http.expectOne('/cacu/seguimiento/pacientes/42/demografia').flush({ pac_id: '42', fecha_nacimiento: '1980-01-02' });
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(nacimiento.nextElementSibling?.textContent?.trim()).toBe('02/01/1980');
|
||||||
|
});
|
||||||
|
// Why: the exact age is shown only when the service gives it, as whole years, and never estimated from the age group.
|
||||||
|
it('muestra la edad exacta en años y distingue la edad ausente de una edad de 0 años', () => {
|
||||||
|
const items = [{ ...fixtureData.items[0], edad_al_corte: 42 }, { ...fixtureData.items[1], edad_al_corte: 1 }, { ...fixtureData.items[2], edad_al_corte: 0 },
|
||||||
|
{ ...fixtureData.items[3], edad_al_corte: null, grupo_edad: '40-49' }, { ...fixtureData.items[4], grupo_edad: '40-49' }];
|
||||||
|
open().flush({ ...fixtureData, items, paginacion: { ...fixtureData.paginacion, total_items: 5 } });
|
||||||
|
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect([...root.querySelectorAll('tbody tr')].map(tr => tr.querySelector('td:nth-child(2)')!.textContent!.trim()))
|
||||||
|
.toEqual(['42 años', '1 año', '0 años', 'No disponible', 'No disponible']);
|
||||||
|
expect(root.querySelector('thead th:nth-child(2)')?.textContent).toBe('Edad');
|
||||||
|
expect(root.textContent).not.toContain('Grupo de edad');
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('la edad exacta solo se acepta como años enteros no negativos', () => {
|
||||||
|
const con = (edad: unknown) => () => seguimientoResponse({ ...fixtureData, items: [{ ...fixtureData.items[0], edad_al_corte: edad }] });
|
||||||
|
for (const valida of [0, 1, 42, null]) expect(con(valida)).not.toThrow();
|
||||||
|
for (const invalida of [-1, 41.5, '42', 131, Number.NaN]) expect(con(invalida)).toThrow();
|
||||||
|
});
|
||||||
|
it('el listado no tiene la columna «Estudio más reciente» y conserva su opción de orden', () => {
|
||||||
|
open().flush({ ...fixtureData, filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 }, horizontes_disponibles: [5] });
|
||||||
|
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect([...root.querySelectorAll('thead th')].map(th => th.textContent)).not.toContain('Estudio más reciente');
|
||||||
|
expect(fixture.componentInstance.ordenes().map(o => o.etiqueta)).toContain('Estudio más reciente');
|
||||||
|
expect(root.querySelectorAll('thead th')).toHaveLength(9 + fixture.componentInstance.columnasProbabilidad().length);
|
||||||
|
});
|
||||||
|
// Why: the exports must list the same columns as the screen; the study stays only as an ordering option.
|
||||||
|
it('la tabla de exportación coincide con el listado: Edad exacta, sin «Estudio más reciente» y con su opción de orden', () => {
|
||||||
|
const respuesta = seguimientoResponse({ ...fixtureData, filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 }, horizontes_disponibles: [5],
|
||||||
|
items: [{ ...fixtureData.items[0], edad_al_corte: 42 }, { ...fixtureData.items[1], grupo_edad: '40-49' }] });
|
||||||
|
const tabla = tablaExportacionCaCu(respuesta, () => 'Citología', () => null);
|
||||||
|
const claves = tabla.columnas.map(c => c.clave);
|
||||||
|
expect(claves).toContain('edad'); expect(claves).not.toContain('grupo_edad'); expect(claves).not.toContain('reciente');
|
||||||
|
expect(tabla.columnas.map(c => c.etiqueta)).not.toContain('Estudio más reciente');
|
||||||
|
expect(tabla.items.map(item => item['edad'])).toEqual(['42 años', null]);
|
||||||
|
expect(tabla.items.every(item => !('reciente' in item))).toBe(true);
|
||||||
|
expect(tabla.filtros_disponibles.find(f => f.clave === 'orden')!.opciones.map(o => o.etiqueta)).toContain('Estudio más reciente');
|
||||||
|
});
|
||||||
|
it.each(['Excel', 'PDF'])('la exportación %s usa el contrato y los filtros aplicados de CaCu, con los filtros de la consulta', formato => {
|
||||||
|
const pagina = {
|
||||||
|
...fixtureData, filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'lieag', horizonte: 3 },
|
||||||
|
paginacion: { ...fixtureData.paginacion, total_items: 201 },
|
||||||
|
};
|
||||||
|
open().flush(pagina);
|
||||||
|
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
|
||||||
|
fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
const botones = () => [...root.querySelectorAll<HTMLButtonElement>('app-seguimiento-exportar button')];
|
||||||
|
botones().find(button => button.textContent!.includes(formato))!.click();
|
||||||
|
const exportacion = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200');
|
||||||
|
expect(exportacion.request.params.get('estatus')).toBe('PRE_COLPOSCOPIA');
|
||||||
|
expect(exportacion.request.params.get('orden')).toBe('lieag');
|
||||||
|
expect(exportacion.request.params.get('horizonte')).toBe('3');
|
||||||
|
expect(exportacion.request.params.get('corte')).toBe(pagina.corte);
|
||||||
|
expect(exportacion.request.params.get('page')).toBe('1');
|
||||||
|
const items = Array.from({ length: 200 }, (_, i) => ({ ...pagina.items[0], id_seudonimo: `PRUEBA-${i}` }));
|
||||||
|
exportacion.flush({ ...pagina, items, paginacion: { page: 1, page_size: 200, total_items: 201, total_pages: 2 } });
|
||||||
|
const siguiente = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page') === '2');
|
||||||
|
fixture.detectChanges();
|
||||||
|
botones().find(button => button.textContent === 'Cancelar')!.click();
|
||||||
|
expect(siguiente.cancelled).toBe(true);
|
||||||
|
});
|
||||||
it.each([404,400,0,503])('HTTP %s no introduce registros ficticios; reintento conserva consulta', code => {
|
it.each([404,400,0,503])('HTTP %s no introduce registros ficticios; reintento conserva consulta', code => {
|
||||||
const req=open(); if(code===0) req.error(new ProgressEvent('error')); else req.flush({error:'private'}, {status:code,statusText:'Failure'});
|
const req=open(); if(code===0) req.error(new ProgressEvent('error')); else req.flush({error:'private'}, {status:code,statusText:'Failure'});
|
||||||
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); expect(fixture.nativeElement.textContent).not.toContain('private');
|
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||||
@@ -85,15 +324,66 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({}, {status:404,statusText:'Absent'}); fixture.detectChanges();
|
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({}, {status:404,statusText:'Absent'}); fixture.detectChanges();
|
||||||
expect(fixture.nativeElement.textContent).toContain('No hay registros');
|
expect(fixture.nativeElement.textContent).toContain('No hay registros');
|
||||||
});
|
});
|
||||||
it('no activa registros reales ni acepta respuestas malformadas', () => {
|
it('acepta ambas marcas de simulación y rechaza respuestas malformadas', () => {
|
||||||
expect(()=>seguimientoResponse({...fixtureData,simulado:false})).toThrow();
|
expect(seguimientoResponse({...fixtureData,simulado:false}).simulado).toBe(false);
|
||||||
|
expect(tablaExportacionCaCu(seguimientoResponse({...fixtureData,simulado:false}), () => '', () => null).simulado).toBe(false);
|
||||||
|
expect(seguimientoResponse({...fixtureData,simulado:true}).simulado).toBe(true);
|
||||||
|
expect(()=>seguimientoResponse({...fixtureData,simulado:'false'})).toThrow();
|
||||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[0],ultimo_vph:{fecha:'bad'}}]})).toThrow();
|
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[0],ultimo_vph:{fecha:'bad'}}]})).toThrow();
|
||||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
open().flush({...fixtureData,simulado:false});
|
||||||
|
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{}});
|
||||||
|
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).not.toBeNull();
|
||||||
});
|
});
|
||||||
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
||||||
const service=TestBed.inject(CacuSeguimientoService);
|
const service=TestBed.inject(CacuSeguimientoService);
|
||||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||||
http.expectNone(()=>true);
|
http.expectNone(()=>true);
|
||||||
});
|
});
|
||||||
|
// Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the
|
||||||
|
// horizon stop reaching the API (the list is paginated, so ordering happens there).
|
||||||
|
it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => {
|
||||||
|
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||||
|
...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' },
|
||||||
|
probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
|
||||||
|
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }],
|
||||||
|
cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] },
|
||||||
|
} : item);
|
||||||
|
const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } };
|
||||||
|
open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
const fila = root.querySelector('tbody tr')!;
|
||||||
|
expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %');
|
||||||
|
expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)');
|
||||||
|
expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']);
|
||||||
|
|
||||||
|
fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1;
|
||||||
|
fixture.componentInstance.apply();
|
||||||
|
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||||
|
expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1');
|
||||||
|
req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fails if the columns stop following the status filtered: each scenario has its own models.
|
||||||
|
it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => {
|
||||||
|
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||||
|
...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' },
|
||||||
|
probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item);
|
||||||
|
const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } };
|
||||||
|
open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim());
|
||||||
|
expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)');
|
||||||
|
expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false);
|
||||||
|
expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)');
|
||||||
|
expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']);
|
||||||
|
|
||||||
|
fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia';
|
||||||
|
fixture.componentInstance.apply();
|
||||||
|
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||||
|
expect(req.request.params.has('orden')).toBe(false);
|
||||||
|
req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges();
|
||||||
|
expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false);
|
||||||
|
expect(root.querySelector('select[name="orden"]')).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,14 +7,19 @@ const HISTOLOGIA: Readonly<Record<string, string>> = {
|
|||||||
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
|
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
|
||||||
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
|
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
|
||||||
};
|
};
|
||||||
|
const ESCENARIOS: Readonly<Record<string, string>> = { POST_TRATAMIENTO: 'Post-tratamiento', EN_OBSERVACION: 'En observación' };
|
||||||
|
|
||||||
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
|
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
|
||||||
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
|
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
|
||||||
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
|
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
|
||||||
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
|
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
|
||||||
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
|
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
|
||||||
|
/** The patient's clinical scenario at the cut-off: «Post-tratamiento» or «En observación». */
|
||||||
|
export const etiquetaEscenario = (codigo: string) => ESCENARIOS[codigo] ?? codigo;
|
||||||
|
|
||||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
|
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = {
|
||||||
|
birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia, escenario_clinico: etiquetaEscenario,
|
||||||
|
};
|
||||||
|
|
||||||
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
|
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
|
||||||
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
|
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { COLUMNAS_DE_PROBABILIDAD, edadAnios, edadTexto, ETIQUETA_PROBABILIDAD, normalizarConsulta, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse } from '../cacu-seguimiento.models';
|
||||||
|
import { ETIQUETA_IDENTIDAD, identidadDe } from '../paciente-identidad';
|
||||||
|
import { SeguimientoTablaQuery, SeguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||||
|
|
||||||
|
const ORDEN_RECIENTE = { codigo: 'reciente', etiqueta: 'Estudio más reciente' };
|
||||||
|
|
||||||
|
export function consultaExportacionCaCu(q: SeguimientoTablaQuery): SeguimientoQuery {
|
||||||
|
const { corte, meses, page, page_size, filtros } = q;
|
||||||
|
if (meses === 0) throw new Error('Ventana de seguimiento CaCu inválida');
|
||||||
|
const orden = filtros?.['orden'];
|
||||||
|
return {
|
||||||
|
corte, meses, page, page_size, estatus: filtros?.['estatus'],
|
||||||
|
orden: orden === 'lieag' || orden === 'cancer' || orden === 'supervivencia' ? orden : 'reciente',
|
||||||
|
horizonte: filtros?.['horizonte'] === undefined ? undefined : Number(filtros['horizonte']),
|
||||||
|
// The whole query: the file holds every record the search and the age range select, not the page on screen.
|
||||||
|
q: normalizarConsulta(filtros?.['q']) || undefined,
|
||||||
|
edad_min: filtros?.['edad_min'] === undefined ? undefined : Number(filtros['edad_min']),
|
||||||
|
edad_max: filtros?.['edad_max'] === undefined ? undefined : Number(filtros['edad_max']),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adapts the validated CaCu list to the shared export table. */
|
||||||
|
export function tablaExportacionCaCu(
|
||||||
|
respuesta: SeguimientoResponse,
|
||||||
|
citologia: (estudio: NonNullable<SeguimientoPaciente['ultima_citologia']>) => string,
|
||||||
|
probabilidad: (item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number) => string | null,
|
||||||
|
consulta: Pick<SeguimientoQuery, 'q' | 'edad_min' | 'edad_max'> = {},
|
||||||
|
): SeguimientoTablaResponse {
|
||||||
|
// The effective query is the one the server confirms; the one asked fills in for servers that do not say.
|
||||||
|
const q = normalizarConsulta(respuesta.filtros.q ?? consulta.q);
|
||||||
|
const edadMin = respuesta.filtros.edad_min ?? consulta.edad_min, edadMax = respuesta.filtros.edad_max ?? consulta.edad_max;
|
||||||
|
const identidad = (respuesta.items[0] && identidadDe(respuesta.items[0]))?.campo ?? 'id_seudonimo';
|
||||||
|
const { estatus, orden, horizonte } = respuesta.filtros;
|
||||||
|
const probabilidades = estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : [];
|
||||||
|
const horizonteMostrado = horizonte ?? 5;
|
||||||
|
return {
|
||||||
|
simulado: respuesta.simulado,
|
||||||
|
corte: respuesta.corte,
|
||||||
|
ventana: respuesta.ventana,
|
||||||
|
paginacion: respuesta.paginacion,
|
||||||
|
filtros: { estatus, orden: orden ?? 'reciente', horizonte: horizonte?.toString() ?? null,
|
||||||
|
q: q || null, edad_min: edadMin?.toString() ?? null, edad_max: edadMax?.toString() ?? null },
|
||||||
|
filtros_disponibles: [
|
||||||
|
{ clave: 'estatus', etiqueta: 'Estatus de seguimiento', opciones: respuesta.estatus_disponibles },
|
||||||
|
{ clave: 'orden', etiqueta: 'Orden', opciones: [ORDEN_RECIENTE, ...probabilidades.map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))] },
|
||||||
|
{ clave: 'horizonte', etiqueta: 'Horizonte de la probabilidad', opciones: (respuesta.horizontes_disponibles ?? [0, 1, 3, 5])
|
||||||
|
.map(h => ({ codigo: String(h), etiqueta: `${h} ${h === 1 ? 'año' : 'años'}` })) },
|
||||||
|
// Free values: the only option is the value applied, so the files say what was searched.
|
||||||
|
{ clave: 'q', etiqueta: 'Identificador contiene', opciones: q ? [{ codigo: q, etiqueta: q }] : [] },
|
||||||
|
{ clave: 'edad_min', etiqueta: 'Edad mínima (años)', opciones: edadMin == null ? [] : [{ codigo: String(edadMin), etiqueta: String(edadMin) }] },
|
||||||
|
{ clave: 'edad_max', etiqueta: 'Edad máxima (años)', opciones: edadMax == null ? [] : [{ codigo: String(edadMax), etiqueta: String(edadMax) }] },
|
||||||
|
],
|
||||||
|
columnas: [
|
||||||
|
{ clave: identidad, etiqueta: ETIQUETA_IDENTIDAD[identidad] },
|
||||||
|
{ clave: 'edad', etiqueta: 'Edad' },
|
||||||
|
{ clave: 'estatus', etiqueta: 'Estatus de seguimiento' },
|
||||||
|
{ clave: 'citologia', etiqueta: 'Última citología', detalles: [{ clave: 'fecha_citologia', etiqueta: 'Fecha' }, { clave: 'calidad', etiqueta: 'Calidad' }] },
|
||||||
|
{ clave: 'vph', etiqueta: 'Último resultado de VPH', detalles: [{ clave: 'fecha_vph', etiqueta: 'Fecha' }, { clave: 'genotipo', etiqueta: 'Genotipo 16/18' }] },
|
||||||
|
{ clave: 'biopsia', etiqueta: 'Última biopsia', detalles: [{ clave: 'fecha_biopsia', etiqueta: 'Fecha' }] },
|
||||||
|
...probabilidades.map(clave => ({ clave, etiqueta: `${ETIQUETA_PROBABILIDAD[clave]} a ${horizonteMostrado} años (%)` })),
|
||||||
|
{ clave: 'dias', etiqueta: 'Días de toma a diagnóstico' },
|
||||||
|
{ clave: 'prioridad', etiqueta: 'Prioridad' },
|
||||||
|
],
|
||||||
|
items: respuesta.items.map(item => ({
|
||||||
|
[identidad]: identidadDe(item)!.id,
|
||||||
|
edad: edadAnios(item) === null ? null : edadTexto(item),
|
||||||
|
estatus: item.estatus.etiqueta,
|
||||||
|
citologia: item.ultima_citologia ? citologia(item.ultima_citologia) : null,
|
||||||
|
fecha_citologia: item.ultima_citologia?.fecha ?? null,
|
||||||
|
calidad: item.ultima_citologia?.calidad ?? null,
|
||||||
|
vph: item.ultimo_vph?.resultado ?? null,
|
||||||
|
fecha_vph: item.ultimo_vph?.fecha ?? null,
|
||||||
|
genotipo: item.ultimo_vph?.genotipo_16_18 == null ? null : item.ultimo_vph.genotipo_16_18 ? 'Presente' : 'No detectado',
|
||||||
|
biopsia: item.ultima_biopsia ? item.ultima_biopsia.grado ?? 'Sin grado' : null,
|
||||||
|
fecha_biopsia: item.ultima_biopsia?.fecha ?? null,
|
||||||
|
...Object.fromEntries(probabilidades.map(c => [c, probabilidad(item, c, horizonteMostrado)])),
|
||||||
|
dias: item.dias_toma_diagnostico,
|
||||||
|
prioridad: item.prioridad?.etiqueta ?? null,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ const pad = (n: number) => String(n).padStart(2, '0');
|
|||||||
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
|
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
|
||||||
* patient identifier, because file names end up in download lists, backups and mail attachments.
|
* patient identifier, because file names end up in download lists, backups and mail attachments.
|
||||||
*/
|
*/
|
||||||
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama' | 'seguimiento-cancer-cervicouterino' | 'ficha-cancer-cervicouterino', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
||||||
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
|
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
|
||||||
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
|
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,9 +57,11 @@ export class TrackingExportBar {
|
|||||||
readonly habilitado = input(true);
|
readonly habilitado = input(true);
|
||||||
/** How the analysis named the selection this answer belongs to; it travels into the files. */
|
/** How the analysis named the selection this answer belongs to; it travels into the files. */
|
||||||
readonly seleccion = input<string | undefined>(undefined);
|
readonly seleccion = input<string | undefined>(undefined);
|
||||||
|
readonly origen = input<Pick<SeguimientoTablaService, 'consultar'> | undefined>();
|
||||||
|
|
||||||
private readonly service = inject(SeguimientoTablaService);
|
private readonly service = inject(SeguimientoTablaService);
|
||||||
private subscription?: Subscription;
|
private subscription?: Subscription;
|
||||||
|
private exportacion = 0;
|
||||||
readonly formatos: readonly ExportFormat[] = ['xlsx', 'pdf'];
|
readonly formatos: readonly ExportFormat[] = ['xlsx', 'pdf'];
|
||||||
readonly label = FORMAT_LABEL;
|
readonly label = FORMAT_LABEL;
|
||||||
readonly limits = EXPORT_LIMITS;
|
readonly limits = EXPORT_LIMITS;
|
||||||
@@ -80,14 +82,14 @@ export class TrackingExportBar {
|
|||||||
});
|
});
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
inject(DestroyRef).onDestroy(() => this.detenerExportacion());
|
||||||
// A result message belongs to the query it was made for: it goes away when another query is shown. An export still
|
// A result message belongs to the query it was made for: it goes away when another query is shown. An export still
|
||||||
// being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one.
|
// being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one.
|
||||||
effect(() => {
|
effect(() => {
|
||||||
this.queryKey();
|
this.queryKey();
|
||||||
untracked(() => {
|
untracked(() => {
|
||||||
if (this.estado() === 'working') {
|
if (this.estado() === 'working') {
|
||||||
this.subscription?.unsubscribe();
|
this.detenerExportacion();
|
||||||
this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.');
|
this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.');
|
||||||
} else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); }
|
} else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); }
|
||||||
});
|
});
|
||||||
@@ -101,35 +103,44 @@ export class TrackingExportBar {
|
|||||||
exportar(formato: ExportFormat) {
|
exportar(formato: ExportFormat) {
|
||||||
if (!this.available(formato)) return;
|
if (!this.available(formato)) return;
|
||||||
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
|
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
|
||||||
this.subscription?.unsubscribe();
|
this.detenerExportacion();
|
||||||
|
const exportacion = this.exportacion;
|
||||||
const clave = this.queryKey(), seleccion = this.seleccion();
|
const clave = this.queryKey(), seleccion = this.seleccion();
|
||||||
this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
const esCaCu = this.dominio() === 'cacu';
|
||||||
|
this.subscription = fetchAllTracking(this.origen() ?? this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
||||||
next: event => {
|
next: event => {
|
||||||
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
|
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
|
||||||
else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave);
|
else void this.generar(formato, { ...event.snapshot, seleccion, titulo: esCaCu ? 'Cáncer cervicouterino' : undefined }, clave, exportacion, esCaCu);
|
||||||
},
|
},
|
||||||
error: error => this.fallar(error),
|
error: error => this.fallar(error),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
cancelar() {
|
cancelar() {
|
||||||
this.subscription?.unsubscribe();
|
this.detenerExportacion();
|
||||||
this.estado.set('idle');
|
this.estado.set('idle');
|
||||||
}
|
}
|
||||||
|
|
||||||
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) {
|
private detenerExportacion() {
|
||||||
|
this.exportacion++;
|
||||||
|
this.subscription?.unsubscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string, exportacion: number, esCaCu: boolean) {
|
||||||
try {
|
try {
|
||||||
// Each generator (and its library) downloads only when its button is used.
|
// Each generator (and its library) downloads only when its button is used.
|
||||||
const blob = formato === 'xlsx'
|
const blob = formato === 'xlsx'
|
||||||
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
|
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
|
||||||
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
|
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
|
||||||
// The query on screen changed while the file was being made: it is not the one that was asked for.
|
// The query on screen changed while the file was being made: it is not the one that was asked for.
|
||||||
if (clave !== this.queryKey()) return;
|
if (exportacion !== this.exportacion || clave !== this.queryKey()) return;
|
||||||
downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato));
|
const nombre = esCaCu ? 'seguimiento-cancer-cervicouterino'
|
||||||
|
: snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama';
|
||||||
|
downloadBlob(blob, exportFilename(nombre, snapshot.corte, formato));
|
||||||
this.estado.set('idle');
|
this.estado.set('idle');
|
||||||
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
|
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
|
||||||
} catch {
|
} catch {
|
||||||
this.fallar(new Error('generation'));
|
if (exportacion === this.exportacion && clave === this.queryKey()) this.fallar(new Error('generation'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ const sameQuery = consultaAplicada;
|
|||||||
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
|
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
|
||||||
* Unsubscribing cancels the pending requests. It fails instead of returning a partial or unstable list.
|
* Unsubscribing cancels the pending requests. It fails instead of returning a partial or unstable list.
|
||||||
*/
|
*/
|
||||||
export function fetchAllTracking(service: SeguimientoTablaService, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable<TrackingExportEvent> {
|
export function fetchAllTracking(service: Pick<SeguimientoTablaService, 'consultar'>, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable<TrackingExportEvent> {
|
||||||
const ask = (q: SeguimientoTablaQuery) => defer(() => service.consultar(dominio, q));
|
const ask = (q: SeguimientoTablaQuery) => defer(() => service.consultar(dominio, q));
|
||||||
return ask({ ...query, page: 1, page_size: PAGE_SIZE_MAX }).pipe(
|
return ask({ ...query, page: 1, page_size: PAGE_SIZE_MAX }).pipe(
|
||||||
switchMap(first => {
|
switchMap(first => {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export type TrackingRow = Record<string, SeguimientoValor>;
|
|||||||
|
|
||||||
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
|
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
|
||||||
export interface TrackingSnapshot {
|
export interface TrackingSnapshot {
|
||||||
|
titulo?: string;
|
||||||
/** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */
|
/** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */
|
||||||
seleccion?: string;
|
seleccion?: string;
|
||||||
corte: string;
|
corte: string;
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ function dataTable(snapshot: TrackingSnapshot) {
|
|||||||
|
|
||||||
/** The document definition of a follow-up report. Exported so its content can be checked without rendering. */
|
/** The document definition of a follow-up report. Exported so its content can be checked without rendering. */
|
||||||
export function trackingDocument(snapshot: TrackingSnapshot, now: Date, logo?: string): PdfDefinition {
|
export function trackingDocument(snapshot: TrackingSnapshot, now: Date, logo?: string): PdfDefinition {
|
||||||
return institutionalDocument({ title: TRACKING_TITLE, logo, now, orientation: 'landscape' }, [
|
return institutionalDocument({ title: snapshot.titulo ?? TRACKING_TITLE, logo, now, orientation: 'landscape' }, [
|
||||||
{ text: 'Resultados de seguimiento', style: 'h1' },
|
{ text: 'Resultados de seguimiento', style: 'h1' },
|
||||||
parameters(snapshot),
|
parameters(snapshot),
|
||||||
{ text: 'Pacientes', style: 'h2' },
|
{ text: 'Pacientes', style: 'h2' },
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData
|
|||||||
});
|
});
|
||||||
return [
|
return [
|
||||||
[header('Parámetro'), header('Valor')],
|
[header('Parámetro'), header('Valor')],
|
||||||
row('Reporte', 'Cáncer de mama'),
|
row('Reporte', snapshot.titulo ?? 'Cáncer de mama'),
|
||||||
...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []),
|
...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []),
|
||||||
row('Fecha de corte', snapshot.corte),
|
row('Fecha de corte', snapshot.corte),
|
||||||
row('Ventana consultada', ventanaConsultada(snapshot)),
|
row('Ventana consultada', ventanaConsultada(snapshot)),
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export interface Concept { coding?: Coding[]; text?: string }
|
|||||||
export interface Quantity { value?: number; unit?: string }
|
export interface Quantity { value?: number; unit?: string }
|
||||||
export interface Extension {
|
export interface Extension {
|
||||||
url: string;
|
url: string;
|
||||||
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
|
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
|
||||||
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
|
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
|
||||||
extension?: Extension[];
|
extension?: Extension[];
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,7 @@ export interface Resource {
|
|||||||
}
|
}
|
||||||
export interface Bundle extends Resource {
|
export interface Bundle extends Resource {
|
||||||
total?: number;
|
total?: number;
|
||||||
|
link?: { relation: string; url: string }[];
|
||||||
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
|
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,9 +31,9 @@ export function code(concept: Concept | undefined): string | undefined {
|
|||||||
export function display(concept: Concept | undefined): string | undefined {
|
export function display(concept: Concept | undefined): string | undefined {
|
||||||
return concept?.coding?.[0]?.display ?? concept?.text;
|
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 {
|
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;
|
return concept?.coding?.find(c => c.system === url)?.code;
|
||||||
}
|
}
|
||||||
// The extensions named `name` (the last segment of their URL).
|
// The extensions named `name` (the last segment of their URL).
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"cacu/CACU-CONFIRMACION-CITOLOGIA": {
|
"cacu/CACU-CONFIRMACION-CITOLOGIA": {
|
||||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
"id": "cacu_confirmacion_citologia",
|
||||||
"indicador": {
|
"indicador": {
|
||||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
"id": "cacu_confirmacion_citologia",
|
||||||
"version": "0.1.2",
|
"version": "0.1.2",
|
||||||
"titulo": "Tasa de confirmación histopatológica",
|
"titulo": "Tasa de confirmación histopatológica",
|
||||||
"contrato": "C2",
|
"contrato": "C2",
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
"filtros": []
|
"filtros": []
|
||||||
},
|
},
|
||||||
"metadatos": {
|
"metadatos": {
|
||||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
"id": "cacu_confirmacion_citologia",
|
||||||
"version": "0.1.2",
|
"version": "0.1.2",
|
||||||
"descripcion": "De las pacientes cuya última citología del periodo con resultado y calidad de espécimen satisfactoria es de alto grado (ASC-H, LIEAG o carcinoma in situ), cuántas tienen cada grado en la biopsia que esa citología originó, por resultado citológico. A la fecha de corte: sin un plazo máximo, una paciente «sin biopsia aún» puede pasar a un grado mientras lleguen reportes.",
|
"descripcion": "De las pacientes cuya última citología del periodo con resultado y calidad de espécimen satisfactoria es de alto grado (ASC-H, LIEAG o carcinoma in situ), cuántas tienen cada grado en la biopsia que esa citología originó, por resultado citológico. A la fecha de corte: sin un plazo máximo, una paciente «sin biopsia aún» puede pasar a un grado mientras lleguen reportes.",
|
||||||
"ficha": {
|
"ficha": {
|
||||||
@@ -41,11 +41,15 @@
|
|||||||
},
|
},
|
||||||
"datos": {
|
"datos": {
|
||||||
"total": {
|
"total": {
|
||||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
"id": "cacu_confirmacion_citologia",
|
||||||
"titulo": "Tasa de confirmación histopatológica",
|
"titulo": "Tasa de confirmación histopatológica",
|
||||||
"version": "0.1.2",
|
"version": "0.1.2",
|
||||||
"contrato": "C2",
|
"contrato": "C2",
|
||||||
"unidad": "paciente",
|
"unidad": "paciente",
|
||||||
|
"unidades_periodo": {
|
||||||
|
"2021-S1": 0,
|
||||||
|
"2025-S2": 1
|
||||||
|
},
|
||||||
"tipo_periodo": "semestre",
|
"tipo_periodo": "semestre",
|
||||||
"periodos": [
|
"periodos": [
|
||||||
"2021-S1",
|
"2021-S1",
|
||||||
@@ -80,51 +84,14 @@
|
|||||||
"filas": []
|
"filas": []
|
||||||
},
|
},
|
||||||
"citologia_alto_grado": {
|
"citologia_alto_grado": {
|
||||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
"error": "Categoría no declarada en el estrato"
|
||||||
"titulo": "Tasa de confirmación histopatológica",
|
|
||||||
"version": "0.1.2",
|
|
||||||
"contrato": "C2",
|
|
||||||
"unidad": "paciente",
|
|
||||||
"tipo_periodo": "semestre",
|
|
||||||
"periodos": [
|
|
||||||
"2021-S1",
|
|
||||||
"2025-S2"
|
|
||||||
],
|
|
||||||
"estrato": "citologia_alto_grado",
|
|
||||||
"valores_estrato": [],
|
|
||||||
"etiquetas_estrato": {},
|
|
||||||
"grupos": {
|
|
||||||
"TOTAL": "Total"
|
|
||||||
},
|
|
||||||
"categorias": {},
|
|
||||||
"grupos_de_categoria": {},
|
|
||||||
"notas": [],
|
|
||||||
"reportes": [
|
|
||||||
{
|
|
||||||
"periodo": "2021-S1",
|
|
||||||
"report_id": 35,
|
|
||||||
"periodo_inicio": "2021-01-01",
|
|
||||||
"periodo_fin": "2021-07-01",
|
|
||||||
"fecha_corte": "2026-11-16",
|
|
||||||
"generado_en": "2026-11-16T23:08:24.181623+00:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"periodo": "2025-S2",
|
|
||||||
"report_id": 44,
|
|
||||||
"periodo_inicio": "2025-07-01",
|
|
||||||
"periodo_fin": "2026-01-01",
|
|
||||||
"fecha_corte": "2026-11-16",
|
|
||||||
"generado_en": "2026-11-16T23:08:24.682752+00:00"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"filas": []
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cacu/CACU-DIAS-TOMA-DIAGNOSTICO": {
|
"cacu/CACU-DIAS-TOMA-DIAGNOSTICO": {
|
||||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
"id": "cacu_dias_toma_diagnostico",
|
||||||
"indicador": {
|
"indicador": {
|
||||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
"id": "cacu_dias_toma_diagnostico",
|
||||||
"version": "0.2.3",
|
"version": "0.2.3",
|
||||||
"titulo": "Tiempo de tamizaje a diagnóstico",
|
"titulo": "Tiempo de tamizaje a diagnóstico",
|
||||||
"contrato": "C3r",
|
"contrato": "C3r",
|
||||||
@@ -139,7 +106,7 @@
|
|||||||
"filtros": []
|
"filtros": []
|
||||||
},
|
},
|
||||||
"metadatos": {
|
"metadatos": {
|
||||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
"id": "cacu_dias_toma_diagnostico",
|
||||||
"version": "0.2.3",
|
"version": "0.2.3",
|
||||||
"descripcion": "Días naturales de la toma de cada citología del periodo 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 citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.",
|
"descripcion": "Días naturales de la toma de cada citología del periodo 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 citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.",
|
||||||
"ficha": {
|
"ficha": {
|
||||||
@@ -171,7 +138,7 @@
|
|||||||
},
|
},
|
||||||
"datos": {
|
"datos": {
|
||||||
"total": {
|
"total": {
|
||||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
"id": "cacu_dias_toma_diagnostico",
|
||||||
"titulo": "Tiempo de tamizaje a diagnóstico",
|
"titulo": "Tiempo de tamizaje a diagnóstico",
|
||||||
"version": "0.2.3",
|
"version": "0.2.3",
|
||||||
"contrato": "C3r",
|
"contrato": "C3r",
|
||||||
@@ -239,9 +206,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cacu/CACU-EU-TIEMPO-REPORTE": {
|
"cacu/CACU-EU-TIEMPO-REPORTE": {
|
||||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
"id": "cacu_eu_tiempo_reporte",
|
||||||
"indicador": {
|
"indicador": {
|
||||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
"id": "cacu_eu_tiempo_reporte",
|
||||||
"version": "0.2.1",
|
"version": "0.2.1",
|
||||||
"titulo": "Días de la toma de la citología a su resultado",
|
"titulo": "Días de la toma de la citología a su resultado",
|
||||||
"contrato": "C3r",
|
"contrato": "C3r",
|
||||||
@@ -256,7 +223,7 @@
|
|||||||
"filtros": []
|
"filtros": []
|
||||||
},
|
},
|
||||||
"metadatos": {
|
"metadatos": {
|
||||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
"id": "cacu_eu_tiempo_reporte",
|
||||||
"version": "0.2.1",
|
"version": "0.2.1",
|
||||||
"descripcion": "Días naturales de la toma de cada citología del periodo 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.",
|
"descripcion": "Días naturales de la toma de cada citología del periodo 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.",
|
||||||
"ficha": {
|
"ficha": {
|
||||||
@@ -288,7 +255,7 @@
|
|||||||
},
|
},
|
||||||
"datos": {
|
"datos": {
|
||||||
"total": {
|
"total": {
|
||||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
"id": "cacu_eu_tiempo_reporte",
|
||||||
"titulo": "Días de la toma de la citología a su resultado",
|
"titulo": "Días de la toma de la citología a su resultado",
|
||||||
"version": "0.2.1",
|
"version": "0.2.1",
|
||||||
"contrato": "C3r",
|
"contrato": "C3r",
|
||||||
@@ -356,9 +323,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cacu/CACU-EU13": {
|
"cacu/CACU-EU13": {
|
||||||
"id": "CACU_EU13",
|
"id": "cacu_eu13",
|
||||||
"indicador": {
|
"indicador": {
|
||||||
"id": "CACU_EU13",
|
"id": "cacu_eu13",
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"titulo": "Tasa de detección histopatológica",
|
"titulo": "Tasa de detección histopatológica",
|
||||||
"contrato": "C1",
|
"contrato": "C1",
|
||||||
@@ -376,7 +343,7 @@
|
|||||||
"filtros": []
|
"filtros": []
|
||||||
},
|
},
|
||||||
"metadatos": {
|
"metadatos": {
|
||||||
"id": "CACU_EU13",
|
"id": "cacu_eu13",
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"descripcion": "De todas las mujeres tamizadas en el periodo, las que tienen una biopsia reportada con LIEAG (CIN 2 y 3), carcinoma in situ o carcinoma invasor, originada por una de sus citologías del periodo.",
|
"descripcion": "De todas las mujeres tamizadas en el periodo, las que tienen una biopsia reportada con LIEAG (CIN 2 y 3), carcinoma in situ o carcinoma invasor, originada por una de sus citologías del periodo.",
|
||||||
"ficha": {
|
"ficha": {
|
||||||
@@ -408,7 +375,7 @@
|
|||||||
},
|
},
|
||||||
"datos": {
|
"datos": {
|
||||||
"total": {
|
"total": {
|
||||||
"id": "CACU_EU13",
|
"id": "cacu_eu13",
|
||||||
"titulo": "Tasa de detección histopatológica",
|
"titulo": "Tasa de detección histopatológica",
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"contrato": "C1",
|
"contrato": "C1",
|
||||||
@@ -421,7 +388,7 @@
|
|||||||
"estrato": null,
|
"estrato": null,
|
||||||
"valores_estrato": [],
|
"valores_estrato": [],
|
||||||
"grupos": {
|
"grupos": {
|
||||||
"principal": "principal"
|
"total": "Total"
|
||||||
},
|
},
|
||||||
"categorias": {},
|
"categorias": {},
|
||||||
"grupos_de_categoria": {},
|
"grupos_de_categoria": {},
|
||||||
@@ -447,7 +414,7 @@
|
|||||||
"filas": [
|
"filas": [
|
||||||
{
|
{
|
||||||
"periodo": "2021-S1",
|
"periodo": "2021-S1",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": null,
|
"estrato": null,
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 0,
|
"numerador": 0,
|
||||||
@@ -460,7 +427,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"periodo": "2025-S2",
|
"periodo": "2025-S2",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": null,
|
"estrato": null,
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 1,
|
"numerador": 1,
|
||||||
@@ -474,7 +441,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"grupo_edad": {
|
"grupo_edad": {
|
||||||
"id": "CACU_EU13",
|
"id": "cacu_eu13",
|
||||||
"titulo": "Tasa de detección histopatológica",
|
"titulo": "Tasa de detección histopatológica",
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"contrato": "C1",
|
"contrato": "C1",
|
||||||
@@ -500,7 +467,7 @@
|
|||||||
"<25": "<25"
|
"<25": "<25"
|
||||||
},
|
},
|
||||||
"grupos": {
|
"grupos": {
|
||||||
"principal": "principal"
|
"total": "Total"
|
||||||
},
|
},
|
||||||
"categorias": {},
|
"categorias": {},
|
||||||
"grupos_de_categoria": {},
|
"grupos_de_categoria": {},
|
||||||
@@ -526,7 +493,7 @@
|
|||||||
"filas": [
|
"filas": [
|
||||||
{
|
{
|
||||||
"periodo": "2025-S2",
|
"periodo": "2025-S2",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": "25-34",
|
"estrato": "25-34",
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 0,
|
"numerador": 0,
|
||||||
@@ -539,7 +506,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"periodo": "2025-S2",
|
"periodo": "2025-S2",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": "35-44",
|
"estrato": "35-44",
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 0,
|
"numerador": 0,
|
||||||
@@ -552,7 +519,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"periodo": "2025-S2",
|
"periodo": "2025-S2",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": "45-54",
|
"estrato": "45-54",
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 1,
|
"numerador": 1,
|
||||||
@@ -565,7 +532,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"periodo": "2025-S2",
|
"periodo": "2025-S2",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": "55-64",
|
"estrato": "55-64",
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 0,
|
"numerador": 0,
|
||||||
@@ -578,7 +545,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"periodo": "2025-S2",
|
"periodo": "2025-S2",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": "<25",
|
"estrato": "<25",
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 0,
|
"numerador": 0,
|
||||||
@@ -592,7 +559,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"estatus_seguimiento": {
|
"estatus_seguimiento": {
|
||||||
"id": "CACU_EU13",
|
"id": "cacu_eu13",
|
||||||
"titulo": "Tasa de detección histopatológica",
|
"titulo": "Tasa de detección histopatológica",
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"contrato": "C1",
|
"contrato": "C1",
|
||||||
@@ -610,7 +577,7 @@
|
|||||||
"PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA"
|
"PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA"
|
||||||
},
|
},
|
||||||
"grupos": {
|
"grupos": {
|
||||||
"principal": "principal"
|
"total": "Total"
|
||||||
},
|
},
|
||||||
"categorias": {},
|
"categorias": {},
|
||||||
"grupos_de_categoria": {},
|
"grupos_de_categoria": {},
|
||||||
@@ -636,7 +603,7 @@
|
|||||||
"filas": [
|
"filas": [
|
||||||
{
|
{
|
||||||
"periodo": "2025-S2",
|
"periodo": "2025-S2",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": "PRE_COLPOSCOPIA",
|
"estrato": "PRE_COLPOSCOPIA",
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 1,
|
"numerador": 1,
|
||||||
@@ -652,9 +619,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cacu/CACU-EU7": {
|
"cacu/CACU-EU7": {
|
||||||
"id": "CACU_EU7",
|
"id": "cacu_eu7",
|
||||||
"indicador": {
|
"indicador": {
|
||||||
"id": "CACU_EU7",
|
"id": "cacu_eu7",
|
||||||
"version": "0.3.3",
|
"version": "0.3.3",
|
||||||
"titulo": "Distribución de resultados citológicos",
|
"titulo": "Distribución de resultados citológicos",
|
||||||
"contrato": "C2",
|
"contrato": "C2",
|
||||||
@@ -672,7 +639,7 @@
|
|||||||
"filtros": []
|
"filtros": []
|
||||||
},
|
},
|
||||||
"metadatos": {
|
"metadatos": {
|
||||||
"id": "CACU_EU7",
|
"id": "cacu_eu7",
|
||||||
"version": "0.3.3",
|
"version": "0.3.3",
|
||||||
"descripcion": "Cuántas pacientes caen en cada resultado citológico en el periodo, cada una en el de su última citología con resultado y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.",
|
"descripcion": "Cuántas pacientes caen en cada resultado citológico en el periodo, cada una en el de su última citología con resultado y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.",
|
||||||
"ficha": {
|
"ficha": {
|
||||||
@@ -694,11 +661,15 @@
|
|||||||
},
|
},
|
||||||
"datos": {
|
"datos": {
|
||||||
"total": {
|
"total": {
|
||||||
"id": "CACU_EU7",
|
"id": "cacu_eu7",
|
||||||
"titulo": "Distribución de resultados citológicos",
|
"titulo": "Distribución de resultados citológicos",
|
||||||
"version": "0.3.3",
|
"version": "0.3.3",
|
||||||
"contrato": "C2",
|
"contrato": "C2",
|
||||||
"unidad": "paciente",
|
"unidad": "paciente",
|
||||||
|
"unidades_periodo": {
|
||||||
|
"2021-S1": 0,
|
||||||
|
"2025-S2": 89
|
||||||
|
},
|
||||||
"tipo_periodo": "semestre",
|
"tipo_periodo": "semestre",
|
||||||
"periodos": [
|
"periodos": [
|
||||||
"2021-S1",
|
"2021-S1",
|
||||||
@@ -733,91 +704,17 @@
|
|||||||
"filas": []
|
"filas": []
|
||||||
},
|
},
|
||||||
"grupo_edad": {
|
"grupo_edad": {
|
||||||
"id": "CACU_EU7",
|
"error": "Categoría no declarada en el estrato"
|
||||||
"titulo": "Distribución de resultados citológicos",
|
|
||||||
"version": "0.3.3",
|
|
||||||
"contrato": "C2",
|
|
||||||
"unidad": "paciente",
|
|
||||||
"tipo_periodo": "semestre",
|
|
||||||
"periodos": [
|
|
||||||
"2021-S1",
|
|
||||||
"2025-S2"
|
|
||||||
],
|
|
||||||
"estrato": "grupo_edad",
|
|
||||||
"valores_estrato": [],
|
|
||||||
"etiquetas_estrato": {},
|
|
||||||
"grupos": {
|
|
||||||
"TOTAL": "Total"
|
|
||||||
},
|
|
||||||
"categorias": {},
|
|
||||||
"grupos_de_categoria": {},
|
|
||||||
"notas": [],
|
|
||||||
"reportes": [
|
|
||||||
{
|
|
||||||
"periodo": "2021-S1",
|
|
||||||
"report_id": 83,
|
|
||||||
"periodo_inicio": "2021-01-01",
|
|
||||||
"periodo_fin": "2021-07-01",
|
|
||||||
"fecha_corte": "2026-11-16",
|
|
||||||
"generado_en": "2026-11-16T23:08:29.557925+00:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"periodo": "2025-S2",
|
|
||||||
"report_id": 92,
|
|
||||||
"periodo_inicio": "2025-07-01",
|
|
||||||
"periodo_fin": "2026-01-01",
|
|
||||||
"fecha_corte": "2026-11-16",
|
|
||||||
"generado_en": "2026-11-16T23:08:31.081202+00:00"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"filas": []
|
|
||||||
},
|
},
|
||||||
"estatus_seguimiento": {
|
"estatus_seguimiento": {
|
||||||
"id": "CACU_EU7",
|
"error": "Categoría no declarada en el estrato"
|
||||||
"titulo": "Distribución de resultados citológicos",
|
|
||||||
"version": "0.3.3",
|
|
||||||
"contrato": "C2",
|
|
||||||
"unidad": "paciente",
|
|
||||||
"tipo_periodo": "semestre",
|
|
||||||
"periodos": [
|
|
||||||
"2021-S1",
|
|
||||||
"2025-S2"
|
|
||||||
],
|
|
||||||
"estrato": "estatus_seguimiento",
|
|
||||||
"valores_estrato": [],
|
|
||||||
"etiquetas_estrato": {},
|
|
||||||
"grupos": {
|
|
||||||
"TOTAL": "Total"
|
|
||||||
},
|
|
||||||
"categorias": {},
|
|
||||||
"grupos_de_categoria": {},
|
|
||||||
"notas": [],
|
|
||||||
"reportes": [
|
|
||||||
{
|
|
||||||
"periodo": "2021-S1",
|
|
||||||
"report_id": 83,
|
|
||||||
"periodo_inicio": "2021-01-01",
|
|
||||||
"periodo_fin": "2021-07-01",
|
|
||||||
"fecha_corte": "2026-11-16",
|
|
||||||
"generado_en": "2026-11-16T23:08:29.557925+00:00"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"periodo": "2025-S2",
|
|
||||||
"report_id": 92,
|
|
||||||
"periodo_inicio": "2025-07-01",
|
|
||||||
"periodo_fin": "2026-01-01",
|
|
||||||
"fecha_corte": "2026-11-16",
|
|
||||||
"generado_en": "2026-11-16T23:08:31.081202+00:00"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"filas": []
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cacu/CACU-RIESGO-BANDA": {
|
"cacu/CACU-RIESGO-BANDA": {
|
||||||
"id": "CACU_RIESGO_BANDA",
|
"id": "cacu_riesgo_banda",
|
||||||
"indicador": {
|
"indicador": {
|
||||||
"id": "CACU_RIESGO_BANDA",
|
"id": "cacu_riesgo_banda",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
|
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
|
||||||
"contrato": "C2",
|
"contrato": "C2",
|
||||||
@@ -831,7 +728,7 @@
|
|||||||
"filtros": []
|
"filtros": []
|
||||||
},
|
},
|
||||||
"metadatos": {
|
"metadatos": {
|
||||||
"id": "CACU_RIESGO_BANDA",
|
"id": "cacu_riesgo_banda",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"descripcion": "Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene evaluación confirmada en ese lote.",
|
"descripcion": "Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene evaluación confirmada en ese lote.",
|
||||||
"ficha": {
|
"ficha": {
|
||||||
@@ -853,11 +750,15 @@
|
|||||||
},
|
},
|
||||||
"datos": {
|
"datos": {
|
||||||
"total": {
|
"total": {
|
||||||
"id": "CACU_RIESGO_BANDA",
|
"id": "cacu_riesgo_banda",
|
||||||
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
|
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"contrato": "C2",
|
"contrato": "C2",
|
||||||
"unidad": "paciente",
|
"unidad": "paciente",
|
||||||
|
"unidades_periodo": {
|
||||||
|
"2021-S1": 0,
|
||||||
|
"2025-S2": 0
|
||||||
|
},
|
||||||
"tipo_periodo": "semestre",
|
"tipo_periodo": "semestre",
|
||||||
"periodos": [
|
"periodos": [
|
||||||
"2021-S1",
|
"2021-S1",
|
||||||
@@ -894,9 +795,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cacu/IND1": {
|
"cacu/IND1": {
|
||||||
"id": "IND1",
|
"id": "ind1",
|
||||||
"indicador": {
|
"indicador": {
|
||||||
"id": "IND1",
|
"id": "ind1",
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"titulo": "Pacientes con citología anómala",
|
"titulo": "Pacientes con citología anómala",
|
||||||
"contrato": "C1",
|
"contrato": "C1",
|
||||||
@@ -911,7 +812,7 @@
|
|||||||
"filtros": []
|
"filtros": []
|
||||||
},
|
},
|
||||||
"metadatos": {
|
"metadatos": {
|
||||||
"id": "IND1",
|
"id": "ind1",
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"descripcion": "Proporción de pacientes con citología tomada en el periodo con al menos un resultado anómalo: ASC-US, LIEBG, ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Una paciente con varias citologías cuenta una vez.",
|
"descripcion": "Proporción de pacientes con citología tomada en el periodo con al menos un resultado anómalo: ASC-US, LIEBG, ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Una paciente con varias citologías cuenta una vez.",
|
||||||
"ficha": {
|
"ficha": {
|
||||||
@@ -943,7 +844,7 @@
|
|||||||
},
|
},
|
||||||
"datos": {
|
"datos": {
|
||||||
"total": {
|
"total": {
|
||||||
"id": "IND1",
|
"id": "ind1",
|
||||||
"titulo": "Pacientes con citología anómala",
|
"titulo": "Pacientes con citología anómala",
|
||||||
"version": "0.3.2",
|
"version": "0.3.2",
|
||||||
"contrato": "C1",
|
"contrato": "C1",
|
||||||
@@ -956,7 +857,7 @@
|
|||||||
"estrato": null,
|
"estrato": null,
|
||||||
"valores_estrato": [],
|
"valores_estrato": [],
|
||||||
"grupos": {
|
"grupos": {
|
||||||
"principal": "principal"
|
"total": "Total"
|
||||||
},
|
},
|
||||||
"categorias": {},
|
"categorias": {},
|
||||||
"grupos_de_categoria": {},
|
"grupos_de_categoria": {},
|
||||||
@@ -982,7 +883,7 @@
|
|||||||
"filas": [
|
"filas": [
|
||||||
{
|
{
|
||||||
"periodo": "2021-S1",
|
"periodo": "2021-S1",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": null,
|
"estrato": null,
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 0,
|
"numerador": 0,
|
||||||
@@ -995,7 +896,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"periodo": "2025-S2",
|
"periodo": "2025-S2",
|
||||||
"grupo": "principal",
|
"grupo": "total",
|
||||||
"estrato": null,
|
"estrato": null,
|
||||||
"suprimido": 0,
|
"suprimido": 0,
|
||||||
"numerador": 19,
|
"numerador": 19,
|
||||||
@@ -2367,7 +2268,7 @@
|
|||||||
"grupo": null
|
"grupo": null
|
||||||
},
|
},
|
||||||
"MALO": {
|
"MALO": {
|
||||||
"etiqueta": "Malo",
|
"etiqueta": "No aceptable",
|
||||||
"color": "#B8433A",
|
"color": "#B8433A",
|
||||||
"grupo": null
|
"grupo": null
|
||||||
},
|
},
|
||||||
@@ -2402,7 +2303,7 @@
|
|||||||
"grupo": null
|
"grupo": null
|
||||||
},
|
},
|
||||||
"MALO": {
|
"MALO": {
|
||||||
"etiqueta": "Malo",
|
"etiqueta": "No aceptable",
|
||||||
"color": "#B8433A",
|
"color": "#B8433A",
|
||||||
"grupo": null
|
"grupo": null
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,835 @@
|
|||||||
|
{
|
||||||
|
"resourceType": "Bundle",
|
||||||
|
"type": "collection",
|
||||||
|
"entry": [
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Observation",
|
||||||
|
"id": "ados2-vista-previa",
|
||||||
|
"status": "final",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2",
|
||||||
|
"display": "ADOS-2"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"effectiveDateTime": "1985-01-01",
|
||||||
|
"component": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.modulo",
|
||||||
|
"display": "Módulo"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.modulo.MODULO_2"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.css",
|
||||||
|
"display": "Puntaje de severidad (CSS)"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.clasificacion",
|
||||||
|
"display": "Clasificación"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueCodeableConcept": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.clasificacion.AUTISMO"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||||
|
"code": "SA",
|
||||||
|
"display": "Afecto social"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 10
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||||
|
"code": "RRB",
|
||||||
|
"display": "Comportamiento restringido y repetitivo"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.rrb_a4",
|
||||||
|
"display": "Uso estereotipado o idiosincrásico de palabras o frases"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 1,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "RRB"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.rrb_d2",
|
||||||
|
"display": "Manierismos de manos y dedos y otros manierismos complejos"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 2,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "RRB"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.rrb_d4",
|
||||||
|
"display": "Intereses inusualmente repetitivos o comportamientos estereotipados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 1,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "RRB"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_a6",
|
||||||
|
"display": "Señalar"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 1,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_a7",
|
||||||
|
"display": "Señalar"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 0,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_b1",
|
||||||
|
"display": "Contacto visual inusual"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 2,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_b12",
|
||||||
|
"display": "Características de las iniciaciones sociales"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 2,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_b2",
|
||||||
|
"display": "Expresiones faciales dirigidas a otros"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 1,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_b3",
|
||||||
|
"display": "Expresiones faciales dirigidas a otros"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 0,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_b5",
|
||||||
|
"display": "Disfrute compartido durante la interacción"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 2,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_b6",
|
||||||
|
"display": "Iniciación espontánea de la atención conjunta"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 1,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "ados2.sa_b8",
|
||||||
|
"display": "Características de las iniciaciones sociales"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"valueInteger": 1,
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||||
|
"valueInteger": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||||
|
"valueCode": "SA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Procedure",
|
||||||
|
"id": "eeg-vista-previa",
|
||||||
|
"status": "completed",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "eeg",
|
||||||
|
"display": "Electroencefalograma"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"performedDateTime": "1985-01-01",
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "DiagnosticReport",
|
||||||
|
"id": "eeg-vista-previa",
|
||||||
|
"status": "final",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||||
|
"code": "eeg",
|
||||||
|
"display": "Electroencefalograma"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"effectiveDateTime": "1985-01-01",
|
||||||
|
"result": [
|
||||||
|
{
|
||||||
|
"reference": "Observation/calidad-bad-scalp-triage-vista-previa"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"reference": "Observation/calidad-clean-windows-vista-previa"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"reference": "Observation/calidad-internal-coverage-vista-previa"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"reference": "Observation/calidad-line-noise-vista-previa"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"reference": "Observation/calidad-triage-level-vista-previa"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"reference": "Observation/calidad-usable-scalp-vista-previa"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"conclusionCode": [
|
||||||
|
{
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/calidad",
|
||||||
|
"code": "MALO"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "urn:tea:validation",
|
||||||
|
"code": "not-valid"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"extension": [
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/duracion-min",
|
||||||
|
"valueDecimal": 2.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/edad-meses",
|
||||||
|
"valueDecimal": 30.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "https://isssteleon.org/fhir/StructureDefinition/canales",
|
||||||
|
"valueInteger": 24
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"conclusion": "EEG de mala calidad: no es válido para el estudio (nivel de triaje: no_analizable).",
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Observation",
|
||||||
|
"id": "calidad-bad-scalp-triage-vista-previa",
|
||||||
|
"status": "final",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "urn:tea:validation",
|
||||||
|
"code": "bad-scalp-triage",
|
||||||
|
"display": "bad-scalp-triage"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "bad-scalp-triage"
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"effectiveDateTime": "1985-01-01",
|
||||||
|
"interpretation": [
|
||||||
|
{
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||||
|
"code": "N"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"valueQuantity": {
|
||||||
|
"value": 0.0,
|
||||||
|
"unit": "electrodes"
|
||||||
|
},
|
||||||
|
"referenceRange": [
|
||||||
|
{
|
||||||
|
"high": {
|
||||||
|
"value": 2.0,
|
||||||
|
"unit": "electrodes"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"component": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"text": "decisive"
|
||||||
|
},
|
||||||
|
"valueBoolean": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Observation",
|
||||||
|
"id": "calidad-clean-windows-vista-previa",
|
||||||
|
"status": "final",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "urn:tea:validation",
|
||||||
|
"code": "clean-windows",
|
||||||
|
"display": "clean-windows"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "clean-windows"
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"effectiveDateTime": "1985-01-01",
|
||||||
|
"interpretation": [
|
||||||
|
{
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||||
|
"code": "N"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"valueQuantity": {
|
||||||
|
"value": 100.0,
|
||||||
|
"unit": "%"
|
||||||
|
},
|
||||||
|
"referenceRange": [
|
||||||
|
{
|
||||||
|
"low": {
|
||||||
|
"value": 60.0,
|
||||||
|
"unit": "%"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"component": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"text": "decisive"
|
||||||
|
},
|
||||||
|
"valueBoolean": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Observation",
|
||||||
|
"id": "calidad-internal-coverage-vista-previa",
|
||||||
|
"status": "final",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "urn:tea:validation",
|
||||||
|
"code": "internal-coverage",
|
||||||
|
"display": "internal-coverage"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "internal-coverage"
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"effectiveDateTime": "1985-01-01",
|
||||||
|
"interpretation": [
|
||||||
|
{
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||||
|
"code": "N"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"valueQuantity": {
|
||||||
|
"value": 1.0,
|
||||||
|
"unit": "fraction"
|
||||||
|
},
|
||||||
|
"referenceRange": [
|
||||||
|
{
|
||||||
|
"low": {
|
||||||
|
"value": 0.9,
|
||||||
|
"unit": "fraction"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"component": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"text": "decisive"
|
||||||
|
},
|
||||||
|
"valueBoolean": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Observation",
|
||||||
|
"id": "calidad-line-noise-vista-previa",
|
||||||
|
"status": "final",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "urn:tea:validation",
|
||||||
|
"code": "line-noise",
|
||||||
|
"display": "line-noise"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "line-noise"
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"effectiveDateTime": "1985-01-01",
|
||||||
|
"interpretation": [
|
||||||
|
{
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||||
|
"code": "N"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"valueQuantity": {
|
||||||
|
"value": 9.231034526452635,
|
||||||
|
"unit": "dB"
|
||||||
|
},
|
||||||
|
"referenceRange": [
|
||||||
|
{
|
||||||
|
"high": {
|
||||||
|
"value": 45.0,
|
||||||
|
"unit": "dB"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"component": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"text": "decisive"
|
||||||
|
},
|
||||||
|
"valueBoolean": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Observation",
|
||||||
|
"id": "calidad-triage-level-vista-previa",
|
||||||
|
"status": "final",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "urn:tea:validation",
|
||||||
|
"code": "triage-level",
|
||||||
|
"display": "triage-level"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "triage-level"
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"effectiveDateTime": "1985-01-01",
|
||||||
|
"interpretation": [
|
||||||
|
{
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||||
|
"code": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"valueString": "no_analizable",
|
||||||
|
"component": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"text": "decisive"
|
||||||
|
},
|
||||||
|
"valueBoolean": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resource": {
|
||||||
|
"resourceType": "Observation",
|
||||||
|
"id": "calidad-usable-scalp-vista-previa",
|
||||||
|
"status": "final",
|
||||||
|
"code": {
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "urn:tea:validation",
|
||||||
|
"code": "usable-scalp",
|
||||||
|
"display": "usable-scalp"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "usable-scalp"
|
||||||
|
},
|
||||||
|
"subject": {
|
||||||
|
"reference": "Patient/vista-previa"
|
||||||
|
},
|
||||||
|
"effectiveDateTime": "1985-01-01",
|
||||||
|
"interpretation": [
|
||||||
|
{
|
||||||
|
"coding": [
|
||||||
|
{
|
||||||
|
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||||
|
"code": "N"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"valueQuantity": {
|
||||||
|
"value": 19.0,
|
||||||
|
"unit": "electrodes"
|
||||||
|
},
|
||||||
|
"referenceRange": [
|
||||||
|
{
|
||||||
|
"low": {
|
||||||
|
"value": 12.0,
|
||||||
|
"unit": "electrodes"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"component": [
|
||||||
|
{
|
||||||
|
"code": {
|
||||||
|
"text": "decisive"
|
||||||
|
},
|
||||||
|
"valueBoolean": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"meta": {
|
||||||
|
"tag": [
|
||||||
|
{
|
||||||
|
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||||
|
"code": "simulado",
|
||||||
|
"display": "Datos simulados"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// Covers the round "?" help of TEA's cards: hover or focus shows the text, a click keeps it until the next click.
|
||||||
|
// Fixture: a host component that projects one line of text into the button.
|
||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { IndicadorAyuda } from './indicador-ayuda';
|
||||||
|
|
||||||
|
@Component({ imports: [IndicadorAyuda], template: `<app-indicador-ayuda etiqueta="Cómo leer: prueba" (opened)="aperturas = aperturas + 1">Texto de ayuda</app-indicador-ayuda>` })
|
||||||
|
class Host { aperturas = 0; }
|
||||||
|
|
||||||
|
describe('Ayuda redonda', () => {
|
||||||
|
function crear() {
|
||||||
|
const fixture = TestBed.createComponent(Host);
|
||||||
|
fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
const boton = () => root.querySelector<HTMLButtonElement>('.ayuda-boton')!;
|
||||||
|
const texto = () => root.querySelector('.ayuda-texto')?.textContent?.trim();
|
||||||
|
const ayuda = root.querySelector('.ayuda')!;
|
||||||
|
return { fixture, boton, texto, ayuda };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('muestra el texto al pasar el cursor y lo oculta al salir', () => {
|
||||||
|
// Fails if hovering stops showing the guide or leaving leaves it open when it was not pinned.
|
||||||
|
const { fixture, texto, ayuda } = crear();
|
||||||
|
expect(texto()).toBeUndefined();
|
||||||
|
ayuda.dispatchEvent(new MouseEvent('mouseenter')); fixture.detectChanges();
|
||||||
|
expect(texto()).toBe('Texto de ayuda');
|
||||||
|
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||||
|
expect(texto()).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un clic fija el texto hasta el siguiente clic', () => {
|
||||||
|
// Fails if the click stops pinning the text, if leaving closes a pinned text, or if a second click does not close it.
|
||||||
|
const { fixture, boton, texto, ayuda } = crear();
|
||||||
|
ayuda.dispatchEvent(new MouseEvent('mouseenter')); boton().click(); fixture.detectChanges();
|
||||||
|
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||||
|
expect(texto()).toBe('Texto de ayuda');
|
||||||
|
expect(boton().getAttribute('aria-expanded')).toBe('true');
|
||||||
|
boton().click(); fixture.detectChanges();
|
||||||
|
expect(texto()).toBeUndefined();
|
||||||
|
expect(boton().getAttribute('aria-expanded')).toBe('false');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('avisa solo al abrirse con un clic y nombra el botón', () => {
|
||||||
|
// Fails if closing also reports an opening (the metadata would be requested again) or the accessible name is lost.
|
||||||
|
const { fixture, boton } = crear();
|
||||||
|
boton().click(); boton().click(); boton().click(); fixture.detectChanges();
|
||||||
|
expect(fixture.componentInstance.aperturas).toBe(2);
|
||||||
|
expect(boton().getAttribute('aria-label')).toBe('Cómo leer: prueba');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { Component, input, output, signal } from '@angular/core';
|
||||||
|
|
||||||
|
// Round "?" button at the top right of a card. Hover or focus shows its text; a click keeps it open until the next click.
|
||||||
|
@Component({
|
||||||
|
selector: 'app-indicador-ayuda',
|
||||||
|
template: `
|
||||||
|
<div class="ayuda" (mouseenter)="sobre.set(true)" (mouseleave)="sobre.set(false)" (focusin)="sobre.set(true)" (focusout)="sobre.set(false)">
|
||||||
|
<button type="button" class="ayuda-boton" [attr.aria-label]="etiqueta()" [attr.aria-expanded]="visible()"
|
||||||
|
[attr.aria-controls]="visible() ? idPanel : null" (click)="alternar()"><span aria-hidden="true">?</span></button>
|
||||||
|
@if (visible()) {
|
||||||
|
<div class="ayuda-texto" role="tooltip" [id]="idPanel"><ng-content /></div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
:host { position: absolute; top: .5rem; right: .5rem; z-index: 2; }
|
||||||
|
.ayuda { position: relative; }
|
||||||
|
.ayuda-boton { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; padding: 0; border: 0;
|
||||||
|
border-radius: 50%; background: transparent; box-shadow: inset 0 0 0 1.5px var(--issste-text-secondary); color: var(--issste-text); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
|
||||||
|
.ayuda-boton:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
|
.ayuda-texto { position: absolute; top: calc(100% + .375rem); right: 0; width: min(22rem, 80vw); box-sizing: border-box; padding: var(--issste-space-3) var(--issste-space-4);
|
||||||
|
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-inline-start: 3px solid var(--issste-accent);
|
||||||
|
border-radius: var(--issste-radius); box-shadow: 0 4px 16px rgb(0 0 0 / .18); font: var(--mat-sys-body-small); line-height: 1.5; text-align: start; overflow-wrap: anywhere; }
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class IndicadorAyuda {
|
||||||
|
readonly etiqueta = input('Cómo leer');
|
||||||
|
readonly opened = output<void>();
|
||||||
|
readonly sobre = signal(false);
|
||||||
|
readonly fijo = signal(false);
|
||||||
|
private static contador = 0;
|
||||||
|
readonly idPanel = 'ayuda-' + ++IndicadorAyuda.contador;
|
||||||
|
visible() { return this.sobre() || this.fijo(); }
|
||||||
|
alternar() {
|
||||||
|
const abre = !this.fijo();
|
||||||
|
this.fijo.set(abre);
|
||||||
|
if (abre) this.opened.emit();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, SimpleChanges } from '@angular/core';
|
||||||
|
import { catchError, of, Subscription } from 'rxjs';
|
||||||
|
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||||
|
import { describePeriods, GlobalApplied } from './indicadores-memory';
|
||||||
|
import { IndicadoresService } from './indicadores.service';
|
||||||
|
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||||
|
import { IndicadorVphGenotipo } from './indicador-vph-genotipo';
|
||||||
|
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||||
|
|
||||||
|
// Three independent CaCu distributions sharing the general period filter.
|
||||||
|
@Component({
|
||||||
|
selector: 'app-indicador-cacu-donas',
|
||||||
|
imports: [IndicadorEu7Escenario, IndicadorVphGenotipo, IndicadorConfirmacionCitologia],
|
||||||
|
template: `
|
||||||
|
<p class="filtro">Filtro general aplicado: {{ filtro }}</p>
|
||||||
|
<div class="donas">
|
||||||
|
<app-indicador-eu7-escenario [mostrarFiltro]="false" [permitirSeleccion]="false" [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="metadataRequested.emit()" />
|
||||||
|
<app-indicador-vph-genotipo [mostrarFiltro]="vphFiltroPropio" [dominio]="dominio" [indicador]="vph" [tema]="tema" [applied]="vphApplied" [visible]="visible" />
|
||||||
|
@if (confirmacion && confirmacionApplied) {
|
||||||
|
<app-indicador-confirmacion-citologia vista="dona" [mostrarFiltro]="filtroPropio" [permitirSeleccion]="false" [dominio]="dominio" [indicador]="confirmacion" [tema]="tema" [applied]="confirmacionApplied" [visible]="visible" [metadata]="confirmacionMetadata" (metadataRequested)="loadConfirmacionMetadata()" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
:host { display: block; min-width: 0; }
|
||||||
|
.filtro { margin: 0 0 var(--issste-space-2); color: var(--issste-text-secondary); }
|
||||||
|
.donas { display: flex; flex-direction: column; }
|
||||||
|
.donas > * { display: block; min-width: 0; padding-block: var(--issste-space-3); }
|
||||||
|
.donas > * + * { border-top: 1px solid var(--issste-border); }
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class IndicadorCacuDonas implements OnChanges, OnDestroy {
|
||||||
|
@Input({ required: true }) dominio!: Dominio;
|
||||||
|
@Input({ required: true }) indicador!: Indicador;
|
||||||
|
@Input({ required: true }) tema!: Tema;
|
||||||
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
|
@Input() visible = true;
|
||||||
|
@Input() metadata?: IndicadorMetadatos;
|
||||||
|
// The biopsy donut belongs to the histopathological confirmation indicator.
|
||||||
|
@Input() confirmacion?: Indicador;
|
||||||
|
@Input() confirmacionApplied?: GlobalApplied;
|
||||||
|
// HPV by genotype: its Measure, when the server publishes it.
|
||||||
|
@Input() vph?: Indicador;
|
||||||
|
@Input() vphApplied?: GlobalApplied;
|
||||||
|
readonly metadataRequested = output<void>();
|
||||||
|
get filtro() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||||
|
get vphFiltroPropio() { return !!this.vphApplied && describePeriods(this.vphApplied.tipo, this.vphApplied.selection) !== this.filtro; }
|
||||||
|
// A donut whose effective period differs from the card's keeps its own line.
|
||||||
|
get filtroPropio() { return !!this.confirmacionApplied && describePeriods(this.confirmacionApplied.tipo, this.confirmacionApplied.selection) !== this.filtro; }
|
||||||
|
confirmacionMetadata?: IndicadorMetadatos;
|
||||||
|
private readonly indicators = inject(IndicadoresService);
|
||||||
|
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||||
|
private metadataSubscription?: Subscription;
|
||||||
|
private metadataKey = '';
|
||||||
|
|
||||||
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
|
if (changes['confirmacion'] && this.metadataKey !== '') {
|
||||||
|
this.metadataSubscription?.unsubscribe(); this.metadataKey = ''; this.confirmacionMetadata = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loadConfirmacionMetadata() {
|
||||||
|
if (!this.confirmacion) return;
|
||||||
|
const key = JSON.stringify([this.dominio, this.confirmacion.id]);
|
||||||
|
if (this.metadataKey === key) return;
|
||||||
|
this.metadataKey = key;
|
||||||
|
this.metadataSubscription?.unsubscribe();
|
||||||
|
this.metadataSubscription = this.indicators.metadatos(this.dominio, this.confirmacion.id)
|
||||||
|
.pipe(catchError(() => of(undefined))).subscribe(value => {
|
||||||
|
if (this.metadataKey !== key) return;
|
||||||
|
if (!value) this.metadataKey = '';
|
||||||
|
this.confirmacionMetadata = value;
|
||||||
|
this.changeDetector.markForCheck();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
ngOnDestroy() { this.metadataSubscription?.unsubscribe(); }
|
||||||
|
}
|
||||||
@@ -36,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
|
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
|
||||||
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
|
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
|
||||||
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
|
expect(fixture.nativeElement.querySelector('.catalog-metadata')).toBeNull();
|
||||||
|
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
|
||||||
// The internal panel heading is deliberately visually hidden and retains identity.
|
// The internal panel heading is deliberately visually hidden and retains identity.
|
||||||
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
|
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
|
||||||
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
|
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
|||||||
import { filterCompatibility } from './indicadores-memory';
|
import { filterCompatibility } from './indicadores-memory';
|
||||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||||
import { IndicadoresService } from './indicadores.service';
|
import { IndicadoresService } from './indicadores.service';
|
||||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
import { IndicadorCacuDonas } from './indicador-cacu-donas';
|
||||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||||
@@ -24,16 +24,18 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
|||||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||||
import { parConteos } from './indicadores-conteos-pareados';
|
import { parConteos } from './indicadores-conteos-pareados';
|
||||||
|
|
||||||
|
const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacientes_evaluados'];
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-catalog-card',
|
selector: 'app-indicador-catalog-card',
|
||||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos', '[class.doble]': 'ocupaDos' },
|
||||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorCacuDonas, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||||
template: `
|
template: `
|
||||||
<mat-card>
|
<mat-card>
|
||||||
@if (!conteos) {
|
@if (!conteos) {
|
||||||
<header>
|
<header>
|
||||||
<div class="card-identity">
|
<div class="card-identity">
|
||||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
<h2 [id]="titleId" tabindex="-1" [class.con-ayuda]="dominio === 'tea'">{{ titulo }}</h2>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
}
|
}
|
||||||
@@ -48,7 +50,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
|
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
|
||||||
@if (isEu7) {
|
@if (isEu7) {
|
||||||
<div #visibilityRegion class="eu7-region">
|
<div #visibilityRegion class="eu7-region">
|
||||||
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
<app-indicador-cacu-donas [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" [confirmacion]="companion" [confirmacionApplied]="companionApplied" [vph]="vph" [vphApplied]="vphApplied" (metadataRequested)="loadMetadata()" />
|
||||||
</div>
|
</div>
|
||||||
} @else if (isConfirmacion) {
|
} @else if (isConfirmacion) {
|
||||||
<div #visibilityRegion class="confirmacion-region">
|
<div #visibilityRegion class="confirmacion-region">
|
||||||
@@ -81,12 +83,13 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
`,
|
`,
|
||||||
styles: `
|
styles: `
|
||||||
:host { display: flex; min-width: 0; margin: 0; }
|
:host { display: flex; min-width: 0; margin: 0; }
|
||||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
mat-card { position: relative; flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||||
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||||
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
|
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
|
||||||
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
||||||
.graphic-region { flex: 1; min-width: 0; }
|
.graphic-region { flex: 1; min-width: 0; }
|
||||||
:host(.dual-card) { grid-column: 1 / -1; }
|
:host(.dual-card) { grid-column: 1 / -1; }
|
||||||
|
:host(.doble) { grid-column: span 2; }
|
||||||
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
|
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
|
||||||
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
|
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
|
||||||
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
|
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
|
||||||
@@ -108,6 +111,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
.card-identity { min-width: 0; }
|
.card-identity { min-width: 0; }
|
||||||
h2, p { overflow-wrap: anywhere; }
|
h2, p { overflow-wrap: anywhere; }
|
||||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
||||||
|
h2.con-ayuda { padding-right: 2.5rem; }
|
||||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||||
@@ -135,15 +139,19 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
|||||||
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
|
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
|
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
|
||||||
get sobrio() { return this.dominio === 'cama'; }
|
get sobrio() { return true; }
|
||||||
|
// TEA's stacked case charts span two columns of its three-column grid.
|
||||||
|
get ocupaDos() { return this.dominio === 'tea' && DOBLE_ANCHO_TEA.includes(this.indicador.id); }
|
||||||
get pair() { return dualFigures(this.indicador); }
|
get pair() { return dualFigures(this.indicador); }
|
||||||
|
// CaCu's first card gathers the three donuts, so it carries its own name.
|
||||||
|
get titulo() { return this.isEu7 ? 'Resultados de citología, VPH y biopsia' : this.indicador.titulo; }
|
||||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||||
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
||||||
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
|
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
|
||||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
get tiempos() { return this.individual ? undefined : parTiempos(this.dominio, this.indicador.id); }
|
||||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||||
@@ -169,7 +177,15 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
|||||||
@Input({ required: true }) tema!: Tema;
|
@Input({ required: true }) tema!: Tema;
|
||||||
@Input({ required: true }) applied!: GlobalApplied;
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
@Input() independentPeriods = false;
|
@Input() independentPeriods = false;
|
||||||
|
// The histopathological confirmation indicator, whose biopsy donut sits on the EU7 card.
|
||||||
|
@Input() companion?: Indicador;
|
||||||
|
@Input() companionApplied?: GlobalApplied;
|
||||||
|
// The HPV-by-genotype indicator, whose donut sits on the same card.
|
||||||
|
@Input() vph?: Indicador;
|
||||||
|
@Input() vphApplied?: GlobalApplied;
|
||||||
@Input() pinned = false;
|
@Input() pinned = false;
|
||||||
|
// Draws the indicator alone even when it belongs to a connected pair.
|
||||||
|
@Input() individual = false;
|
||||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||||
readonly pinChanged = output<void>();
|
readonly pinChanged = output<void>();
|
||||||
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
||||||
|
|||||||
@@ -1,51 +1,67 @@
|
|||||||
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
|
<section class="confirmacion" [class.vista-dona]="vista === 'dona'" [attr.aria-label]="vista === 'dona' ? 'Resultado de la biopsia' : 'Confirmación histopatológica por resultado de la citología'">
|
||||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
<div class="encabezado">
|
||||||
|
@if (mostrarFiltro) { <p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p> }
|
||||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||||
@if (helpOpen) {
|
@if (helpOpen) {
|
||||||
<div class="methodology">
|
<div class="methodology">
|
||||||
@if (metadata) {
|
@if (!permitirSeleccion && vista === 'dona') {
|
||||||
|
<p>Cada barra muestra mujeres por grado de biopsia y su porcentaje del total con biopsia. Los encabezados reúnen los grados en grupos clínicos. Los casos sin biopsia o sin grado se informan fuera de la distribución.</p>
|
||||||
|
} @else if (metadata) {
|
||||||
@for (guide of readingGuide; track guide.figura) {
|
@for (guide of readingGuide; track guide.figura) {
|
||||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||||
<h3>{{ guide.nombre }}</h3>
|
<h3>{{ guide.nombre }}</h3>
|
||||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||||
</section>
|
</section>
|
||||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
} @empty { <p>El servicio no publica instrucciones de lectura para {{ vista === 'dona' ? 'esta figura' : 'estas figuras' }}.</p> }
|
||||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@switch (status()) {
|
@switch (status()) {
|
||||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando citologías y biopsias" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando citologías y biopsias" /><p role="status">{{ vista === 'dona' ? 'Cargando resultados de biopsia…' : 'Cargando tasas de confirmación…' }}</p> }
|
||||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
}
|
}
|
||||||
@if (status() === 'ready' || status() === 'empty') {
|
@if (status() === 'ready' || status() === 'empty') {
|
||||||
@if (periods.length > 1) {
|
@if (periods.length > 1) {
|
||||||
<nav class="periods" aria-label="Periodos de la confirmación histopatológica">
|
<nav class="periods" [attr.aria-label]="vista === 'dona' ? 'Periodos del resultado de la biopsia' : 'Periodos de la confirmación histopatológica'">
|
||||||
<button type="button" aria-label="Periodo anterior de la confirmación" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
<button type="button" [attr.aria-label]="vista === 'dona' ? 'Periodo anterior del resultado de la biopsia' : 'Periodo anterior de la confirmación'" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||||
<button type="button" aria-label="Periodo siguiente de la confirmación" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
<button type="button" [attr.aria-label]="vista === 'dona' ? 'Periodo siguiente del resultado de la biopsia' : 'Periodo siguiente de la confirmación'" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
@if (model; as m) {
|
@if (model; as m) {
|
||||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
@if (permitirSeleccion) { <p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}@if (vista === 'tasas') { . {{ reading }} }</p> }
|
||||||
@if (status() === 'empty') { <p role="status">No hay citologías de alto grado publicadas para este periodo.</p> }
|
@if (status() === 'empty') { <p role="status">No hay citologías de alto grado publicadas para este periodo.</p> }
|
||||||
@else {
|
@else if (permitirSeleccion) {
|
||||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
<div class="legend" role="group" [attr.aria-label]="vista === 'dona' ? 'Seleccionar resultado de biopsia en la gráfica' : 'Seleccionar resultado de biopsia para las tasas'">
|
||||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista base de la confirmación">Volver</button>
|
<div class="tab-bar"><div class="tabs" role="group" aria-label="Grupos del anillo interior">
|
||||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
|
||||||
@for (g of m.grupos; track g.id; let i = $index) {
|
@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>
|
<button type="button" class="tab" [style.--swatch]="g.color" [attr.aria-pressed]="selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||||
}
|
}
|
||||||
</div>
|
</div></div>
|
||||||
<div class="keys" role="group" aria-label="Grados del anillo exterior">
|
<div class="child-groups" role="group" aria-label="Categorías del anillo exterior">
|
||||||
@for (c of m.grados; track c.id; let i = $index) {
|
@for (g of m.grupos; track g.id) {
|
||||||
<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 class="tab-panel" role="group" [attr.aria-label]="g.etiqueta">
|
||||||
|
@for (c of m.grados; track c.id; let i = $index) {
|
||||||
|
@if (c.grupo === g.id) {
|
||||||
|
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="figures">
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="cuerpo">
|
||||||
|
@if (status() === 'ready' || status() === 'empty') {
|
||||||
|
@if (model; as m) {
|
||||||
|
@if (status() !== 'empty') {
|
||||||
|
@if (vista === 'tasas') {
|
||||||
<section class="figure rates"><h3>Por resultado de la citología, {{ m.periodo }}</h3>
|
<section class="figure rates"><h3>Por resultado de la citología, {{ m.periodo }}</h3>
|
||||||
@if (ratesFigure) {
|
@if (ratesFigure) {
|
||||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación, tasas por citología, ' + m.periodo + ', ' + selectionLabel" />
|
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación, tasas por citología, ' + m.periodo + ', ' + selectionLabel" />
|
||||||
@@ -54,24 +70,47 @@
|
|||||||
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
} @else {
|
||||||
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
||||||
@if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) {
|
@if (m.conBiopsia === 0) { <p role="status">Sin mujeres con biopsia en el periodo.</p> }
|
||||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
@else {
|
||||||
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}</p> }
|
@if (m.conBiopsia === null) { <p role="status">Total no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial ni porcentajes.</p> }
|
||||||
|
@if (barras) { <app-barras-horizontales [conjunto]="barras" [titulo]="'Resultado de la biopsia, ' + m.periodo + (permitirSeleccion ? ', selección: ' + selectionLabel : '')" /> }
|
||||||
|
}
|
||||||
|
@if (totales; as t) {
|
||||||
|
<p class="aparte">Fuera de la distribución:
|
||||||
|
@for (a of t.aparte; track a.id; let last = $last) { {{ a.etiqueta }}: {{ a.n === null ? a.estado : a.n.toLocaleString('es-MX') }}{{ last ? '.' : ';' }} }
|
||||||
|
</p>
|
||||||
|
}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
}
|
||||||
|
}
|
||||||
|
@if (vista === 'tasas') {
|
||||||
|
@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 contingencia de citología y biopsia" tabindex="0">
|
||||||
|
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</caption>
|
||||||
|
<thead><tr><th scope="col">Citología</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
|
||||||
|
<tbody>@for (fila of m.filas; track fila.id) {
|
||||||
|
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (g of m.grados; track g.id) { <td>{{ cellText(fila.celdas[g.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }</tr>
|
||||||
|
}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
} @else if (totales; as t) {
|
||||||
|
<details class="published-values"><summary>Valores publicados</summary>
|
||||||
|
<div class="table-scroll" role="region" aria-label="Tabla de resultados de biopsia" tabindex="0">
|
||||||
|
<table><caption>Mujeres por resultado de la biopsia, {{ m.periodo }}</caption>
|
||||||
|
<thead><tr><th scope="col">Resultado</th><th scope="col">Mujeres</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@for (g of t.grados; track g.id) { <tr><th scope="row">{{ g.etiqueta }}</th><td>{{ g.n === null ? g.estado : g.n.toLocaleString('es-MX') }}</td></tr> }
|
||||||
|
@for (a of t.aparte; track a.id) { <tr><th scope="row">{{ a.etiqueta }}</th><td>{{ a.n === null ? a.estado : a.n.toLocaleString('es-MX') }}</td></tr> }
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
}
|
}
|
||||||
@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 contingencia de citología y biopsia" tabindex="0">
|
|
||||||
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</caption>
|
|
||||||
<thead><tr><th scope="col">Citología</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
|
|
||||||
<tbody>@for (fila of m.filas; track fila.id) {
|
|
||||||
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (g of m.grados; track g.id) { <td>{{ cellText(fila.celdas[g.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }</tr>
|
|
||||||
}</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inse
|
|||||||
button:disabled { opacity: .5; cursor: default; }
|
button:disabled { opacity: .5; cursor: default; }
|
||||||
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
||||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
|
|
||||||
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||||
h3 { font-size: 1rem; line-height: 1.5; }
|
h3 { font-size: 1rem; line-height: 1.5; }
|
||||||
app-plotly-chart { --plot-height: 440px; }
|
app-plotly-chart { --plot-height: 440px; }
|
||||||
@@ -59,8 +58,20 @@ caption { text-align: start; font-weight: 600; }
|
|||||||
app-plotly-chart { --plot-height: 360px; }
|
app-plotly-chart { --plot-height: 360px; }
|
||||||
.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
|
.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
|
||||||
.rate-states:empty { display: none; }
|
.rate-states:empty { display: none; }
|
||||||
/* Rates on the left, donut on the right (the reverse of EU7). */
|
.aparte { color: var(--issste-text-secondary); }
|
||||||
@media (min-width: 1100px) {
|
@media (min-width: 1100px) {
|
||||||
.figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); }
|
|
||||||
.histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; }
|
.histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.confirmacion:not(.histo) .legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
|
||||||
|
.confirmacion:not(.histo) .legend > button { align-self: flex-start; margin-bottom: .4rem; }
|
||||||
|
.confirmacion:not(.histo) .tab-bar { display: flex; align-items: flex-end; border-bottom: 1px solid var(--issste-border); }
|
||||||
|
.confirmacion:not(.histo) .tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
|
||||||
|
.confirmacion:not(.histo) .tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
|
||||||
|
.confirmacion:not(.histo) .tabs .tab[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
|
||||||
|
.confirmacion:not(.histo) .child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
|
||||||
|
.confirmacion:not(.histo) .tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
|
||||||
|
.confirmacion:not(.histo) .tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); text-align: start; overflow-wrap: anywhere; }
|
||||||
|
.confirmacion:not(.histo) .tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); box-shadow: inset 0 0 0 1px var(--swatch); }
|
||||||
|
.confirmacion:not(.histo) .tab .swatch, .confirmacion:not(.histo) .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
|
||||||
|
|||||||
@@ -4,20 +4,25 @@ import { Subscription, timeout, TimeoutError } from 'rxjs';
|
|||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { BarrasHorizontales } from './barras-horizontales';
|
||||||
|
import { ConjuntoBarras } from './indicadores-barras';
|
||||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||||
import { httpMessage } from './indicadores-http';
|
import { httpMessage } from './indicadores-http';
|
||||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
|
import { clicConfirmacion, barrasBiopsia, ConfirmacionIncompatible, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
|
||||||
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
||||||
Celda, tasas } from './indicadores-confirmacion-citologia';
|
Celda, tasas, totalesPublicados } from './indicadores-confirmacion-citologia';
|
||||||
|
|
||||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
// Figure of the kit whose "Cómo leer" describes each view of this indicator.
|
||||||
const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const;
|
const FIGURAS = {
|
||||||
|
dona: [['fig_c2_donas', 'Grados de biopsia']],
|
||||||
|
tasas: [['fig_c2_barras', 'Tasas por resultado de la citología']],
|
||||||
|
} as const;
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-confirmacion-citologia',
|
selector: 'app-indicador-confirmacion-citologia',
|
||||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, BarrasHorizontales],
|
||||||
templateUrl: './indicador-confirmacion-citologia.html',
|
templateUrl: './indicador-confirmacion-citologia.html',
|
||||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||||
})
|
})
|
||||||
@@ -27,6 +32,11 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
@Input({ required: true }) tema!: Tema;
|
@Input({ required: true }) tema!: Tema;
|
||||||
@Input({ required: true }) applied!: GlobalApplied;
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
@Input() visible = true;
|
@Input() visible = true;
|
||||||
|
// False when the card above already says the general filter this view follows.
|
||||||
|
@Input() mostrarFiltro = true;
|
||||||
|
@Input() permitirSeleccion = true;
|
||||||
|
// The indicator has two views with their own selection: the biopsy donut and the rates by cytology.
|
||||||
|
@Input() vista: 'dona' | 'tasas' = 'tasas';
|
||||||
@Input() metadata?: IndicadorMetadatos;
|
@Input() metadata?: IndicadorMetadatos;
|
||||||
readonly metadataRequested = output<void>();
|
readonly metadataRequested = output<void>();
|
||||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||||
@@ -35,7 +45,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
periods: string[] = [];
|
periods: string[] = [];
|
||||||
periodIndex = 0;
|
periodIndex = 0;
|
||||||
model?: ModeloConfirmacion;
|
model?: ModeloConfirmacion;
|
||||||
donutFigure?: PlotlyFigure;
|
barras?: ConjuntoBarras;
|
||||||
ratesFigure?: PlotlyFigure;
|
ratesFigure?: PlotlyFigure;
|
||||||
helpOpen = false;
|
helpOpen = false;
|
||||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||||
@@ -48,6 +58,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||||
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||||
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
||||||
|
get totales() { return this.model ? totalesPublicados(this.model) : undefined; }
|
||||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
||||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||||
readonly estadoTasa = estadoTasa;
|
readonly estadoTasa = estadoTasa;
|
||||||
@@ -55,7 +66,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||||
get readingGuide() {
|
get readingGuide() {
|
||||||
const details = this.metadata?.figuras_detalle ?? [];
|
const details = this.metadata?.figuras_detalle ?? [];
|
||||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
return FIGURAS[this.vista].flatMap(([figura, nombre]) => {
|
||||||
const detail = details.find(item => item.figura === figura);
|
const detail = details.find(item => item.figura === figura);
|
||||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||||
@@ -73,12 +84,12 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
if (!this.visible) { this.status.set('deferred'); return; }
|
if (!this.visible) { this.status.set('deferred'); return; }
|
||||||
this.load();
|
this.load();
|
||||||
} else if (this.visible && !this.loaded) this.load();
|
} else if (this.visible && !this.loaded) this.load();
|
||||||
else if (this.model && changes['tema']) this.draw();
|
else if (this.model && (changes['tema'] || changes['permitirSeleccion'])) this.draw();
|
||||||
}
|
}
|
||||||
retry() { if (this.visible) this.load(); }
|
retry() { if (this.visible) this.load(); }
|
||||||
private clear() {
|
private clear() {
|
||||||
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
||||||
this.donutFigure = undefined; this.ratesFigure = undefined;
|
this.barras = undefined; this.ratesFigure = undefined;
|
||||||
}
|
}
|
||||||
private load() {
|
private load() {
|
||||||
this.subscription?.unsubscribe();
|
this.subscription?.unsubscribe();
|
||||||
@@ -123,17 +134,16 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
this.periodIndex += step; this.activatePeriod();
|
this.periodIndex += step; this.activatePeriod();
|
||||||
}
|
}
|
||||||
select(trace: string, index = 0) {
|
select(trace: string, index = 0) {
|
||||||
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
if (!this.permitirSeleccion || !this.model || !this.selection || this.status() !== 'ready') return;
|
||||||
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
|
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
|
||||||
}
|
}
|
||||||
plotClicked(event: unknown) {
|
|
||||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
|
||||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
|
||||||
}
|
|
||||||
private draw() {
|
private draw() {
|
||||||
if (!this.model || !this.selection) return;
|
if (!this.model || !this.selection) return;
|
||||||
this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema);
|
if (this.vista === 'dona') {
|
||||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
const barras = barrasBiopsia(this.model, this.selection);
|
||||||
|
this.barras = this.permitirSeleccion ? barras : { ...barras, activas: null };
|
||||||
|
}
|
||||||
|
else this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
||||||
this.changeDetector.markForCheck();
|
this.changeDetector.markForCheck();
|
||||||
}
|
}
|
||||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||||
|
|||||||
@@ -7,8 +7,8 @@
|
|||||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
}
|
}
|
||||||
@if (status() === 'ready' && model; as m) {
|
@if (status() === 'ready' && model; as m) {
|
||||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
|
@let tituloMastografias = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en ' + m.periodo;
|
||||||
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
|
@let tituloPacientes = 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en ' + m.periodo;
|
||||||
@if (pages.length > 1) {
|
@if (pages.length > 1) {
|
||||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||||
|
|||||||
@@ -1,64 +1,74 @@
|
|||||||
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
|
<section class="eu7" aria-label="Resultados citológicos">
|
||||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
<div class="encabezado">
|
||||||
|
@if (mostrarFiltro) { <p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p> }
|
||||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||||
@if (helpOpen) {
|
@if (helpOpen) {
|
||||||
<div class="methodology">
|
<div class="methodology">
|
||||||
@if (metadata) {
|
@if (!permitirSeleccion) {
|
||||||
|
<p>Cada barra muestra pacientes por resultado citológico y su porcentaje del total con resultado disponible. Los encabezados reúnen las categorías en grupos clínicos. «Sin dato» se informa fuera de la distribución.</p>
|
||||||
|
} @else if (metadata) {
|
||||||
@for (guide of readingGuide; track guide.figura) {
|
@for (guide of readingGuide; track guide.figura) {
|
||||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||||
<h3>{{ guide.nombre }}</h3>
|
<h3>{{ guide.nombre }}</h3>
|
||||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||||
</section>
|
</section>
|
||||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
} @empty { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
|
||||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@switch (status()) {
|
@switch (status()) {
|
||||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos" /><p role="status">Cargando resultados citológicos…</p> }
|
||||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
}
|
}
|
||||||
@if (status() === 'ready' || status() === 'empty') {
|
@if (status() === 'ready' || status() === 'empty') {
|
||||||
@if (periods.length > 1) {
|
@if (periods.length > 1) {
|
||||||
<nav class="periods" aria-label="Periodos de dona y barras EU7">
|
<nav class="periods" aria-label="Periodos de resultados citológicos">
|
||||||
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
<button type="button" aria-label="Periodo anterior de resultados citológicos" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||||
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
<button type="button" aria-label="Periodo siguiente de resultados citológicos" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
@if (model; as m) {
|
@if (model; as m) {
|
||||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
|
@if (permitirSeleccion) { <p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p> }
|
||||||
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
||||||
@else {
|
@else if (permitirSeleccion) {
|
||||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
|
<div class="legend" role="group" aria-label="Explorar grupos y categorías de resultados citológicos">
|
||||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
|
<div class="tab-bar"><div class="tabs" role="group" aria-label="Grupos del anillo interior">
|
||||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
|
||||||
@for (g of m.grupos; track g.id; let i = $index) {
|
@for (g of m.grupos; track g.id; let i = $index) {
|
||||||
<button type="button" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
<button type="button" class="tab" [style.--swatch]="g.color" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||||
}
|
}
|
||||||
</div>
|
</div></div>
|
||||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
<div class="child-groups" role="group" aria-label="Categorías del anillo exterior">
|
||||||
@for (c of m.categorias; track c.id; let i = $index) {
|
@for (g of m.grupos; track g.id) {
|
||||||
<button type="button" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
<div class="tab-panel" role="group" [attr.aria-label]="g.etiqueta">
|
||||||
|
@for (c of m.categorias; track c.id; let i = $index) {
|
||||||
|
@if (c.grupo === g.id) {
|
||||||
|
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="figures">
|
}
|
||||||
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
|
}
|
||||||
@if (m.total !== null && m.total > 0 && donutFigure) {
|
}
|
||||||
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
</div>
|
||||||
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
|
<div class="cuerpo">
|
||||||
<p>{{ sinDatoNote }}</p>
|
@if (status() === 'ready' || status() === 'empty') {
|
||||||
</section>
|
@if (model; as m) {
|
||||||
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
|
@if (status() !== 'empty') {
|
||||||
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
|
<section class="figure"><h3>Distribución de resultados citológicos, {{ m.periodo }}</h3>
|
||||||
@if (m.escenarios.length && barsFigure) {
|
@if (m.total === 0) { <p role="status">Sin pacientes con resultado disponible.</p> }
|
||||||
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
@else {
|
||||||
}
|
@if (m.total === null) { <p role="status">Total no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial ni porcentajes.</p> }
|
||||||
</section>
|
@if (barras) { <app-barras-horizontales [conjunto]="barras" [titulo]="'Resultados citológicos, ' + m.periodo + (permitirSeleccion ? ', selección: ' + selectionLabel : '')" /> }
|
||||||
</div>
|
}
|
||||||
|
<p>{{ sinDatoNote }}</p>
|
||||||
|
</section>
|
||||||
}
|
}
|
||||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||||
<details class="published-values"><summary>Valores publicados</summary>
|
<details class="published-values"><summary>Valores publicados</summary>
|
||||||
@@ -75,4 +85,5 @@
|
|||||||
</details>
|
</details>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
@use './indicadores-cacu-botones';
|
||||||
:host { display: block; min-width: 0; }
|
:host { display: block; min-width: 0; }
|
||||||
.eu7 { min-width: 0; padding-top: var(--issste-space-3); }
|
.eu7 { min-width: 0; padding-top: var(--issste-space-3); }
|
||||||
p, h3, summary { overflow-wrap: anywhere; }
|
p, h3, summary { overflow-wrap: anywhere; }
|
||||||
@@ -14,10 +15,8 @@ button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inse
|
|||||||
button:disabled { opacity: .5; cursor: default; }
|
button:disabled { opacity: .5; cursor: default; }
|
||||||
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
||||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
|
|
||||||
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||||
h3 { font-size: 1rem; line-height: 1.5; }
|
h3 { font-size: 1rem; line-height: 1.5; }
|
||||||
app-plotly-chart { --plot-height: 440px; }
|
|
||||||
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||||
.periods span { text-align: center; }
|
.periods span { text-align: center; }
|
||||||
.periods button { min-width: 44px; font-size: 1.5rem; }
|
.periods button { min-width: 44px; font-size: 1.5rem; }
|
||||||
@@ -26,7 +25,6 @@ summary { cursor: pointer; padding-block: .75rem; }
|
|||||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||||
caption { text-align: start; font-weight: 600; }
|
caption { text-align: start; font-weight: 600; }
|
||||||
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } }
|
|
||||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||||
.reading-guide + .reading-guide { margin-top: 1rem; }
|
.reading-guide + .reading-guide { margin-top: 1rem; }
|
||||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { Component, input, output } from '@angular/core';
|
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
@@ -8,15 +7,9 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
|||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
|
||||||
import { GlobalApplied } from './indicadores-memory';
|
import { GlobalApplied } from './indicadores-memory';
|
||||||
import { Indicador } from './indicadores.models';
|
import { Indicador } from './indicadores.models';
|
||||||
|
|
||||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
|
||||||
class ChartStub {
|
|
||||||
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>();
|
|
||||||
plotClick = output<unknown>();
|
|
||||||
}
|
|
||||||
describe('EU7 integración Angular y caché compartida', () => {
|
describe('EU7 integración Angular y caché compartida', () => {
|
||||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||||
const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0',
|
const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0',
|
||||||
@@ -27,7 +20,6 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
let data: typeof fixtureData;
|
let data: typeof fixtureData;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||||
TestBed.overrideComponent(IndicadorEu7Escenario, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
|
||||||
http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData);
|
http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData);
|
||||||
f = TestBed.createComponent(IndicadorEu7Escenario);
|
f = TestBed.createComponent(IndicadorEu7Escenario);
|
||||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
|
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
|
||||||
@@ -46,23 +38,33 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
|
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
|
||||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||||
flush(); expect(f.componentInstance.model!.total).toBe(946);
|
flush(); expect(f.componentInstance.model!.total).toBe(946);
|
||||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||||
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
|
expect(f.nativeElement.querySelector('app-barras-horizontales .den').textContent).toContain('946');
|
||||||
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
|
|
||||||
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
|
|
||||||
const general = data.general; const original = structuredClone(applied);
|
const general = data.general; const original = structuredClone(applied);
|
||||||
const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>).find(b => b.textContent!.includes('Anormal'))!;
|
const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>).find(b => b.textContent!.includes('Anormal'))!;
|
||||||
anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL');
|
anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL');
|
||||||
const chart = f.debugElement.queryAll(By.directive(ChartStub))[0].componentInstance as ChartStub;
|
f.componentInstance.select('categorias', 4); f.detectChanges();
|
||||||
chart.plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 4 }] }); f.detectChanges();
|
|
||||||
expect(f.componentInstance.selection.categoria).toBe('LIEAG');
|
expect(f.componentInstance.selection.categoria).toBe('LIEAG');
|
||||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG');
|
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG');
|
||||||
f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges();
|
f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges();
|
||||||
expect(f.componentInstance.selection).toEqual({});
|
expect(f.componentInstance.selection).toEqual({});
|
||||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
|
||||||
expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839');
|
|
||||||
expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe();
|
expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe();
|
||||||
});
|
});
|
||||||
|
it('desde TOTAL, elegir un hijo activa y abre su grupo sin volver a pedir datos', () => {
|
||||||
|
f.detectChanges(); flush();
|
||||||
|
const button = (name: string) => Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>)
|
||||||
|
.find(item => item.textContent?.trim() === name)!;
|
||||||
|
const child = button('LIEAG'), parent = button('Anormal');
|
||||||
|
expect(parent.getAttribute('aria-pressed')).toBe('false');
|
||||||
|
child.click(); f.detectChanges();
|
||||||
|
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' });
|
||||||
|
expect(parent.getAttribute('aria-pressed')).toBe('true');
|
||||||
|
expect(child.getAttribute('aria-pressed')).toBe('true');
|
||||||
|
expect([...f.componentInstance.barras!.activas!]).toEqual(['LIEAG']);
|
||||||
|
child.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||||
|
parent.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({});
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => {
|
it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => {
|
||||||
const periods: [string, string] = ['2025-S1', '2025-S2'];
|
const periods: [string, string] = ['2025-S1', '2025-S2'];
|
||||||
for (const d of [data.general, data.estatus_seguimiento]) {
|
for (const d of [data.general, data.estatus_seguimiento]) {
|
||||||
@@ -71,15 +73,26 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
}
|
}
|
||||||
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
|
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
|
||||||
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
|
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
|
||||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub);
|
const barrasAntes = f.nativeElement.querySelectorAll('app-barras-horizontales')[0];
|
||||||
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
|
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
|
||||||
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
|
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
|
||||||
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
|
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
|
||||||
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')[0]).toBe(barrasAntes);
|
||||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
|
|
||||||
expect(charts.map(chart => chart.animated())).toEqual([true, true]);
|
|
||||||
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
|
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
|
||||||
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
// The card draws one donut whatever is selected: no scenario bars in any selection state, and the scenario values stay in the table.
|
||||||
|
it('no dibuja barras por escenario en ningún estado de selección y conserva sus valores en la tabla', () => {
|
||||||
|
f.detectChanges(); flush();
|
||||||
|
const estados: [string, number][] = [['grupos', 1], ['categorias', 4], ['centro', 0]];
|
||||||
|
for (const [traza, indice] of [['', 0] as [string, number], ...estados]) {
|
||||||
|
if (traza) f.componentInstance.select(traza, indice);
|
||||||
|
f.detectChanges();
|
||||||
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||||
|
expect((f.componentInstance as unknown as { barsFigure?: unknown }).barsFigure).toBeUndefined();
|
||||||
|
expect(f.nativeElement.textContent).not.toContain('por escenario clínico,');
|
||||||
|
}
|
||||||
|
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').textContent).toContain('Denominador válido');
|
||||||
});
|
});
|
||||||
it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => {
|
it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => {
|
||||||
f.detectChanges(); const r = requests(); r.general.flush(data.general);
|
f.detectChanges(); const r = requests(); r.general.flush(data.general);
|
||||||
@@ -99,7 +112,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
it('error de red permite reintento sin figuras engañosas', () => {
|
it('error de red permite reintento sin figuras engañosas', () => {
|
||||||
f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges();
|
f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges();
|
||||||
expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error');
|
expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error');
|
||||||
expect(f.componentInstance.donutFigure).toBeUndefined();
|
expect(f.componentInstance.barras).toBeUndefined();
|
||||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||||
});
|
});
|
||||||
it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => {
|
it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => {
|
||||||
@@ -112,12 +125,12 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
});
|
});
|
||||||
it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => {
|
it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => {
|
||||||
data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush();
|
data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush();
|
||||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0);
|
||||||
});
|
});
|
||||||
it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => {
|
it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => {
|
||||||
data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = [];
|
data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = [];
|
||||||
f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty');
|
f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty');
|
||||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0);
|
||||||
expect(f.nativeElement.textContent).toContain('No hay pacientes publicados');
|
expect(f.nativeElement.textContent).toContain('No hay pacientes publicados');
|
||||||
});
|
});
|
||||||
it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => {
|
it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => {
|
||||||
@@ -134,13 +147,13 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
});
|
});
|
||||||
it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => {
|
it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => {
|
||||||
f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges();
|
f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges();
|
||||||
const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure;
|
const barras = f.componentInstance.barras;
|
||||||
f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges();
|
f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges();
|
||||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||||
expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
|
expect(f.componentInstance.barras).toBe(barras);
|
||||||
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true);
|
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('«Cómo leer» muestra solo la descripción y el como_leer publicados de dona y barras, sin la ficha', () => {
|
it('«Cómo leer» muestra solo la descripción y el como_leer publicados de la dona, sin la ficha', () => {
|
||||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||||
const toggle = f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
const toggle = f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||||
@@ -159,11 +172,10 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
}); f.detectChanges();
|
}); f.detectChanges();
|
||||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||||
const guides = [...help.querySelectorAll('.reading-guide')] as HTMLElement[];
|
const guides = [...help.querySelectorAll('.reading-guide')] as HTMLElement[];
|
||||||
expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Dona de dos anillos', 'Barras por escenario clínico']);
|
expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Distribución de resultados citológicos']);
|
||||||
expect([...guides[0].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona así.']);
|
expect([...guides[0].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona así.']);
|
||||||
expect(guides[1].querySelector('p')!.textContent).toBe('Barras por escenario.');
|
expect(help.textContent).not.toContain('Lee las barras así.');
|
||||||
expect([...guides[1].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las barras así.']);
|
for (const absent of ['Barras por escenario', 'Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior'])
|
||||||
for (const absent of ['Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior'])
|
|
||||||
expect(help.textContent).not.toContain(absent);
|
expect(help.textContent).not.toContain(absent);
|
||||||
expect(help.querySelector('details')).toBeNull();
|
expect(help.querySelector('details')).toBeNull();
|
||||||
f.componentRef.setInput('metadata', { figuras_detalle: [] }); f.detectChanges();
|
f.componentRef.setInput('metadata', { figuras_detalle: [] }); f.detectChanges();
|
||||||
|
|||||||
@@ -3,21 +3,23 @@ import { HttpErrorResponse } from '@angular/common/http';
|
|||||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { BarrasHorizontales } from './barras-horizontales';
|
||||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { ConjuntoBarras } from './indicadores-barras';
|
||||||
|
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||||
import { httpMessage } from './indicadores-http';
|
import { httpMessage } from './indicadores-http';
|
||||||
import { percentText } from './indicadores-format';
|
import { percentText } from './indicadores-format';
|
||||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
import { barrasCitologia, Celda, clic, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||||
|
|
||||||
const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const;
|
// Only the donut is drawn; the scenario figure has no entry in the reading guide.
|
||||||
|
const EU7_FIGURES = [['fig_c2_donas', 'Distribución de resultados citológicos']] as const;
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-eu7-escenario',
|
selector: 'app-indicador-eu7-escenario',
|
||||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
imports: [MatButtonModule, MatProgressBarModule, BarrasHorizontales],
|
||||||
templateUrl: './indicador-eu7-escenario.html',
|
templateUrl: './indicador-eu7-escenario.html',
|
||||||
styleUrl: './indicador-eu7-escenario.scss',
|
styleUrl: './indicador-eu7-escenario.scss',
|
||||||
})
|
})
|
||||||
@@ -27,6 +29,9 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
@Input({ required: true }) tema!: Tema;
|
@Input({ required: true }) tema!: Tema;
|
||||||
@Input({ required: true }) applied!: GlobalApplied;
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
@Input() visible = true;
|
@Input() visible = true;
|
||||||
|
// False when the card above already says the general filter this view follows.
|
||||||
|
@Input() mostrarFiltro = true;
|
||||||
|
@Input() permitirSeleccion = true;
|
||||||
@Input() metadata?: IndicadorMetadatos;
|
@Input() metadata?: IndicadorMetadatos;
|
||||||
readonly metadataRequested = output<void>();
|
readonly metadataRequested = output<void>();
|
||||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||||
@@ -35,8 +40,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
periods: string[] = [];
|
periods: string[] = [];
|
||||||
periodIndex = 0;
|
periodIndex = 0;
|
||||||
model?: Modelo;
|
model?: Modelo;
|
||||||
donutFigure?: PlotlyFigure;
|
barras?: ConjuntoBarras;
|
||||||
barsFigure?: PlotlyFigure;
|
|
||||||
helpOpen = false;
|
helpOpen = false;
|
||||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||||
@@ -51,9 +55,9 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
if (!m) return '';
|
if (!m) return '';
|
||||||
if (m.vacio) return 'No hay registros publicados en este periodo.';
|
if (m.vacio) return 'No hay registros publicados en este periodo.';
|
||||||
const n = m.sinDato.n;
|
const n = m.sinDato.n;
|
||||||
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la distribución.`
|
||||||
: m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.`
|
: m.total === null ? `Fuera de la distribución: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la distribución no disponible.`
|
||||||
: `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
|
: `Fuera de la distribución: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
|
||||||
}
|
}
|
||||||
get generalCells() {
|
get generalCells() {
|
||||||
const m = this.model;
|
const m = this.model;
|
||||||
@@ -86,22 +90,23 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
if (key !== this.key) {
|
if (key !== this.key) {
|
||||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||||
this.pages = []; this.periods = []; this.model = undefined;
|
this.pages = []; this.periods = []; this.model = undefined;
|
||||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
this.selection = {}; this.barras = undefined;
|
||||||
if (!this.visible) { this.status.set('deferred'); return; }
|
if (!this.visible) { this.status.set('deferred'); return; }
|
||||||
this.load();
|
this.load();
|
||||||
} else if (this.visible && !this.loaded) this.load();
|
} else if (this.visible && !this.loaded) this.load();
|
||||||
else if (this.model && changes['tema']) this.draw();
|
else if (this.model && (changes['tema'] || changes['permitirSeleccion'])) this.draw();
|
||||||
// Visibility and metadata changes must not restart Plotly rendering.
|
// Visibility and metadata changes must not restart Plotly rendering.
|
||||||
}
|
}
|
||||||
retry() { if (this.visible) this.load(); }
|
retry() { if (this.visible) this.load(); }
|
||||||
private load() {
|
private load() {
|
||||||
this.subscription?.unsubscribe();
|
this.subscription?.unsubscribe();
|
||||||
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
||||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
this.selection = {}; this.barras = undefined;
|
||||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
||||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||||
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|
|| !(stratifiedCapabilities(this.indicador).includes(ESTRATO) || declaraEstrato(this.indicador, ESTRATO))
|
||||||
|
|| !compatibility.compatible) {
|
||||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
||||||
this.status.set('incompatible'); return;
|
this.status.set('incompatible'); return;
|
||||||
}
|
}
|
||||||
@@ -124,7 +129,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
private failure(error: unknown) {
|
private failure(error: unknown) {
|
||||||
this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined;
|
this.model = undefined; this.barras = undefined;
|
||||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||||
: error instanceof Eu7Incompatible ? error.message
|
: error instanceof Eu7Incompatible ? error.message
|
||||||
: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit'
|
: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit'
|
||||||
@@ -141,17 +146,12 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
this.periodIndex += step; this.activatePeriod();
|
this.periodIndex += step; this.activatePeriod();
|
||||||
}
|
}
|
||||||
select(trace: string, index = 0) {
|
select(trace: string, index = 0) {
|
||||||
if (!this.model || this.status() !== 'ready') return;
|
if (!this.permitirSeleccion || !this.model || this.status() !== 'ready') return;
|
||||||
this.selection = clic(this.model, this.selection, trace, index); this.draw();
|
this.selection = clic(this.model, this.selection, trace, index); this.draw();
|
||||||
}
|
}
|
||||||
plotClicked(event: unknown) {
|
|
||||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
|
||||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
|
||||||
}
|
|
||||||
private draw() {
|
private draw() {
|
||||||
if (!this.model) return;
|
if (!this.model) return;
|
||||||
this.donutFigure = dona(this.model, this.selection, this.tema);
|
this.barras = barrasCitologia(this.model, this.permitirSeleccion ? this.selection : {});
|
||||||
this.barsFigure = barras(this.model, this.selection, this.tema);
|
|
||||||
this.changeDetector.markForCheck();
|
this.changeDetector.markForCheck();
|
||||||
}
|
}
|
||||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { Component, Input } from '@angular/core';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
|
||||||
|
/** A figure the catalog does not publish yet: it keeps its place and title, with no figure and no number. */
|
||||||
|
@Component({
|
||||||
|
selector: 'app-indicador-figura-pendiente',
|
||||||
|
imports: [MatCardModule],
|
||||||
|
template: `
|
||||||
|
<mat-card>
|
||||||
|
<h2>{{ titulo }}</h2>
|
||||||
|
<p class="estado" role="status"><strong>Integración pendiente.</strong> {{ detalle }}</p>
|
||||||
|
<div class="vacio">Sin datos publicados</div>
|
||||||
|
</mat-card>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
:host { display: flex; min-width: 0; margin: 0; }
|
||||||
|
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text);
|
||||||
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||||
|
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||||
|
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||||
|
.estado { color: var(--issste-text-secondary); }
|
||||||
|
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
|
||||||
|
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class IndicadorFiguraPendiente {
|
||||||
|
@Input({ required: true }) titulo!: string;
|
||||||
|
@Input() detalle = 'Este indicador aún no está publicado por el catálogo institucional.';
|
||||||
|
}
|
||||||
@@ -1,5 +1,12 @@
|
|||||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
<mat-card class="figure-card" [class.sin-marco]="ayudaRedonda" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||||
@if (selected) {
|
@if (selected && ayudaRedonda) {
|
||||||
|
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + selected.titulo" (opened)="!metadata && metadataRequested.emit()">
|
||||||
|
<ul class="ayuda-lista">@for (line of interpretation; track $index) { <li>{{ line }}</li> }</ul>
|
||||||
|
@if (state.status === 'ready' && state.footnotes?.length) {
|
||||||
|
@for (note of state.footnotes; track $index) { <p class="ayuda-nota">{{ note }}</p> }
|
||||||
|
}
|
||||||
|
</app-indicador-ayuda>
|
||||||
|
} @else if (selected) {
|
||||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
|
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
|
||||||
@@ -37,8 +44,10 @@
|
|||||||
@if (hasNoVisibleValues(figure)) {
|
@if (hasNoVisibleValues(figure)) {
|
||||||
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
|
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
|
||||||
}
|
}
|
||||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
@if (!ayudaRedonda) {
|
||||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||||
|
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||||
|
}
|
||||||
} @else {
|
} @else {
|
||||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||||
}
|
}
|
||||||
@@ -84,7 +93,7 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (state.status === 'ready' && state.highlight; as h) {
|
@if (state.status === 'ready' && state.highlight; as h) {
|
||||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
<div class="highlight-legend" [class.sin-estado]="ayudaRedonda" role="group" aria-label="Resaltar partes de la figura">
|
||||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
|
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
|
||||||
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
||||||
|
.figure-card.sin-marco { position: static; border: 0; box-shadow: none; background: transparent; --mat-card-outlined-outline-width: 0; --mat-card-elevated-container-elevation: none; }
|
||||||
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
|
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
|
||||||
.interpretation { grid-row: 1; }
|
.interpretation { grid-row: 1; }
|
||||||
.figure-legend { grid-row: 3; min-width: 0; }
|
.figure-legend { grid-row: 3; min-width: 0; }
|
||||||
@@ -117,6 +118,7 @@
|
|||||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||||
.dark .highlight-legend { color: #eef1f7; }
|
.dark .highlight-legend { color: #eef1f7; }
|
||||||
.highlight-status { margin: 0; font-weight: 600; }
|
.highlight-status { margin: 0; font-weight: 600; }
|
||||||
|
.sin-estado .highlight-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||||
.highlight-back { justify-self: start; }
|
.highlight-back { justify-self: start; }
|
||||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||||
@@ -126,3 +128,6 @@
|
|||||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||||
.highlight-legend .highlight-group { font-weight: 600; }
|
.highlight-legend .highlight-group { font-weight: 600; }
|
||||||
|
|
||||||
|
.ayuda-lista { margin: 0; padding-left: 1.1rem; }
|
||||||
|
.ayuda-nota { margin: .5rem 0 0; }
|
||||||
|
|||||||
@@ -515,4 +515,14 @@ describe('IndicadorFigureCard', () => {
|
|||||||
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
|
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('con la ayuda redonda no repite el título ni el nombre de la figura', () => {
|
||||||
|
// Fails if TEA's cards bring back the heading box with the title and «Figura: …» under the card's own title.
|
||||||
|
fixture.componentRef.setInput('ayudaRedonda', true);
|
||||||
|
ready({ data: [{ y: [1] }], layout: {} });
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect(root.querySelector('.figure-title')).toBeNull();
|
||||||
|
expect(root.querySelector('.figure-id')).toBeNull();
|
||||||
|
expect(root.querySelector('.ayuda-boton')).not.toBeNull();
|
||||||
|
expect(root.querySelector('.interpretation')).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { figureDisplayName } from './indicadores-figure-labels';
|
|||||||
import { CategoryLabel } from './indicadores-axis-labels';
|
import { CategoryLabel } from './indicadores-axis-labels';
|
||||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { IndicadorAyuda } from './indicador-ayuda';
|
||||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||||
@@ -41,7 +42,7 @@ export interface FigureState {
|
|||||||
selector: 'app-indicador-figure-card',
|
selector: 'app-indicador-figure-card',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
|
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
|
||||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
|
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, IndicadorAyuda],
|
||||||
templateUrl: './indicador-figure-card.html',
|
templateUrl: './indicador-figure-card.html',
|
||||||
styleUrl: './indicador-figure-card.scss',
|
styleUrl: './indicador-figure-card.scss',
|
||||||
})
|
})
|
||||||
@@ -142,6 +143,8 @@ export class IndicadorFigureCard implements OnChanges {
|
|||||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||||
}
|
}
|
||||||
|
// A round "?" button with the reading guide instead of the «Cómo leer» box.
|
||||||
|
@Input() ayudaRedonda = false;
|
||||||
@Input() selected?: Indicador;
|
@Input() selected?: Indicador;
|
||||||
@Input() metadata?: IndicadorMetadatos;
|
@Input() metadata?: IndicadorMetadatos;
|
||||||
@Input({ required: true }) figuraId!: string;
|
@Input({ required: true }) figuraId!: string;
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
fixture.componentRef.setInput('dominio', 'tea');
|
fixture.componentRef.setInput('dominio', 'tea');
|
||||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||||
fixture.componentRef.setInput('figuraId', 'f1');
|
fixture.componentRef.setInput('figuraId', 'f1');
|
||||||
|
// These tests cover the «Cómo leer» box shared by the domains; TEA's round help has its own spec.
|
||||||
|
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||||
fixture.componentRef.setInput('tema', 'claro');
|
fixture.componentRef.setInput('tema', 'claro');
|
||||||
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
||||||
fixture.componentRef.setInput('applied', state.applied);
|
fixture.componentRef.setInput('applied', state.applied);
|
||||||
@@ -373,6 +375,7 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
||||||
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
||||||
|
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||||
fixture.componentRef.setInput('applied', state.applied);
|
fixture.componentRef.setInput('applied', state.applied);
|
||||||
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
||||||
expect(JSON.stringify(state)).toBe(snapshot);
|
expect(JSON.stringify(state)).toBe(snapshot);
|
||||||
|
|||||||
@@ -16,17 +16,58 @@ import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
|||||||
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||||
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||||
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified';
|
||||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-figure-panel',
|
selector: 'app-indicador-figure-panel',
|
||||||
|
host: { '[class.ayuda-externa]': 'conAyudaRedonda' },
|
||||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||||
template: `
|
template: `
|
||||||
<section class="figure-panel" [attr.aria-labelledby]="titleId">
|
<section class="figure-panel" [class.sin-linea]="conAyudaRedonda" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||||
|
@if (sidebar) {
|
||||||
|
<aside class="strata-sidebar" aria-label="Estratificación">
|
||||||
|
<fieldset class="sidebar-group">
|
||||||
|
<legend>Estratificar por</legend>
|
||||||
|
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
|
||||||
|
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
|
||||||
|
(click)="changeDimension('')">Sin estratificar</button>
|
||||||
|
@for (d of capabilities; track d) {
|
||||||
|
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||||
|
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
|
||||||
|
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
|
||||||
|
@if (dimension && estratos.length > 1) {
|
||||||
|
<fieldset class="sidebar-group">
|
||||||
|
<legend>Mostrar</legend>
|
||||||
|
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
|
||||||
|
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
|
||||||
|
@for (e of estratos; track e.valor) {
|
||||||
|
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
|
||||||
|
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
|
||||||
|
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
|
||||||
|
</fieldset>
|
||||||
|
}
|
||||||
|
@if (dimension) {
|
||||||
|
<fieldset class="sidebar-group">
|
||||||
|
<legend>Medida</legend>
|
||||||
|
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||||
|
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||||
|
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
}
|
||||||
|
</aside>
|
||||||
|
}
|
||||||
<header class="panel-controls">
|
<header class="panel-controls">
|
||||||
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
|
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
|
||||||
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
|
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
|
||||||
@@ -36,7 +77,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
|||||||
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
|
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
|
||||||
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
||||||
<legend>Distribución</legend>
|
<legend>Distribución</legend>
|
||||||
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
|
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
|
||||||
@@ -49,10 +90,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
|||||||
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
||||||
@for (d of capabilities; track d) {
|
@for (d of capabilities; track d) {
|
||||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||||
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
|
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
@if (dimension) {
|
||||||
|
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||||
|
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||||
|
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
</fieldset>
|
</fieldset>
|
||||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||||
}
|
}
|
||||||
@@ -64,15 +111,15 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
|||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
</header>
|
</header>
|
||||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
<app-indicador-figure-card [ayudaRedonda]="conAyudaRedonda" [state]="result()" [selected]="indicador"
|
||||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||||
<div class="stratified-detail">
|
<div class="stratified-detail">
|
||||||
@if (dimension && result().status === 'ready') {
|
@if (dimension && result().status === 'ready') {
|
||||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||||
<details><summary>Valores publicados</summary>
|
<details><summary>Valores publicados</summary>
|
||||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
|
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
|
||||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
|
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
|
||||||
</tbody></table></div>
|
</tbody></table></div>
|
||||||
</details>
|
</details>
|
||||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||||
@@ -84,6 +131,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
|||||||
:host { display: grid; min-width: 0; }
|
:host { display: grid; min-width: 0; }
|
||||||
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
|
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
|
||||||
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
|
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
|
||||||
|
.sin-linea .panel-controls { border-top: 0; padding-block: 0; }
|
||||||
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||||
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
|
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
|
||||||
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
|
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
|
||||||
@@ -117,6 +165,32 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
|||||||
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
|
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
|
||||||
.donut-periods button:disabled { opacity: .45; }
|
.donut-periods button:disabled { opacity: .45; }
|
||||||
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
|
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
|
||||||
|
shared with the neighbouring panel, so the bars line up with the donut. */
|
||||||
|
:host { container-type: inline-size; }
|
||||||
|
// A container is a containing block for absolute children; the round help must reach the outer card.
|
||||||
|
:host(.ayuda-externa) { container-type: normal; }
|
||||||
|
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
|
||||||
|
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
|
||||||
|
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
|
||||||
|
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
|
||||||
|
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||||
|
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
|
||||||
|
.sidebar-list { display: grid; gap: .25rem; }
|
||||||
|
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
|
||||||
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
|
||||||
|
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
|
||||||
|
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||||
|
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
|
||||||
|
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
|
||||||
|
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||||
|
.sidebar-reset { margin-top: .5rem; }
|
||||||
|
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||||
|
@container (max-width: 559px) {
|
||||||
|
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
|
||||||
|
.strata-sidebar { position: static; }
|
||||||
|
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
|
||||||
|
}
|
||||||
.visually-hidden {
|
.visually-hidden {
|
||||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||||
@@ -128,6 +202,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
@Input({ required: true }) indicador!: Indicador;
|
@Input({ required: true }) indicador!: Indicador;
|
||||||
@Input() metadata?: IndicadorMetadatos;
|
@Input() metadata?: IndicadorMetadatos;
|
||||||
@Input({ required: true }) figuraId!: string;
|
@Input({ required: true }) figuraId!: string;
|
||||||
|
// Round "?" help instead of the «Cómo leer» box; TEA draws it unless told otherwise.
|
||||||
|
@Input() ayudaRedonda?: boolean;
|
||||||
|
get conAyudaRedonda() { return this.ayudaRedonda ?? this.dominio === 'tea'; }
|
||||||
@Input({ required: true }) tema!: Tema;
|
@Input({ required: true }) tema!: Tema;
|
||||||
@Input({ required: true }) applied!: GlobalApplied;
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
@Input() independentPeriods = false;
|
@Input() independentPeriods = false;
|
||||||
@@ -165,7 +242,39 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||||
}
|
}
|
||||||
dimension: DimensionEstrato | '' = '';
|
dimension: DimensionEstrato | '' = '';
|
||||||
|
readonly etiquetaDimension = etiquetaDimension;
|
||||||
|
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
|
||||||
|
private medidaElegida?: MedidaEstrato;
|
||||||
|
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
|
||||||
|
changeMedida(medida: MedidaEstrato) {
|
||||||
|
if (medida === this.medida) return;
|
||||||
|
this.medidaElegida = medida;
|
||||||
|
this.representStratified();
|
||||||
|
}
|
||||||
cells: StratifiedCell[] = [];
|
cells: StratifiedCell[] = [];
|
||||||
|
/** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */
|
||||||
|
get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; }
|
||||||
|
estratos: StratumOption[] = [];
|
||||||
|
ocultos = new Set<string>();
|
||||||
|
toggleEstrato(valor: string) {
|
||||||
|
const ocultos = new Set(this.ocultos);
|
||||||
|
if (ocultos.has(valor)) ocultos.delete(valor);
|
||||||
|
else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor);
|
||||||
|
else return;
|
||||||
|
this.ocultos = ocultos;
|
||||||
|
this.representStratified();
|
||||||
|
}
|
||||||
|
mostrarTodos() {
|
||||||
|
if (!this.ocultos.size) return;
|
||||||
|
this.ocultos = new Set();
|
||||||
|
this.representStratified();
|
||||||
|
}
|
||||||
|
private representStratified() {
|
||||||
|
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||||
|
try { this.result.set(this.presentStratified(this.stratifiedData)); }
|
||||||
|
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
|
||||||
|
}
|
||||||
|
}
|
||||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||||
private stratifiedData?: IndicadorDatos;
|
private stratifiedData?: IndicadorDatos;
|
||||||
@@ -177,14 +286,18 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
changeDimension(value: DimensionEstrato | '') {
|
changeDimension(value: DimensionEstrato | '') {
|
||||||
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
|
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
|
||||||
if (this.dimension === value) return;
|
if (this.dimension === value) return;
|
||||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
|
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set();
|
||||||
|
this.requestFigure();
|
||||||
}
|
}
|
||||||
chooseStratified() {
|
chooseStratified() {
|
||||||
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
|
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
|
||||||
}
|
}
|
||||||
private presentStratified(data: IndicadorDatos): FigureState {
|
private presentStratified(data: IndicadorDatos): FigureState {
|
||||||
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
||||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
|
this.estratos = stratumOptions(data);
|
||||||
|
const publicados = new Set(this.estratos.map(e => e.valor));
|
||||||
|
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
|
||||||
|
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos, this.dominio);
|
||||||
this.cells = adapted.cells;
|
this.cells = adapted.cells;
|
||||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||||
@@ -349,7 +462,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ngOnChanges(changes: SimpleChanges) {
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
|
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) {
|
||||||
|
this.dimension = ''; this.estratos = []; this.ocultos = new Set();
|
||||||
|
}
|
||||||
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
||||||
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
|
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
|
||||||
this.titleId = identityElementId(identity) + '-title';
|
this.titleId = identityElementId(identity) + '-title';
|
||||||
|
|||||||
@@ -37,10 +37,9 @@ import { MatCardModule } from '@angular/material/card';
|
|||||||
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||||
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
|
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
|
||||||
.value span { margin-inline-start: .3em; }
|
.value span { margin-inline-start: .3em; }
|
||||||
// CaMa's cards are as tall as their grid row.
|
:host-context(.kpi-section) { display: flex; flex-direction: column; }
|
||||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
:host-context(.kpi-section) mat-card { flex: 1 1 auto; height: auto; }
|
||||||
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
|
:host-context(.kpi-section) .value { font-size: 1.65rem; }
|
||||||
:host-context(.kpi-section[data-domain='cama']) .value { font-size: 1.65rem; }
|
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
export class IndicadorKpiCard {
|
export class IndicadorKpiCard {
|
||||||
@@ -48,7 +47,7 @@ export class IndicadorKpiCard {
|
|||||||
@Input() value?: string | number | null;
|
@Input() value?: string | number | null;
|
||||||
@Input() unit?: string;
|
@Input() unit?: string;
|
||||||
@Input() temporalReference?: string;
|
@Input() temporalReference?: string;
|
||||||
// CaMa's opportunity strip shares one period, shown by the parent instead of on every card.
|
// The opportunity strip shares one period, shown by the parent instead of on every card.
|
||||||
@Input() showPeriod = true;
|
@Input() showPeriod = true;
|
||||||
@Input() loading = false;
|
@Input() loading = false;
|
||||||
@Input() notes: string[] = [];
|
@Input() notes: string[] = [];
|
||||||
|
|||||||
@@ -39,7 +39,8 @@ describe('KPI búsqueda inicial del último dato visible', () => {
|
|||||||
latest.flush(data(periods[0], 'suppressed'));
|
latest.flush(data(periods[0], 'suppressed'));
|
||||||
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
|
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
|
||||||
expect(fixture.componentInstance.result().value).toBe(5);
|
expect(fixture.componentInstance.result().value).toBe(5);
|
||||||
expect(fixture.nativeElement.textContent).toContain('Último dato visible, 2025-S1');
|
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible, 2025-S1');
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('Último dato visible');
|
||||||
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
|
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -182,22 +182,19 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
|
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
|
||||||
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
|
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
const cards = [...fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')];
|
||||||
expect(cards).toHaveLength(5);
|
expect(cards).toHaveLength(5);
|
||||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
|
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
|
||||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
|
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
|
||||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
|
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
|
||||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
|
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Integración pendiente', 'Integración pendiente']
|
||||||
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
||||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||||
]));
|
]));
|
||||||
if (domain === 'cama') {
|
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||||
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
|
||||||
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
|
expect(cards.filter(card => card.querySelector('.value')).every(card => card.querySelector('.kpi-state')?.classList.contains('visually-hidden'))).toBe(true);
|
||||||
} else {
|
|
||||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([expect.stringContaining('2025-S1')]));
|
|
||||||
}
|
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||||
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
|
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
|
||||||
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
|
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
|
||||||
|
|||||||
@@ -19,15 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
|||||||
imports: [IndicadorKpiCard, MatButtonModule],
|
imports: [IndicadorKpiCard, MatButtonModule],
|
||||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||||
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'"
|
[loading]="result().loading ?? false" [notes]="notes" [quietWhenAvailable]="true"
|
||||||
[showPeriod]="dominio !== 'cama'" />
|
[showPeriod]="showPeriod" />
|
||||||
@if (result().state === 'Error de consulta') {
|
@if (result().state === 'Error de consulta') {
|
||||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||||
}`,
|
}`,
|
||||||
styles: `
|
styles: `
|
||||||
:host { display: block; min-width: 0; }
|
:host { display: block; min-width: 0; }
|
||||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
:host-context(.kpi-section) { display: flex; flex-direction: column; }
|
||||||
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
|
:host-context(.kpi-section) app-indicador-kpi-card { flex: 1 1 auto; }
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
export class IndicadorKpiPanel implements OnChanges {
|
export class IndicadorKpiPanel implements OnChanges {
|
||||||
@@ -37,6 +37,7 @@ export class IndicadorKpiPanel implements OnChanges {
|
|||||||
@Input() applied?: GlobalApplied;
|
@Input() applied?: GlobalApplied;
|
||||||
@Input() availability?: PeriodAvailability;
|
@Input() availability?: PeriodAvailability;
|
||||||
@Input() initialPresentation = false;
|
@Input() initialPresentation = false;
|
||||||
|
@Input() showPeriod = false;
|
||||||
private readonly queries = inject(IndicadoresKpiQueries);
|
private readonly queries = inject(IndicadoresKpiQueries);
|
||||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
@@ -44,6 +45,10 @@ export class IndicadorKpiPanel implements OnChanges {
|
|||||||
private key = '';
|
private key = '';
|
||||||
readonly usedPeriod = signal<string | undefined>(undefined);
|
readonly usedPeriod = signal<string | undefined>(undefined);
|
||||||
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
||||||
|
get notes(): string[] {
|
||||||
|
const notes = this.dominio === 'tea' ? this.result().notes ?? [] : [];
|
||||||
|
return this.definition.note ? [this.definition.note, ...notes] : notes;
|
||||||
|
}
|
||||||
get temporalReference() {
|
get temporalReference() {
|
||||||
if (this.result().earlier) return 'Último dato visible, ' + this.usedPeriod();
|
if (this.result().earlier) return 'Último dato visible, ' + this.usedPeriod();
|
||||||
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<section class="route" aria-label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje">
|
||||||
|
<h3 class="figure-title">Tiempos de la ruta del tamizaje</h3>
|
||||||
|
@switch (status()) {
|
||||||
|
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||||
|
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando los tiempos de la ruta del tamizaje" /><p role="status">Cargando los tiempos de la ruta…</p> }
|
||||||
|
@case ('error') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
|
@case ('incompatible') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
|
}
|
||||||
|
@if (model(); as m) {
|
||||||
|
<div class="controls">
|
||||||
|
@if (m.period) { <p class="period">Periodo: {{ periodLabel(m.period) }}</p> }
|
||||||
|
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
|
||||||
|
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
|
||||||
|
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
|
||||||
|
</mat-button-toggle-group>
|
||||||
|
</div>
|
||||||
|
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
|
||||||
|
@else if (figure(); as figure) {
|
||||||
|
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
|
||||||
|
<details class="how-to-read"><summary>Cómo leer</summary>
|
||||||
|
<p class="note">
|
||||||
|
@if (view() === 'cumulative') {
|
||||||
|
Barra: mediana de días desde la toma hasta el evento; bigote: Q1 a Q3. Cada evento cuenta solo a quienes llegaron a él.
|
||||||
|
El diagnóstico también se da tras el tamizaje o la colposcopía, por eso puede quedar antes que la biopsia.
|
||||||
|
} @else {
|
||||||
|
Cada barra es el tramo desde el evento anterior; en color, el más lento. Cuenta a quienes llegaron a sus dos eventos,
|
||||||
|
y las medianas de los tramos no suman el acumulado.
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
<details class="published-values"><summary>Valores publicados</summary>
|
||||||
|
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
|
||||||
|
<table><caption>Días por evento en {{ m.period ? periodLabel(m.period) : 'el periodo' }}</caption>
|
||||||
|
<thead><tr><th scope="col">Evento</th><th scope="col">Desde la toma</th><th scope="col">Desde el paso anterior</th></tr></thead>
|
||||||
|
<tbody>@for (row of m.rows; track row.step.id) {
|
||||||
|
<tr><th scope="row">{{ row.step.label }}</th><td>{{ cellText(row.fromSample) }}</td><td>{{ cellText(row.fromPrevious) }}</td></tr>
|
||||||
|
}</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
:host { display: block; min-width: 0; }
|
||||||
|
.route { min-width: 0; padding-top: var(--issste-space-3); }
|
||||||
|
p, h3, summary { overflow-wrap: anywhere; }
|
||||||
|
h3 { font-size: 1rem; line-height: 1.5; }
|
||||||
|
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
|
||||||
|
.how-to-read summary { cursor: pointer; color: var(--issste-text-secondary); }
|
||||||
|
.note { color: var(--issste-text-secondary); max-width: 70ch; }
|
||||||
|
app-plotly-chart { --plot-height: 360px; }
|
||||||
|
summary { cursor: pointer; padding-block: .75rem; }
|
||||||
|
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
|
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||||
|
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||||
|
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||||
|
caption { text-align: start; font-weight: 600; }
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// What this module covers: the screening route component: when it loads, the seven requests it makes, what it draws for
|
||||||
|
// each view and period, and its empty, error and incompatible states. The model and the figure have their own spec
|
||||||
|
// (`screening-route.spec.ts`).
|
||||||
|
// Fixtures: `payload`, synthetic C3r /datos shaped like /cacu/indicadores/<id>/datos; `ChartStub` stands for the chart.
|
||||||
|
import { Component, input } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { By } from '@angular/platform-browser';
|
||||||
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||||
|
import { IndicadorDatos } from './indicadores.models';
|
||||||
|
import { ROUTE_IDS } from './screening-route';
|
||||||
|
|
||||||
|
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||||
|
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
||||||
|
|
||||||
|
const row = (periodo: string, n: number, q1: number, mediana: number, q3: number, suprimido = 0) =>
|
||||||
|
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
|
||||||
|
const MEDIANAS: Record<string, number> = {
|
||||||
|
cacu_eu_tiempo_reporte: 7.9, cacu_dias_toma_colposcopia: 35.7, cacu_dias_resultado_colposcopia: 27.8, cacu_dias_toma_biopsia: 52.1,
|
||||||
|
cacu_dias_colposcopia_biopsia: 16.4, cacu_dias_toma_diagnostico: 18.4, cacu_dias_biopsia_diagnostico: 12.8,
|
||||||
|
};
|
||||||
|
const payload = (id: string, suprimido = 0): IndicadorDatos => ({
|
||||||
|
id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], version: '1',
|
||||||
|
filas: [row('2025-S1', 100, 3, MEDIANAS[id] + 1, MEDIANAS[id] + 9, suprimido), row('2025-S2', 120, 4, MEDIANAS[id], MEDIANAS[id] + 8, suprimido)],
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Ruta del tamizaje: componente', () => {
|
||||||
|
let f: ReturnType<typeof TestBed.createComponent<IndicadorScreeningRoute>>;
|
||||||
|
let http: HttpTestingController;
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({ imports: [IndicadorScreeningRoute], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||||
|
TestBed.overrideComponent(IndicadorScreeningRoute, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
|
f = TestBed.createComponent(IndicadorScreeningRoute);
|
||||||
|
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('tema', 'claro');
|
||||||
|
});
|
||||||
|
afterEach(() => { f.destroy(); http.match(() => true); http.verify(); });
|
||||||
|
// The shared request queue runs a few at a time: answer in waves until nothing is left.
|
||||||
|
function responder(entrega: (id: string) => IndicadorDatos = id => payload(id)) {
|
||||||
|
const vistos: string[] = [];
|
||||||
|
for (;;) {
|
||||||
|
const pendientes = http.match(r => r.url.endsWith('/datos'));
|
||||||
|
if (!pendientes.length) return vistos;
|
||||||
|
for (const r of pendientes) { const id = r.request.url.split('/').at(-2)!; vistos.push(id); r.flush(entrega(id)); }
|
||||||
|
f.detectChanges();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const charts = () => f.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||||
|
|
||||||
|
it('carga diferida; pide las siete medidas; dibuja una gráfica y cambia de vista y de periodo sin otra petición', () => {
|
||||||
|
// Pins down: nothing is requested while hidden, each of the seven measures is requested once, the view and the period
|
||||||
|
// are chosen without new requests, and the theme redraws the same data. Fails if the region loads before it is
|
||||||
|
// visible, a measure is missing or repeated, or a control triggers a request.
|
||||||
|
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||||
|
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||||
|
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||||
|
expect(f.componentInstance.status()).toBe('loading');
|
||||||
|
expect(responder().sort()).toEqual([...ROUTE_IDS].sort());
|
||||||
|
expect(f.componentInstance.status()).toBe('ready');
|
||||||
|
expect(charts()).toHaveLength(1);
|
||||||
|
expect(charts()[0].figure()).toBe(f.componentInstance.figure());
|
||||||
|
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
|
||||||
|
f.componentInstance.selectView('steps'); f.detectChanges();
|
||||||
|
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
|
||||||
|
// the period follows the page's filter, with no request of its own
|
||||||
|
f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges();
|
||||||
|
expect(f.componentInstance.model()!.period).toBe('2025-S1');
|
||||||
|
expect(f.nativeElement.querySelector('mat-select')).toBeNull();
|
||||||
|
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||||
|
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('la tabla de valores publicados dice la mediana de cada evento y el estado si no hay caja', () => {
|
||||||
|
// Fails if the table drops an event or shows a suppressed box as a number.
|
||||||
|
f.detectChanges();
|
||||||
|
responder(id => (id === 'cacu_dias_toma_biopsia' ? payload(id, 1) : payload(id)));
|
||||||
|
const text = f.nativeElement.querySelector('table').textContent as string;
|
||||||
|
expect(text).toContain('Resultado de citología');
|
||||||
|
expect(text).toContain('mediana 35.7');
|
||||||
|
expect(text).toContain('Suprimido');
|
||||||
|
});
|
||||||
|
it('la lectura de la gráfica es breve y va plegada en «Cómo leer»', () => {
|
||||||
|
// Fails if the reading note goes back to an open paragraph under the chart.
|
||||||
|
f.detectChanges();
|
||||||
|
responder(id => payload(id));
|
||||||
|
const guia = f.nativeElement.querySelector('details.how-to-read') as HTMLDetailsElement;
|
||||||
|
expect(guia.querySelector('summary')!.textContent).toBe('Cómo leer');
|
||||||
|
expect(guia.open).toBe(false);
|
||||||
|
expect(guia.textContent).toContain('bigote: Q1 a Q3');
|
||||||
|
expect(f.nativeElement.querySelector('section > p.note')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||||
|
// Fails if an empty route draws a chart or hides the reason.
|
||||||
|
f.detectChanges();
|
||||||
|
responder(id => payload(id, 1));
|
||||||
|
expect(f.componentInstance.status()).toBe('empty');
|
||||||
|
expect(charts()).toHaveLength(0);
|
||||||
|
expect(f.nativeElement.textContent).toContain('No hay tiempos publicados');
|
||||||
|
});
|
||||||
|
it('un fallo del servicio se anuncia como error y reintentar vuelve a pedir', () => {
|
||||||
|
// Fails if an error leaves a stale chart, hides the alert, or retry does not request again.
|
||||||
|
f.detectChanges();
|
||||||
|
http.match(r => r.url.endsWith('/datos'))[0].flush({}, { status: 500, statusText: 'Server Error' });
|
||||||
|
f.detectChanges();
|
||||||
|
expect(f.componentInstance.status()).toBe('error');
|
||||||
|
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||||
|
expect(charts()).toHaveLength(0);
|
||||||
|
http.match(() => true); // the other requests of the first try were cancelled with it
|
||||||
|
f.componentInstance.retry(); f.detectChanges();
|
||||||
|
expect(f.componentInstance.status()).toBe('loading');
|
||||||
|
expect(responder().length).toBe(ROUTE_IDS.length);
|
||||||
|
expect(f.componentInstance.status()).toBe('ready');
|
||||||
|
});
|
||||||
|
it('datos de otro contrato quedan incompatibles y no se dibujan', () => {
|
||||||
|
// Fails if a payload that is not a duration is drawn as one.
|
||||||
|
f.detectChanges();
|
||||||
|
responder(id => (id === 'cacu_dias_toma_biopsia' ? { ...payload(id), contrato: 'C1' } : payload(id)));
|
||||||
|
expect(f.componentInstance.status()).toBe('incompatible');
|
||||||
|
expect(charts()).toHaveLength(0);
|
||||||
|
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||||
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||||
|
import { etiquetaPeriodo } from './indicadores-historico-figures';
|
||||||
|
import { httpMessage } from './indicadores-http';
|
||||||
|
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||||
|
import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, routeHasData, routeModel } from './screening-route';
|
||||||
|
|
||||||
|
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
|
||||||
|
@Component({
|
||||||
|
selector: 'app-indicador-screening-route',
|
||||||
|
imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
|
||||||
|
templateUrl: './indicador-screening-route.html',
|
||||||
|
styleUrl: './indicador-screening-route.scss',
|
||||||
|
})
|
||||||
|
export class IndicadorScreeningRoute {
|
||||||
|
readonly dominio = input.required<Dominio>();
|
||||||
|
readonly tema = input.required<Tema>();
|
||||||
|
readonly tipo = input<TipoPeriodo>('semestre');
|
||||||
|
/** The periods of the page's filter: the chart shows the newest of them with data, and has no period filter of its own. */
|
||||||
|
readonly periodos = input<readonly string[] | undefined>(undefined);
|
||||||
|
/** The measures load once the region is visible. */
|
||||||
|
readonly visible = input(true);
|
||||||
|
|
||||||
|
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||||
|
readonly message = signal('');
|
||||||
|
readonly view = signal<RouteView>('cumulative');
|
||||||
|
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
|
||||||
|
readonly model = computed(() => {
|
||||||
|
const data = this.payloads();
|
||||||
|
return data ? routeModel(data, this.tipo(), this.periodos()) : undefined;
|
||||||
|
});
|
||||||
|
readonly figure = computed(() => {
|
||||||
|
const model = this.model();
|
||||||
|
return model && routeHasData(model) ? routeFigure(model, this.view(), this.tema()) : undefined;
|
||||||
|
});
|
||||||
|
readonly periodLabel = etiquetaPeriodo;
|
||||||
|
readonly cellText = routeCellText;
|
||||||
|
|
||||||
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||||
|
private subscription?: Subscription;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
effect(() => {
|
||||||
|
const dominio = this.dominio(), tipo = this.tipo();
|
||||||
|
if (!this.visible()) { this.status.set('deferred'); return; }
|
||||||
|
untracked(() => this.load(dominio, tipo));
|
||||||
|
});
|
||||||
|
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
||||||
|
}
|
||||||
|
|
||||||
|
retry() { this.load(this.dominio(), this.tipo()); }
|
||||||
|
selectView(view: RouteView) { this.view.set(view); }
|
||||||
|
|
||||||
|
private load(dominio: Dominio, tipo: TipoPeriodo) {
|
||||||
|
this.subscription?.unsubscribe();
|
||||||
|
this.payloads.set(undefined);
|
||||||
|
this.status.set('loading');
|
||||||
|
const requests = Object.fromEntries(ROUTE_IDS.map(id => [id, this.snapshots.datos(dominio, id, tipo)]));
|
||||||
|
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
|
||||||
|
next: data => {
|
||||||
|
try {
|
||||||
|
const model = routeModel(data, tipo, this.periodos());
|
||||||
|
this.payloads.set(data);
|
||||||
|
this.status.set(routeHasData(model) ? 'ready' : 'empty');
|
||||||
|
} catch (error) { this.failure(error); }
|
||||||
|
},
|
||||||
|
error: error => this.failure(error),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private failure(error: unknown) {
|
||||||
|
this.payloads.set(undefined);
|
||||||
|
this.message.set(error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||||
|
: error instanceof RouteIncompatible ? error.message : httpMessage(error));
|
||||||
|
this.status.set(error instanceof RouteIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError))
|
||||||
|
? 'incompatible' : 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { Subscription, timeout, TimeoutError } from 'rxjs';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
|
import { BarrasHorizontales } from './barras-horizontales';
|
||||||
|
import { ConjuntoBarras } from './indicadores-barras';
|
||||||
|
import { Dominio, Indicador, Tema } from './indicadores.models';
|
||||||
|
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||||
|
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||||
|
import { httpMessage } from './indicadores-http';
|
||||||
|
import { barrasVph, ModeloVph, modeloVph, periodosVph, porcentajeVph, VphIncompatible } from './indicadores-vph-genotipo';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HPV result by genotype, on its own: no selection, no link to the cytology or biopsy donuts, its own request, states
|
||||||
|
* and errors. Without the Measure (an older server) it says so and nothing else changes.
|
||||||
|
*/
|
||||||
|
@Component({
|
||||||
|
selector: 'app-indicador-vph-genotipo',
|
||||||
|
imports: [MatButtonModule, MatProgressBarModule, BarrasHorizontales],
|
||||||
|
template: `
|
||||||
|
<div class="encabezado">
|
||||||
|
@if (mostrarFiltro && indicador) { <p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p> }
|
||||||
|
@switch (status()) {
|
||||||
|
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando VPH por genotipo" /><p role="status">Cargando resultados de VPH…</p> }
|
||||||
|
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
|
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
|
}
|
||||||
|
@if (periods.length > 1 && (status() === 'ready')) {
|
||||||
|
<nav class="periods" aria-label="Periodos de VPH por genotipo">
|
||||||
|
<button type="button" aria-label="Periodo anterior de VPH por genotipo" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||||
|
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||||
|
<button type="button" aria-label="Periodo siguiente de VPH por genotipo" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||||
|
</nav>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<section class="vph" aria-label="Resultados de VPH por genotipo">
|
||||||
|
<h3>Resultados de VPH por genotipo@if (model) {, {{ model.periodo }}}</h3>
|
||||||
|
@if (!indicador) { <p class="estado" role="status">No disponible: el servicio todavía no publica este indicador. No se muestran valores.</p> }
|
||||||
|
@else if (status() === 'deferred') { <p class="estado" role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||||
|
@else if (model; as m) {
|
||||||
|
@switch (m.estado) {
|
||||||
|
@case ('ausente') { <p class="estado" role="status">Sin reporte publicado para {{ m.periodo }}.</p> }
|
||||||
|
@case ('cero') { <p class="estado" role="status">Sin reportes de VPH elegibles en {{ m.periodo }}: no hay distribución que mostrar.</p> }
|
||||||
|
@default {
|
||||||
|
<app-barras-horizontales [conjunto]="barras!" [titulo]="'VPH por genotipo, ' + m.periodo" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (m.estado === 'datos') {
|
||||||
|
<details class="published-values"><summary>Valores publicados</summary>
|
||||||
|
<div class="table-scroll" role="region" aria-label="Tabla de VPH por genotipo" tabindex="0">
|
||||||
|
<table><caption>Reportes de VPH por categoría, {{ m.periodo }}</caption>
|
||||||
|
<thead><tr><th scope="col">Categoría</th><th scope="col">Reportes</th><th scope="col">Porcentaje</th></tr></thead>
|
||||||
|
<tbody>@for (c of m.categorias; track c.id) { <tr><th scope="row">{{ c.etiqueta }}</th><td>{{ c.n.toLocaleString('es-MX') }}</td><td>{{ pct(c.n, m.total!) }}</td></tr> }</tbody>
|
||||||
|
<tfoot><tr><th scope="row">Total de reportes</th><td>{{ m.total!.toLocaleString('es-MX') }}</td><td></td></tr></tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
:host { display: block; min-width: 0; }
|
||||||
|
.vph { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||||
|
.encabezado { padding-top: var(--issste-space-3); }
|
||||||
|
h3 { font-size: 1rem; line-height: 1.5; }
|
||||||
|
h3, p, summary, li { overflow-wrap: anywhere; }
|
||||||
|
.applied-summary, .nota { color: var(--issste-text-secondary); }
|
||||||
|
.estado { display: flex; align-items: center; justify-content: center; box-sizing: border-box; margin: 0; padding: 1rem; text-align: center;
|
||||||
|
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); }
|
||||||
|
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||||
|
button { min-height: 44px; padding: .5rem .8rem; border: 1px solid var(--issste-border); border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||||
|
button:disabled { opacity: .5; cursor: default; }
|
||||||
|
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
|
.periods button { min-width: 44px; font-size: 1.5rem; }
|
||||||
|
summary { cursor: pointer; padding-block: .75rem; }
|
||||||
|
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||||
|
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||||
|
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||||
|
caption { text-align: start; font-weight: 600; }
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class IndicadorVphGenotipo implements OnChanges, OnDestroy {
|
||||||
|
@Input() dominio: Dominio = 'cacu';
|
||||||
|
/** The published indicator; absent when the server does not publish the Measure. */
|
||||||
|
@Input() indicador?: Indicador;
|
||||||
|
@Input() tema: Tema = 'claro';
|
||||||
|
@Input() applied?: GlobalApplied;
|
||||||
|
@Input() visible = true;
|
||||||
|
@Input() mostrarFiltro = true;
|
||||||
|
readonly status = signal<'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'>('idle');
|
||||||
|
message = '';
|
||||||
|
periods: string[] = [];
|
||||||
|
periodIndex = 0;
|
||||||
|
model?: ModeloVph;
|
||||||
|
barras?: ConjuntoBarras;
|
||||||
|
readonly pct = porcentajeVph;
|
||||||
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||||
|
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||||
|
private subscription?: Subscription;
|
||||||
|
private key = '';
|
||||||
|
private loaded = false;
|
||||||
|
private pages: ModeloVph[] = [];
|
||||||
|
get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : ''; }
|
||||||
|
|
||||||
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
|
if (!this.indicador || !this.applied) { this.subscription?.unsubscribe(); this.clear(); this.key = ''; this.status.set('idle'); return; }
|
||||||
|
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]);
|
||||||
|
if (key !== this.key) {
|
||||||
|
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear();
|
||||||
|
if (!this.visible) { this.status.set('deferred'); return; }
|
||||||
|
this.load();
|
||||||
|
} else if (this.visible && !this.loaded) this.load();
|
||||||
|
else if (this.model && changes['tema']) this.draw();
|
||||||
|
}
|
||||||
|
retry() { if (this.visible) this.load(); }
|
||||||
|
private clear() { this.pages = []; this.periods = []; this.model = undefined; this.barras = undefined; }
|
||||||
|
private load() {
|
||||||
|
const indicador = this.indicador!, applied = this.applied!;
|
||||||
|
this.subscription?.unsubscribe(); this.loaded = true; this.clear();
|
||||||
|
const compatibility = filterCompatibility(applied, indicador.tipos_periodo);
|
||||||
|
if (indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||||
|
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||||
|
this.status.set('incompatible'); return;
|
||||||
|
}
|
||||||
|
const key = this.key, periods = applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined;
|
||||||
|
this.status.set('loading');
|
||||||
|
this.subscription = this.snapshots.datos(this.dominio, indicador.id, applied.tipo, periods, indicador.version).pipe(timeout({ first: 40000 })).subscribe({
|
||||||
|
next: datos => {
|
||||||
|
if (key !== this.key) return;
|
||||||
|
try {
|
||||||
|
this.periods = periodosVph(datos, applied.tipo, periods);
|
||||||
|
this.pages = this.periods.map(p => modeloVph(datos, p));
|
||||||
|
this.periodIndex = this.periods.length ? this.periods.length - 1 : 0; this.activate();
|
||||||
|
} catch (error) { this.failure(error); }
|
||||||
|
},
|
||||||
|
error: error => { if (key === this.key) this.failure(error); },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private failure(error: unknown) {
|
||||||
|
this.clear();
|
||||||
|
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' : error instanceof VphIncompatible ? error.message
|
||||||
|
: httpMessage(error);
|
||||||
|
this.status.set(error instanceof VphIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)) ? 'incompatible' : 'error');
|
||||||
|
this.changeDetector.markForCheck();
|
||||||
|
}
|
||||||
|
private activate() { this.model = this.pages[this.periodIndex]; this.draw(); this.status.set('ready'); this.changeDetector.markForCheck(); }
|
||||||
|
changePeriod(step: number) {
|
||||||
|
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||||
|
this.periodIndex += step; this.activate();
|
||||||
|
}
|
||||||
|
private draw() { this.barras = this.model?.estado === 'datos' ? barrasVph(this.model) : undefined; this.changeDetector.markForCheck(); }
|
||||||
|
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||||
|
}
|
||||||
@@ -97,13 +97,13 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
|
|||||||
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
|
<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">
|
<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>
|
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
|
||||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
|
||||||
<tbody>@for (i of d.items; track i.codigo) {
|
<tbody>@for (i of d.items; track i.codigo) {
|
||||||
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
|
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
|
||||||
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
|
<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>{{ 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)"
|
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
|
||||||
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
|
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Análisis de riesgos'">Ver pacientes</button> }</td></tr>
|
||||||
}</tbody></table>
|
}</tbody></table>
|
||||||
</div>
|
</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> }
|
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
|
||||||
@@ -155,7 +155,7 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
|
|||||||
}
|
}
|
||||||
@if (m(); as mm) {
|
@if (m(); as mm) {
|
||||||
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
|
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
|
||||||
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
|
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Análisis de riesgos.</p>
|
||||||
<details><summary>Valores publicados</summary>
|
<details><summary>Valores publicados</summary>
|
||||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
|
<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>
|
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
|
||||||
|
|||||||
@@ -127,7 +127,7 @@ describe('Pestaña Análisis epidemiológico', () => {
|
|||||||
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
|
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
|
||||||
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
|
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
|
||||||
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
|
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
|
||||||
expect(text()).toContain('abrir la lista en Seguimiento');
|
expect(text()).toContain('abrir la lista en Análisis de riesgos');
|
||||||
});
|
});
|
||||||
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
|
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
|
||||||
// Fails if the cards stay on screen without an answer with categories.
|
// Fails if the cards stay on screen without an answer with categories.
|
||||||
@@ -177,7 +177,7 @@ describe('Pestaña Análisis epidemiológico', () => {
|
|||||||
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
|
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
|
||||||
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
|
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
|
||||||
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
|
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
|
||||||
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
|
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Análisis de riesgos');
|
||||||
});
|
});
|
||||||
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
|
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
|
||||||
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
|
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
|
||||||
|
|||||||
@@ -93,18 +93,18 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
|
|||||||
<p class="aviso" role="status">{{ aviso() }}</p>
|
<p class="aviso" role="status">{{ aviso() }}</p>
|
||||||
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
|
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
|
||||||
label="Pacientes por categoría BI-RADS" />
|
label="Pacientes por categoría BI-RADS" />
|
||||||
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
|
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Análisis de riesgos. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
|
||||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
|
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
|
||||||
<table>
|
<table>
|
||||||
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
|
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
|
||||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@for (g of d.grupos; track g.codigo) {
|
@for (g of d.grupos; track g.codigo) {
|
||||||
<tr [attr.data-grupo]="g.codigo">
|
<tr [attr.data-grupo]="g.codigo">
|
||||||
<th scope="row">{{ etiqueta(g.codigo) }}</th>
|
<th scope="row">{{ etiqueta(g.codigo) }}</th>
|
||||||
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
|
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
|
||||||
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
|
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
|
||||||
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
|
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Análisis de riesgos'">Ver pacientes</button> }</td>
|
||||||
</tr>
|
</tr>
|
||||||
}
|
}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Data shape of the horizontal bars that show the CaCu results (cytology, HPV by genotype, biopsy): one bar per
|
||||||
|
// category, optional clinical groups as headers with their subtotal, absolute counts as the scale and the
|
||||||
|
// percentage of the published denominator beside each count. A group is a header, not a category of the distribution.
|
||||||
|
export type EstadoCelda = 'Publicado' | 'Suprimido' | 'No disponible';
|
||||||
|
export interface FilaBarra { id: string; etiqueta: string; n: number | null; estado: EstadoCelda; color: string; }
|
||||||
|
export interface GrupoBarras {
|
||||||
|
/** Null for a flat distribution (HPV): no header. */
|
||||||
|
id: string | null; etiqueta: string | null; color: string;
|
||||||
|
/** Sum of its categories; null when any of them is unknown. */
|
||||||
|
subtotal: number | null; filas: FilaBarra[];
|
||||||
|
}
|
||||||
|
export interface ConjuntoBarras {
|
||||||
|
grupos: GrupoBarras[];
|
||||||
|
/** The published denominator the percentages use; null when it is not available. */
|
||||||
|
den: number | null;
|
||||||
|
/** What the denominator counts: «pacientes con resultado», «reportes de VPH elegibles»… */
|
||||||
|
unidad: string;
|
||||||
|
/** The ids of the categories the selection highlights; null when nothing is selected. */
|
||||||
|
activas: ReadonlySet<string> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BASES = [2, 4, 6, 8, 10, 12, 16, 20, 24, 30, 40, 50, 60, 80, 100];
|
||||||
|
/** The upper limit of the count scale: the smallest round, even number that holds the largest bar or subtotal. */
|
||||||
|
export function limiteEscala(maximo: number): number {
|
||||||
|
if (!(maximo > 0)) return 2;
|
||||||
|
for (let potencia = 1; ; potencia *= 10) for (const base of BASES) if (base * potencia / 10 >= maximo && Number.isInteger(base * potencia / 10 / 2)) return base * potencia / 10;
|
||||||
|
}
|
||||||
|
export function maximoDelConjunto(c: ConjuntoBarras): number {
|
||||||
|
return Math.max(0, ...c.grupos.flatMap(g => [g.subtotal ?? 0, ...g.filas.map(f => f.n ?? 0)]));
|
||||||
|
}
|
||||||
|
/** Sum of the categories the selection highlights, or null when there is no selection or any of them is unknown. */
|
||||||
|
export function sumaActivas(c: ConjuntoBarras): number | null {
|
||||||
|
if (!c.activas) return null;
|
||||||
|
const filas = c.grupos.flatMap(g => g.filas).filter(f => c.activas!.has(f.id));
|
||||||
|
return filas.some(f => f.n === null) ? null : filas.reduce((s, f) => s + f.n!, 0);
|
||||||
|
}
|
||||||
@@ -59,8 +59,8 @@ describe('Dona de dos anillos para C1', () => {
|
|||||||
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||||
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
||||||
});
|
});
|
||||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
|
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, tomado de la paleta compartida', () => {
|
||||||
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
|
const colores = ['#A8C243', '#42C29C', '#9C42C2'];
|
||||||
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||||
if (dona.status !== 'supported') throw new Error('sin figura');
|
if (dona.status !== 'supported') throw new Error('sin figura');
|
||||||
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
|
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
|
||||||
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
|
import { c2Color, C2_PALETTE, recolorFigure, seriesColors } from './indicadores-c2-palette';
|
||||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||||
import { FigureSelection } from './indicadores.models';
|
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||||
import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||||
import { figurePresentation } from './indicadores.presentation';
|
import { figurePresentation } from './indicadores.presentation';
|
||||||
|
import { historicoFigura } from './indicadores-historico-figures';
|
||||||
|
import { stratifiedBars } from './indicadores-stratified';
|
||||||
|
|
||||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||||
function supported(data = c2Fixture(), s = selection) {
|
function supported(data = c2Fixture(), s = selection) {
|
||||||
@@ -13,6 +15,32 @@ function supported(data = c2Fixture(), s = selection) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
describe('C2: datos publicados a Plotly', () => {
|
describe('C2: datos publicados a Plotly', () => {
|
||||||
|
it('comparte el color de LIEBG entre dona, barras, estratos e histórico solo para CaCu', () => {
|
||||||
|
const data: IndicadorDatos = { ...c2Fixture(), id: 'cacu_eu7' };
|
||||||
|
const original = data['categorias'] as Record<string, object>;
|
||||||
|
data['categorias'] = { LIEBG: { ...original['A'], color: '#E8C28E' }, B: original['B'], C: original['C'] };
|
||||||
|
data.filas[0]['categoria'] = 'LIEBG';
|
||||||
|
const cacu = { ...selection, dominio: 'cacu' as const, indicador: data.id };
|
||||||
|
const pie = supported(data, cacu).figure;
|
||||||
|
const bars = supported(data, { ...cacu, figura: 'fig_c2_barras' }).figure;
|
||||||
|
const history = historicoFigura(data, 'claro').figure;
|
||||||
|
const stratum = { ...data, estrato: 'grupo_edad', valores_estrato: ['estrato'], etiquetas_estrato: { estrato: 'Estrato' },
|
||||||
|
filas: data.filas.map(row => ({ ...row, estrato: 'estrato' as const })) };
|
||||||
|
const chart = (domain: 'cacu' | 'tea' | 'cama') => stratifiedBars(stratum, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(), domain);
|
||||||
|
expect(pie.data[0]['marker']).toMatchObject({ colors: expect.arrayContaining(['#AD8F20']) });
|
||||||
|
expect(bars.data[0]['marker']).toMatchObject({ color: expect.arrayContaining(['#AD8F20']) });
|
||||||
|
expect(history.data[0]['marker']).toMatchObject({ color: '#AD8F20' });
|
||||||
|
expect(chart('cacu').figure.data[0]['marker']).toMatchObject({ color: expect.arrayContaining(['#AD8F20']) });
|
||||||
|
expect(chart('cacu').figure.data[0]['marker']).not.toHaveProperty('pattern');
|
||||||
|
expect(chart('cacu').cells).toEqual(chart('tea').cells);
|
||||||
|
for (const domain of ['tea', 'cama'] as const) {
|
||||||
|
expect(chart(domain).figure.data[0]['marker']).toHaveProperty('pattern.shape', '');
|
||||||
|
expect(chart(domain).figure.data[0]['marker']).toMatchObject({ color: [C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]] });
|
||||||
|
expect(supported(data, { ...selection, indicador: data.id, dominio: domain }).figure.data[0]['marker']).toMatchObject({ colors: [C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]] });
|
||||||
|
}
|
||||||
|
expect(recolorFigure(pie)).toBe(pie); expect(recolorFigure(bars)).toBe(bars);
|
||||||
|
expect(recolorFigure(history)).toBe(history);
|
||||||
|
});
|
||||||
it('equivale a los dos anillos publicados: valores, orden, relaciones, periodo y total', () => {
|
it('equivale a los dos anillos publicados: valores, orden, relaciones, periodo y total', () => {
|
||||||
const data = c2Fixture(), before = structuredClone(data), result = supported(data), server = donutFixture().figure;
|
const data = c2Fixture(), before = structuredClone(data), result = supported(data), server = donutFixture().figure;
|
||||||
expect(result.figure.data.map(t => [t['labels'], t['values'], t['name']])).toEqual(server.data.map(t => [t['labels'], t['values'], t['name']]));
|
expect(result.figure.data.map(t => [t['labels'], t['values'], t['name']])).toEqual(server.data.map(t => [t['labels'], t['values'], t['name']]));
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
||||||
import { DonutHierarchy } from './indicadores-donut-drilldown';
|
import { DonutHierarchy } from './indicadores-donut-drilldown';
|
||||||
import { basesPorGrupo, C2_PALETTE, c2Theme, seriesColors } from './indicadores-c2-palette';
|
import { basesPorGrupo, C2_PALETTE, c2Theme, seriesColors } from './indicadores-c2-palette';
|
||||||
|
import { cacuCategoryColor, cacuGroupColor } from './indicadores-cacu-palette';
|
||||||
|
|
||||||
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
|
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
|
||||||
// Normalized presentation nodes and a selection path are independent of Plotly.
|
// Normalized presentation nodes and a selection path are independent of Plotly.
|
||||||
@@ -81,8 +82,13 @@ 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 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 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 theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
|
||||||
const colors = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
|
const isCaCu = selection.dominio === 'cacu';
|
||||||
|
const defaults = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
|
||||||
|
const cacuColors = isCaCu ? categories.map(c => cacuCategoryColor(c.id)) : [];
|
||||||
|
const colors = defaults.map((color, i) => cacuColors[i] ?? color);
|
||||||
const bases = basesPorGrupo(parentIds);
|
const bases = basesPorGrupo(parentIds);
|
||||||
|
const groupColors = parentIds.map(id => (isCaCu ? cacuGroupColor(id) : undefined) ?? bases.get(id) ?? C2_PALETTE.series[0]);
|
||||||
|
const edge = cacuColors.some(Boolean) ? { color: theme.background, width: 1.5 } : { color: theme.outline, width: 0.7 };
|
||||||
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 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,
|
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 },
|
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
|
||||||
@@ -94,7 +100,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
|||||||
const figure: PlotlyFigure = { data: [], layout };
|
const figure: PlotlyFigure = { data: [], layout };
|
||||||
if (selection.figura === 'fig_c2_barras') {
|
if (selection.figura === 'fig_c2_barras') {
|
||||||
if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels,
|
if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels,
|
||||||
marker: { color: colors, line: { color: theme.outline, width: 0.7 } },
|
marker: { color: colors, line: edge },
|
||||||
hovertemplate: '%{y}<br>%{x} ' + model.unit + '<extra></extra>' }];
|
hovertemplate: '%{y}<br>%{x} ' + model.unit + '<extra></extra>' }];
|
||||||
layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true,
|
layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true,
|
||||||
gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1,
|
gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1,
|
||||||
@@ -105,12 +111,12 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
|||||||
} else if (total > 0) {
|
} else if (total > 0) {
|
||||||
layout['annotations'] = [{ x: 0.5, y: 0.5, xref: 'paper', yref: 'paper', showarrow: false,
|
layout['annotations'] = [{ x: 0.5, y: 0.5, xref: 'paper', yref: 'paper', showarrow: false,
|
||||||
text: '<b>' + total + '</b>', font: { color: theme.text, size: 18 } }];
|
text: '<b>' + total + '</b>', font: { color: theme.text, size: 18 } }];
|
||||||
figure.data = [{ type: 'pie', labels, values, marker: { colors, line: { color: theme.outline, width: 0.7 } },
|
figure.data = [{ type: 'pie', labels, values, marker: { colors, line: edge },
|
||||||
hole: 0.62, sort: false, name: period, textinfo: 'none', legendgroup: 'categorias', domain: { x: [0, 0.72], y: [0, 1] },
|
hole: 0.62, sort: false, name: period, textinfo: 'none', legendgroup: 'categorias', domain: { x: [0, 0.72], y: [0, 1] },
|
||||||
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
|
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),
|
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)),
|
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
|
||||||
marker: { colors: parents.map(p => bases.get(p.id.replace(/^group:/, '')) ?? C2_PALETTE.series[0]), line: { color: theme.outline, width: 0.7 } },
|
marker: { colors: groupColors, line: edge },
|
||||||
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
|
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
|
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ export const C2_PALETTE = Object.freeze({
|
|||||||
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
|
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
|
||||||
]),
|
]),
|
||||||
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
||||||
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
|
// Age groups of the EEG indicators (M21, M22): the same lime, teal and purple the other domains' series use.
|
||||||
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
|
edades: Object.freeze(['#A8C243', '#42C29C', '#9C42C2']),
|
||||||
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
|
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.
|
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
|
||||||
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
|
|||||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(),provideHttpClientTesting()] });
|
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(),provideHttpClientTesting()] });
|
||||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadorFigurePanel);
|
http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied })) fixture.componentRef.setInput(name,value);
|
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied, ayudaRedonda: false })) fixture.componentRef.setInput(name,value);
|
||||||
});
|
});
|
||||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||||
const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos'));
|
const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos'));
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
|
||||||
|
.legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
|
||||||
|
.legend > button { align-self: flex-start; margin-bottom: .4rem; }
|
||||||
|
.tab-bar { display: flex; align-items: flex-end; border-bottom: 1px solid var(--issste-border); }
|
||||||
|
.tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
|
||||||
|
.tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
|
||||||
|
.tabs .tab[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
|
||||||
|
.child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
|
||||||
|
.tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
|
||||||
|
.tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); text-align: start; overflow-wrap: anywhere; }
|
||||||
|
.tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); box-shadow: inset 0 0 0 1px var(--swatch); }
|
||||||
|
.tab .swatch, .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
// What this module covers: CaCu's compositions as the page reads them from FHIR once the Measure publishes category
|
||||||
|
// groups and the reports their crossed strata: the groups, the rows by stratum (codes, captions, explicit zeros, totals),
|
||||||
|
// the contract errors that must never become zeros, the EU7 view by follow-up status and the histopathological
|
||||||
|
// confirmation, a period without units, and that measures without groups (CaMa's) read unchanged.
|
||||||
|
// Fixtures: `fixtures/cacu_fhir_measures.json` (the Measure bundle `GET /cacu/fhir/Measure` returns with the groups
|
||||||
|
// declared) and `fixtures/cacu_fhir_reportes_estratos.json` (real `GET /cacu/fhir/MeasureReport` answers of EU7 and the
|
||||||
|
// confirmation for 2025-S2, with units, and 2021-S1, without; synthetic data of the isolated installation, N_CACU=300).
|
||||||
|
import { Bundle, resources } from './fhir';
|
||||||
|
import { categorias, datosDeReportes, gruposDeCategoria, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
|
||||||
|
import { barras, dona, modelo } from './indicadores-eu7-escenario';
|
||||||
|
import { donaConfirmacion, modeloConfirmacion } from './indicadores-confirmacion-citologia';
|
||||||
|
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||||
|
import { IndicadorDatos } from './indicadores.models';
|
||||||
|
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||||
|
import reportsData from './fixtures/cacu_fhir_reportes_estratos.json';
|
||||||
|
import camaData from './fixtures/cama_fhir_measures.json';
|
||||||
|
|
||||||
|
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||||
|
const measure = (id: string) => measures.find(m => m.id === id)!;
|
||||||
|
const answers = reportsData as unknown as Record<string, Bundle>;
|
||||||
|
const reports = (key: string) => resources(answers[key], 'MeasureReport') as Report[];
|
||||||
|
const EU7 = 'CACU-EU7', CONF = 'CACU-CONFIRMACION-CITOLOGIA';
|
||||||
|
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
||||||
|
type Fila = Record<string, unknown>;
|
||||||
|
const n = (filas: Fila[], estrato: string | null, categoria: string) =>
|
||||||
|
filas.filter(f => f['estrato'] === estrato && f['categoria'] === categoria).reduce((s, f) => s + (f['n'] as number), 0);
|
||||||
|
|
||||||
|
describe('Grupos de categoría publicados por la Measure', () => {
|
||||||
|
it('EU7 y la confirmación leen el grupo de cada categoría y los nombres de los grupos, en su orden', () => {
|
||||||
|
// Pins down: the optional `grupo` inside each `categoria` and the `categoria-grupo` captions reach the page as the
|
||||||
|
// EU7 and confirmation views read them; «Sin biopsia aún» keeps no group. Fails if either is dropped or reordered.
|
||||||
|
expect(Object.fromEntries(Object.entries(categorias(measure(EU7))).map(([c, v]) => [c, v.grupo]))).toEqual({
|
||||||
|
NORMAL: 'NO_ANORMAL', 'ASC-US': 'ANORMAL', LIEBG: 'ANORMAL', 'ASC-H': 'ANORMAL', LIEAG: 'ANORMAL', CIS: 'ANORMAL', SIN_DATO: 'SIN_DATO' });
|
||||||
|
expect(Object.entries(gruposDeCategoria(measure(EU7)))).toEqual([
|
||||||
|
['NO_ANORMAL', 'Sin anomalía'], ['ANORMAL', 'Anormal'], ['SIN_DATO', 'Sin dato']]);
|
||||||
|
expect(categorias(measure(CONF))['SIN_BIOPSIA'].grupo).toBeNull();
|
||||||
|
expect(gruposDeCategoria(measure(CONF))).toEqual({ NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Biopsia sin grado' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('una Measure sin grupos se lee como antes: sin grupo por categoría y sin grupos de categoría', () => {
|
||||||
|
// Pins down: groups are opt-in. CaMa's Measures declare none, so every category keeps `grupo: null` and the data
|
||||||
|
// carry no `grupos_de_categoria`. Fails if reading the new extensions changes what CaMa's views receive.
|
||||||
|
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
|
||||||
|
for (const m of cama) {
|
||||||
|
expect(Object.values(categorias(m)).every(c => c.grupo === null), m.id).toBe(true);
|
||||||
|
expect(gruposDeCategoria(m), m.id).toEqual({});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Composiciones por estrato desde el estratificador cruzado', () => {
|
||||||
|
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre');
|
||||||
|
const porEstatus = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' });
|
||||||
|
|
||||||
|
it('cada estrato tiene una fila por categoría declarada, con su código y su etiqueta, y ceros explícitos', () => {
|
||||||
|
// Pins down: one row per (status, category), the status code as the value and its caption from the report, and a
|
||||||
|
// zero for every cell FHIR doesn't list (the report is complete). Fails if a cell goes missing or a code is replaced.
|
||||||
|
const valores = porEstatus['valores_estrato'] as string[];
|
||||||
|
expect(valores.length).toBeGreaterThan(0);
|
||||||
|
expect(porEstatus.filas.length).toBe(valores.length * Object.keys(porEstatus['categorias'] as object).length);
|
||||||
|
expect((porEstatus['etiquetas_estrato'] as Record<string, string>)['PRE_COLPOSCOPIA']).toBe('Pre colposcopia');
|
||||||
|
const listadas = (reports('eu7_2025S2')[0].group![0].stratifier as { code: unknown[]; stratum: unknown[] }[])
|
||||||
|
.find(s => s.code.length === 2 && JSON.stringify(s.code[0]).includes('estatus_seguimiento'))!.stratum.length;
|
||||||
|
expect(porEstatus.filas.filter(f => f['n'] === 0).length).toBe(porEstatus.filas.length - listadas);
|
||||||
|
expect(porEstatus.filas.every(f => f['suprimido'] === 0 && f['grupo'] === 'TOTAL')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('los conteos por estrato suman los de la distribución general, categoría por categoría y en total', () => {
|
||||||
|
// Pins down: the strata partition the period's units (112 patients in 2025-S2) and each category adds up across
|
||||||
|
// them; the per-stratum totals are published. Fails if the crossed stratifier is read with a shift or a loss.
|
||||||
|
const totales = porEstatus['totales_estrato'] as { n: number }[];
|
||||||
|
expect(totales.reduce((s, t) => s + t.n, 0)).toBe(112);
|
||||||
|
for (const categoria of Object.keys(general['categorias'] as object)) {
|
||||||
|
const porEstratos = (porEstatus['valores_estrato'] as string[]).reduce((s, e) => s + n(porEstatus.filas, e, categoria), 0);
|
||||||
|
expect(porEstratos, categoria).toBe(n(general.filas, null, categoria));
|
||||||
|
}
|
||||||
|
const porEdad = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'grupo_edad' });
|
||||||
|
expect((porEdad['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(112);
|
||||||
|
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['25-34']).toBe('25-34');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('una celda que falta, una categoría no declarada o un estratificador ausente son errores de contrato, no ceros', () => {
|
||||||
|
// Pins down: what can't be read as a complete partition fails loudly: cells that no longer add up to the units, a
|
||||||
|
// category the Measure doesn't declare, and a period with units but without the crossed stratifier. Fails if any
|
||||||
|
// of them is silently turned into a zero.
|
||||||
|
const sinCelda = clone(reports('eu7_2025S2'));
|
||||||
|
const cruzado = sinCelda[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as { stratum: unknown[] };
|
||||||
|
cruzado.stratum.shift();
|
||||||
|
expect(() => datosDeReportes(measure(EU7), sinCelda, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||||
|
.toThrowError('Los conteos por estrato no suman las unidades del periodo');
|
||||||
|
const ajena = clone(reports('eu7_2025S2'));
|
||||||
|
const celda = (ajena[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as
|
||||||
|
{ stratum: { component: { value: { coding: { code: string }[] } }[] }[] }).stratum[0];
|
||||||
|
celda.component[1].value.coding[0].code = 'GLANDULAR';
|
||||||
|
expect(() => datosDeReportes(measure(EU7), ajena, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||||
|
.toThrowError('Categoría no declarada en el estrato');
|
||||||
|
const sinCruce = clone(reports('eu7_2025S2'));
|
||||||
|
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
|
||||||
|
expect(() => datosDeReportes(measure(EU7), sinCruce, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||||
|
.toThrowError('Dimensión no admitida');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un periodo sin unidades no tiene filas por estrato y no es un error', () => {
|
||||||
|
// Pins down: 2021-S1 has no patients; its report has nothing to cross, so the stratified data carry the period but
|
||||||
|
// no rows, and the general distribution is all zeros. Fails if an empty period is read as an error or as data.
|
||||||
|
const vacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' });
|
||||||
|
expect(vacio.periodos).toEqual(['2021-S1']);
|
||||||
|
expect(vacio.filas).toEqual([]);
|
||||||
|
const generalVacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre');
|
||||||
|
expect(generalVacio.filas.every(f => f['n'] === 0)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Vistas propias de CaCu con los datos de FHIR', () => {
|
||||||
|
it('EU7: el modelo por escenario se construye y la dona y las barras tienen datos', () => {
|
||||||
|
// Pins down: with the groups and the rows by follow-up status, EU7's coordinated view builds its model (112
|
||||||
|
// patients in groups Anormal / Sin anomalía, «Sin dato» apart) and both figures have traces. Fails if the view
|
||||||
|
// falls back to «incompatible» with the data FHIR publishes.
|
||||||
|
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||||
|
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||||
|
const m = modelo(general, escenarios, '2025-S2');
|
||||||
|
expect(m.vacio).toBe(false);
|
||||||
|
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Sin anomalía', 'Anormal']);
|
||||||
|
expect(m.escenarios.map(e => e.etiqueta)).toContain('Pre colposcopia');
|
||||||
|
expect(dona(m, {}, 'claro').data.length).toBeGreaterThan(0);
|
||||||
|
expect(barras(m, {}, 'claro').data.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('EU7: el texto emergente de cada sector de la dona nombra la categoría, los pacientes y el porcentaje', () => {
|
||||||
|
// Pins down: both rings carry one pre-formatted hover text per sector («2 pacientes, 2.1 % del total con
|
||||||
|
// resultado» for LIEAG, 2 of the 95 patients with a result) and their template reads it by name. A pie wraps
|
||||||
|
// `customdata` in an extra array, so a template that indexes it printed «2,2.1 pacientes, - %». Fails if the
|
||||||
|
// template goes back to indexing `customdata` or a sector loses its text.
|
||||||
|
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||||
|
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||||
|
const m = modelo(general, escenarios, '2025-S2');
|
||||||
|
const anillos = dona(m, {}, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
|
||||||
|
expect(anillos.length).toBe(2);
|
||||||
|
for (const anillo of anillos) {
|
||||||
|
expect(anillo['hovertemplate']).not.toContain('customdata');
|
||||||
|
expect(anillo['hovertemplate']).toContain('%{hovertext}');
|
||||||
|
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
|
||||||
|
}
|
||||||
|
const exterior = anillos.find(t => t['name'] === 'categorias')!;
|
||||||
|
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
|
||||||
|
expect(m.total).toBe(95);
|
||||||
|
expect(textos[etiquetas.indexOf('LIEAG')]).toBe('2 pacientes, 2.1 % del total con resultado');
|
||||||
|
expect(textos.every(t => /^\d+ pacientes, \d+(\.\d)? % del total con resultado$/.test(t))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('EU7: un periodo sin pacientes es un periodo vacío, no una respuesta incompatible', () => {
|
||||||
|
// Pins down: for 2021-S1 FHIR publishes the general distribution as explicit zeros and no scenario; the view reads
|
||||||
|
// it as empty. A positive count without scenarios is still rejected. Fails if an empty period shows
|
||||||
|
// «incompatible», or if a real mismatch is hidden as empty.
|
||||||
|
const general = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre') as IndicadorDatos;
|
||||||
|
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||||
|
const m = modelo(general, escenarios, '2021-S1');
|
||||||
|
expect(m.vacio).toBe(true);
|
||||||
|
expect(m.escenarios).toEqual([]);
|
||||||
|
const conPacientes = clone(general);
|
||||||
|
conPacientes.filas[0]['n'] = 3;
|
||||||
|
expect(() => modelo(conPacientes, escenarios, '2021-S1')).toThrow(/No hay escenarios que correspondan/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('EU7: el mismo reporte servido en dos respuestas es una sola procedencia aunque cambie la hora de la respuesta', () => {
|
||||||
|
// Pins down: the view asks for the general and the stratified data in two requests; the WebApi serves the same
|
||||||
|
// stored report (same id and cut-off) with each response's own `date`. That is one provenance; without report ids,
|
||||||
|
// a different generation time still means different reports. Fails if the view rejects FHIR's two responses of one
|
||||||
|
// report, or accepts two anonymous answers generated apart.
|
||||||
|
const segunda = clone(reports('eu7_2025S2'));
|
||||||
|
segunda[0].date = '2099-01-01T00:00:00Z';
|
||||||
|
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||||
|
const escenarios = datosDeReportes(measure(EU7), segunda, 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||||
|
expect(modelo(general, escenarios, '2025-S2').vacio).toBe(false);
|
||||||
|
const anonimo = (d: IndicadorDatos) => ({ ...d, reportes: (d['reportes'] as Fila[]).map(r => ({ ...r, report_id: null })) }) as IndicadorDatos;
|
||||||
|
expect(() => modelo(anonimo(general), anonimo(escenarios), '2025-S2')).toThrow(/reportes distintos/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('confirmación: la tabla por citología y los dos grupos de grados se construyen', () => {
|
||||||
|
// Pins down: the confirmation by cytology result builds its table from the crossed stratifier (6 patients in
|
||||||
|
// 2025-S2), with its two groups and LIEAG's as the base view, and «Sin biopsia aún» / «Biopsia sin grado»
|
||||||
|
// apart. Fails if the view can't read FHIR's groups or strata.
|
||||||
|
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
|
||||||
|
const m = modeloConfirmacion(datos, '2025-S2');
|
||||||
|
expect(m.vacio).toBe(false);
|
||||||
|
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Menor que LIEAG', 'LIEAG o más']);
|
||||||
|
expect(m.base).toBe('ANORMAL');
|
||||||
|
expect(m.aparte.map(a => a.id).sort()).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
|
||||||
|
expect((datos['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('confirmación: el texto emergente de cada sector de la dona nombra el grado, las mujeres con biopsia y el porcentaje', () => {
|
||||||
|
// Pins down: both rings carry one pre-formatted hover text per sector («3 mujeres con biopsia, 75.0 %» for the
|
||||||
|
// grades LIEAG o más… of the 4 women with a biopsy in 2025-S2) and their template reads it by name, because a pie
|
||||||
|
// wraps `customdata` in an extra array and indexing it printed «3,75.0 % mujeres con biopsia, -». Fails if the
|
||||||
|
// template goes back to indexing `customdata` or a sector loses its text.
|
||||||
|
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
|
||||||
|
const m = modeloConfirmacion(datos, '2025-S2');
|
||||||
|
const anillos = donaConfirmacion(m, { grupo: m.base }, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
|
||||||
|
expect(anillos.length).toBe(2);
|
||||||
|
for (const anillo of anillos) {
|
||||||
|
expect(anillo['hovertemplate']).not.toContain('customdata');
|
||||||
|
expect(anillo['hovertemplate']).toContain('%{hovertext}');
|
||||||
|
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
|
||||||
|
}
|
||||||
|
const exterior = anillos.find(t => t['name'] === 'categorias')!;
|
||||||
|
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
|
||||||
|
expect(textos[etiquetas.indexOf('LIEAG (CIN 2 y 3)')]).toBe('3 mujeres con biopsia, 75.0 %');
|
||||||
|
expect(textos.every(t => /^\d+ mujeres con biopsia, \d+(\.\d)? %$/.test(t))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('la compuerta de EU7 usa los estratos que declara la Measure y no activa filtros para otras composiciones', () => {
|
||||||
|
// Pins down: EU7 declares `estatus_seguimiento`, so its view opens without local filters; the stratified
|
||||||
|
// capabilities of the generic figure panel stay empty for every CaCu and CaMa measure. Fails if the gate is lost
|
||||||
|
// or if filters appear for compositions that never had them.
|
||||||
|
const eu7 = indicadorDeMeasure(measure(EU7));
|
||||||
|
expect(declaraEstrato(eu7, 'estatus_seguimiento')).toBe(true);
|
||||||
|
expect(declaraEstrato(indicadorDeMeasure(measure(CONF)), 'estatus_seguimiento')).toBe(false);
|
||||||
|
expect(declaraEstrato(indicadorDeMeasure(measure('CACU-EU13')), 'estatus_seguimiento')).toBe(false);
|
||||||
|
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
|
||||||
|
for (const item of [...measures, ...cama].map(indicadorDeMeasure)) expect(stratifiedCapabilities(item), item.id).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
// What this module covers: how CaCu's FHIR measures reach the indicator page: the page's id of each measure, and what the
|
||||||
|
// initial-period anchor (`cacu_eu7`) makes of a C2 Measure that publishes, or does not publish, its category labels.
|
||||||
|
// The Measure and the report are synthetic and minimal: the shape of `GET /cacu/fhir/Measure` and `/MeasureReport`.
|
||||||
|
import { Bundle, resources } from './fhir';
|
||||||
|
import { Measure, Report, datosDeReportes, indicadorDeMeasure, indicadorId } from './indicadores-fhir';
|
||||||
|
import { c2Figure } from './indicadores-c2-adapter';
|
||||||
|
import { FigureSelection } from './indicadores.models';
|
||||||
|
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||||
|
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||||
|
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||||
|
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||||
|
import { GlobalApplied } from './indicadores-memory';
|
||||||
|
import { historicoFigura } from './indicadores-historico-figures';
|
||||||
|
|
||||||
|
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||||
|
const ENDPOINT = ['CACU-CONFIRMACION-CITOLOGIA', 'CACU-DIAS-TOMA-DIAGNOSTICO', 'CACU-EU-TIEMPO-REPORTE', 'CACU-EU13', 'CACU-EU7',
|
||||||
|
'CACU-RIESGO-BANDA', 'IND1'];
|
||||||
|
const etiqueta = (codigo: string, texto: string, color: string) => ({ url: `${STRUCTURE}/categoria`, extension: [
|
||||||
|
{ url: 'codigo', valueCode: codigo }, { url: 'etiqueta', valueString: texto }, { url: 'color', valueString: color }] });
|
||||||
|
const eu7 = (extra: object[]): Measure => ({
|
||||||
|
resourceType: 'Measure', id: 'CACU-EU7', version: '0.3.3', title: 'Distribución de resultados citológicos',
|
||||||
|
subjectCodeableConcept: { coding: [{ code: 'paciente' }] },
|
||||||
|
extension: [{ url: `${STRUCTURE}/contrato`, valueCode: 'C2' }, { url: `${STRUCTURE}/tipos-periodo`, valueCode: 'semestre' }, ...extra],
|
||||||
|
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [], stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [] }] }],
|
||||||
|
} as unknown as Measure);
|
||||||
|
const reporte = (): Report => ({
|
||||||
|
resourceType: 'MeasureReport', id: 'CACU-EU7-1', period: { start: '2025-07-01', end: '2025-12-31' },
|
||||||
|
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 12 }],
|
||||||
|
stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [
|
||||||
|
{ value: { coding: [{ code: 'NORMAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 8 }] },
|
||||||
|
{ value: { coding: [{ code: 'ASC-US' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 3 }] },
|
||||||
|
{ value: { coding: [{ code: 'SIN_DATO' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 1 }] },
|
||||||
|
] }] }],
|
||||||
|
} as unknown as Report);
|
||||||
|
const aplicado: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 0 };
|
||||||
|
const ancla = KPI_BY_DOMAIN.cacu[0];
|
||||||
|
|
||||||
|
describe('Identificadores de CaCu entre FHIR y la página', () => {
|
||||||
|
it('cada medida que publica el WebApi tiene el id de minúsculas que usa la página y ninguno se repite', () => {
|
||||||
|
// Pins down: the table covers the seven measures `GET /cacu/fhir/Measure` lists and the ids are unique. Fails if a
|
||||||
|
// measure is published without a correspondence (it would come back as `CACU_X`, which no card matches) or two
|
||||||
|
// measures collapse into one page id.
|
||||||
|
const ids = ENDPOINT.map(indicadorId);
|
||||||
|
expect(ids.sort()).toEqual(['cacu_confirmacion_citologia', 'cacu_dias_toma_diagnostico', 'cacu_eu13', 'cacu_eu7',
|
||||||
|
'cacu_eu_tiempo_reporte', 'cacu_riesgo_banda', 'ind1']);
|
||||||
|
expect(ENDPOINT.every(id => Object.hasOwn(CACU_MEASURE_IDS, id))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('los ids que la página busca (ancla, tiempos, confirmación) existen entre los publicados', () => {
|
||||||
|
// Pins down: the page's own constants (the KPI definitions of CaCu, the confirmation card's id and the result-time KPI)
|
||||||
|
// are values of the table. Fails if the page renames one of them without the table: the catalog would keep `CACU_EU7`
|
||||||
|
// while the page looks for `cacu_eu7`, and no initial period would be searched.
|
||||||
|
const publicados = Object.values(CACU_MEASURE_IDS);
|
||||||
|
for (const id of [...KPI_BY_DOMAIN.cacu.map(k => k.id), CACU_RESULTADO_KPI.id, ID_CONFIRMACION, 'cacu_eu7']) {
|
||||||
|
expect(publicados).toContain(id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el catálogo de una medida de CaCu lleva el id de la página y sus figuras', () => {
|
||||||
|
// Pins down: the catalog entry takes the page id and the `figuras` the Measure publishes. Fails if the mapper stops
|
||||||
|
// using the CaCu table or drops the figures.
|
||||||
|
const item = indicadorDeMeasure(eu7([{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_donas' },
|
||||||
|
{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_barras' }]));
|
||||||
|
expect(item.id).toBe('cacu_eu7');
|
||||||
|
expect(item.figuras).toEqual(['fig_c2_donas', 'fig_c2_barras']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('El ancla de CaCu con y sin etiquetas de categoría publicadas', () => {
|
||||||
|
it('rechaza una categoría EU7 publicada que no figura en la Measure, sin descartar su conteo', () => {
|
||||||
|
const measure = eu7([etiqueta('NORMAL', 'Normal', '#9DBFE3'), etiqueta('SIN_DATO', 'Sin dato', '#C9CDD2')]);
|
||||||
|
const cod = (value: string) => ({ coding: [{ code: value }] });
|
||||||
|
const report = { resourceType: 'MeasureReport', period: { start: '2025-01-01', end: '2025-06-30' }, group: [{
|
||||||
|
code: cod('TOTAL'), population: [{ code: cod('initial-population'), count: 2 }],
|
||||||
|
stratifier: [{ code: [cod('estatus_seguimiento'), cod('resultado')], stratum: [{
|
||||||
|
component: [{ code: cod('estatus_seguimiento'), value: cod('PRE_COLPOSCOPIA') },
|
||||||
|
{ code: cod('resultado'), value: cod('NEGATIVO') }], population: [{ count: 2 }],
|
||||||
|
}] }],
|
||||||
|
}] } as unknown as Report;
|
||||||
|
expect(() => datosDeReportes(measure, [report], 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||||
|
.toThrow('Categoría no declarada en el estrato');
|
||||||
|
});
|
||||||
|
it('con etiquetas, los conteos del periodo son filas y el ancla muestra el total', () => {
|
||||||
|
// Pins down: a C2 Measure that publishes its categories gives one row per category and the anchor KPI the sum
|
||||||
|
// (12 patients), so the initial-period search can stop on the period. Fails if the rows stop following the Measure's
|
||||||
|
// categories or the anchor no longer accepts a CaCu partition.
|
||||||
|
const measure = eu7([etiqueta('NORMAL', 'Normal', '#9DBFE3'), etiqueta('ASC-US', 'ASC-US', '#2F6DB3'),
|
||||||
|
etiqueta('SIN_DATO', 'Sin dato', '#C9CDD2')]);
|
||||||
|
const datos = datosDeReportes(measure, [reporte()], 'semestre');
|
||||||
|
expect(datos.filas.map(f => [f['categoria'], f['n']])).toEqual([['NORMAL', 8], ['ASC-US', 3], ['SIN_DATO', 1]]);
|
||||||
|
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
|
||||||
|
expect(resultado.state).toBe('Disponible');
|
||||||
|
expect(resultado.value).toBe(12);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sin etiquetas, el mismo reporte no deja filas y el ancla no encuentra periodo', () => {
|
||||||
|
// Pins down the failure the Measure without `categoria` causes: the report counts 12 patients, but with no declared
|
||||||
|
// category there is no row, so the anchor reads «Sin filas utilizables» and the initial period stays empty. Fails
|
||||||
|
// if the page starts inventing categories from the report (it must keep asking the Measure).
|
||||||
|
const datos = datosDeReportes(eu7([]), [reporte()], 'semestre');
|
||||||
|
expect(datos.filas).toEqual([]);
|
||||||
|
expect(kpiResult(datos, ancla, 'cacu', aplicado).state).toBe('Sin filas utilizables');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// `fixtures/cacu_fhir_measures.json` is the Measure bundle `GET /cacu/fhir/Measure` returns from the dbt definitions once
|
||||||
|
// CaCu declares its figures and category labels (WebApi with the figures and labels declared in Transformation); the reports are built
|
||||||
|
// from the categories each Measure declares, as the WebApi would count them.
|
||||||
|
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||||
|
const medida = (id: string) => publicadas.find(m => m.id === id)!;
|
||||||
|
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
|
||||||
|
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
|
||||||
|
const codigo = (c: string) => ({ coding: [{ code: c }] });
|
||||||
|
const reporteDe = (m: Measure, conteos: number[]): Report => ({
|
||||||
|
resourceType: 'MeasureReport', id: `${m.id}-1`, period: { start: '2025-07-01', end: '2025-12-31' },
|
||||||
|
group: [{ code: codigo('TOTAL'), population: [{ code: codigo('initial-population'), count: conteos.reduce((a, b) => a + b, 0) }],
|
||||||
|
stratifier: [{ code: [codigo('categoria')], stratum: declaradas(m).map((c, i) => ({
|
||||||
|
value: codigo(c), population: [{ code: codigo('initial-population'), count: conteos[i] }] })) }] }],
|
||||||
|
} as unknown as Report);
|
||||||
|
|
||||||
|
describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => {
|
||||||
|
it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => {
|
||||||
|
// Pins down: C2 measures offer the donut and the bars, the C3r the box plot, and the C1 and the risk bands none
|
||||||
|
// yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not
|
||||||
|
// checked against the renderer.
|
||||||
|
const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras]));
|
||||||
|
expect(figuras).toEqual({
|
||||||
|
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_diagnostico_tratamiento: ['fig_c3r_caja'],
|
||||||
|
cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||||
|
cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||||
|
cacu_riesgo_banda: [], ind1: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('con las etiquetas publicadas, el ancla muestra el total y el donut y las barras se dibujan', () => {
|
||||||
|
// Pins down the whole chain for the anchor: published categories -> rows -> «Pacientes evaluadas» total (16) ->
|
||||||
|
// supported C2 donut and bars. Fails if the page cannot read what the WebApi publishes for CaCu's distribution.
|
||||||
|
const eu7 = medida('CACU-EU7');
|
||||||
|
const datos = datosDeReportes(eu7, [reporteDe(eu7, [8, 3, 2, 1, 1, 0, 1])], 'semestre');
|
||||||
|
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
|
||||||
|
expect(resultado).toMatchObject({ state: 'Disponible', value: 16 });
|
||||||
|
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
|
||||||
|
const dibujo = c2Figure(datos, { dominio: 'cacu', indicador: 'cacu_eu7', figura, tipoPeriodo: 'semestre', tema: 'claro',
|
||||||
|
periodos: ['2025-S2'] } as unknown as FigureSelection);
|
||||||
|
expect(dibujo.status).toBe('supported');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un C1 publicado con su intervalo de Wilson llena la banda del histórico, en porcentaje', () => {
|
||||||
|
// Pins down: the `ic-bajo` and `ic-alto` of a proportion's score (proportions) reach the rows as percentages and
|
||||||
|
// the history trend draws them as its band. Fails if the bounds are read unconverted or dropped.
|
||||||
|
const eu13 = medida('CACU-EU13');
|
||||||
|
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||||
|
const reporte13 = { resourceType: 'MeasureReport', id: 'CACU-EU13-1', period: { start: '2025-01-01', end: '2025-06-30' },
|
||||||
|
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
|
||||||
|
measureScore: { value: 0.25, extension: [{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 }, { url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 }] } }] } as unknown as Report;
|
||||||
|
const datos = datosDeReportes(eu13, [reporte13], 'semestre');
|
||||||
|
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
|
||||||
|
const banda = (historicoFigura(datos, 'claro').figure as unknown as { data: { name: string; y: number[] }[] }).data[0];
|
||||||
|
expect(banda.name).toBe('Intervalo de confianza');
|
||||||
|
expect(banda.y).toEqual([69.9, 4.6]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un C1 de CaCu cuyo grupo se llama principal dibuja su tendencia en el histórico', () => {
|
||||||
|
// Pins down: the WebApi names the group of a proportion `principal`; the page reads it as `total`, the group the
|
||||||
|
// history trend draws, for CaCu as for CaMa. Fails if the rows keep the group `principal` and the trend comes out
|
||||||
|
// empty, with its period listed as having no data.
|
||||||
|
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||||
|
for (const id of ['CACU-EU13', 'IND1']) {
|
||||||
|
const medida13 = medida(id);
|
||||||
|
const reporte = { resourceType: 'MeasureReport', id: id + '-1', period: { start: '2025-01-01', end: '2025-06-30' },
|
||||||
|
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
|
||||||
|
measureScore: { value: 0.25 } }] } as unknown as Report;
|
||||||
|
const datos = datosDeReportes(medida13, [reporte], 'semestre');
|
||||||
|
expect(datos.filas[0]['grupo']).toBe('total');
|
||||||
|
const figura = historicoFigura(datos, 'claro');
|
||||||
|
expect((figura.figure as unknown as { data: { y: number[] }[] }).data[1].y).toEqual([25]);
|
||||||
|
expect(figura.sinDato).toEqual([]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// How CaCu's FHIR measures map onto what the indicator page reads: the page's id of each measure.
|
||||||
|
//
|
||||||
|
// The WebApi names a measure `CACU-EU7`, `CACU-CONFIRMACION-CITOLOGIA` or `IND1`; the page, its KPI definitions, the
|
||||||
|
// initial-period anchor and the cards that have a view of their own (`cacu_eu7`, `cacu_confirmacion_citologia`, the
|
||||||
|
// time pair) all use the lower-case ids below. The generic rule would give `CACU_EU7`, which none of them matches, so
|
||||||
|
// the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule.
|
||||||
|
export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
|
||||||
|
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
|
||||||
|
'CACU-DIAS-BIOPSIA-DIAGNOSTICO': 'cacu_dias_biopsia_diagnostico',
|
||||||
|
'CACU-DIAS-COLPOSCOPIA-BIOPSIA': 'cacu_dias_colposcopia_biopsia',
|
||||||
|
'CACU-DIAS-DIAGNOSTICO-TRATAMIENTO': 'cacu_dias_diagnostico_tratamiento',
|
||||||
|
'CACU-DIAS-RESULTADO-COLPOSCOPIA': 'cacu_dias_resultado_colposcopia',
|
||||||
|
'CACU-DIAS-TOMA-BIOPSIA': 'cacu_dias_toma_biopsia',
|
||||||
|
'CACU-DIAS-TOMA-COLPOSCOPIA': 'cacu_dias_toma_colposcopia',
|
||||||
|
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
|
||||||
|
'CACU-DIAS-TOMA-TRATAMIENTO': 'cacu_dias_toma_tratamiento',
|
||||||
|
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
|
||||||
|
'CACU-EU13': 'cacu_eu13',
|
||||||
|
'CACU-EU7': 'cacu_eu7',
|
||||||
|
'CACU-RIESGO-BANDA': 'cacu_riesgo_banda',
|
||||||
|
'CACU-VPH-GENOTIPO': 'cacu_vph_genotipo',
|
||||||
|
'IND1': 'ind1',
|
||||||
|
};
|
||||||
@@ -19,7 +19,7 @@ import { figureApplied } from './indicadores-figure-selection';
|
|||||||
class ChartStub {}
|
class ChartStub {}
|
||||||
const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({
|
const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({
|
||||||
id, titulo, contrato, tipos_periodo: ['semestre', 'mes'],
|
id, titulo, contrato, tipos_periodo: ['semestre', 'mes'],
|
||||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
|
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : contrato === 'C2' ? ['fig_c2_barras'] : [], version: '1',
|
||||||
});
|
});
|
||||||
const catalog = [
|
const catalog = [
|
||||||
item('cacu_eu13', 'Tasa de detección histopatológica'),
|
item('cacu_eu13', 'Tasa de detección histopatológica'),
|
||||||
@@ -67,7 +67,8 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
});
|
});
|
||||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||||
const cards = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
|
// The clinical section only: CaCu's time figures sit in the opportunity section.
|
||||||
|
const cards = () => fixture.debugElement.query(By.css('.graphic-section')).queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
|
||||||
const card = (id: string) => cards().find(c => c.indicador.id === id)!;
|
const card = (id: string) => cards().find(c => c.indicador.id === id)!;
|
||||||
const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel))
|
const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel))
|
||||||
.map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!;
|
.map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!;
|
||||||
@@ -84,11 +85,12 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
|||||||
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||||
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
|
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
|
||||||
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
|
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
|
||||||
'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
'Pacientes evaluadas', 'Tiempo desde la toma de muestra al resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||||
]);
|
]);
|
||||||
for (const kpi of kpis.slice(3)) {
|
for (const kpi of kpis.slice(3)) {
|
||||||
expect(kpi.querySelectorAll('p')).toHaveLength(1);
|
expect(kpi.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
|
||||||
expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
|
expect(kpi.textContent).toContain('aún no está publicado');
|
||||||
|
expect(kpi.querySelector('.value, .period')).toBeNull();
|
||||||
}
|
}
|
||||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
|
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
|
||||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
|
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
|
||||||
@@ -101,12 +103,12 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
|||||||
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
|
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
|
||||||
expect(before[0].indicador.id).toBe('cacu_eu7');
|
expect(before[0].indicador.id).toBe('cacu_eu7');
|
||||||
page.togglePinned(original[0]); fixture.detectChanges();
|
page.togglePinned(original[0]); fixture.detectChanges();
|
||||||
expect(cards()[0]).toBe(card('cacu_eu13'));
|
expect(cards()[0]).toBe(card('cacu_eu7'));
|
||||||
page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
|
page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
|
||||||
expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
|
expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
|
||||||
for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
|
for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
|
||||||
page.showAllIndicators(); fixture.detectChanges();
|
page.showAllIndicators(); fixture.detectChanges();
|
||||||
expect(cards()[0].indicador.id).toBe('cacu_eu13');
|
expect(cards()[0].indicador.id).toBe('cacu_eu7');
|
||||||
expect(page.catalog()).toBe(original);
|
expect(page.catalog()).toBe(original);
|
||||||
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
|
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { isCoffeeColor } from './indicadores-c2-palette';
|
||||||
|
|
||||||
|
// Exact codes from the CaCu catalog. Cytology and biopsy keep their own groups.
|
||||||
|
// The ochre sits outside the coffee range that the shared Plotly renderer recolors.
|
||||||
|
const CATEGORY_COLORS: Readonly<Record<string, string>> = Object.freeze({
|
||||||
|
NORMAL: '#438B53',
|
||||||
|
'ASC-US': '#2879BD',
|
||||||
|
LIEBG: '#AD8F20',
|
||||||
|
'ASC-H': '#7959B8',
|
||||||
|
LIEAG: '#D14D78',
|
||||||
|
CIS: '#AE4050',
|
||||||
|
CARCINOMA: '#925078',
|
||||||
|
SIN_DATO: '#C9CDD2',
|
||||||
|
SIN_BIOPSIA: '#C9CDD2',
|
||||||
|
// HPV by genotype: outside the coffee hues, apart from the cytology and biopsy colours; unknown and inconsistent stay grey.
|
||||||
|
NEGATIVO: '#5F9EA0',
|
||||||
|
POSITIVO_16: '#3E6FB0',
|
||||||
|
POSITIVO_18: '#7B5EA7',
|
||||||
|
POSITIVO_16_18: '#B0457A',
|
||||||
|
POSITIVO_SIN_16_18: '#4F7942',
|
||||||
|
POSITIVO_INCOMPLETO: '#9A9A2F',
|
||||||
|
INDETERMINADO: '#8A9199',
|
||||||
|
INCONSISTENTE: '#C9CDD2',
|
||||||
|
});
|
||||||
|
|
||||||
|
const GROUP_COLORS: Readonly<Record<string, string>> = Object.freeze({
|
||||||
|
NO_ANORMAL: '#247A71',
|
||||||
|
ANORMAL: '#656677',
|
||||||
|
SIN_DATO: '#C9CDD2',
|
||||||
|
});
|
||||||
|
|
||||||
|
export function cacuCategoryColor(id: string): string | undefined {
|
||||||
|
return Object.hasOwn(CATEGORY_COLORS, id) ? CATEGORY_COLORS[id] : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cacuGroupColor(id: string): string | undefined {
|
||||||
|
return Object.hasOwn(GROUP_COLORS, id) ? GROUP_COLORS[id] : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cacuClinicalColor(id: string, published: string | null): string {
|
||||||
|
// A new catalog code can keep a valid published color when the renderer can keep it too.
|
||||||
|
return cacuCategoryColor(id) ?? (published && !isCoffeeColor(published) ? published : '#8A9199');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export function cacuRgba(hex: string, alpha: number): string {
|
||||||
|
const v = parseInt(hex.slice(1), 16);
|
||||||
|
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// Covers how the Indicadores tab arranges CaCu's figures: the five times of «Tiempo de tamizaje a diagnóstico» under
|
||||||
|
// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures. Fixtures: a CaCu catalog shaped like /cacu/indicadores.
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { IndicadoresPage } from './indicadores-page';
|
||||||
|
import { IndicadoresMemory } from './indicadores-memory';
|
||||||
|
|
||||||
|
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||||
|
const CACU = [
|
||||||
|
item('cacu_eu13', 'Tasa de detección histopatológica', 'C1', []),
|
||||||
|
item('cacu_eu7', 'Distribución de resultados citológicos', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
||||||
|
item('cacu_eu_tiempo_reporte', 'Días de la toma de la citología a su resultado', 'C3r', ['fig_c3r_caja']),
|
||||||
|
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||||
|
item('cacu_confirmacion_citologia', 'Tasa de confirmación histopatológica', 'C2', ['fig_c2_donas']),
|
||||||
|
item('ind1', 'Pacientes con citología anómala', 'C1', []),
|
||||||
|
];
|
||||||
|
|
||||||
|
// The route measures besides the cytology and diagnosis ones in CACU; with all of them the screening route chart appears.
|
||||||
|
const RUTA = ['cacu_dias_resultado_colposcopia', 'cacu_dias_toma_colposcopia', 'cacu_dias_colposcopia_biopsia', 'cacu_dias_toma_biopsia', 'cacu_dias_biopsia_diagnostico']
|
||||||
|
.map(id => item(id, id, 'C3r', ['fig_c3r_caja']));
|
||||||
|
|
||||||
|
describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () => {
|
||||||
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||||
|
const abrir = (catalogo: ReturnType<typeof item>[]) => {
|
||||||
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||||
|
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||||
|
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||||
|
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||||
|
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||||
|
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||||
|
http.expectOne('/cacu/indicadores').flush(catalogo); fixture.detectChanges();
|
||||||
|
http.match(() => true); fixture.detectChanges();
|
||||||
|
};
|
||||||
|
// The KPI and period requests are not what these tests are about.
|
||||||
|
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||||
|
const root = () => fixture.nativeElement as HTMLElement;
|
||||||
|
const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')]
|
||||||
|
.map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim());
|
||||||
|
|
||||||
|
it('las figuras disponibles conservan su orden sin reservas vacías', () => {
|
||||||
|
// Fails if a time figure changes place, if a missing indicator is drawn as a figure or if the published ones lose
|
||||||
|
// the names of the request.
|
||||||
|
abrir(CACU);
|
||||||
|
expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico');
|
||||||
|
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||||
|
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||||
|
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('con la ruta del tamizaje no hay subsección «Tiempo de tamizaje a diagnóstico»: la gráfica dibuja los tiempos', () => {
|
||||||
|
// Fails if the times the route chart draws also get a figure or a «pendiente» slot of their own next to it.
|
||||||
|
abrir([...CACU, ...RUTA]);
|
||||||
|
expect(root().querySelector('.subsection-title')).toBeNull();
|
||||||
|
expect(titulos('.kpi-section .catalog-grid')).toEqual([]);
|
||||||
|
expect(root().querySelector('app-indicador-screening-route')).not.toBeNull();
|
||||||
|
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||||
|
'catalog-card: Resultados de citología, VPH y biopsia', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sin la gráfica de la ruta, colposcopía y biopsia publicadas son figuras con su nombre', () => {
|
||||||
|
// Fails if a published measure of the route stays a pending slot while the chart that would draw it is not there.
|
||||||
|
abrir([...CACU, ...RUTA.filter(medida => medida.id === 'cacu_dias_toma_colposcopia' || medida.id === 'cacu_dias_toma_biopsia')]);
|
||||||
|
expect(root().querySelector('app-indicador-screening-route')).toBeNull();
|
||||||
|
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||||
|
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||||
|
'catalog-card: Tiempo de toma de muestra a resultado de colposcopía',
|
||||||
|
'catalog-card: Tiempo de toma de muestra a resultado de biopsia',
|
||||||
|
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el resultado de laboratorio se llama «Tiempo desde la toma de muestra al resultado»', () => {
|
||||||
|
// Fails if the opportunity card goes back to «Días de toma a resultado».
|
||||||
|
abrir(CACU);
|
||||||
|
const titulosKpi = [...root().querySelectorAll('.kpi-section app-indicador-kpi-card h3')].map(h => h.textContent?.trim());
|
||||||
|
expect(titulosKpi).toContain('Tiempo desde la toma de muestra al resultado');
|
||||||
|
expect(titulosKpi).not.toContain('Días de toma a resultado');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('los indicadores clínicos son los dos pedidos, sin tarjetas vacías ni figuras pendientes', () => {
|
||||||
|
// Fails if the time figures stay in the clinical section, if indicators with no figure get a card, or if a pending
|
||||||
|
// figure («Progresión por grupo de riesgo», withdrawn) comes back.
|
||||||
|
abrir(CACU);
|
||||||
|
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||||
|
'catalog-card: Resultados de citología, VPH y biopsia', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||||
|
expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Datos y definiciones conserva todo el catálogo', () => {
|
||||||
|
// Fails if moving the time figures or hiding figure-less indicators removes them from the definitions tab.
|
||||||
|
abrir(CACU);
|
||||||
|
const definiciones = root().querySelector('#panel-datos')!.textContent!;
|
||||||
|
for (const titulo of ['Tasa de detección histopatológica', 'Pacientes con citología anómala', 'Tiempo de toma de muestra a diagnóstico']) expect(definiciones).toContain(titulo);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -32,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () =>
|
|||||||
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
|
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
|
||||||
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
|
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
|
||||||
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
|
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
|
||||||
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.' });
|
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.', numerador: 0, denominador: 1 });
|
||||||
});
|
});
|
||||||
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
|
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
|
||||||
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||||
@@ -143,8 +143,8 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
|||||||
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
||||||
expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
|
expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
|
||||||
expect(titulos.filter(([, estado]) => estado === 'dibujado'))
|
expect(titulos.filter(([, estado]) => estado === 'dibujado'))
|
||||||
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado']]);
|
.toEqual([['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Resultado histopatológico', 'dibujado']]);
|
||||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2]);
|
expect(graficas().map(g => g.figure!.data.length)).toEqual([2, 6]);
|
||||||
});
|
});
|
||||||
it('el panel C3r avisa el periodo suprimido y la matriz CAM-03 sigue visible', () => {
|
it('el panel C3r avisa el periodo suprimido y la matriz CAM-03 sigue visible', () => {
|
||||||
montar(false);
|
montar(false);
|
||||||
@@ -199,15 +199,15 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
|||||||
return pedidos;
|
return pedidos;
|
||||||
}
|
}
|
||||||
const root = () => fixture.nativeElement as HTMLElement;
|
const root = () => fixture.nativeElement as HTMLElement;
|
||||||
const kpis = () => [...root().querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
const kpis = () => [...root().querySelectorAll('.kpi-section .kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||||
const tarjetas = () => [...root().querySelectorAll('.catalog-grid > *')] as HTMLElement[];
|
const tarjetas = () => [...root().querySelectorAll('.graphic-section .catalog-grid > *')] as HTMLElement[];
|
||||||
const completo = () => [...KPI_BY_DOMAIN.cama.map(propios), ...REALES];
|
const completo = () => [...KPI_BY_DOMAIN.cama.map(propios), ...REALES];
|
||||||
|
|
||||||
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
|
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
|
||||||
// Fails if the unavailable slot displays a value or displaces the published measures.
|
// Fails if the unavailable slot displays a value or displaces the published measures.
|
||||||
const pedidos = cargar(completo());
|
const pedidos = cargar(completo());
|
||||||
expect(kpis()).toHaveLength(5);
|
expect(kpis()).toHaveLength(5);
|
||||||
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
expect(root().querySelector('.kpi-section .kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
||||||
expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
|
expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
|
||||||
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
|
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
|
||||||
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con riesgo a carcinoma.');
|
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con riesgo a carcinoma.');
|
||||||
@@ -215,10 +215,11 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
|||||||
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
|
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
|
||||||
expect(kpis()[4].querySelector('.value')).toBeNull();
|
expect(kpis()[4].querySelector('.value')).toBeNull();
|
||||||
});
|
});
|
||||||
it('CAM-03 ocupa el lugar de la tarjeta pendiente, primero y con su vista especializada; no se consulta mientras no es visible', () => {
|
it('CAM-03 ocupa el lugar de la tarjeta pendiente, después de los conteos y con su vista especializada; no se consulta mientras no es visible', () => {
|
||||||
const pedidos = cargar(completo());
|
const pedidos = cargar(completo());
|
||||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||||
const primera = tarjetas()[0];
|
// The exams' and patients' counts go first; the histopathology card is the last of the grid (the confirmation rate follows it).
|
||||||
|
const primera = tarjetas().at(-1)!;
|
||||||
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
||||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||||
expect(primera.querySelector('h2')!.textContent).toBe('Histopatología por BI-RADS');
|
expect(primera.querySelector('h2')!.textContent).toBe('Histopatología por BI-RADS');
|
||||||
|
|||||||
@@ -50,10 +50,10 @@ describe('Identificadores de CaMa entre FHIR y la página', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('el id de una medida de otro dominio sigue la regla general', () => {
|
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
|
// Pins down: only CaMa's table maps CaMa's measures, and TEA's keep `-` to `_` (CaCu has a table of its own, see
|
||||||
// ids of other domains or the generic rule changes.
|
// indicadores-cacu-fhir.spec.ts). Fails if CaMa's table captures ids of other domains or the generic rule changes.
|
||||||
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
|
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
|
||||||
expect(indicadorId('CACU-EU7')).toBe('CACU_EU7');
|
expect(Object.hasOwn(CAMA_MEASURE_IDS, 'CACU-EU7')).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
|
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => {
|
|||||||
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
|
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
|
||||||
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
|
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
|
||||||
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||||
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
|
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.', numerador: 3, denominador: 20 });
|
||||||
});
|
});
|
||||||
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
|
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
|
||||||
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||||
@@ -205,13 +205,15 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
|||||||
}
|
}
|
||||||
return requested;
|
return requested;
|
||||||
}
|
}
|
||||||
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-section .kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||||
const text = (card: HTMLElement, selector: string) => card.querySelector(selector)?.textContent?.trim();
|
const text = (card: HTMLElement, selector: string) => card.querySelector(selector)?.textContent?.trim();
|
||||||
|
|
||||||
it('con el catálogo actual: dos tarjetas con datos, dos pendientes y diagnóstico a tratamiento sin dato ni consulta', () => {
|
it('con el catálogo actual: dos tarjetas con datos, dos pendientes y diagnóstico a tratamiento sin dato ni consulta', () => {
|
||||||
// Fails if any card without a published measure makes a request or displays a value.
|
// Fails if any card without a published measure makes a request or displays a value. The confirmation rate of the
|
||||||
const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
// clinical section is a published measure with its own panel, so it is requested too.
|
||||||
expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
const publicados = [...KPI_BY_DOMAIN.cama, CAMA_CONFIRMACION_KPI];
|
||||||
|
const urls = load(publicados, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||||
|
expect([...new Set(urls)].sort()).toEqual(publicados.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
||||||
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
||||||
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||||
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
|
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
|
||||||
@@ -260,7 +262,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
|||||||
});
|
});
|
||||||
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
|
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
|
||||||
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
|
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
|
||||||
load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
load([...KPI_BY_DOMAIN.cama, CAMA_CONFIRMACION_KPI], { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||||
const ids = fixture.componentInstance.searchResults().items.map(item => item.id);
|
const ids = fixture.componentInstance.searchResults().items.map(item => item.id);
|
||||||
expect(ids).not.toContain('cama_biopsias');
|
expect(ids).not.toContain('cama_biopsias');
|
||||||
expect(ids).toContain('cama_birads_456_mastografia');
|
expect(ids).toContain('cama_birads_456_mastografia');
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// Covers the clinical section of CaMa's summary: its heading and counter, and the controls the mockup does not
|
// Covers the clinical section: its heading, and the controls the mockup does not have
|
||||||
// have (search, pins, floating navigation, representation selector, figure count), which CaCu and TEA keep.
|
// (search, pins, floating navigation, representation selector, figure count) in every domain.
|
||||||
// Fixtures are catalogs shaped like /<dominio>/indicadores; no figure is requested (the cards stay out of view).
|
// Fixtures are catalogs shaped like /<dominio>/indicadores; no figure is requested (the cards stay out of view).
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
@@ -44,7 +44,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
|||||||
}
|
}
|
||||||
const root = () => fixture.nativeElement as HTMLElement;
|
const root = () => fixture.nativeElement as HTMLElement;
|
||||||
const section = () => root().querySelector('.graphic-section') as HTMLElement;
|
const section = () => root().querySelector('.graphic-section') as HTMLElement;
|
||||||
const titles = () => [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
const titles = () => [...root().querySelectorAll('.graphic-section .catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||||
|
|
||||||
it('CaMa: «Indicadores clínicos» muestra las tarjetas de la sección, sin el conteo de publicados', () => {
|
it('CaMa: «Indicadores clínicos» muestra las tarjetas de la sección, sin el conteo de publicados', () => {
|
||||||
// Fails if the heading goes back to the whole catalog while a card is not drawn.
|
// Fails if the heading goes back to the whole catalog while a card is not drawn.
|
||||||
@@ -62,7 +62,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
|||||||
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
|
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
|
||||||
// Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones.
|
// Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones.
|
||||||
open('cama', CAMA);
|
open('cama', CAMA);
|
||||||
for (const titulo of ['Tasa de confirmación histopatológica', 'Tiempo de tamizaje a diagnóstico', 'Días de la toma de la mastografía a su resultado']) {
|
for (const titulo of ['Tiempo de tamizaje a diagnóstico', 'Días de la toma de la mastografía a su resultado']) {
|
||||||
expect(section().textContent).not.toContain(titulo);
|
expect(section().textContent).not.toContain(titulo);
|
||||||
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
|
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
|||||||
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
|
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
|
||||||
open('cama', CAMA);
|
open('cama', CAMA);
|
||||||
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
|
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
|
||||||
expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6');
|
expect(nombres).toContain('Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6');
|
||||||
expect(nombres).not.toContain(CAMA[1].titulo);
|
expect(nombres).not.toContain(CAMA[1].titulo);
|
||||||
});
|
});
|
||||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
||||||
@@ -82,8 +82,23 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
|||||||
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
|
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
|
||||||
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
|
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
|
||||||
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
|
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
|
||||||
// It comes first, as in the reference, and is not counted as a published indicator.
|
// It follows the exams' and patients' counts, as the request orders them, and is not counted as a published indicator.
|
||||||
expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta);
|
expect(root().querySelector('.graphic-section .catalog-grid')!.lastElementChild).toBe(tarjeta);
|
||||||
|
});
|
||||||
|
it('CaMa: el orden clínico es mastografías, pacientes, histopatología y tasa de confirmación', () => {
|
||||||
|
// Fails if the clinical figures change order, if the confirmation rate leaves the clinical section or if the two
|
||||||
|
// counts lose the titles of the request (BI-RADS 4, 5 ó 6, with the period).
|
||||||
|
open('cama', CAMA);
|
||||||
|
const orden = [...section().querySelectorAll('.catalog-grid > *, .kpi-grid > *')].map(e => e.tagName.toLowerCase());
|
||||||
|
expect(orden).toEqual(['app-indicador-catalog-card', 'app-indicador-histopatologia-pendiente', 'app-indicador-kpi-panel']);
|
||||||
|
expect(section().querySelector('.kpi-grid h3')?.textContent?.trim()).toBe('Tasa de confirmación histopatológica');
|
||||||
|
});
|
||||||
|
it('CaMa: sin la tasa de confirmación en el catálogo queda como pendiente al final', () => {
|
||||||
|
// Fails if a missing indicator is dropped silently or drawn with numbers.
|
||||||
|
open('cama', CAMA.filter(medida => medida.id !== 'cama_confirmacion_birads45'));
|
||||||
|
const ultima = section().querySelector('.kpi-grid app-indicador-kpi-card') as HTMLElement;
|
||||||
|
expect(ultima.textContent).toContain('Tasa de confirmación histopatológica');
|
||||||
|
expect(ultima.textContent).toContain('Integración pendiente');
|
||||||
});
|
});
|
||||||
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
|
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
|
||||||
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
||||||
@@ -113,18 +128,14 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
|||||||
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
|
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
|
||||||
expect(titles()).toEqual(before);
|
expect(titles()).toEqual(before);
|
||||||
});
|
});
|
||||||
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados y conteo de figuras', domain => {
|
it.each(['tea', 'cacu'] as const)('%s usa el mismo resumen clínico que CaMa: sin buscador, fijados ni conteo de figuras', domain => {
|
||||||
// Fails if CaMa's simplified section leaks into the other domains.
|
|
||||||
open(domain, OTRO(domain));
|
open(domain, OTRO(domain));
|
||||||
expect(root().querySelector('.catalog-search')).not.toBeNull();
|
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||||
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
|
expect(root().querySelector('#dashboard-title')?.textContent?.trim()).toBe(domain === 'tea' ? 'Trastorno del espectro autista' : 'Cáncer cervicouterino');
|
||||||
expect(section().textContent).toContain('2 figuras publicadas');
|
expect(root().querySelector('header .domain')).toBeNull();
|
||||||
|
expect(root().querySelector('.catalog-search')).toBeNull();
|
||||||
|
expect(root().querySelector('.pin-toggle')).toBeNull();
|
||||||
|
expect(section().textContent).not.toContain('figuras publicadas');
|
||||||
expect(root().textContent).not.toContain('indicadores publicados');
|
expect(root().textContent).not.toContain('indicadores publicados');
|
||||||
});
|
});
|
||||||
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
|
|
||||||
open('cacu', OTRO('cacu'));
|
|
||||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
|
||||||
open('tea', OTRO('tea'));
|
|
||||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores gráficos');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
// Covers CaMa's «Tiempo de tamizaje a diagnóstico» in Indicadores de oportunidad: the five figures in the order of the
|
||||||
|
// request, each pending while the catalog does not publish its indicator. Fixtures: a CaMa catalog shaped like /cama/indicadores.
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { IndicadoresPage } from './indicadores-page';
|
||||||
|
import { IndicadoresMemory } from './indicadores-memory';
|
||||||
|
|
||||||
|
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||||
|
const CAMA = [
|
||||||
|
item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas']),
|
||||||
|
item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja']),
|
||||||
|
item('cama_dias_resultado_diagnostico', 'Tiempo de resultado a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||||
|
item('cama_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||||
|
];
|
||||||
|
|
||||||
|
describe('Indicadores de CaMa: tiempos de oportunidad', () => {
|
||||||
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||||
|
function abrir(catalogo: ReturnType<typeof item>[]) {
|
||||||
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||||
|
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||||
|
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||||
|
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||||
|
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||||
|
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||||
|
http.expectOne('/cama/indicadores').flush(catalogo); fixture.detectChanges();
|
||||||
|
http.match(() => true); fixture.detectChanges();
|
||||||
|
}
|
||||||
|
// The KPI and period requests are not what these tests are about.
|
||||||
|
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||||
|
const root = () => fixture.nativeElement as HTMLElement;
|
||||||
|
const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')]
|
||||||
|
.map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim());
|
||||||
|
|
||||||
|
it('las cinco figuras van en su orden con los nombres pedidos; las no publicadas quedan pendientes', () => {
|
||||||
|
// Fails if a time figure changes place, keeps the catalog's own title, or a missing indicator is drawn as a figure.
|
||||||
|
abrir(CAMA);
|
||||||
|
expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico');
|
||||||
|
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||||
|
'catalog-card: Tiempo de toma de mastografía a interpretación radiológica',
|
||||||
|
'catalog-card: Tiempo de interpretación radiológica a diagnóstico',
|
||||||
|
'figura-pendiente: Tiempo de interpretación radiológica a resultado de biopsia',
|
||||||
|
'figura-pendiente: Tiempo de diagnóstico a tratamiento',
|
||||||
|
'catalog-card: Tiempo de tamizaje a diagnóstico']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un indicador de tiempo que el catálogo no publica queda pendiente sin dejar de ocupar su lugar', () => {
|
||||||
|
// Fails if a missing measure shifts the order or disappears instead of showing as pending.
|
||||||
|
abrir(CAMA.filter(medida => medida.id !== 'cama_dias_resultado_diagnostico'));
|
||||||
|
expect(titulos('.kpi-section .catalog-grid').slice(0, 2)).toEqual([
|
||||||
|
'catalog-card: Tiempo de toma de mastografía a interpretación radiológica',
|
||||||
|
'figura-pendiente: Tiempo de interpretación radiológica a diagnóstico']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('las figuras de tiempo no se repiten en Indicadores clínicos ni salen del catálogo de Datos y definiciones', () => {
|
||||||
|
// Fails if a time figure gets a second card in the clinical section or loses its definition entry.
|
||||||
|
abrir(CAMA);
|
||||||
|
expect(root().querySelector('.graphic-section')!.textContent).not.toContain('Tiempo de tamizaje a diagnóstico');
|
||||||
|
expect(root().querySelector('#panel-datos')!.textContent).toContain('Días de la toma de la mastografía a su resultado');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -33,8 +33,7 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(text()).not.toContain('Indicador de CaMa');
|
expect(text()).not.toContain('Indicador de CaMa');
|
||||||
});
|
});
|
||||||
it('los controles propios de cada dominio se conservan al ir y volver', () => {
|
it('el resumen clínico es el mismo al ir y volver, y el catálogo no se mezcla', () => {
|
||||||
// CaCu keeps its multiple selection, search and pins; CaMa does not have them; neither state contaminates the other.
|
|
||||||
const abrir = (d: 'cacu' | 'cama', n: number) => {
|
const abrir = (d: 'cacu' | 'cama', n: number) => {
|
||||||
fixture.componentInstance.changeDominio(d); fixture.detectChanges();
|
fixture.componentInstance.changeDominio(d); fixture.detectChanges();
|
||||||
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
|
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
|
||||||
@@ -42,8 +41,9 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
|||||||
};
|
};
|
||||||
const el = () => fixture.nativeElement as HTMLElement;
|
const el = () => fixture.nativeElement as HTMLElement;
|
||||||
abrir('cacu', 6);
|
abrir('cacu', 6);
|
||||||
expect(el().querySelector('.catalog-search')).not.toBeNull();
|
expect(el().querySelector('.catalog-search')).toBeNull();
|
||||||
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
|
expect(el().querySelector('.pin-toggle')).toBeNull();
|
||||||
|
expect(el().querySelector('#dashboard-title')?.textContent?.trim()).toBe('Cáncer cervicouterino');
|
||||||
expect(el().textContent).toContain('Intervalo de análisis');
|
expect(el().textContent).toContain('Intervalo de análisis');
|
||||||
abrir('cama', 6);
|
abrir('cama', 6);
|
||||||
expect(el().querySelector('.catalog-search')).toBeNull();
|
expect(el().querySelector('.catalog-search')).toBeNull();
|
||||||
@@ -51,9 +51,8 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
|||||||
expect(el().textContent).not.toContain('Buscar indicadores');
|
expect(el().textContent).not.toContain('Buscar indicadores');
|
||||||
expect(el().textContent).not.toContain('cacu_');
|
expect(el().textContent).not.toContain('cacu_');
|
||||||
abrir('cacu', 6);
|
abrir('cacu', 6);
|
||||||
// On the way back the page state (not only the DOM) says CaCu has its search again.
|
|
||||||
expect(fixture.componentInstance.dominio).toBe('cacu');
|
expect(fixture.componentInstance.dominio).toBe('cacu');
|
||||||
expect(fixture.componentInstance.searchVisible()).toBe(true);
|
expect(fixture.componentInstance.searchVisible()).toBe(false);
|
||||||
expect(el().textContent).toContain('Intervalo de análisis');
|
expect(el().textContent).toContain('Intervalo de análisis');
|
||||||
expect(el().textContent).not.toContain('cama_');
|
expect(el().textContent).not.toContain('cama_');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { strFromU8, unzipSync } from 'fflate';
|
|||||||
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
|
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
|
||||||
import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf';
|
import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf';
|
||||||
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
|
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
|
||||||
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte';
|
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaEscenario, etiquetaHistologia } from './etiquetas-cohorte';
|
||||||
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
|
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
|
||||||
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||||
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
|
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
|
||||||
@@ -33,6 +33,17 @@ describe('Etiquetas de la cohorte', () => {
|
|||||||
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
|
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
|
||||||
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
|
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
|
||||||
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
|
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
|
||||||
|
expect(['POST_TRATAMIENTO', 'EN_OBSERVACION', 'CONTROL'].map(etiquetaEscenario)).toEqual(['Post-tratamiento', 'En observación', 'CONTROL']);
|
||||||
|
});
|
||||||
|
it('el escenario clínico de una fila se lee «Post-tratamiento» o «En observación» en la lista y en la ficha, con su código guardado', () => {
|
||||||
|
// Fails if the list or the record show the scenario's code, or the code the filter sends is lost.
|
||||||
|
const cruda = listaCohorte();
|
||||||
|
const items = cruda['items'] as Record<string, unknown>[];
|
||||||
|
items[0]['escenario_clinico'] = 'POST_TRATAMIENTO'; items[1]['escenario_clinico'] = 'EN_OBSERVACION';
|
||||||
|
const r = seguimientoTablaResponse(cruda);
|
||||||
|
expect(r.items[0]).toMatchObject({ escenario_clinico: 'Post-tratamiento', escenario_clinico_codigo: 'POST_TRATAMIENTO' });
|
||||||
|
expect(r.items[1]).toMatchObject({ escenario_clinico: 'En observación', escenario_clinico_codigo: 'EN_OBSERVACION' });
|
||||||
|
expect(toCamaPatientSummary(r.items[0], '2026-01-01')?.clinicalScenario).toBe('Post-tratamiento');
|
||||||
});
|
});
|
||||||
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
|
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
|
||||||
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
|
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
|
||||||
|
|||||||
@@ -3,17 +3,21 @@ import { TestBed } from '@angular/core/testing';
|
|||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
|
import eu7Fixture from './fixtures/eu7-c2-ejemplos.json';
|
||||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||||
|
import { IndicadorCacuDonas } from './indicador-cacu-donas';
|
||||||
|
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { GlobalApplied } from './indicadores-memory';
|
import { GlobalApplied } from './indicadores-memory';
|
||||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||||
|
import { recolorFigure } from './indicadores-c2-palette';
|
||||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||||
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
|
periodosConfirmacion, rangoTasas, seleccionBase, tasas, totalesPublicados, wilson } from './indicadores-confirmacion-citologia';
|
||||||
|
|
||||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
|
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
|
||||||
|
|
||||||
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
|
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
|
||||||
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
|
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
|
||||||
@@ -128,7 +132,16 @@ describe('Confirmación histopatológica: modelo', () => {
|
|||||||
const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro');
|
const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro');
|
||||||
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
||||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/);
|
expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/);
|
||||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0.3\)$/);
|
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0\.45\)$/);
|
||||||
|
});
|
||||||
|
it('el carcinoma conserva el color del marcador, intervalo y dona al seleccionar', () => {
|
||||||
|
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||||
|
const sel = { grupo: 'ANORMAL', categoria: 'CARCINOMA' };
|
||||||
|
const tasa = figuraTasas(m, sel, 'oscuro'), pie = donaConfirmacion(m, sel, 'oscuro');
|
||||||
|
expect(tasa.data[0]).toMatchObject({ marker: { color: '#925078' }, error_x: { color: '#925078' } });
|
||||||
|
const i = m.grados.findIndex(g => g.id === 'CARCINOMA');
|
||||||
|
expect((pie.data[2]['marker'] as { colors: string[] }).colors[i]).toBe('rgba(146,80,120,1)');
|
||||||
|
expect(recolorFigure(tasa)).toBe(tasa); expect(recolorFigure(pie)).toBe(pie);
|
||||||
});
|
});
|
||||||
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
|
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
|
||||||
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||||
@@ -160,21 +173,22 @@ describe('Confirmación histopatológica: componente', () => {
|
|||||||
expect(r.request.params.get('periodos')).toBe('2026-S1,2026-S2');
|
expect(r.request.params.get('periodos')).toBe('2026-S1,2026-S2');
|
||||||
r.flush(body as Record<string, unknown>); f.detectChanges();
|
r.flush(body as Record<string, unknown>); f.detectChanges();
|
||||||
}
|
}
|
||||||
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible, periodos y tabla', () => {
|
it('carga diferida, solo las tasas (la dona vive en otra tarjeta), leyenda accesible, periodos y tabla', () => {
|
||||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||||
flush(); expect(f.componentInstance.status()).toBe('ready');
|
flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||||
expect(f.componentInstance.model!.periodo).toBe('2026-S2');
|
expect(f.componentInstance.model!.periodo).toBe('2026-S2');
|
||||||
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
|
const figures = [...f.nativeElement.querySelectorAll('.figure')] as HTMLElement[];
|
||||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
|
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas']);
|
||||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
|
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1);
|
||||||
const normal = [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
|
expect(f.componentInstance.barras).toBeUndefined();
|
||||||
|
const normal = [...f.nativeElement.querySelectorAll('.legend .child, .legend .tab')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
|
||||||
normal.click(); f.detectChanges();
|
normal.click(); f.detectChanges();
|
||||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||||
expect(normal.getAttribute('aria-pressed')).toBe('true');
|
expect(normal.getAttribute('aria-pressed')).toBe('true');
|
||||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Falsos positivos');
|
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Falsos positivos');
|
||||||
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
|
([...f.nativeElement.querySelectorAll('.legend .tab')] as HTMLButtonElement[]).find(b => b.textContent!.trim() === 'LIEAG o más')!.click(); f.detectChanges();
|
||||||
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||||
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
|
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
|
||||||
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Citología', ...GRADOS.map(g => g === 'CIS' ? 'Carcinoma in situ' : g), 'CIN2', 'Con biopsia', 'Sin biopsia aún', 'Sin dato']);
|
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Citología', ...GRADOS.map(g => g === 'CIS' ? 'Carcinoma in situ' : g), 'CIN2', 'Con biopsia', 'Sin biopsia aún', 'Sin dato']);
|
||||||
@@ -195,7 +209,7 @@ describe('Confirmación histopatológica: componente', () => {
|
|||||||
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
|
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
|
||||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('«Cómo leer» muestra solo descripción y como_leer de fig_c2_donas y fig_c2_barras', () => {
|
it('«Cómo leer» de las tasas muestra solo descripción y como_leer de fig_c2_barras', () => {
|
||||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||||
@@ -206,8 +220,8 @@ describe('Confirmación histopatológica: componente', () => {
|
|||||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] },
|
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] },
|
||||||
{ figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); f.detectChanges();
|
{ figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); f.detectChanges();
|
||||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||||
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.', 'Lee las tasas.']);
|
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']);
|
||||||
for (const absent of ['No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent);
|
for (const absent of ['Lee la dona.', 'No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent);
|
||||||
});
|
});
|
||||||
it('la tarjeta conecta el panel solo por id de CaCu; cacu_eu13 sigue igual', () => {
|
it('la tarjeta conecta el panel solo por id de CaCu; cacu_eu13 sigue igual', () => {
|
||||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||||
@@ -223,3 +237,162 @@ describe('Confirmación histopatológica: componente', () => {
|
|||||||
card.destroy(); http.expectNone(() => true);
|
card.destroy(); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Confirmación histopatológica: vista de la dona de biopsia', () => {
|
||||||
|
const indicador: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1',
|
||||||
|
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] };
|
||||||
|
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2026-S1', '2026-S2'] }, revision: 1 };
|
||||||
|
let f: ReturnType<typeof TestBed.createComponent<IndicadorConfirmacionCitologia>>;
|
||||||
|
let http: HttpTestingController;
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({ imports: [IndicadorConfirmacionCitologia], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||||
|
TestBed.overrideComponent(IndicadorConfirmacionCitologia, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
|
f = TestBed.createComponent(IndicadorConfirmacionCitologia);
|
||||||
|
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('vista', 'dona');
|
||||||
|
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||||
|
});
|
||||||
|
afterEach(() => { f.destroy(); http.verify(); });
|
||||||
|
const flush = (body: IndicadorDatos = respuesta(['2026-S1', '2026-S2'])) => {
|
||||||
|
http.expectOne(req => req.url.endsWith('/datos')).flush(body as Record<string, unknown>); f.detectChanges();
|
||||||
|
};
|
||||||
|
const apartado = () => (f.nativeElement.querySelector('.aparte').textContent as string).replace(/\s+/g, ' ');
|
||||||
|
// Why: the donut moved to the first card; it must draw only itself, answer its own buttons and keep what it leaves out.
|
||||||
|
it('dibuja solo las barras de la biopsia, responde a sus botones y dice qué queda fuera de la distribución', () => {
|
||||||
|
f.detectChanges(); flush();
|
||||||
|
expect(f.componentInstance.ratesFigure).toBeUndefined();
|
||||||
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||||
|
// Two group headers with their subtotals; the six grades are the bars (a group is not a category).
|
||||||
|
const grupos = [...f.nativeElement.querySelectorAll('.grupo .cabecera')] as HTMLElement[];
|
||||||
|
expect(grupos.map(g => g.textContent!.replace(/\s+/g, ' ').trim())).toEqual(['Grupo Menor que LIEAG 45 41.7 %', 'Grupo LIEAG o más 63 58.3 %']);
|
||||||
|
expect([...f.nativeElement.querySelectorAll('.filas .fila')].map((x: Element) => x.textContent!.replace(/\s+/g, ' ').trim())).toEqual([
|
||||||
|
'NORMAL 22 20.4 %', 'LIEBG 22 20.4 %', 'CIN2 1 0.9 %', 'LIEAG 44 40.7 %', 'Carcinoma in situ 13 12.0 %', 'CARCINOMA 6 5.6 %']);
|
||||||
|
const button = (name: string) => ([...f.nativeElement.querySelectorAll('.legend button')] as HTMLButtonElement[]).find(b => b.textContent!.trim() === name)!;
|
||||||
|
button('NORMAL').click(); f.detectChanges();
|
||||||
|
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||||
|
expect(f.nativeElement.querySelector('.selection-status').textContent).not.toContain('Falsos positivos');
|
||||||
|
button('LIEAG o más').click(); f.detectChanges();
|
||||||
|
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||||
|
expect(f.nativeElement.querySelector('.seleccion').textContent.replace(/\s+/g, ' ')).toContain('Selección: 63 de 108 (58.3 %)');
|
||||||
|
expect(apartado()).toContain('Sin biopsia aún: 53; Sin dato: 6.');
|
||||||
|
expect(f.nativeElement.querySelector('[aria-label="Tabla de resultados de biopsia"]').textContent).toContain('Sin biopsia aún');
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('«Cómo leer» muestra solo la guía de la figura de biopsia', () => {
|
||||||
|
f.componentRef.setInput('metadata', { figuras_detalle: [
|
||||||
|
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] },
|
||||||
|
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] }] });
|
||||||
|
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||||
|
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||||
|
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||||
|
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.']);
|
||||||
|
});
|
||||||
|
it('una celda fuera de la dona suprimida se dice «Suprimido» y no se convierte en cero', () => {
|
||||||
|
const datos = respuesta(['2026-S1', '2026-S2']);
|
||||||
|
Object.assign(datos.filas.find(r => r['periodo'] === '2026-S2' && r['estrato'] === 'LIEAG' && r['categoria'] === 'SIN_BIOPSIA')!, { n: 987654, suprimido: 1 });
|
||||||
|
f.detectChanges(); flush(datos);
|
||||||
|
expect(apartado()).toContain('Sin biopsia aún: Suprimido'); expect(apartado()).not.toContain('987654');
|
||||||
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||||
|
});
|
||||||
|
it('totalesPublicados suma por grado y deja desconocido lo suprimido', () => {
|
||||||
|
const t = totalesPublicados(modeloConfirmacion(respuesta(['2026-S2']), '2026-S2'));
|
||||||
|
expect(t.grados.map(g => [g.id, g.n])).toEqual([['NORMAL', 22], ['LIEBG', 22], ['LIEAG', 44], ['CIS', 13], ['CARCINOMA', 6], ['CIN2', 1]]);
|
||||||
|
expect(t.aparte.map(a => [a.id, a.n, a.estado])).toEqual([['SIN_BIOPSIA', 53, 'Publicado'], ['SIN_DATO', 6, 'Publicado']]);
|
||||||
|
const datos = respuesta(['2026-S2']);
|
||||||
|
Object.assign(datos.filas.find(r => r['estrato'] === 'CIS' && r['categoria'] === 'SIN_DATO')!, { suprimido: 1 });
|
||||||
|
const s = totalesPublicados(modeloConfirmacion(datos, '2026-S2'));
|
||||||
|
expect(s.aparte.find(a => a.id === 'SIN_DATO')).toMatchObject({ n: null, estado: 'Suprimido' });
|
||||||
|
expect(s.aparte.find(a => a.id === 'SIN_BIOPSIA')!.n).toBe(53);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Tres donas de CaCu: independencia y reparto de solicitudes', () => {
|
||||||
|
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||||
|
const eu7: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0',
|
||||||
|
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'],
|
||||||
|
filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus de seguimiento', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] };
|
||||||
|
const confirmacion: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1',
|
||||||
|
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] };
|
||||||
|
let http: HttpTestingController;
|
||||||
|
let f: ReturnType<typeof TestBed.createComponent<IndicadorCacuDonas>>;
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({ imports: [IndicadorCacuDonas], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||||
|
for (const component of [IndicadorEu7Escenario, IndicadorConfirmacionCitologia])
|
||||||
|
TestBed.overrideComponent(component, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
|
f = TestBed.createComponent(IndicadorCacuDonas);
|
||||||
|
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', eu7);
|
||||||
|
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||||
|
f.componentRef.setInput('confirmacion', confirmacion); f.componentRef.setInput('confirmacionApplied', applied);
|
||||||
|
});
|
||||||
|
afterEach(() => { f.destroy(); http.verify(); });
|
||||||
|
const eu7Requests = () => ({
|
||||||
|
general: http.expectOne(r => r.url.includes('/cacu_eu7/') && !r.params.has('estrato')),
|
||||||
|
escenarios: http.expectOne(r => r.url.includes('/cacu_eu7/') && r.params.get('estrato') === 'estatus_seguimiento'),
|
||||||
|
});
|
||||||
|
const biopsia = () => http.expectOne(r => r.url.includes('/cacu_confirmacion_citologia/'));
|
||||||
|
const eu7Component = () => f.debugElement.query(By.directive(IndicadorEu7Escenario)).componentInstance as IndicadorEu7Escenario;
|
||||||
|
const biopsiaComponent = () => f.debugElement.query(By.directive(IndicadorConfirmacionCitologia)).componentInstance as IndicadorConfirmacionCitologia;
|
||||||
|
it('muestra las distribuciones completas sin controles ni atenuación en la tarjeta', () => {
|
||||||
|
f.detectChanges();
|
||||||
|
const e = eu7Requests(); const b = biopsia();
|
||||||
|
e.general.flush(structuredClone(eu7Fixture.general)); e.escenarios.flush(structuredClone(eu7Fixture.estatus_seguimiento));
|
||||||
|
b.flush(respuesta(['2025-S2']) as Record<string, unknown>); f.detectChanges();
|
||||||
|
expect([...f.nativeElement.querySelectorAll('h3')].map((h: HTMLElement) => h.textContent!.replace(/, 2025-S2$/, ''))).toEqual([
|
||||||
|
'Distribución de resultados citológicos', 'Resultados de VPH por genotipo', 'Resultado de la biopsia']);
|
||||||
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(2);
|
||||||
|
expect(f.nativeElement.querySelectorAll('.legend button, .selection-status, .seleccion, .atenuada')).toHaveLength(0);
|
||||||
|
expect(eu7Component().barras!.activas).toBeNull();
|
||||||
|
expect(biopsiaComponent().barras!.activas).toBeNull();
|
||||||
|
eu7Component().select('grupos', 1); biopsiaComponent().select('categorias', 0); f.detectChanges();
|
||||||
|
expect(eu7Component().selection).toEqual({});
|
||||||
|
expect(biopsiaComponent().selection).toEqual({ grupo: 'ANORMAL' });
|
||||||
|
expect(f.nativeElement.querySelectorAll('.atenuada, .seleccion')).toHaveLength(0);
|
||||||
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales .cabecera').length).toBeGreaterThan(0);
|
||||||
|
expect(f.nativeElement.querySelectorAll('details.published-values')).toHaveLength(2);
|
||||||
|
const vph = f.nativeElement.querySelector('app-indicador-vph-genotipo') as HTMLElement;
|
||||||
|
expect(vph.textContent).toContain('No disponible'); expect(vph.querySelectorAll('button')).toHaveLength(0);
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
// Why: the general filter is said once in the card header; a donut with a different effective period keeps its own line.
|
||||||
|
it('dice el filtro general una vez y conserva una indicación propia solo si el periodo efectivo difiere', () => {
|
||||||
|
f.detectChanges();
|
||||||
|
expect(f.nativeElement.querySelectorAll('.applied-summary')).toHaveLength(0);
|
||||||
|
expect(f.nativeElement.querySelector('.filtro').textContent).toContain('2025-S2');
|
||||||
|
f.componentRef.setInput('confirmacionApplied', { ...applied, selection: { mode: 'explicit', periodos: ['2025-S1'] } });
|
||||||
|
f.detectChanges();
|
||||||
|
expect(f.nativeElement.querySelectorAll('.applied-summary')).toHaveLength(1);
|
||||||
|
expect(f.nativeElement.querySelector('app-indicador-confirmacion-citologia .applied-summary').textContent).toContain('2025-S1');
|
||||||
|
http.expectOne(r => r.url.includes('/cacu_eu7/') && !r.params.has('estrato')).flush({}, { status: 500, statusText: 'x' });
|
||||||
|
http.match(() => true);
|
||||||
|
});
|
||||||
|
// Why: one failing donut must not hide the other two, and its retry repeats only its own request.
|
||||||
|
it('un error en la dona de biopsia no oculta la dona citológica y el reintento solo repite su solicitud', () => {
|
||||||
|
f.detectChanges();
|
||||||
|
const e = eu7Requests(); const b = biopsia();
|
||||||
|
e.general.flush(structuredClone(eu7Fixture.general)); e.escenarios.flush(structuredClone(eu7Fixture.estatus_seguimiento));
|
||||||
|
b.flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
||||||
|
expect(biopsiaComponent().status()).toBe('error');
|
||||||
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||||
|
expect(f.nativeElement.querySelector('app-indicador-eu7-escenario [role=alert]')).toBeNull();
|
||||||
|
expect(f.nativeElement.querySelector('app-indicador-vph-genotipo').textContent).toContain('No disponible');
|
||||||
|
biopsiaComponent().retry(); http.expectNone(r => r.url.includes('/cacu_eu7/'));
|
||||||
|
biopsia().flush(respuesta(['2025-S2']) as Record<string, unknown>); f.detectChanges();
|
||||||
|
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(2);
|
||||||
|
});
|
||||||
|
// Why: the bars and the rates read the same source; a second HTTP request would double the load.
|
||||||
|
it('la dona y las tasas de la confirmación comparten una sola solicitud y conservan selecciones propias', () => {
|
||||||
|
const tasas = TestBed.createComponent(IndicadorConfirmacionCitologia);
|
||||||
|
tasas.componentRef.setInput('dominio', 'cacu'); tasas.componentRef.setInput('indicador', confirmacion);
|
||||||
|
tasas.componentRef.setInput('tema', 'claro'); tasas.componentRef.setInput('applied', applied);
|
||||||
|
f.detectChanges(); tasas.detectChanges();
|
||||||
|
eu7Requests();
|
||||||
|
biopsia().flush(respuesta(['2025-S2']) as Record<string, unknown>); f.detectChanges(); tasas.detectChanges();
|
||||||
|
expect(tasas.componentInstance.status()).toBe('ready');
|
||||||
|
biopsiaComponent().select('grupos', 0); tasas.componentInstance.select('categorias', 0);
|
||||||
|
expect(biopsiaComponent().selection).toEqual({ grupo: 'ANORMAL' });
|
||||||
|
expect(biopsiaComponent().barras!.activas).toBeNull();
|
||||||
|
expect(tasas.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||||
|
http.expectNone(() => true); tasas.destroy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||||
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
|
import { c2Theme } from './indicadores-c2-palette';
|
||||||
|
import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette';
|
||||||
import { percentNumber, shareText } from './indicadores-format';
|
import { percentNumber, shareText } from './indicadores-format';
|
||||||
|
import { ConjuntoBarras } from './indicadores-barras';
|
||||||
|
|
||||||
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
||||||
// a C2 stratified by the last valid cytology of the period; the category is the grade
|
// a C2 stratified by the last valid cytology of the period; the category is the grade
|
||||||
@@ -41,6 +43,7 @@ export interface ModeloConfirmacion {
|
|||||||
}
|
}
|
||||||
export interface SeleccionConfirmacion { grupo: string; categoria?: string; }
|
export interface SeleccionConfirmacion { grupo: string; categoria?: string; }
|
||||||
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||||
|
export interface TotalPublicado { id: string; etiqueta: string; n: number | null; estado: Celda['estado']; }
|
||||||
export class ConfirmacionIncompatible extends Error {}
|
export class ConfirmacionIncompatible extends Error {}
|
||||||
|
|
||||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||||
@@ -69,10 +72,6 @@ function suma(celdas: Celda[]): number | null {
|
|||||||
function estado(celdas: Celda[]): Celda['estado'] {
|
function estado(celdas: Celda[]): Celda['estado'] {
|
||||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||||
}
|
}
|
||||||
function rgba(hex: string, alfa: number): string {
|
|
||||||
const v = parseInt(hex.slice(1), 16);
|
|
||||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
|
||||||
}
|
|
||||||
// grupos_de_categoria publishes a label, or an object with `etiqueta`.
|
// grupos_de_categoria publishes a label, or an object with `etiqueta`.
|
||||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||||
|
|
||||||
@@ -97,20 +96,15 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
|
|||||||
const c = cats[a.id];
|
const c = cats[a.id];
|
||||||
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
||||||
});
|
});
|
||||||
const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
const grados: 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'])))
|
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.');
|
|| 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'] };
|
return { id, etiqueta: c['etiqueta'], color: cacuClinicalColor(id, c['color'] as string | null), 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 bases = basesPorGrupo(conColor.map(g => g.grupo));
|
|
||||||
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
||||||
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
|
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
|
||||||
const propios = grados.filter(g => g.grupo === id);
|
const propios = grados.filter(g => g.grupo === id);
|
||||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: bases.get(id) ?? COLOR_RESPALDO,
|
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: cacuGroupColor(id) ?? COLOR_RESPALDO,
|
||||||
grados: propios.map(g => g.id) };
|
grados: propios.map(g => g.id) };
|
||||||
});
|
});
|
||||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||||
@@ -159,6 +153,34 @@ export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion)
|
|||||||
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||||
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta;
|
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Women per grade (what the donut draws) and per category kept outside it, summed over the cytology rows.
|
||||||
|
* An unknown or suppressed cell makes its total unknown, never zero.
|
||||||
|
*/
|
||||||
|
export function totalesPublicados(m: ModeloConfirmacion): { grados: TotalPublicado[]; aparte: TotalPublicado[] } {
|
||||||
|
return {
|
||||||
|
grados: m.grados.map(g => {
|
||||||
|
const n = m.totales[g.id] ?? null;
|
||||||
|
return { id: g.id, etiqueta: g.etiqueta, n, estado: n !== null ? 'Publicado' as const : estado(m.filas.map(f => ({ n: f.den, estado: f.estado }))) };
|
||||||
|
}),
|
||||||
|
aparte: m.aparte.map(a => {
|
||||||
|
const celdas = m.filas.map(f => f.aparte[a.id]), n = suma(celdas);
|
||||||
|
return { id: a.id, etiqueta: a.etiqueta, n, estado: n !== null ? 'Publicado' as const : estado(celdas) };
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/** The biopsy bars: the two groups of grades as headers, the grades as bars; what has no biopsy or no grade stays outside. */
|
||||||
|
export function barrasBiopsia(m: ModeloConfirmacion, sel: SeleccionConfirmacion): ConjuntoBarras {
|
||||||
|
const t = totalesPublicados(m);
|
||||||
|
return {
|
||||||
|
grupos: m.grupos.map(g => {
|
||||||
|
const filas = g.grados.map(id => { const grado = m.grados.find(x => x.id === id)!, total = t.grados.find(x => x.id === id)!;
|
||||||
|
return { id, etiqueta: grado.etiqueta, n: total.n, estado: total.estado, color: grado.color }; });
|
||||||
|
return { id: g.id, etiqueta: g.etiqueta, color: g.color, subtotal: filas.some(f => f.n === null) ? null : filas.reduce((s, f) => s + f.n!, 0), filas };
|
||||||
|
}),
|
||||||
|
den: m.conBiopsia, unidad: 'mujeres con biopsia', activas: new Set(seleccionados(m, sel)),
|
||||||
|
};
|
||||||
|
}
|
||||||
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
|
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
|
||||||
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||||
if (traza === 'centro') return seleccionBase(m);
|
if (traza === 'centro') return seleccionBase(m);
|
||||||
@@ -204,7 +226,7 @@ export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, t
|
|||||||
const y = valores.map(t => t.fila.etiqueta);
|
const y = valores.map(t => t.fila.etiqueta);
|
||||||
return { data: [{
|
return { data: [{
|
||||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||||
marker: { size: 12, color }, cliponaxis: false,
|
marker: { size: 12, color, line: { color: p.text, width: 1 } }, cliponaxis: false,
|
||||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
||||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||||
@@ -228,18 +250,19 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
|||||||
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
|
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
|
||||||
const exterior = m.grados.map(g => m.totales[g.id]!);
|
const exterior = m.grados.map(g => m.totales[g.id]!);
|
||||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia, %{customdata[1]}<extra></extra>' };
|
// A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
|
||||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
|
||||||
|
const hoverText = (values: number[]) => values.map(n => `${miles(n)} mujeres con biopsia, ${shareText(n, total)}`);
|
||||||
return { data: [
|
return { data: [
|
||||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
|
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
|
||||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(interior),
|
||||||
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
marker: { colors: m.grupos.map(g => cacuRgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .45)), line: { color: p.background, width: 2 } } },
|
||||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||||
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior),
|
labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(exterior),
|
||||||
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
marker: { colors: m.grados.map(g => cacuRgba(g.color, activos.has(g.id) ? 1 : .45)), line: { color: p.background, width: 2 } } },
|
||||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||||
config: { displayModeBar: false } };
|
config: { displayModeBar: false } };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -213,11 +213,11 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
|||||||
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
|
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
|
||||||
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
|
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
|
||||||
expect(h3).toEqual([
|
expect(h3).toEqual([
|
||||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, 2025-S2',
|
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en 2025-S2',
|
||||||
'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 2025-S2',
|
'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en 2025-S2',
|
||||||
]);
|
]);
|
||||||
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
|
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
|
||||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, por paciente y por mastografía');
|
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6, por paciente y por mastografía');
|
||||||
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||||
expect(graficas).toHaveLength(2);
|
expect(graficas).toHaveLength(2);
|
||||||
expect(graficas.map(g => g.label)).toEqual(h3);
|
expect(graficas.map(g => g.label)).toEqual(h3);
|
||||||
|
|||||||
@@ -19,7 +19,9 @@ export class IndicadoresDefinitions {
|
|||||||
@Input() loading = false;
|
@Input() loading = false;
|
||||||
@Input() error = '';
|
@Input() error = '';
|
||||||
readonly retry = output<void>();
|
readonly retry = output<void>();
|
||||||
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
|
readonly domainNames: Record<Dominio, string> = {
|
||||||
|
tea: 'trastorno del espectro autista', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama',
|
||||||
|
};
|
||||||
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
|
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
|
||||||
readonly figureDisplayName = figureDisplayName;
|
readonly figureDisplayName = figureDisplayName;
|
||||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import fixture from './fixtures/eu7-c2-ejemplos.json';
|
|||||||
import { IndicadorDatos } from './indicadores.models';
|
import { IndicadorDatos } from './indicadores.models';
|
||||||
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
|
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
|
||||||
import { percentNumber } from './indicadores-format';
|
import { percentNumber } from './indicadores-format';
|
||||||
|
import { recolorFigure } from './indicadores-c2-palette';
|
||||||
|
|
||||||
function eu7Datos() {
|
function eu7Datos() {
|
||||||
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
|
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
|
||||||
@@ -19,6 +20,30 @@ describe('EU7 modelo de presentación del entregable', () => {
|
|||||||
expect(f.data[2]['values']).toEqual([798, 62, 46, 17, 19, 4]);
|
expect(f.data[2]['values']).toEqual([798, 62, 46, 17, 19, 4]);
|
||||||
expect(data).toEqual(original);
|
expect(data).toEqual(original);
|
||||||
});
|
});
|
||||||
|
it.each(['claro', 'oscuro'] as const)('conserva colores lisos en dona y barras hasta Plotly, tema %s', tema => {
|
||||||
|
const m = model();
|
||||||
|
const expected = {
|
||||||
|
NORMAL: '#438B53', 'ASC-US': '#2879BD', LIEBG: '#AD8F20', 'ASC-H': '#7959B8', LIEAG: '#D14D78', CIS: '#AE4050',
|
||||||
|
};
|
||||||
|
expect(Object.fromEntries(m.categorias.map(c => [c.id, c.color]))).toEqual(expected);
|
||||||
|
for (const payload of [data.general, data.escenarios]) {
|
||||||
|
payload['categorias'] = Object.fromEntries(Object.entries(payload['categorias'] as object).reverse());
|
||||||
|
payload.filas.reverse();
|
||||||
|
for (const row of payload.filas) if (typeof row['orden'] === 'number') row['orden'] = 10 - row['orden'];
|
||||||
|
}
|
||||||
|
expect(model().categorias.map(c => c.id)).not.toEqual(m.categorias.map(c => c.id));
|
||||||
|
expect(Object.fromEntries(model().categorias.map(c => [c.id, c.color]))).toEqual(expected);
|
||||||
|
const pie = dona(m, {}, tema), bar = barras(m, {}, tema);
|
||||||
|
expect(recolorFigure(pie)).toBe(pie); expect(recolorFigure(bar)).toBe(bar);
|
||||||
|
expect(pie.data[2]['marker']).not.toHaveProperty('pattern');
|
||||||
|
const i = m.categorias.findIndex(c => c.id === 'LIEBG');
|
||||||
|
expect(pie.data[2]['marker']).toMatchObject({ colors: expect.arrayContaining(['rgba(173,143,32,1)']) });
|
||||||
|
expect(bar.data[i]).toMatchObject({ uid: 'LIEBG', marker: { color: '#AD8F20' } });
|
||||||
|
expect(bar.data[i]['marker']).not.toHaveProperty('pattern');
|
||||||
|
const selected = dona(m, { categoria: 'LIEBG' }, tema);
|
||||||
|
expect(recolorFigure(selected)).toBe(selected);
|
||||||
|
expect(selected.data[2]['marker']).toMatchObject({ colors: expect.arrayContaining(['rgba(121,89,184,0.45)']) });
|
||||||
|
});
|
||||||
it('TOTAL → Anormal → LIEAG → grupo → TOTAL y toggles', () => {
|
it('TOTAL → Anormal → LIEAG → grupo → TOTAL y toggles', () => {
|
||||||
const m = model(); let s: Seleccion = {};
|
const m = model(); let s: Seleccion = {};
|
||||||
const g = m.grupos.findIndex(g => g.id === 'ANORMAL'), c = m.categorias.findIndex(c => c.id === 'LIEAG');
|
const g = m.grupos.findIndex(g => g.id === 'ANORMAL'), c = m.categorias.findIndex(c => c.id === 'LIEAG');
|
||||||
@@ -29,26 +54,33 @@ describe('EU7 modelo de presentación del entregable', () => {
|
|||||||
s = clic(m, s, 'centro', 0); expect(s).toEqual({});
|
s = clic(m, s, 'centro', 0); expect(s).toEqual({});
|
||||||
expect(clic(m, { grupo: 'ANORMAL' }, 'grupos', g)).toEqual({});
|
expect(clic(m, { grupo: 'ANORMAL' }, 'grupos', g)).toEqual({});
|
||||||
expect(clic(m, { categoria: 'LIEAG' }, 'centro', 0)).toEqual({});
|
expect(clic(m, { categoria: 'LIEAG' }, 'centro', 0)).toEqual({});
|
||||||
expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: undefined, categoria: 'LIEAG' });
|
expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' });
|
||||||
expect(clic(m, {}, 'otra', c)).toEqual({});
|
expect(clic(m, {}, 'otra', c)).toEqual({});
|
||||||
expect(clic(m, {}, 'grupos', -1)).toEqual({});
|
expect(clic(m, {}, 'grupos', -1)).toEqual({});
|
||||||
expect(clic(m, { grupo: 'ANORMAL' }, 'categorias', 0)).toEqual({ grupo: 'ANORMAL' });
|
expect(clic(m, { grupo: 'ANORMAL' }, 'categorias', 0)).toEqual({ grupo: 'ANORMAL' });
|
||||||
});
|
});
|
||||||
it('cada escenario suma 100 % en TOTAL y Anormal conserva 5.0, 24.3, 21.7, 7.8 %', () => {
|
it('barras agrupadas: conteos absolutos por categoría y escenario, sin apilar ni normalizar', () => {
|
||||||
const m = model(), f = barras(m, {}, 'claro');
|
const m = model(), f = barras(m, {}, 'claro');
|
||||||
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBeCloseTo(100, 8));
|
expect(f.layout['barmode']).toBe('group');
|
||||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(m.escenarios.map(s => `${s.den}`));
|
expect(f.data.map(t => t['uid'])).toEqual(m.categorias.map(c => c.id));
|
||||||
|
f.data.forEach((t, i) => expect(t['x']).toEqual(m.escenarios.map(s => s.celdas[m.categorias[i].id].n)));
|
||||||
|
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBe(s.den));
|
||||||
|
const labels = (f.layout['yaxis'] as { categoryarray: string[] }).categoryarray;
|
||||||
|
m.escenarios.forEach((s, i) => { expect(labels[i]).toContain(s.etiqueta); expect(labels[i]).not.toContain('Total válido'); });
|
||||||
|
expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Número de pacientes');
|
||||||
|
const todos = f.data.flatMap(t => t['x'] as number[]);
|
||||||
|
expect((f.layout['xaxis'] as { range: number[] }).range[0]).toBe(0);
|
||||||
|
expect((f.layout['xaxis'] as { range: number[] }).range[1]).toBeGreaterThan(Math.max(...todos));
|
||||||
const selected = barras(m, { grupo: 'ANORMAL' }, 'claro');
|
const selected = barras(m, { grupo: 'ANORMAL' }, 'claro');
|
||||||
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
|
expect(selected.data.map(t => t['uid'])).toEqual(m.categorias.filter(c => c.grupo === 'ANORMAL').map(c => c.id));
|
||||||
.toEqual(['5.0', '24.3', '21.7', '7.8']);
|
const anormales = m.categorias.filter(c => c.grupo === 'ANORMAL');
|
||||||
|
m.escenarios.forEach((s, i) => expect(selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBe(anormales.reduce((n, c) => n + s.celdas[c.id].n!, 0)));
|
||||||
|
// The selected scale is common and fits the selected counts, not the whole distribution.
|
||||||
|
expect((selected.layout['xaxis'] as { range: number[] }).range[1]).toBeLessThan((f.layout['xaxis'] as { range: number[] }).range[1]);
|
||||||
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
|
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||||
// Same traces in every selection (animation identity); unselected ones are zero-width.
|
expect(category.data).toHaveLength(1);
|
||||||
expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid']));
|
expect(category.data[0]['x']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n));
|
||||||
const lieag = category.data.find(t => t['uid'] === 'LIEAG')!;
|
expect(category.data[0]['text']).toEqual(m.escenarios.map(s => String(s.celdas['LIEAG'].n)));
|
||||||
expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
|
|
||||||
expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true);
|
|
||||||
expect((category.layout['annotations'] as { text: string }[]).map(a => a.text))
|
|
||||||
.toEqual(m.escenarios.map(s => `<b>${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} %</b> (${s.celdas['LIEAG'].n}/${s.den})`));
|
|
||||||
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
|
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
|
||||||
});
|
});
|
||||||
it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => {
|
it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => {
|
||||||
@@ -71,16 +103,19 @@ describe('EU7 modelo de presentación del entregable', () => {
|
|||||||
data.general['reportes'] = [{ periodo, report_id: 1 }]; data.escenarios['reportes'] = [{ periodo, report_id: 2 }];
|
data.general['reportes'] = [{ periodo, report_id: 1 }]; data.escenarios['reportes'] = [{ periodo, report_id: 2 }];
|
||||||
expect(model).toThrow(/reportes distintos/);
|
expect(model).toThrow(/reportes distintos/);
|
||||||
});
|
});
|
||||||
it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: todos los puntos son null y no hay denominador inventado', kind => {
|
it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: el estado se dice, nunca se dibuja un cero ni un total inventado', kind => {
|
||||||
const row = data.escenarios.filas.find(f => f['estrato'] === 'VIGILANCIA' && f['categoria'] === (kind === 'sin dato suprimido' ? 'SIN_DATO' : 'LIEAG'))!;
|
const row = data.escenarios.filas.find(f => f['estrato'] === 'VIGILANCIA' && f['categoria'] === (kind === 'sin dato suprimido' ? 'SIN_DATO' : 'LIEAG'))!;
|
||||||
if (kind === 'sin fila') data.escenarios.filas = data.escenarios.filas.filter(f => f !== row);
|
if (kind === 'sin fila') data.escenarios.filas = data.escenarios.filas.filter(f => f !== row);
|
||||||
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
|
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
|
||||||
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
|
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
|
||||||
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
|
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||||
expect(m.escenarios[0].den).toBeNull(); expect(f.data.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
|
expect(m.escenarios[0].den).toBeNull();
|
||||||
expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true);
|
const t = f.data[0], celda = m.escenarios[0].celdas['LIEAG'];
|
||||||
expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t =>
|
expect(f.data).toHaveLength(1);
|
||||||
t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true);
|
expect(t['x']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n ?? 0));
|
||||||
|
expect(t['text']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n === null ? s.celdas['LIEAG'].estado : String(s.celdas['LIEAG'].n)));
|
||||||
|
if (celda.n === null) expect((t['hovertext'] as string[])[0]).toContain('no es cero');
|
||||||
|
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray[0]).toMatch(/Total (suprimido|no disponible)/);
|
||||||
expect(JSON.stringify(f)).not.toContain('123456');
|
expect(JSON.stringify(f)).not.toContain('123456');
|
||||||
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
|
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
|
||||||
});
|
});
|
||||||
@@ -96,30 +131,30 @@ describe('EU7 modelo de presentación del entregable', () => {
|
|||||||
const m = model(); expect(m.escenarios.map(s => s.id)).not.toContain('INFO_INSUFICIENTE');
|
const m = model(); expect(m.escenarios.map(s => s.id)).not.toContain('INFO_INSUFICIENTE');
|
||||||
expect(barras(m, {}, 'claro').data[0]['x']).toHaveLength(3);
|
expect(barras(m, {}, 'claro').data[0]['x']).toHaveLength(3);
|
||||||
});
|
});
|
||||||
it('escenario vacío y periodo de ceros no producen porcentajes 0/0', () => {
|
it('escenario vacío y periodo de ceros: ceros publicados, sin porcentajes ni totales inventados', () => {
|
||||||
data.general.filas.forEach(f => f['n'] = 0); data.escenarios.filas.forEach(f => f['n'] = 0);
|
data.general.filas.forEach(f => f['n'] = 0); data.escenarios.filas.forEach(f => f['n'] = 0);
|
||||||
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
|
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
|
||||||
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
|
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
|
||||||
expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
|
for (const sel of [{}, { categoria: 'LIEAG' }]) {
|
||||||
expect(barras(m, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
|
const f = barras(m, sel, 'claro');
|
||||||
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
|
expect(f.data.every(t => (t['x'] as number[]).every(v => v === 0) && (t['text'] as string[]).every(x => x === '0'))).toBe(true);
|
||||||
|
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray.every(l => l.includes('Sin pacientes con resultado'))).toBe(true);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
|
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
|
||||||
data.general.filas = []; data.escenarios.filas = []; data.escenarios['totales_estrato'] = [];
|
data.general.filas = []; data.escenarios.filas = []; data.escenarios['totales_estrato'] = [];
|
||||||
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
|
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
|
||||||
expect(m.celdas['NORMAL'].n).toBeNull();
|
expect(m.celdas['NORMAL'].n).toBeNull();
|
||||||
});
|
});
|
||||||
it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => {
|
it('selección jerárquica y Volver conservan orden, denominadores y datos fuente; las barras solo eligen categorías', () => {
|
||||||
const original = structuredClone(data), m = model(), snapshot = structuredClone(m);
|
const original = structuredClone(data), m = model(), snapshot = structuredClone(m);
|
||||||
const ids = m.categorias.map(c => c.id);
|
const esperadas = (s: Seleccion) => m.categorias.filter(c => s.categoria ? c.id === s.categoria : s.grupo ? c.grupo === s.grupo : true).map(c => c.id);
|
||||||
for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) {
|
for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, { grupo: 'NO_ANORMAL' }, {}]) {
|
||||||
const f = barras(m, selection, 'claro');
|
const f = barras(m, selection, 'claro');
|
||||||
expect(f.data.map(t => t['uid'])).toEqual(ids);
|
expect(f.data.map(t => t['uid'])).toEqual(esperadas(selection));
|
||||||
expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length);
|
f.data.forEach(t => {
|
||||||
f.data.forEach((t, i) => {
|
expect(t['x']).toEqual(m.escenarios.map(s => s.celdas[t['uid'] as string].n));
|
||||||
if (t['hoverinfo'] === 'skip') {
|
expect(t['marker']).toMatchObject({ color: m.categorias.find(c => c.id === t['uid'])!.color });
|
||||||
expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => ''));
|
|
||||||
} else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i])));
|
|
||||||
});
|
});
|
||||||
dona(m, selection, 'claro');
|
dona(m, selection, 'claro');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||||
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
|
import { c2Theme } from './indicadores-c2-palette';
|
||||||
|
import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette';
|
||||||
import { percentNumber, shareText } from './indicadores-format';
|
import { percentNumber, shareText } from './indicadores-format';
|
||||||
|
import { ConjuntoBarras } from './indicadores-barras';
|
||||||
|
|
||||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||||
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
|
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
|
||||||
@@ -39,10 +41,6 @@ function estado(celdas: Celda[]): Escenario['estado'] {
|
|||||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido'
|
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido'
|
||||||
: celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
: celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||||
}
|
}
|
||||||
function rgba(hex: string, alfa: number): string {
|
|
||||||
const v = parseInt(hex.slice(1), 16);
|
|
||||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
|
||||||
}
|
|
||||||
function catalogo(data: IndicadorDatos): Categoria[] {
|
function catalogo(data: IndicadorDatos): Categoria[] {
|
||||||
const cats = data['categorias'], grupos = data['grupos_de_categoria'];
|
const cats = data['categorias'], grupos = data['grupos_de_categoria'];
|
||||||
if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.');
|
if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.');
|
||||||
@@ -119,17 +117,20 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
|||||||
return active[0];
|
return active[0];
|
||||||
};
|
};
|
||||||
const rg = reporte(general), re = reporte(porEscenario);
|
const rg = reporte(general), re = reporte(porEscenario);
|
||||||
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha']
|
// With a report id on both sides, the report is identified by it and its cut-off and versions: a FHIR report's
|
||||||
.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
// `date` (`generado_en`) is when the answer was served, so the same stored report served twice differs only there.
|
||||||
|
// Without ids, the generation time is still part of the provenance.
|
||||||
|
const identificados = rg?.['report_id'] != null && re?.['report_id'] != null;
|
||||||
|
const procedencia = ['report_id', 'fecha_corte', ...(identificados ? [] : ['generado_en']), 'kit_version', 'toml_sha', 'parametros_sha'];
|
||||||
|
if (!!rg !== !!re || (rg && re && procedencia.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
||||||
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
|
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
|
// 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.
|
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||||
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
||||||
const claves = baseCategorias.map(c => c.grupo);
|
const categorias = baseCategorias.map(c => ({ ...c, color: cacuClinicalColor(c.id, c.color) }));
|
||||||
const bases = basesPorGrupo(claves);
|
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({
|
||||||
const colores = paintByGroup(claves);
|
id, etiqueta: nombres[id], color: cacuGroupColor(id) ?? '#8A9199',
|
||||||
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
|
}));
|
||||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], color: bases.get(id)! }));
|
|
||||||
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
|
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
|
||||||
const totals = porEscenario['totales_estrato'];
|
const totals = porEscenario['totales_estrato'];
|
||||||
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
||||||
@@ -145,21 +146,33 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
|||||||
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
|
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
|
||||||
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
|
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
|
||||||
});
|
});
|
||||||
|
// A period without patients may publish its general distribution as explicit zeros (FHIR's complete report) and no
|
||||||
|
// scenario at all: that's an empty period, not a mismatch. A null or positive count without scenarios still is one.
|
||||||
|
const generalEnCeros = g.size > 0 && [...g.values()].every(row => row['n'] === 0);
|
||||||
// Compare only fully published sums. Never derive a hidden value by subtraction.
|
// Compare only fully published sums. Never derive a hidden value by subtraction.
|
||||||
if (escenarios.length) {
|
if (escenarios.length) {
|
||||||
for (const c of cats) {
|
for (const c of cats) {
|
||||||
const total = suma(escenarios.map(s => s.celdas[c.id]));
|
const total = suma(escenarios.map(s => s.celdas[c.id]));
|
||||||
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
|
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
|
||||||
}
|
}
|
||||||
} else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.');
|
} else if (g.size && !generalEnCeros) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||||
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
|
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
|
||||||
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
|
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
|
||||||
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
|
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
|
||||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size,
|
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size || (generalEnCeros && !escenarios.length),
|
||||||
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
|
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
|
||||||
}
|
}
|
||||||
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
|
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
|
||||||
const nGrupo = (m: Modelo, grupo: string) => suma(hijas(m, grupo).map(c => m.celdas[c.id]));
|
const nGrupo = (m: Modelo, grupo: string) => suma(hijas(m, grupo).map(c => m.celdas[c.id]));
|
||||||
|
/** The cytology bars: the groups of the inner ring as headers, the categories of the outer ring as bars; «Sin dato» stays outside. */
|
||||||
|
export function barrasCitologia(m: Modelo, sel: Seleccion): ConjuntoBarras {
|
||||||
|
return {
|
||||||
|
grupos: m.grupos.map(g => ({ id: g.id, etiqueta: g.etiqueta, color: g.color, subtotal: nGrupo(m, g.id),
|
||||||
|
filas: hijas(m, g.id).map(c => ({ id: c.id, etiqueta: c.etiqueta, n: m.celdas[c.id].n, estado: m.celdas[c.id].estado, color: c.color })) })),
|
||||||
|
den: m.total, unidad: 'pacientes con resultado',
|
||||||
|
activas: sel.categoria ? new Set([sel.categoria]) : sel.grupo ? new Set(hijas(m, sel.grupo).map(c => c.id)) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
export function seleccionEtiqueta(m: Modelo, sel: Seleccion): string {
|
export function seleccionEtiqueta(m: Modelo, sel: Seleccion): string {
|
||||||
return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta
|
return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta
|
||||||
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'TOTAL';
|
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'TOTAL';
|
||||||
@@ -174,7 +187,7 @@ export function clic(m: Modelo, sel: Seleccion, traza: string, indice: number):
|
|||||||
if (traza !== 'categorias') return sel;
|
if (traza !== 'categorias') return sel;
|
||||||
const c = m.categorias[indice];
|
const c = m.categorias[indice];
|
||||||
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
|
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
|
||||||
return sel.categoria === c.id ? { grupo: sel.grupo } : { grupo: sel.grupo, categoria: c.id };
|
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||||
}
|
}
|
||||||
export function porcentaje(s: Escenario, categoria: string): number | null {
|
export function porcentaje(s: Escenario, categoria: string): number | null {
|
||||||
const n = s.celdas[categoria]?.n;
|
const n = s.celdas[categoria]?.n;
|
||||||
@@ -186,6 +199,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
|||||||
const p = c2Theme(tema);
|
const p = c2Theme(tema);
|
||||||
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0);
|
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0);
|
||||||
const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0);
|
const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0);
|
||||||
|
const alpha = (id: string) => sel.categoria && id !== sel.categoria ? .45 : 1;
|
||||||
const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total;
|
const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total;
|
||||||
const rotulos = (values: number[], labels: string[], pct: boolean) => {
|
const rotulos = (values: number[], labels: string[], pct: boolean) => {
|
||||||
const total = values.reduce((s, n) => s + n, 0);
|
const total = values.reduce((s, n) => s + n, 0);
|
||||||
@@ -193,53 +207,53 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
|||||||
};
|
};
|
||||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
|
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
|
||||||
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
|
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
|
||||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % del total con resultado<extra></extra>' };
|
// A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
|
||||||
const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]);
|
const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
|
||||||
|
const hoverText = (values: number[]) => values.map(n => `${miles(n)} pacientes, ${percentNumber(100 * n / m.total!)} % del total con resultado`);
|
||||||
return { data: [
|
return { data: [
|
||||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
||||||
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
|
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
|
||||||
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
|
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
|
||||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||||
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||||
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
|
hovertext: hoverText(interior),
|
||||||
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
marker: { colors: m.grupos.map(g => cacuRgba(g.color, sel.categoria ? .45 : 1)), line: { color: p.background, width: 2 } } },
|
||||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||||
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
|
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
|
||||||
textfont: { size: 11 }, customdata: custom(exterior),
|
textfont: { size: 11 }, hovertext: hoverText(exterior),
|
||||||
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
marker: { colors: m.categorias.map(c => cacuRgba(c.color, alpha(c.id))), line: { color: p.background, width: 2 } } },
|
||||||
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||||
config: { displayModeBar: false } };
|
config: { displayModeBar: false } };
|
||||||
}
|
}
|
||||||
/** Selection never changes the original denominator or renormalizes a subset. */
|
/** Absolute counts, one independent bar per category inside each clinical scenario. The selection only chooses which
|
||||||
|
* categories are drawn; it never renormalizes anything and every scenario shares one horizontal scale. */
|
||||||
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||||
const p = c2Theme(tema);
|
const p = c2Theme(tema);
|
||||||
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
|
const visibles = m.categorias.filter(c => sel.categoria ? c.id === sel.categoria : sel.grupo ? c.grupo === sel.grupo : true);
|
||||||
const y = m.escenarios.map(s => escapar(s.etiqueta));
|
// The valid total of each scenario travels with its name; an unknown total is said, never drawn as zero.
|
||||||
const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0));
|
const y = m.escenarios.map(s => `${escapar(s.etiqueta)}${s.den === null ? `<br>Total ${s.estado === 'Suprimido' ? 'suprimido' : 'no disponible'}`
|
||||||
// Every category keeps its trace (same uid and count) so a selection animates;
|
: s.den === 0 ? '<br>Sin pacientes con resultado' : ''}`);
|
||||||
// an unselected category is a zero-width bar without text or hover, never data.
|
const traces = visibles.map(c => {
|
||||||
return { data: m.categorias.map(c => {
|
const celdas = m.escenarios.map(s => s.celdas[c.id]);
|
||||||
const visible = visibles.includes(c.id);
|
// An unknown cell draws no bar (width 0) and says its state instead of a number; a published zero says «0».
|
||||||
const x = m.escenarios.map(s => {
|
const x = celdas.map(v => v.n ?? 0);
|
||||||
const value = porcentaje(s, c.id);
|
|
||||||
return value === null ? null : visible ? value : 0;
|
|
||||||
});
|
|
||||||
return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x,
|
return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x,
|
||||||
marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } },
|
marker: { color: c.color, line: { color: p.background, width: 1 } },
|
||||||
text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
|
text: celdas.map(v => v.n === null ? v.estado : miles(v.n)), textposition: 'outside', cliponaxis: false,
|
||||||
customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [],
|
textfont: { size: 12, color: p.text },
|
||||||
...(visible ? { hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` }
|
hovertext: celdas.map((v, i) => `${escapar(m.escenarios[i].etiqueta)}<br>${escapar(c.etiqueta)}: ${v.n === null
|
||||||
: { hoverinfo: 'skip' }) };
|
? `${v.estado} (no es cero)` : `${miles(v.n)} ${v.n === 1 ? 'paciente' : 'pacientes'}`}`),
|
||||||
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
|
hovertemplate: '%{hovertext}<extra></extra>' };
|
||||||
|
});
|
||||||
|
const mayor = Math.max(1, ...traces.flatMap(t => t.x));
|
||||||
|
return { data: traces, layout: { barmode: 'group', bargap: .45, bargroupgap: .08, autosize: true,
|
||||||
|
height: Math.max(360, 110 + m.escenarios.length * (visibles.length * 22 + 36)),
|
||||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||||
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
|
margin: { t: 16, l: 150, r: 24, b: 64 }, showlegend: false,
|
||||||
|
// A thin rule between scenarios so each group reads as one unit.
|
||||||
|
shapes: m.escenarios.slice(1).map((_, i) => ({ type: 'line', xref: 'paper', x0: 0, x1: 1, yref: 'y', y0: i + .5, y1: i + .5, line: { color: p.outline, width: 1, dash: 'dot' } })),
|
||||||
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
|
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
|
||||||
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
|
xaxis: { title: { text: 'Número de pacientes' }, tickformat: ',d', gridcolor: p.grid, zeroline: false,
|
||||||
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112],
|
range: [0, mayor * 1.2], ...(mayor <= 8 ? { dtick: 1 } : {}) },
|
||||||
tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] },
|
|
||||||
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
|
|
||||||
font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado'
|
|
||||||
: sel.grupo || sel.categoria ? `<b>${percentNumber(sumas[i]!)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
|
|
||||||
: miles(s.den) })),
|
|
||||||
}, config: { displayModeBar: false } };
|
}, config: { displayModeBar: false } };
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -2,12 +2,14 @@
|
|||||||
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
|
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
|
||||||
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
|
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
|
||||||
// the shapes the page reads and passed through the same checks.
|
// the shapes the page reads and passed through the same checks.
|
||||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
|
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database; `conModelo`
|
||||||
|
// below adds to its patient summary the age at the EEG, a metric's age-norm curve and the ADOS-2 association model,
|
||||||
|
// in the shape `webapi/fhir/tea.py` emits them.
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom } from 'rxjs';
|
||||||
import { Bundle, resources } from './fhir';
|
import { Bundle, Resource, resources } from './fhir';
|
||||||
import {
|
import {
|
||||||
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
|
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
|
||||||
periodosDesde, Report,
|
periodosDesde, Report,
|
||||||
@@ -15,11 +17,56 @@ import {
|
|||||||
import * as fx from './indicadores-fhir.fixtures';
|
import * as fx from './indicadores-fhir.fixtures';
|
||||||
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
|
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||||
import { c2Figure } from './indicadores-c2-adapter';
|
import { c2Figure } from './indicadores-c2-adapter';
|
||||||
|
import { historicoFigura } from './indicadores-historico-figures';
|
||||||
import { datosValidos } from './indicadores.service';
|
import { datosValidos } from './indicadores.service';
|
||||||
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
||||||
import { IndicadorDatos } from './indicadores.models';
|
import { IndicadorDatos } from './indicadores.models';
|
||||||
|
import vistaPreviaBundle from './fixtures/tea_vista_previa_bundle.json';
|
||||||
|
|
||||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||||
|
|
||||||
|
const SD = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||||
|
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||||
|
const CURVA = `${SD}/curva-referencia`;
|
||||||
|
const curva = {
|
||||||
|
url: CURVA, extension: [
|
||||||
|
{ url: `${CURVA}/fuente`, valueString: 'tea-ritmo_posterior/3' }, { url: `${CURVA}/estado`, valueString: 'validada' },
|
||||||
|
...[12, 24, 36].map(v => ({ url: `${CURVA}/edad-meses`, valueDecimal: v })),
|
||||||
|
...([['p5', [4, 4.5, 5]], ['p25', [5, 5.5, 6]], ['mediana', [5.5, 6, 6.5]], ['p75', [6, 6.5, 7]], ['p95', [6.5, 7, 7.5]]] as [string, number[]][])
|
||||||
|
.flatMap(([p, vs]) => vs.map(v => ({ url: `${CURVA}/${p}`, valueDecimal: v }))),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const prediccion = (zona: string, z: number | null) => ({
|
||||||
|
outcome: { coding: [{ system: `${CS}/tea-ados2-resultado`, code: 'ados2_item_11', display: 'Mostrar' }] },
|
||||||
|
probabilityDecimal: 0.41,
|
||||||
|
extension: [
|
||||||
|
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
|
||||||
|
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
|
||||||
|
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=1' },
|
||||||
|
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
|
||||||
|
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
|
||||||
|
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
// The fixture's patient summary with what the WebApi adds when the analysis and the association model have data.
|
||||||
|
function conModelo(): Bundle {
|
||||||
|
const bundle = structuredClone(fx.resumenPaciente) as Bundle;
|
||||||
|
for (const r of resources(bundle)) {
|
||||||
|
if (r.resourceType === 'DiagnosticReport') r.extension = [...(r.extension ?? []), { url: `${SD}/edad-meses`, valueDecimal: 23.6 }];
|
||||||
|
const codigo = (r['code'] as { coding?: { code?: string }[] } | undefined)?.coding?.[0]?.code;
|
||||||
|
if (r.resourceType === 'Observation' && codigo === 'ritmo_posterior' && !r.id?.startsWith('electrodos-'))
|
||||||
|
r.extension = [...(r.extension ?? []), curva];
|
||||||
|
}
|
||||||
|
const riesgo: Resource = {
|
||||||
|
resourceType: 'RiskAssessment', id: 'relacion-ados2-P-4A59E9D8B4', status: 'final',
|
||||||
|
meta: { tag: resources(bundle)[0].meta?.tag },
|
||||||
|
extension: [{ url: `${SD}/modelo-version`, valueString: '1.0.0' }, { url: `${SD}/modelo-validado`, valueBoolean: false },
|
||||||
|
{ url: `${SD}/modelo-nivel`, valueString: 'item' }, { url: `${SD}/modelo-n-cohorte`, valueInteger: 40 }],
|
||||||
|
prediction: [prediccion('occipital', -2.6), prediccion('parietal', null)],
|
||||||
|
};
|
||||||
|
bundle.entry = [...(bundle.entry ?? []), { resource: riesgo }];
|
||||||
|
return bundle;
|
||||||
|
}
|
||||||
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
|
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
|
||||||
|
|
||||||
describe('Indicadores sobre FHIR', () => {
|
describe('Indicadores sobre FHIR', () => {
|
||||||
@@ -85,6 +132,42 @@ describe('Indicadores sobre FHIR', () => {
|
|||||||
expect(figure.status).toBe('supported');
|
expect(figure.status).toBe('supported');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('la calidad del EEG muestra «No aceptable» en lugar de «Malo» sin cambiar los códigos de la categoría', () => {
|
||||||
|
// Pins down: the caption is a presentation choice; the rows, the category catalog and the Measure keep MALO, and no
|
||||||
|
// category is invented for «aceptable». Fails if the caption leaks into the codes, if «Malo» is drawn again or if a
|
||||||
|
// fourth category appears.
|
||||||
|
const datos = datosDeReportes(measure('M29-calidad-eeg'), reports(fx.m29Semestres), 'semestre');
|
||||||
|
const s1 = datos.filas.filter(f => f['periodo'] === '2025-S1');
|
||||||
|
expect(s1.map(f => f['categoria'])).toEqual(['BUENO', 'MALO', 'SIN_ANALIZAR']);
|
||||||
|
const categorias = datos['categorias'] as Record<string, { etiqueta: string }>;
|
||||||
|
expect(Object.entries(categorias).map(([codigo, c]) => [codigo, c.etiqueta]))
|
||||||
|
.toEqual([['BUENO', 'Bueno'], ['MALO', 'No aceptable'], ['SIN_ANALIZAR', 'Sin analizar']]);
|
||||||
|
const unPeriodo = datosDeReportes(measure('M29-calidad-eeg'), [reports(fx.m29Semestres)[0]], 'semestre');
|
||||||
|
const figura = c2Figure(unPeriodo, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||||
|
expect(figura.status).toBe('supported');
|
||||||
|
const dibujo = JSON.stringify(figura.status === 'supported' ? figura.figure : {});
|
||||||
|
for (const etiqueta of ['Bueno', 'No aceptable', 'Sin analizar']) expect(dibujo).toContain(etiqueta);
|
||||||
|
expect(dibujo).not.toContain('Malo');
|
||||||
|
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||||
|
.toEqual(['Bueno', 'No aceptable', 'Sin analizar']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('presenta Aceptable en ambas gráficas cuando M29 lo declara como categoría propia', () => {
|
||||||
|
const actual = measure('M29-calidad-eeg');
|
||||||
|
const conAceptable: Measure = {
|
||||||
|
...actual, extension: [...actual.extension ?? [], { url: `${SD}/categoria`, extension: [
|
||||||
|
{ url: 'codigo', valueCode: 'ACEPTABLE' }, { url: 'etiqueta', valueString: 'ACEPTABLE' },
|
||||||
|
] }],
|
||||||
|
};
|
||||||
|
const datos = datosDeReportes(conAceptable, [reports(fx.m29Semestres)[0]], 'semestre');
|
||||||
|
expect(datos.filas.find(fila => fila['categoria'] === 'ACEPTABLE')).toMatchObject({ n: 0 });
|
||||||
|
const figura = c2Figure(datos, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||||
|
expect(figura.status).toBe('supported');
|
||||||
|
expect(JSON.stringify(figura.status === 'supported' ? figura.figure : {})).toContain('Aceptable');
|
||||||
|
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||||
|
.toEqual(['Bueno', 'No aceptable', 'Sin analizar', 'Aceptable']);
|
||||||
|
});
|
||||||
|
|
||||||
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
||||||
// Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here
|
// Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here
|
||||||
// instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period.
|
// instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period.
|
||||||
@@ -126,6 +209,36 @@ describe('Servicios FHIR de indicadores', () => {
|
|||||||
expect((await answer).filas.length).toBe(2);
|
expect((await answer).filas.length).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('sigue next para recuperar 201 periodos sin cambiar de endpoint ni de selección', async () => {
|
||||||
|
// The links can contain the upstream origin. The second request must stay on the application's FHIR route.
|
||||||
|
const service = TestBed.inject(FhirIndicadoresService);
|
||||||
|
const periodos = periodosDesde('2009-01-01', 'mes', 201);
|
||||||
|
const report = reports(fx.m21Semestres)[0];
|
||||||
|
const entry = periodos.map(p => ({ resource: { ...report, period: { start: p + '-01', end: p + '-28' } } }));
|
||||||
|
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'mes', periodos));
|
||||||
|
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||||
|
const page = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
|
||||||
|
page.flush({ resourceType: 'Bundle', total: 201, entry: entry.slice(0, 200),
|
||||||
|
link: [{ relation: 'next', url: 'http://webapi:5050/tea/fhir/MeasureReport?_offset=200' }] });
|
||||||
|
const next = http.expectOne(r => r.url === '/tea/fhir/MeasureReport' && r.params.get('_offset') === '200');
|
||||||
|
expect(next.request.params.get('measure')).toBe(page.request.params.get('measure'));
|
||||||
|
expect(next.request.params.get('periodo')).toBe(periodos.join(','));
|
||||||
|
expect(next.request.params.get('_count')).toBe('200');
|
||||||
|
next.flush({ resourceType: 'Bundle', total: 201, entry: entry.slice(200) });
|
||||||
|
expect((await answer).periodos).toHaveLength(201);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rechaza un next que repite el offset sin volver a solicitar reportes', async () => {
|
||||||
|
const service = TestBed.inject(FhirIndicadoresService);
|
||||||
|
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'semestre'));
|
||||||
|
const error = expect(answer).rejects.toThrow('Paginación FHIR inválida');
|
||||||
|
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||||
|
http.expectOne(r => r.url === '/tea/fhir/MeasureReport').flush({ ...fx.m21Semestres,
|
||||||
|
link: [{ relation: 'next', url: '?_offset=0' }] });
|
||||||
|
await error;
|
||||||
|
http.expectNone(r => r.url === '/tea/fhir/MeasureReport');
|
||||||
|
});
|
||||||
|
|
||||||
it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => {
|
it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => {
|
||||||
// Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each
|
// Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each
|
||||||
// measure computes its own periods or every period is evaluated to list them.
|
// measure computes its own periods or every period is evaluated to list them.
|
||||||
@@ -173,14 +286,15 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
|||||||
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
|
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,
|
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: [] });
|
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');
|
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 () => {
|
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
|
// Pins down: the age group from the summary's episode, ADOS-2 domains whose totals add up (the page checks it),
|
||||||
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
|
// the EEG analysis's checks as its report writes them (value or text, A/N, decisive), each metric's state, effects
|
||||||
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
|
// 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'));
|
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||||
@@ -188,13 +302,70 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
|||||||
expect(detalle.grupo_edad).toBe('16-23 meses');
|
expect(detalle.grupo_edad).toBe('16-23 meses');
|
||||||
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
|
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
|
||||||
expect(detalle.eeg!.calidad).toBe('bueno');
|
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')!;
|
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(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||||
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
|
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('el mapa de electrodos del reporte no da una segunda tarjeta a su métrica', async () => {
|
||||||
|
// Pins down: the report's result lists each metric's observation and its electrode-map one, both coded under the
|
||||||
|
// metric's code, and only the metric observation becomes a card. Fails if the alteraciones filter stops skipping
|
||||||
|
// `electrodos-*` observations and the metric shows up twice.
|
||||||
|
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);
|
||||||
|
const detalle = await answer;
|
||||||
|
const codigos = detalle.eeg!.alteraciones.map(a => a.codigo);
|
||||||
|
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el resumen lleva la edad al EEG y la norma por edad de la métrica cuando la WebApi las manda', async () => {
|
||||||
|
// Pins down: the report's `edad-meses` extension as the EEG's age and a metric observation's `curva-referencia`
|
||||||
|
// sub-extensions read back in order as the age norm (ages, five percentiles, source and state), so the page's
|
||||||
|
// checks accept it. Fails if the adapter stops reading either extension or scrambles the series.
|
||||||
|
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||||
|
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||||
|
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||||
|
const detalle = await answer;
|
||||||
|
expect(detalle.eeg!.edad_meses).toBe(23.6);
|
||||||
|
expect(detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!.curva_referencia).toEqual({
|
||||||
|
fuente: 'tea-ritmo_posterior/3', estado: 'validada', edad_meses: [12, 24, 36],
|
||||||
|
p5: [4, 4.5, 5], p25: [5, 5.5, 6], mediana: [5.5, 6, 6.5], p75: [6, 6.5, 7], p95: [6.5, 7, 7.5] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el resumen arma la relación con el ADOS-2 del RiskAssessment y deja fuera la fila incompleta', async () => {
|
||||||
|
// Pins down: the model's version, validation, level and cohort from the resource's extensions, and each
|
||||||
|
// prediction as a row with the metric's and zone's labels, the outcome, OR, interval, q, z, both probabilities
|
||||||
|
// and the observed score; a prediction without its z is dropped instead of failing the page's checks. Fails if
|
||||||
|
// the adapter stops reading the RiskAssessment or lets an incomplete row through.
|
||||||
|
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||||
|
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||||
|
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||||
|
const relacion = (await answer).relacion_ados2!;
|
||||||
|
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
|
||||||
|
expect(relacion.filas).toEqual([{
|
||||||
|
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
|
||||||
|
resultado: 'ados2_item_11', resultado_etiqueta: 'Mostrar', evento: '>=1', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||||
|
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sin edad, norma ni modelo el resumen no inventa esos campos', async () => {
|
||||||
|
// Pins down: a summary without the new extensions or a RiskAssessment (the fixture as the WebApi served it before
|
||||||
|
// the analysis wrote them) leaves `edad_meses`, `curva_referencia` and `relacion_ados2` out, so the page hides
|
||||||
|
// the chart and the panel. Fails if the adapter fills them with defaults.
|
||||||
|
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);
|
||||||
|
const detalle = await answer;
|
||||||
|
expect('edad_meses' in detalle.eeg!).toBe(false);
|
||||||
|
expect(detalle.eeg!.alteraciones.some(a => 'curva_referencia' in a)).toBe(false);
|
||||||
|
expect('relacion_ados2' in detalle).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
|
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
|
||||||
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
|
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
|
||||||
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
|
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
|
||||||
@@ -205,4 +376,27 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
|||||||
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
|
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
|
||||||
expect(mapa.regiones[0].valor_z).toBe(-2.6);
|
expect(mapa.regiones[0].valor_z).toBe(-2.6);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('las regiones del mapa son las zonas del análisis del EEG', () => {
|
||||||
|
// Pins down: Fz is its own region (frontal media) and the central region averages C3, Cz and C4 only, as the
|
||||||
|
// EEG analysis's zones do, so a region on the map is the zone the association model names. Fails if Fz goes
|
||||||
|
// back into the central average or the frontal media region disappears.
|
||||||
|
const mapa = mapaDeElectrodos('picos_paroxisticos', 'Picos paroxísticos', { Fz: 3, C3: 1, Cz: 1.5, C4: 2 });
|
||||||
|
expect(mapa.regiones.map(r => [r.codigo, r.etiqueta, r.valor_z])).toEqual([
|
||||||
|
['frontal_media', 'Frontal media', 3], ['central', 'Central', 1.5]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('la vista previa de un EDF y su ADOS-2 se lee como la ficha de un paciente guardado', async () => {
|
||||||
|
// The fixture is what `POST /governance/tea/eeg/preview` answered for a short synthetic EDF with an ADOS-2 report.
|
||||||
|
// Pins that the bundle the server builds without storing anything passes the same converter and checks as a
|
||||||
|
// stored patient's summary. Fails if the server's shape and the converter drift apart.
|
||||||
|
const answer = firstValueFrom(service.vistaPrevia(vistaPreviaBundle));
|
||||||
|
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush({ concept: [] });
|
||||||
|
const detalle = await answer;
|
||||||
|
expect(detalle.id_seudonimo).toBe('vista-previa');
|
||||||
|
expect(detalle.ados2?.modulo).toBe('2');
|
||||||
|
expect(detalle.ados2?.dominios.length).toBe(2);
|
||||||
|
expect(detalle.eeg?.calidad).toBe('malo');
|
||||||
|
expect(detalle.eeg?.criterios_calidad.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { inject, Injectable } from '@angular/core';
|
import { inject, Injectable } from '@angular/core';
|
||||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
import { map, Observable, shareReplay, switchMap } from 'rxjs';
|
import { EMPTY, expand, map, Observable, reduce, shareReplay, switchMap } from 'rxjs';
|
||||||
import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir';
|
import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir';
|
||||||
import { periodLabel } from './measure-report';
|
import { periodLabel } from './measure-report';
|
||||||
import {
|
import {
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
|
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
|
||||||
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
|
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
|
||||||
} from './indicadores-cama-fhir';
|
} from './indicadores-cama-fhir';
|
||||||
|
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||||
|
|
||||||
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
|
// 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
|
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
|
||||||
@@ -40,8 +41,8 @@ const POPULATION_GROUP: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures
|
// `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`).
|
// and CaCu's have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`, `CACU-EU7` -> `cacu_eu7`).
|
||||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? CACU_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
||||||
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
|
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`.
|
// Age groups travel as `16_23`; the page names them `16-23`.
|
||||||
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
|
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
|
||||||
@@ -55,11 +56,31 @@ function decimal(score: Score | undefined, name: string): number | null {
|
|||||||
return typeof value === 'number' ? value : null;
|
return typeof value === 'number' ? value : null;
|
||||||
}
|
}
|
||||||
const round1 = (value: number) => Math.round(value * 10) / 10;
|
const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||||
|
// A proportion's bounds travel as proportions; the rows hold percentages, like `valor`.
|
||||||
|
const percent = (value: number | null) => value === null ? null : round1(value * 100);
|
||||||
|
|
||||||
|
// Captions the page shows instead of the ones a Measure publishes; the category codes stay those of the data.
|
||||||
|
// TEA's EEG quality shows its invalid exams as «No aceptable».
|
||||||
|
const ROTULOS_DE_CATEGORIA: Readonly<Record<string, Readonly<Record<string, string>>>> = {
|
||||||
|
'M29-calidad-eeg': { MALO: 'No aceptable', ACEPTABLE: 'Aceptable' },
|
||||||
|
};
|
||||||
|
|
||||||
|
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||||
|
// keeps every category ungrouped.
|
||||||
export function categorias(measure: Measure): Record<string, Categoria> {
|
export function categorias(measure: Measure): Record<string, Categoria> {
|
||||||
|
const rotulos = ROTULOS_DE_CATEGORIA[measure.id ?? ''] ?? {};
|
||||||
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
|
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
|
||||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||||
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : [];
|
return codigo && etiqueta ? [[codigo, { etiqueta: rotulos[codigo] ?? etiqueta, color: extension(e, 'color')?.valueString ?? null,
|
||||||
|
grupo: extension(e, 'grupo')?.valueCode ?? null }]] : [];
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
// The groups a composition's categories belong to (`categoria-grupo`: code and caption), in the Measure's order; empty
|
||||||
|
// when the Measure declares none.
|
||||||
|
export function gruposDeCategoria(measure: Measure): Record<string, string> {
|
||||||
|
return Object.fromEntries(extensions(measure, 'categoria-grupo').flatMap(e => {
|
||||||
|
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||||
|
return codigo && etiqueta ? [[codigo, etiqueta]] : [];
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
function contrato(measure: Measure): string {
|
function contrato(measure: Measure): string {
|
||||||
@@ -134,7 +155,7 @@ function proporcion(populations: Population[] | undefined, score: Score | undefi
|
|||||||
return {
|
return {
|
||||||
suprimido: 0, numerador, denominador,
|
suprimido: 0, numerador, denominador,
|
||||||
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
|
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
|
||||||
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
|
ic_bajo: percent(decimal(score, 'ic-bajo')), ic_alto: percent(decimal(score, 'ic-alto')),
|
||||||
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
|
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
|
||||||
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
|
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
|
||||||
};
|
};
|
||||||
@@ -193,13 +214,45 @@ function cruceDeHistopatologia(group: Group, estrato: string): Map<string, numbe
|
|||||||
return celdas;
|
return celdas;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A composition (C2) by one of its strata, from the report's stratifier that crosses the stratum with the category
|
||||||
|
// (`[estrato, categoria]`, as the WebApi publishes it): each stratum value with its caption, and each cell's count.
|
||||||
|
// FHIR lists only the cells that have units and the report is complete, so a cell it doesn't list is a zero; a stratum
|
||||||
|
// value nobody falls in isn't listed at all. A report with no units has no cell to cross. A missing component, a
|
||||||
|
// category the Measure doesn't declare, a repeated cell or cells that don't add up to the period's units are contract
|
||||||
|
// errors, never a silent zero. FHIR publishes no suppression marker, so nothing here is read as suppressed.
|
||||||
|
function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly string[]) {
|
||||||
|
const unidades = count(group.population, 'initial-population');
|
||||||
|
const valores = new Map<string, string>(), celdas = new Map<string, number>();
|
||||||
|
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
|
||||||
|
if (!stratifier && unidades === 0) return { valores, celdas };
|
||||||
|
if (!stratifier) throw new Error('Dimensión no admitida');
|
||||||
|
let suma = 0;
|
||||||
|
for (const stratum of stratifier.stratum ?? []) {
|
||||||
|
const del = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
|
||||||
|
const valor = code(del?.value), categoria = code(cat?.value), n = stratum.population?.[0]?.count;
|
||||||
|
if (!valor || !categoria || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) throw new Error('Celda del estrato incompleta');
|
||||||
|
if (!declaradas.includes(categoria)) throw new Error('Categoría no declarada en el estrato');
|
||||||
|
const e = estratoValor(valor), clave = `${e}|${categoria}`;
|
||||||
|
if (celdas.has(clave)) throw new Error('Celda del estrato repetida');
|
||||||
|
if (!valores.has(e)) valores.set(e, display(del!.value) ?? e);
|
||||||
|
celdas.set(clave, n);
|
||||||
|
suma += n;
|
||||||
|
}
|
||||||
|
if (unidades !== null && suma !== unidades) throw new Error('Los conteos por estrato no suman las unidades del periodo');
|
||||||
|
return { valores, celdas };
|
||||||
|
}
|
||||||
|
|
||||||
// The `/datos` answer for `measure`, from one report per period.
|
// The `/datos` answer for `measure`, from one report per period.
|
||||||
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
|
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
|
||||||
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
|
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
|
||||||
|
const cacu = measure.id !== undefined && Object.hasOwn(CACU_MEASURE_IDS, measure.id);
|
||||||
|
const unidadesPeriodo: Record<string, number> = {};
|
||||||
const declaradas = categorias(measure);
|
const declaradas = categorias(measure);
|
||||||
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
|
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).
|
// 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 cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
|
||||||
|
// Any other composition asked by a stratum is read from its crossed stratifier (`cruceDeComposicion`).
|
||||||
|
const porEstrato = kind === 'C2' && estrato !== undefined && !cruzado;
|
||||||
const cats: Record<string, Categoria> = cruzado
|
const cats: Record<string, Categoria> = cruzado
|
||||||
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
|
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
|
||||||
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
|
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
|
||||||
@@ -209,10 +262,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
|||||||
: { ...declaradas,
|
: { ...declaradas,
|
||||||
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
|
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
|
||||||
const totales: Record<string, unknown>[] = [];
|
const totales: Record<string, unknown>[] = [];
|
||||||
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
|
// The page names the primary group of a proportion `total`; the WebApi names it `principal`.
|
||||||
const nombre = (codigo: string | undefined) => {
|
const nombre = (codigo: string | undefined) => {
|
||||||
const grupo = codigo ?? 'TOTAL';
|
const grupo = codigo ?? 'TOTAL';
|
||||||
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
|
return kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
|
||||||
};
|
};
|
||||||
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
|
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
|
||||||
const id = nombre(code(g.code));
|
const id = nombre(code(g.code));
|
||||||
@@ -241,6 +294,21 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
|||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (porEstrato) {
|
||||||
|
const declaradasEnOrden = Object.keys(cats);
|
||||||
|
const { valores: delPeriodo, celdas } = cruceDeComposicion(group, estrato!, declaradasEnOrden);
|
||||||
|
for (const [e, etiqueta] of delPeriodo) {
|
||||||
|
let total = 0;
|
||||||
|
declaradasEnOrden.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 });
|
||||||
|
if (!valores.has(e)) valores.set(e, etiqueta);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (kind === 'C2') {
|
if (kind === 'C2') {
|
||||||
const strata = group.stratifier?.[0]?.stratum ?? [];
|
const strata = group.stratifier?.[0]?.stratum ?? [];
|
||||||
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
|
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
|
||||||
@@ -249,6 +317,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
|||||||
if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) {
|
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');
|
throw new Error('Los conteos por categoría no suman las unidades del periodo');
|
||||||
}
|
}
|
||||||
|
if (cacu && units !== null) unidadesPeriodo[periodo] = units;
|
||||||
Object.keys(cats).forEach((categoria, orden) =>
|
Object.keys(cats).forEach((categoria, orden) =>
|
||||||
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
|
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
|
||||||
continue;
|
continue;
|
||||||
@@ -280,10 +349,11 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
|||||||
periodos,
|
periodos,
|
||||||
estrato: estrato ?? null,
|
estrato: estrato ?? null,
|
||||||
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
|
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
|
||||||
...(cruzado ? { totales_estrato: totales } : {}),
|
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
|
||||||
|
...(cacu && kind === 'C2' ? { unidades_periodo: unidadesPeriodo } : {}),
|
||||||
grupos,
|
grupos,
|
||||||
categorias: cats,
|
categorias: cats,
|
||||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
|
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
|
||||||
notas: [],
|
notas: [],
|
||||||
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
|
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
|
||||||
filas,
|
filas,
|
||||||
@@ -349,6 +419,29 @@ export class FhirMeasures {
|
|||||||
reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Bundle> {
|
reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Bundle> {
|
||||||
return this.http.get<Bundle>(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') });
|
return this.http.get<Bundle>(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
allReports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Report[]> {
|
||||||
|
const path = `/${requireDominio(dominio)}/fhir/MeasureReport`;
|
||||||
|
return this.reports(dominio, measure, params).pipe(
|
||||||
|
map(bundle => ({ bundle, offset: 0 })),
|
||||||
|
expand(({ bundle, offset }) => {
|
||||||
|
const next = bundle.link?.find(link => link.relation === 'next');
|
||||||
|
if (!next) return EMPTY;
|
||||||
|
// A reverse proxy may expose the API's own origin in the link. Keep the request on the original endpoint
|
||||||
|
// with the same measure and filters, advancing only by the offset that the server supplied.
|
||||||
|
const url = new URL(next.url, `http://localhost${path}`);
|
||||||
|
const raw = url.searchParams.get('_offset');
|
||||||
|
const nextOffset = raw === null ? NaN : Number(raw);
|
||||||
|
if (url.pathname !== path || !Number.isSafeInteger(nextOffset) || nextOffset <= offset) {
|
||||||
|
throw new Error('Paginación FHIR inválida');
|
||||||
|
}
|
||||||
|
return this.reports(dominio, measure, params.set('_offset', nextOffset)).pipe(
|
||||||
|
map(page => ({ bundle: page, offset: nextOffset })),
|
||||||
|
);
|
||||||
|
}, 1),
|
||||||
|
reduce((reports, { bundle }) => reports.concat(resources(bundle, 'MeasureReport') as Report[]), [] as Report[]),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -366,8 +459,8 @@ export class FhirIndicadoresService extends IndicadoresService {
|
|||||||
let params = new HttpParams().set('_count', MAX_COUNT);
|
let params = new HttpParams().set('_count', MAX_COUNT);
|
||||||
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
|
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
|
||||||
return this.measures.one(dominio, indicador).pipe(
|
return this.measures.one(dominio, indicador).pipe(
|
||||||
switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
|
switchMap(measure => this.measures.allReports(dominio, measure, params).pipe(
|
||||||
map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
|
map(reports => datosValidos(datosDeReportes(measure, reports, tipo, scope), indicador, tipo, periodos, scope)))));
|
||||||
}
|
}
|
||||||
override figura(selection: FigureSelection) {
|
override figura(selection: FigureSelection) {
|
||||||
const dominio = requireDominio(selection.dominio ?? 'tea');
|
const dominio = requireDominio(selection.dominio ?? 'tea');
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// Presentation labels for representations confirmed in the published catalog.
|
// Presentation labels for representations confirmed in the published catalog.
|
||||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
// Exact IDs remain the option values and HTTP identities; never infer a type
|
||||||
// from a prefix. Unknown options keep a neutral label in publication order.
|
// from a prefix. Unknown options keep a neutral label in publication order.
|
||||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||||
|
|
||||||
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||||
fig_c1_barras_alteracion: 'Barras por alteración',
|
fig_c1_barras_alteracion: 'Barras por alteración',
|
||||||
|
|||||||
@@ -26,8 +26,13 @@ export function percentText(value: number | null | undefined, fallback = 'No dis
|
|||||||
return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback;
|
return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** «12.3» from a count over its denominator. */
|
||||||
|
export function shareNumber(k: number, n: number): string {
|
||||||
|
const value = sharePercent(k, n);
|
||||||
|
return value > 0 && value < 0.1 ? String(value) : value.toFixed(1);
|
||||||
|
}
|
||||||
|
|
||||||
/** «12.3 %» from a count over its denominator. */
|
/** «12.3 %» from a count over its denominator. */
|
||||||
export function shareText(k: number, n: number): string {
|
export function shareText(k: number, n: number): string {
|
||||||
const value = sharePercent(k, n);
|
return `${shareNumber(k, n)} %`;
|
||||||
return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
// What this module covers: how CaCu's FHIR measures, as the WebApi publishes them, reach the history figures: the
|
||||||
|
// primary group of a proportion (`principal`), the page ids, the unit labels, the reconciliation of a composition and
|
||||||
|
// the periods without units. The Measures are the catalog fixture (`fixtures/cacu_fhir_measures.json`); the reports
|
||||||
|
// are synthetic and carry what the WebApi serialises, `group.code` included: the older bundle fixtures name the group
|
||||||
|
// with `group.id` only, which hides the `principal` / `TOTAL` mismatch this spec pins down.
|
||||||
|
import { Bundle, resources } from './fhir';
|
||||||
|
import { Measure, Report, datosDeReportes, indicadorDeMeasure } from './indicadores-fhir';
|
||||||
|
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||||
|
import { HISTORICO_CACU, historicoDeDominio } from './indicadores-historico-config';
|
||||||
|
import { historicoFigura, HistoricoOpciones } from './indicadores-historico-figures';
|
||||||
|
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||||
|
import camaMeasuresData from './fixtures/cama_fhir_measures.json';
|
||||||
|
|
||||||
|
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||||
|
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||||
|
const medida = (id: string) => publicadas.find(m => m.id === id)!;
|
||||||
|
const cod = (c: string) => ({ coding: [{ code: c }] });
|
||||||
|
const pob = (c: string, count: number) => ({ code: cod(c), count });
|
||||||
|
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
|
||||||
|
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
|
||||||
|
const SEMESTRE = { start: '2025-01-01', end: '2025-06-30' };
|
||||||
|
const SEMESTRE_2 = { start: '2025-07-01', end: '2025-12-31' };
|
||||||
|
|
||||||
|
// A proportion as the WebApi serialises it: group `principal`, a score only when the denominator is positive.
|
||||||
|
const c1 = (period: { start: string; end: string }, numerador: number, denominador: number): Report => ({
|
||||||
|
resourceType: 'MeasureReport', id: 'r', period,
|
||||||
|
group: [{ code: cod('principal'), population: [pob('initial-population', denominador), pob('denominator', denominador), pob('numerator', numerador)],
|
||||||
|
...(denominador > 0 ? { measureScore: { value: numerador / denominador } } : {}) }],
|
||||||
|
} as unknown as Report);
|
||||||
|
// A composition: the categories as the first stratifier, the units as the initial population.
|
||||||
|
const c2 = (m: Measure, period: { start: string; end: string }, conteos: Record<string, number>, unidades?: number): Report => ({
|
||||||
|
resourceType: 'MeasureReport', id: 'r', period,
|
||||||
|
group: [{ code: cod('TOTAL'), population: [pob('initial-population', unidades ?? Object.values(conteos).reduce((a, b) => a + b, 0))],
|
||||||
|
stratifier: [{ code: [cod('categoria')], stratum: Object.entries(conteos).map(([c, n]) => ({ value: cod(c), population: [pob('initial-population', n)] })) }] }],
|
||||||
|
} as unknown as Report);
|
||||||
|
// A duration: the median and the quartiles as extensions of the score.
|
||||||
|
const c3r = (period: { start: string; end: string }, n: number, mediana?: number): Report => ({
|
||||||
|
resourceType: 'MeasureReport', id: 'r', period,
|
||||||
|
group: [{ code: cod('TOTAL'), population: [pob('initial-population', n + 1), pob('measure-observation', n), pob('measure-population-exclusion', 1)],
|
||||||
|
...(mediana === undefined ? {} : { measureScore: { value: mediana, unit: 'd', extension: [
|
||||||
|
{ url: `${STRUCTURE}/q1`, valueDecimal: mediana - 2 }, { url: `${STRUCTURE}/q3`, valueDecimal: mediana + 3 }] } }) }],
|
||||||
|
} as unknown as Report);
|
||||||
|
const traza = (datos: ReturnType<typeof datosDeReportes>, i: number, opciones?: HistoricoOpciones) =>
|
||||||
|
historicoFigura(datos, 'claro', opciones).figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
|
||||||
|
const CACU: HistoricoOpciones = { unidades: historicoDeDominio('cacu')!.unidades, conciliarC2: true, c2SinPoblacionSinDato: true };
|
||||||
|
|
||||||
|
describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
|
||||||
|
it('EU13 con el grupo `principal` que publica el WebApi: el cero es un valor y el panel no queda vacío', () => {
|
||||||
|
// Pins down: the proportion's group reaches the history as the total. Fails if `principal` stays as it is and the
|
||||||
|
// selector of the total drops every row, which left EU13's panel empty.
|
||||||
|
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 4)], 'semestre');
|
||||||
|
expect(datos.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 4, valor: 0 });
|
||||||
|
expect(Object.keys(datos['grupos'] as object)).toEqual(['total']);
|
||||||
|
const figura = historicoFigura(datos, 'claro');
|
||||||
|
expect(traza(datos, 1).y).toEqual([0]);
|
||||||
|
expect(figura.sinDato).toEqual([]);
|
||||||
|
});
|
||||||
|
it('IND1 se publica como `ind1` y conserva su valor', () => {
|
||||||
|
const datos = datosDeReportes(medida('IND1'), [c1(SEMESTRE, 1, 4), c1(SEMESTRE_2, 1, 4)], 'semestre');
|
||||||
|
expect(datos.id).toBe('ind1');
|
||||||
|
expect(traza(datos, 1).y).toEqual([25, 25]);
|
||||||
|
});
|
||||||
|
it('el intervalo de Wilson publicado usa la misma escala porcentual que el valor', () => {
|
||||||
|
// Fails if the history drops the FHIR bounds or scales them a second time.
|
||||||
|
for (const id of ['CACU-EU13', 'IND1']) {
|
||||||
|
const reporte = c1(SEMESTRE, 1, 4);
|
||||||
|
reporte.group![0].measureScore!.extension = [
|
||||||
|
{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 },
|
||||||
|
{ url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 },
|
||||||
|
];
|
||||||
|
const datos = datosDeReportes(medida(id), [reporte], 'semestre');
|
||||||
|
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
|
||||||
|
expect(traza(datos, 0).y).toEqual([69.9, 4.6]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('un denominador cero es «sin dato», no un cero', () => {
|
||||||
|
// The WebApi omits the score when there is no denominator: the period is listed as missing, not drawn at zero.
|
||||||
|
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 0), c1(SEMESTRE_2, 1, 4)], 'semestre');
|
||||||
|
expect(datos.filas[0]).toMatchObject({ valor: null, denominador: 0 });
|
||||||
|
expect(traza(datos, 1).y).toEqual([null, 25]);
|
||||||
|
expect(historicoFigura(datos, 'claro').sinDato).toEqual(['2025 S1']);
|
||||||
|
});
|
||||||
|
it('sin intervalo publicado la banda queda vacía: el cliente no lo calcula ni lo inventa', () => {
|
||||||
|
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 1, 4)], 'semestre');
|
||||||
|
expect(datos.filas[0]).toMatchObject({ ic_bajo: null, ic_alto: null });
|
||||||
|
expect(traza(datos, 0)).toMatchObject({ name: 'Intervalo de confianza', x: [], y: [] });
|
||||||
|
});
|
||||||
|
it('en CaMa el grupo principal sigue siendo `total`', () => {
|
||||||
|
// Regression: the normalisation CaCu shares with CaMa keeps CaMa's own result.
|
||||||
|
const cama = (resources(camaMeasuresData as unknown as Bundle, 'Measure') as Measure[]).find(m => m.id === 'CAMA-CONFIRMACION-BIRADS45')!;
|
||||||
|
const datos = datosDeReportes(cama, [c1(SEMESTRE, 2, 4)], 'semestre');
|
||||||
|
expect(datos.filas[0]).toMatchObject({ grupo: 'total', valor: 50 });
|
||||||
|
});
|
||||||
|
it('los paneles activos usan ids de página y contratos que el catálogo publica', () => {
|
||||||
|
// Pins down the compatibility of the identifiers: every active panel is a measure `dev` publishes, under the id
|
||||||
|
// the page gives it, and with the contract the panel expects.
|
||||||
|
const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)]));
|
||||||
|
const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo);
|
||||||
|
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||||
|
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']);
|
||||||
|
for (const panel of activos) {
|
||||||
|
expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id);
|
||||||
|
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('ningún panel queda reservado: los nueve leen su medida del catálogo', () => {
|
||||||
|
// Pins down: every CaCu history panel is active, the risk bands included, under the page id of its measure.
|
||||||
|
expect(HISTORICO_CACU.filter(p => p.enDesarrollo)).toEqual([]);
|
||||||
|
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Histórico de CaCu: composiciones (C2)', () => {
|
||||||
|
const eu7 = () => medida('CACU-EU7');
|
||||||
|
const conteos = (extra: Record<string, number> = {}) => ({ ...Object.fromEntries(declaradas(eu7()).map((c, i) => [c, [8, 3, 2, 1, 1, 0, 1][i]])), ...extra });
|
||||||
|
|
||||||
|
it('el reporte de EU7 conserva las unidades de cada periodo y la conciliación pasa', () => {
|
||||||
|
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos())], 'semestre');
|
||||||
|
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 16 });
|
||||||
|
const figura = historicoFigura(datos, 'claro', CACU);
|
||||||
|
expect(figura.figure.data.map(t => (t['y'] as number[])[0])).toEqual([8, 3, 2, 1, 1, 0, 1]);
|
||||||
|
expect(figura.sinDato).toEqual([]);
|
||||||
|
});
|
||||||
|
it('una categoría que el Measure no declara rompe la conciliación del Histórico y no cambia el Resumen', () => {
|
||||||
|
// Pins down: a category the report counts but the Measure does not declare (the glandular results are still an open
|
||||||
|
// decision) is no longer a shorter bar. The adapter itself reads the report as before.
|
||||||
|
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos({ AGC: 2 }))], 'semestre');
|
||||||
|
expect(datos.filas.map(f => f['categoria'])).not.toContain('AGC');
|
||||||
|
expect(() => historicoFigura(datos, 'claro', CACU)).toThrow('Los conteos por categoría no suman las unidades del periodo');
|
||||||
|
expect(() => historicoFigura(datos, 'claro')).not.toThrow();
|
||||||
|
});
|
||||||
|
it('un periodo sin pacientes es «sin dato» en CaCu y no barras en cero', () => {
|
||||||
|
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
|
||||||
|
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0), c2(eu7(), SEMESTRE_2, conteos())], 'semestre');
|
||||||
|
const figura = historicoFigura(datos, 'claro', CACU);
|
||||||
|
expect(figura.sinDato).toEqual(['2025 S1']);
|
||||||
|
expect(figura.figure.data.every(t => (t['y'] as (number | null)[])[0] === null)).toBe(true);
|
||||||
|
expect((figura.figure.data[0]['y'] as number[])[1]).toBe(8);
|
||||||
|
});
|
||||||
|
it('sin la opción de CaCu un periodo sin unidades se dibuja como antes (CaMa no cambia)', () => {
|
||||||
|
// Regression: the rule is the domain's, not the figure module's.
|
||||||
|
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
|
||||||
|
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0)], 'semestre');
|
||||||
|
const figura = historicoFigura(datos, 'claro');
|
||||||
|
expect(figura.sinDato).toEqual([]);
|
||||||
|
expect(figura.figure.data.every(t => (t['y'] as number[])[0] === 0)).toBe(true);
|
||||||
|
});
|
||||||
|
it('la confirmación por citología declara sus categorías y se concilia igual', () => {
|
||||||
|
const m = medida('CACU-CONFIRMACION-CITOLOGIA');
|
||||||
|
const datos = datosDeReportes(m, [c2(m, SEMESTRE, Object.fromEntries(declaradas(m).map((c, i) => [c, i])))], 'semestre');
|
||||||
|
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 21 });
|
||||||
|
expect(() => historicoFigura(datos, 'claro', CACU)).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Histórico de CaCu: tiempos (C3r) y etiquetas de unidad', () => {
|
||||||
|
const m = () => medida('CACU-EU-TIEMPO-REPORTE');
|
||||||
|
it('la mediana y los cuartiles hablan de citologías en CaCu', () => {
|
||||||
|
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12), c3r(SEMESTRE_2, 0)], 'semestre');
|
||||||
|
expect(datos.filas[0]).toMatchObject({ mediana: 12, q1: 10, q3: 15, n: 6, unidad: 'dias' });
|
||||||
|
const figura = historicoFigura(datos, 'claro', CACU);
|
||||||
|
expect(traza(datos, 1, CACU)['text'][0]).toBe('Mediana: 12 días<br>Q1 a Q3: 10 a 15 días<br>6 citologías');
|
||||||
|
expect(figura.comoLeer).toContain('las citologías');
|
||||||
|
expect(figura.comoLeer).not.toContain('mastograf');
|
||||||
|
// A period without observations is missing, not zero.
|
||||||
|
expect(traza(datos, 1, CACU)['y']).toEqual([12, null]);
|
||||||
|
expect(figura.sinDato).toEqual(['2025 S2']);
|
||||||
|
});
|
||||||
|
it('sin la configuración de CaCu el texto de los exámenes sigue siendo el de CaMa', () => {
|
||||||
|
// Regression: `examen` keeps reading «mastografías» wherever the domain does not name it otherwise.
|
||||||
|
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12)], 'semestre');
|
||||||
|
expect(traza(datos, 1)['text'][0]).toContain('6 mastografías');
|
||||||
|
expect(historicoFigura(datos, 'claro').comoLeer).toContain('las mastografías');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing
|
||||||
|
// until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and
|
||||||
|
// the notice. Responses are synthetic, shaped like /cacu/indicadores/<id>/periodos and /datos.
|
||||||
|
import { Component } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { By } from '@angular/platform-browser';
|
||||||
|
import { MatDialog } from '@angular/material/dialog';
|
||||||
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { IndicadoresHistorico } from './indicadores-historico';
|
||||||
|
import { HISTORICO_CACU } from './indicadores-historico-config';
|
||||||
|
import { Indicador } from './indicadores.models';
|
||||||
|
|
||||||
|
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||||
|
class ChartStub { figure?: { data: { name?: string; y?: (number | null)[]; text?: string[] }[] }; label?: string; }
|
||||||
|
|
||||||
|
const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStart(2, '0')}`);
|
||||||
|
const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1'];
|
||||||
|
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
|
||||||
|
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
|
||||||
|
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||||
|
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||||
|
const RESERVADOS: string[] = [];
|
||||||
|
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
||||||
|
// Every measure the catalog could publish, reserved ones included: publishing them must not activate them.
|
||||||
|
const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item);
|
||||||
|
|
||||||
|
function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) {
|
||||||
|
const contrato = opciones.contrato ?? CONTRATOS[id];
|
||||||
|
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
|
||||||
|
const vacio = (p: string) => p === opciones.sinPoblacion;
|
||||||
|
const filas = contrato === 'C2'
|
||||||
|
? periodos.flatMap(p => [fila(p, { categoria: 'NORMAL', n: vacio(p) ? 0 : 7, orden: 0 }), fila(p, { categoria: 'ASC-US', n: vacio(p) ? 0 : 5, orden: 1 })])
|
||||||
|
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 0, numerador: 0, denominador: 10, ic_bajo: null, ic_alto: null }))
|
||||||
|
: periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' }));
|
||||||
|
return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' ? 'paciente' : 'examen', filas,
|
||||||
|
categorias: { NORMAL: { etiqueta: 'Normal', color: '#9DBFE3' }, 'ASC-US': { etiqueta: 'ASC-US', color: '#2F6DB3' } },
|
||||||
|
...(contrato === 'C2' ? { unidades_periodo: Object.fromEntries(periodos.map(p => [p, vacio(p) ? 0 : 12])) } : {}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Histórico de CaCu', () => {
|
||||||
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
|
||||||
|
const abrirDialogo = vi.fn();
|
||||||
|
function montar(catalog: Indicador[] = CATALOGO, active = false) {
|
||||||
|
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [
|
||||||
|
provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } },
|
||||||
|
] });
|
||||||
|
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
|
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
|
||||||
|
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog);
|
||||||
|
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active);
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
|
||||||
|
// Answers in waves, because the shared request queue runs four at a time. `pedidos` keeps what each data request asked for.
|
||||||
|
const pedidos: { id: string; periodos: string[] }[] = [];
|
||||||
|
function responder(opciones: { fallo?: (r: TestRequest) => boolean; datos?: (id: string) => { contrato?: string; sinPoblacion?: string } } = {}) {
|
||||||
|
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||||
|
for (const r of ola) {
|
||||||
|
const url = r.request.url, id = url.split('/').at(-2)!;
|
||||||
|
if (opciones.fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; }
|
||||||
|
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||||
|
else {
|
||||||
|
const periodos = r.request.params.get('periodos')!.split(',');
|
||||||
|
pedidos.push({ id, periodos });
|
||||||
|
r.flush(datos(id, periodos[0].includes('S') ? 'semestre' : 'mes', periodos, opciones.datos?.(id)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
beforeEach(() => { pedidos.length = 0; });
|
||||||
|
const root = () => fixture.nativeElement as HTMLElement;
|
||||||
|
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
|
||||||
|
const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!;
|
||||||
|
const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo;
|
||||||
|
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||||
|
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Trazabilidad de ' + titulo))!;
|
||||||
|
|
||||||
|
it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => {
|
||||||
|
// Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it.
|
||||||
|
montar();
|
||||||
|
http.expectNone(() => true);
|
||||||
|
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||||
|
const vistos = new Set<string>();
|
||||||
|
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||||
|
for (const r of ola) {
|
||||||
|
vistos.add(r.request.url.split('/').at(-2)!);
|
||||||
|
const id = r.request.url.split('/').at(-2)!;
|
||||||
|
if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: MESES.map(periodo => ({ periodo, tipo: 'mes' })) });
|
||||||
|
else r.flush(datos(id, 'mes', r.request.params.get('periodos')!.split(',')));
|
||||||
|
}
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
|
||||||
|
for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false);
|
||||||
|
});
|
||||||
|
it('dibuja los nueve paneles en orden: los activos con gráfica y los reservados sin consultar', () => {
|
||||||
|
montar(CATALOGO, true); responder();
|
||||||
|
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
|
||||||
|
expect(paneles()).toHaveLength(9);
|
||||||
|
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||||
|
const reservados = paneles().slice(ACTIVOS.length);
|
||||||
|
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
|
||||||
|
expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual(
|
||||||
|
HISTORICO_CACU.slice(ACTIVOS.length).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
||||||
|
});
|
||||||
|
it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => {
|
||||||
|
// Pins down: the state of a reserved panel comes from the config alone.
|
||||||
|
for (const catalogo of [ACTIVOS.map(item), CATALOGO]) {
|
||||||
|
montar(catalogo, true); responder();
|
||||||
|
expect(paneles().slice(ACTIVOS.length).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(RESERVADOS.length).fill('Trabajo en desarrollo'));
|
||||||
|
fixture.destroy(); TestBed.resetTestingModule();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('no antepone ningún aviso a los paneles', () => {
|
||||||
|
// Fails if a notice about clinical validation or suppression is shown again above the history's panels.
|
||||||
|
montar();
|
||||||
|
expect(root().querySelector('[data-aviso="historico"]')).toBeNull();
|
||||||
|
expect(root().textContent).not.toContain('sujetos a validación clínica');
|
||||||
|
});
|
||||||
|
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
|
||||||
|
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
|
||||||
|
montar(CATALOGO, true); responder();
|
||||||
|
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||||
|
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5));
|
||||||
|
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||||
|
});
|
||||||
|
it('elegir «Todos» pide solo los periodos que faltan y los suma', () => {
|
||||||
|
montar(CATALOGO, true); responder();
|
||||||
|
pedidos.length = 0;
|
||||||
|
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
|
||||||
|
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||||
|
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7));
|
||||||
|
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
|
||||||
|
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||||
|
// Going back to five is local: nothing is asked again.
|
||||||
|
pedidos.length = 0;
|
||||||
|
fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); responder();
|
||||||
|
expect(pedidos).toEqual([]);
|
||||||
|
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||||
|
});
|
||||||
|
it.each([false, true])('acumula 5→10→Todos sin duplicados al recibir primero la segunda respuesta: %s', invertir => {
|
||||||
|
// The two expansions are disjoint. Either arrival order must preserve all twelve periods.
|
||||||
|
montar([item('ind1')], true); responder();
|
||||||
|
fixture.componentInstance.elegirVentana(10);
|
||||||
|
fixture.componentInstance.elegirVentana(0);
|
||||||
|
fixture.componentInstance.elegirVentana(0);
|
||||||
|
const ampliaciones = http.match(r => r.url.endsWith('/datos'));
|
||||||
|
const periodos = (r: TestRequest) => r.request.params.get('periodos')!.split(',');
|
||||||
|
expect(ampliaciones.map(periodos)).toEqual([MESES.slice(2, 7), MESES.slice(0, 2)]);
|
||||||
|
for (const r of invertir ? ampliaciones.reverse() : ampliaciones) {
|
||||||
|
r.flush(datos('ind1', 'mes', periodos(r)));
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('reintenta la ampliación fallida conservando los cinco periodos y sin repetir periodos cargados', () => {
|
||||||
|
montar([item('ind1')], true); responder();
|
||||||
|
fixture.componentInstance.elegirVentana(0);
|
||||||
|
http.expectOne(r => r.url.endsWith('/datos')).flush('private', { status: 500, statusText: 'Error' });
|
||||||
|
fixture.detectChanges();
|
||||||
|
const panel = panelDe(tituloDe('ind1'));
|
||||||
|
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(5);
|
||||||
|
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Error');
|
||||||
|
(panel.querySelector('button') as HTMLButtonElement).click();
|
||||||
|
const reintento = http.expectOne(r => r.url.endsWith('/datos'));
|
||||||
|
expect(reintento.request.params.get('periodos')?.split(',')).toEqual(MESES.slice(0, 7));
|
||||||
|
reintento.flush(datos('ind1', 'mes', MESES.slice(0, 7)));
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||||
|
expect(panel.querySelector('[role="alert"]')).toBeNull();
|
||||||
|
});
|
||||||
|
it('cambiar a Semestral pide los últimos cinco semestres una vez y volver a Mensual no repite', () => {
|
||||||
|
montar(CATALOGO, true); responder();
|
||||||
|
pedidos.length = 0;
|
||||||
|
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||||
|
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||||
|
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
|
||||||
|
pedidos.length = 0;
|
||||||
|
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
|
||||||
|
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||||
|
expect(pedidos).toEqual([]);
|
||||||
|
});
|
||||||
|
it('una medida ausente muestra «Trabajo en desarrollo» y no se consulta', () => {
|
||||||
|
montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder();
|
||||||
|
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||||
|
expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo');
|
||||||
|
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
|
||||||
|
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||||
|
});
|
||||||
|
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
|
||||||
|
montar(CATALOGO, true);
|
||||||
|
responder({ fallo: r => r.request.url.includes('/cacu_eu13/') && r.request.url.endsWith('/datos') });
|
||||||
|
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||||
|
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
|
||||||
|
expect(panel.textContent).not.toContain('private');
|
||||||
|
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||||
|
const reintentar = panel.querySelector('button') as HTMLButtonElement;
|
||||||
|
reintentar.click(); fixture.detectChanges(); responder();
|
||||||
|
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||||
|
});
|
||||||
|
it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => {
|
||||||
|
// Pins down the expected contract: the panel does not draw a C1 where it declared a composition.
|
||||||
|
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} });
|
||||||
|
const panel = panelDe(tituloDe('cacu_eu7'));
|
||||||
|
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1');
|
||||||
|
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||||
|
});
|
||||||
|
it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => {
|
||||||
|
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} });
|
||||||
|
expect(graficaDe(tituloDe('cacu_eu13')).figure!.data[1].y).toEqual([0, 0, 0, 0, 0]);
|
||||||
|
expect(panelDe(tituloDe('cacu_eu13')).querySelector('[data-plegable="sin-dato"]')).toBeNull();
|
||||||
|
const eu7 = panelDe(tituloDe('cacu_eu7'));
|
||||||
|
expect(eu7.querySelector('[data-plegable="sin-dato"]')?.textContent).toContain('Periodos sin dato (1)');
|
||||||
|
expect(eu7.textContent).toContain('oct 2025');
|
||||||
|
expect(graficaDe(tituloDe('cacu_eu7')).figure!.data[0].y).toEqual([7, 7, null, 7, 7]);
|
||||||
|
});
|
||||||
|
it('los tiempos hablan de citologías', () => {
|
||||||
|
montar(CATALOGO, true); responder();
|
||||||
|
for (const id of ['cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']) {
|
||||||
|
expect(graficaDe(tituloDe(id)).figure!.data[1].text![0]).toContain('20 citologías');
|
||||||
|
expect(panelDe(tituloDe(id)).textContent).toContain('las citologías');
|
||||||
|
expect(panelDe(tituloDe(id)).textContent).not.toContain('mastograf');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => {
|
||||||
|
montar(RESERVADOS.map(item), true);
|
||||||
|
expect(paneles()).toHaveLength(9);
|
||||||
|
expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true);
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('sin periodos con reportes un panel activo muestra «Sin datos»', () => {
|
||||||
|
montar([item('ind1')], true);
|
||||||
|
http.expectOne(r => r.url.endsWith('/periodos')).flush({ id: 'ind1', periodos: [] });
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(panelDe(tituloDe('ind1')).querySelector('[role="status"]')?.textContent).toBe('Sin datos');
|
||||||
|
expect(graficas()).toHaveLength(0);
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -81,13 +81,21 @@ describe('Histórico de CaMa', () => {
|
|||||||
});
|
});
|
||||||
it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
|
it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
|
||||||
montar(CATALOGO, true); responder();
|
montar(CATALOGO, true); responder();
|
||||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual([
|
||||||
|
'Días de la toma de la mastografía a su resultado',
|
||||||
|
'Días del resultado de la mastografía al diagnóstico',
|
||||||
|
'Días de tamizaje a diagnóstico',
|
||||||
|
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||||
|
'Pacientes con resultado BI-RADS 4, 5 ó 6',
|
||||||
|
'Resultado histopatológico',
|
||||||
|
'Tasa de confirmación histopatológica',
|
||||||
|
]);
|
||||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
||||||
expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico']);
|
expect(pendientes).toEqual(['Días del resultado de la mastografía al diagnóstico', 'Resultado histopatológico']);
|
||||||
expect(paneles()).toHaveLength(7);
|
expect(paneles()).toHaveLength(7);
|
||||||
const titulo = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
const titulo = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||||
expect(paneles()[2].querySelector('h2')?.textContent).toBe(titulo);
|
expect(paneles()[3].querySelector('h2')?.textContent).toBe(titulo);
|
||||||
expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true);
|
expect(graficas().some(g => g.label?.startsWith('Trazabilidad de ' + titulo))).toBe(true);
|
||||||
expect(graficas()).toHaveLength(5);
|
expect(graficas()).toHaveLength(5);
|
||||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
||||||
});
|
});
|
||||||
@@ -96,7 +104,7 @@ describe('Histórico de CaMa', () => {
|
|||||||
// closed disclosure labelled «Periodos sin dato (n)»; opening it shows every month, as the note read before. Fails if the
|
// 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.
|
// 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));
|
montar(CATALOGO, true); responder(undefined, periodo => !['2025-01', '2025-02'].includes(periodo));
|
||||||
const panel = paneles()[1];
|
const panel = paneles()[4];
|
||||||
const plegable = panel.querySelector<HTMLDetailsElement>('details[data-plegable="sin-dato"]')!;
|
const plegable = panel.querySelector<HTMLDetailsElement>('details[data-plegable="sin-dato"]')!;
|
||||||
expect(plegable).not.toBeNull();
|
expect(plegable).not.toBeNull();
|
||||||
expect(plegable.open).toBe(false);
|
expect(plegable.open).toBe(false);
|
||||||
@@ -117,7 +125,7 @@ describe('Histórico de CaMa', () => {
|
|||||||
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
|
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
|
||||||
montar(CATALOGO, true); responder();
|
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');
|
expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual');
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
|
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
|
||||||
});
|
});
|
||||||
it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => {
|
it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => {
|
||||||
montar(CATALOGO, true); responder();
|
montar(CATALOGO, true); responder();
|
||||||
@@ -126,7 +134,7 @@ describe('Histórico de CaMa', () => {
|
|||||||
const semestrales = responder();
|
const semestrales = responder();
|
||||||
expect(semestrales.length).toBeGreaterThan(0);
|
expect(semestrales.length).toBeGreaterThan(0);
|
||||||
expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true);
|
expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true);
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
|
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
|
||||||
toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges();
|
toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges();
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
@@ -135,7 +143,7 @@ describe('Histórico de CaMa', () => {
|
|||||||
const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } };
|
const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } };
|
||||||
expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']);
|
expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']);
|
||||||
fixture.componentInstance.elegirVentana(5); fixture.detectChanges();
|
fixture.componentInstance.elegirVentana(5); fixture.detectChanges();
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
|
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
|
||||||
});
|
});
|
||||||
it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => {
|
it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => {
|
||||||
montar(CATALOGO, true); responder();
|
montar(CATALOGO, true); responder();
|
||||||
@@ -144,10 +152,10 @@ describe('Histórico de CaMa', () => {
|
|||||||
expect(abrirDialogo).toHaveBeenCalledTimes(1);
|
expect(abrirDialogo).toHaveBeenCalledTimes(1);
|
||||||
const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] };
|
const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] };
|
||||||
expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES);
|
expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES);
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||||
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) });
|
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) });
|
||||||
fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges();
|
fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges();
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||||
});
|
});
|
||||||
it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => {
|
it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => {
|
||||||
// Fails if one failing indicator blanks the others, leaks its body, or cannot be retried.
|
// Fails if one failing indicator blanks the others, leaks its body, or cannot be retried.
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { Dominio } from './indicadores.models';
|
||||||
|
|
||||||
|
// What each domain's history tab draws, declared as data: the panels and their order, the contract each one is
|
||||||
|
// expected to carry, the labels of its unit and what the tab may ask for. A domain without an entry here (TEA) draws
|
||||||
|
// its whole catalog.
|
||||||
|
|
||||||
|
export type ContratoHistorico = 'C1' | 'C2' | 'C3r';
|
||||||
|
// The mark each contract gets in `historicoFigura`: counts add up to a total, percentages and medians do not.
|
||||||
|
export type GraficaHistorico = 'barras_apiladas' | 'linea_porcentaje' | 'linea_mediana';
|
||||||
|
export interface PanelHistorico {
|
||||||
|
// The page's id of the measure (what `indicadorId` gives).
|
||||||
|
id: string;
|
||||||
|
titulo: string;
|
||||||
|
contrato?: ContratoHistorico;
|
||||||
|
grafica?: GraficaHistorico;
|
||||||
|
enDesarrollo?: boolean;
|
||||||
|
// The FHIR ids the reserved panels will use even if the catalog already publishes them.
|
||||||
|
fhir?: readonly string[];
|
||||||
|
}
|
||||||
|
export interface UnidadHistorico { plural: string; eje: string }
|
||||||
|
export interface HistoricoDominio {
|
||||||
|
paneles: readonly PanelHistorico[];
|
||||||
|
// The unit a measure publishes (`examen`) named as the domain calls it; overrides the figure module's default.
|
||||||
|
unidades?: Readonly<Record<string, UnidadHistorico>>;
|
||||||
|
// How many of the latest periods are requested when the tab opens. Without it, every period is requested.
|
||||||
|
periodosIniciales?: number;
|
||||||
|
// A composition (C2) whose categories do not add up to the report's units is an error, not a shorter bar.
|
||||||
|
conciliarC2?: boolean;
|
||||||
|
// A composition period with no units is «sin dato», not a bar of zeros.
|
||||||
|
c2SinPoblacionSinDato?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
|
||||||
|
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||||
|
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
|
||||||
|
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6' },
|
||||||
|
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes con resultado BI-RADS 4, 5 ó 6' },
|
||||||
|
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||||
|
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||||
|
];
|
||||||
|
|
||||||
|
// CaCu's history. The active panels read the measures the catalog publishes; the reserved ones (`enDesarrollo`) never ask.
|
||||||
|
export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||||
|
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||||
|
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||||
|
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||||
|
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||||
|
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||||
|
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||||
|
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||||
|
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||||
|
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||||
|
cama: { paneles: HISTORICO_CAMA },
|
||||||
|
cacu: {
|
||||||
|
paneles: HISTORICO_CACU,
|
||||||
|
// `examen` is the citology here.
|
||||||
|
unidades: { examen: { plural: 'citologías', eje: 'Citologías' } },
|
||||||
|
periodosIniciales: 5,
|
||||||
|
conciliarC2: true,
|
||||||
|
c2SinPoblacionSinDato: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// The domain's declared history, if it has one and the tab is on.
|
||||||
|
export const historicoDeDominio = (dominio: Dominio): HistoricoDominio | undefined => HISTORICOS[dominio];
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user