Compare commits
142 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 3385df4ba3 | |||
| 96b1cabb5a | |||
| 366591f247 | |||
| 241631b884 | |||
| 6c063344a3 | |||
| 2f5b1ce1f2 | |||
| 56b3ac6b0c | |||
| f6603ae76e | |||
| 21ae95b5ed | |||
| ce2e86c045 | |||
| 0f8eb0ec94 | |||
| 2f6d419453 | |||
| f34f9e1607 | |||
| c7dd134fce | |||
| 03cc9c9800 | |||
| 04795a09cc | |||
| de3d247d0d | |||
| ee87bcb8d0 | |||
| aaeea7a7b0 | |||
| 7f17681409 | |||
| d72c18756f | |||
| fefa28ae7a | |||
| a217ddae38 | |||
| 97fcb37761 |
@@ -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;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 717 B |
@@ -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()
|
||||||
@@ -37,10 +37,11 @@ describe('Encabezado del marco', () => {
|
|||||||
|
|
||||||
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
|
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
|
||||||
// Fails if the selector would point at a route the application does not have.
|
// Fails if the selector would point at a route the application does not have.
|
||||||
const paths = routes.map(r => r.path);
|
// The application's routes live under the guarded parent ('login' is its sibling).
|
||||||
|
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 + ' ▾');
|
||||||
@@ -59,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');
|
||||||
});
|
});
|
||||||
@@ -68,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));
|
||||||
@@ -79,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 },
|
||||||
|
]
|
||||||
|
};
|
||||||
@@ -12,6 +12,8 @@ export const appConfig: ApplicationConfig = {
|
|||||||
providers: [
|
providers: [
|
||||||
provideBrowserGlobalErrorListeners(),
|
provideBrowserGlobalErrorListeners(),
|
||||||
provideRouter(routes),
|
provideRouter(routes),
|
||||||
|
// La sesión es del navegador (`auth/auth.service.ts`): no hay interceptor
|
||||||
|
// porque la WebApi no responde 401.
|
||||||
provideHttpClient(),
|
provideHttpClient(),
|
||||||
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
||||||
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
||||||
|
|||||||
+41
-23
@@ -1,33 +1,51 @@
|
|||||||
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
|
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
|
||||||
<header class="site-header">
|
@if (!sinCromo()) {
|
||||||
<div class="site-header__content">
|
<header class="site-header">
|
||||||
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
<div class="site-header__content">
|
||||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
||||||
</a>
|
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||||
@if (activeDomain(); as domain) {
|
</a>
|
||||||
<span class="platform-title">{{ title }}</span>
|
@if (activeDomain(); as domain) {
|
||||||
@defer (on immediate) {
|
<span class="platform-title">{{ title }}</span>
|
||||||
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
|
@if (otherDomains().length) {
|
||||||
} @placeholder {
|
@defer (on immediate) {
|
||||||
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
|
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
|
||||||
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
|
} @placeholder {
|
||||||
}
|
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
|
||||||
} @else {
|
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
|
||||||
<nav class="site-header__nav" aria-label="Secciones">
|
}
|
||||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
} @else {
|
||||||
@if (breadcrumb(); as crumb) {
|
<!-- An account with a single domain has nothing to switch to: the domain is a label. -->
|
||||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
<span class="domain-selector domain-selector--espera">{{ domainLabels[domain] }}</span>
|
||||||
}
|
}
|
||||||
</nav>
|
} @else {
|
||||||
}
|
<nav class="site-header__nav" aria-label="Secciones">
|
||||||
</div>
|
@if (breadcrumb(); as crumb) {
|
||||||
</header>
|
<span class="site-header__crumb" aria-current="page">{{ crumb }}</span>
|
||||||
|
}
|
||||||
|
</nav>
|
||||||
|
}
|
||||||
|
@if (usuario(); as sesion) {
|
||||||
|
<button
|
||||||
|
class="site-header__salir"
|
||||||
|
type="button"
|
||||||
|
(click)="salir()"
|
||||||
|
[attr.title]="'Cerrar sesión de ' + sesion.nombre"
|
||||||
|
[attr.aria-label]="'Cerrar sesión de ' + sesion.nombre"
|
||||||
|
>
|
||||||
|
<mat-icon aria-hidden="true">logout</mat-icon>
|
||||||
|
<span class="site-header__salir-nombre">{{ sesion.nombre }}</span>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
}
|
||||||
|
|
||||||
<main class="app-main">
|
<main class="app-main">
|
||||||
<router-outlet />
|
<router-outlet />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
@if (!workspace()) {
|
@if (!workspace() && !sinCromo()) {
|
||||||
<footer class="site-footer">
|
<footer class="site-footer">
|
||||||
<div class="site-footer__content">
|
<div class="site-footer__content">
|
||||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||||
|
|||||||
+57
-37
@@ -1,49 +1,69 @@
|
|||||||
import { Routes } from '@angular/router';
|
import { Routes } from '@angular/router';
|
||||||
import { Home } from './home';
|
import { Home } from './home';
|
||||||
|
import { authGuard } from './auth/auth.guard';
|
||||||
|
import { dominioGuard } from './auth/dominio.guard';
|
||||||
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
||||||
|
|
||||||
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
|
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
|
||||||
|
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
|
||||||
{
|
{
|
||||||
path: 'indicadores/tea-estatus',
|
path: 'login',
|
||||||
title: 'Casos por estatus | ISSSTELEON',
|
title: 'Inicio de sesión | ISSSTELEON',
|
||||||
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
loadComponent: () => import('./auth/login-page').then((m) => m.LoginPage),
|
||||||
data: { workspace: true, breadcrumb: 'Casos por estatus' },
|
// Sin encabezado ni pie: la pantalla ocupa la ventana completa.
|
||||||
|
data: { sinCromo: true },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'conectar',
|
// Todo lo demás vive detrás de la sesión; el guard corre en cada ruta hija.
|
||||||
title: 'Conectar datos | ISSSTELEON',
|
path: '',
|
||||||
// Lazy: the workspace (and the ~15 Material modules it uses) only
|
canActivateChild: [authGuard],
|
||||||
// downloads when someone actually opens it.
|
children: [
|
||||||
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
|
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||||
data: { workspace: true, breadcrumb: 'Conectar datos' },
|
{
|
||||||
|
path: 'indicadores/tea-estatus',
|
||||||
|
title: 'Casos por estatus | ISSSTELEON',
|
||||||
|
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
||||||
|
canActivate: [dominioGuard],
|
||||||
|
data: { workspace: true, breadcrumb: 'Casos por estatus', dominio: 'tea' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'conectar',
|
||||||
|
title: 'Conectar datos | ISSSTELEON',
|
||||||
|
// Lazy: the workspace (and the ~15 Material modules it uses) only
|
||||||
|
// downloads when someone actually opens it.
|
||||||
|
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
|
||||||
|
data: { workspace: true, breadcrumb: 'Conectar datos' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'gobernanza',
|
||||||
|
title: 'Gobernanza de modelos | ISSSTELEON',
|
||||||
|
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
|
||||||
|
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'bitacora',
|
||||||
|
title: 'Bitácora de cargas | ISSSTELEON',
|
||||||
|
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
|
||||||
|
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'kpis',
|
||||||
|
title: 'Indicadores | ISSSTELEON',
|
||||||
|
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
|
||||||
|
// The page reads CaCu's measures: an account of another domain goes to its own.
|
||||||
|
canActivate: [dominioGuard],
|
||||||
|
data: { workspace: true, breadcrumb: 'Indicadores', dominio: 'cacu' },
|
||||||
|
},
|
||||||
|
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||||
|
...DOMINIOS.map(dominio => ({
|
||||||
|
path: `indicadores/${dominio}`,
|
||||||
|
title: 'Indicadores | ISSSTELEON',
|
||||||
|
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
|
||||||
|
canActivate: [dominioGuard],
|
||||||
|
loadComponent: loadIndicadores,
|
||||||
|
})),
|
||||||
|
{ path: '**', redirectTo: '' },
|
||||||
|
],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
path: 'gobernanza',
|
|
||||||
title: 'Gobernanza de modelos | ISSSTELEON',
|
|
||||||
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
|
|
||||||
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: 'bitacora',
|
|
||||||
title: 'Bitácora de cargas | ISSSTELEON',
|
|
||||||
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
|
|
||||||
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: 'kpis',
|
|
||||||
title: 'Indicadores | ISSSTELEON',
|
|
||||||
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
|
|
||||||
data: { workspace: true, breadcrumb: 'Indicadores' },
|
|
||||||
},
|
|
||||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
|
||||||
...DOMINIOS.map(dominio => ({
|
|
||||||
path: `indicadores/${dominio}`,
|
|
||||||
title: 'Indicadores | ISSSTELEON',
|
|
||||||
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
|
|
||||||
loadComponent: loadIndicadores,
|
|
||||||
})),
|
|
||||||
{ path: '**', redirectTo: '' },
|
|
||||||
];
|
];
|
||||||
|
|||||||
+69
-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,12 +104,75 @@
|
|||||||
|
|
||||||
.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;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
/* Session exit: the same action look as the home buttons, in header size. */
|
||||||
@media (max-width: 599px) {
|
.site-header__salir {
|
||||||
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
align-items: center;
|
||||||
.app-shell--indicadores .brand { margin-inline-end: auto; }
|
background: transparent;
|
||||||
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
|
border: 1px solid var(--color-action);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: var(--color-text);
|
||||||
|
cursor: pointer;
|
||||||
|
display: inline-flex;
|
||||||
|
flex: none;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
gap: 6px;
|
||||||
|
margin-inline-start: var(--space-4);
|
||||||
|
min-height: 34px;
|
||||||
|
padding: 0 var(--space-3);
|
||||||
|
transition:
|
||||||
|
background-color 0.2s ease,
|
||||||
|
border-color 0.2s ease,
|
||||||
|
color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-header__salir:hover {
|
||||||
|
background: var(--color-action-hover);
|
||||||
|
border-color: var(--color-action);
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-header__salir:focus-visible {
|
||||||
|
outline: 2px solid var(--color-action);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-header__salir mat-icon {
|
||||||
|
color: var(--color-action);
|
||||||
|
font-size: 18px;
|
||||||
|
height: 18px;
|
||||||
|
width: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full domain names need their own track. On a wide header they sit beside the title;
|
||||||
|
// below 900px the name takes a row of its own so the logo and the exit stay together.
|
||||||
|
.app-shell--indicadores .site-header__content {
|
||||||
|
display: grid;
|
||||||
|
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; }
|
||||||
}
|
}
|
||||||
|
|||||||
+105
-25
@@ -1,46 +1,126 @@
|
|||||||
|
import { signal } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideRouter, Router } from '@angular/router';
|
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { provideRouter, Router } from '@angular/router';
|
||||||
|
import { of } from 'rxjs';
|
||||||
import { App } from './app';
|
import { App } from './app';
|
||||||
import { routes } from './app.routes';
|
import { routes } from './app.routes';
|
||||||
|
import { AuthService, Usuario } from './auth/auth.service';
|
||||||
|
|
||||||
|
const TODOS: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Doble de la sesión: `App` lee la señal y los guards preguntan si hay sesión y
|
||||||
|
* qué dominios alcanza. Las pruebas de este archivo cubren el marco, no el
|
||||||
|
* inicio de sesión en sí (`auth/auth.service.spec.ts`).
|
||||||
|
*/
|
||||||
|
function authFalso(sesion: Usuario | null) {
|
||||||
|
return {
|
||||||
|
usuario: signal(sesion),
|
||||||
|
autenticado: signal(sesion !== null),
|
||||||
|
sesion: () => of(sesion),
|
||||||
|
puedeVer: (dominio: string) => sesion?.dominios.includes(dominio) ?? false,
|
||||||
|
logout: () => of(undefined),
|
||||||
|
limpiar: () => undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function montar(sesion: Usuario | null): Promise<Router> {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [App],
|
||||||
|
providers: [
|
||||||
|
provideRouter(routes),
|
||||||
|
provideHttpClient(),
|
||||||
|
provideHttpClientTesting(),
|
||||||
|
{ provide: AuthService, useValue: authFalso(sesion) },
|
||||||
|
],
|
||||||
|
}).compileComponents();
|
||||||
|
return TestBed.inject(Router);
|
||||||
|
}
|
||||||
|
|
||||||
describe('App', () => {
|
describe('App', () => {
|
||||||
beforeEach(async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [App],
|
|
||||||
providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
|
|
||||||
}).compileComponents();
|
|
||||||
});
|
|
||||||
|
|
||||||
async function render(url: string) {
|
async function render(url: string) {
|
||||||
const fixture = TestBed.createComponent(App);
|
const fixture = TestBed.createComponent(App);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
await TestBed.inject(Router).navigateByUrl(url);
|
await TestBed.inject(Router).navigateByUrl(url).catch(() => false);
|
||||||
await fixture.whenStable();
|
await fixture.whenStable();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
return fixture.nativeElement as HTMLElement;
|
return fixture.nativeElement as HTMLElement;
|
||||||
}
|
}
|
||||||
|
|
||||||
it('renders the ISSSTELEON shell and home page with its footer', async () => {
|
describe('con sesión de administrador', () => {
|
||||||
const page = await render('/');
|
beforeEach(() => montar(TODOS));
|
||||||
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
|
|
||||||
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
|
it('renders the ISSSTELEON shell and home page with its footer', async () => {
|
||||||
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
|
const page = await render('/');
|
||||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
|
||||||
|
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
|
||||||
|
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
|
||||||
|
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('home shows only the brand name as eyebrow and names the risk models action', async () => {
|
||||||
|
// Fails if the eyebrow regains the section text or the action goes back to «Indicadores».
|
||||||
|
const page = await render('/');
|
||||||
|
expect(page.querySelector('.home__eyebrow')?.textContent?.trim()).toBe('ISSSTELEON');
|
||||||
|
const acciones = Array.from(page.querySelectorAll('.home__action')).map(a => a.textContent?.replace(/\s+/g, ' ').trim());
|
||||||
|
expect(acciones.some(t => t?.endsWith('Modelos predictivos de riesgo'))).toBe(true);
|
||||||
|
expect(acciones.some(t => t?.endsWith('Indicadores'))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||||
|
const page = await render('/conectar');
|
||||||
|
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||||
|
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
|
||||||
|
expect(page.querySelector('.site-footer')).toBeNull();
|
||||||
|
}, 15000);
|
||||||
|
|
||||||
|
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
|
||||||
|
const page = await render('/gobernanza');
|
||||||
|
expect(page.querySelector('app-governance-page')).not.toBeNull();
|
||||||
|
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
|
||||||
|
expect(page.querySelector('.site-footer')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el encabezado nombra al usuario de la sesión y ofrece cerrarla', async () => {
|
||||||
|
// Fails if the shell forgets the session: the user would have no way out.
|
||||||
|
const page = await render('/');
|
||||||
|
expect(page.querySelector('.site-header__salir')?.textContent).toContain('Administrador');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
describe('con una cuenta de un solo dominio', () => {
|
||||||
const page = await render('/conectar');
|
beforeEach(() => montar({ usuario: 'cacu', nombre: 'Equipo CaCu', dominios: ['cacu'] }));
|
||||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
|
||||||
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
|
it('no deja abrir el dominio ajeno: la manda al suyo', async () => {
|
||||||
expect(page.querySelector('.site-footer')).toBeNull();
|
// Fails if the domain scope exists only on the server: the interface would show an empty page.
|
||||||
|
await render('/indicadores/cama');
|
||||||
|
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
|
||||||
|
}, 15000);
|
||||||
|
|
||||||
|
it('el encabezado no ofrece los otros dominios', async () => {
|
||||||
|
const page = await render('/indicadores/cacu');
|
||||||
|
expect(page.querySelector('app-domain-selector')).toBeNull();
|
||||||
|
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('Cáncer cervicouterino');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
|
describe('sin sesión', () => {
|
||||||
const page = await render('/gobernanza');
|
beforeEach(() => montar(null));
|
||||||
expect(page.querySelector('app-governance-page')).not.toBeNull();
|
|
||||||
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
|
it('cualquier ruta manda al inicio de sesión y no muestra el marco', async () => {
|
||||||
expect(page.querySelector('.site-footer')).toBeNull();
|
const page = await render('/conectar');
|
||||||
|
expect(TestBed.inject(Router).url).toContain('/login');
|
||||||
|
expect(page.querySelector('.login')).not.toBeNull();
|
||||||
|
expect(page.querySelector('.site-header')).toBeNull();
|
||||||
|
expect(page.querySelector('.site-footer')).toBeNull();
|
||||||
|
expect(page.querySelector('app-connect-page')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el destino pedido viaja en returnUrl para volver después de entrar', async () => {
|
||||||
|
await render('/gobernanza');
|
||||||
|
expect(TestBed.inject(Router).url).toContain('returnUrl=%2Fgobernanza');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+25
-3
@@ -1,12 +1,14 @@
|
|||||||
import { Component, computed, inject } from '@angular/core';
|
import { Component, computed, inject } from '@angular/core';
|
||||||
import { toSignal } from '@angular/core/rxjs-interop';
|
import { toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||||
import { filter, map } from 'rxjs';
|
import { filter, map } from 'rxjs';
|
||||||
|
import { AuthService } from './auth/auth.service';
|
||||||
import { DomainSelector } from './domain-selector';
|
import { DomainSelector } from './domain-selector';
|
||||||
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
imports: [RouterLink, RouterOutlet, DomainSelector],
|
imports: [MatIconModule, RouterLink, RouterOutlet, DomainSelector],
|
||||||
selector: 'app-root',
|
selector: 'app-root',
|
||||||
styleUrl: './app.scss',
|
styleUrl: './app.scss',
|
||||||
templateUrl: './app.html',
|
templateUrl: './app.html',
|
||||||
@@ -14,6 +16,7 @@ import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
|||||||
export class App {
|
export class App {
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
|
|
||||||
private readonly leafRouteData = toSignal(
|
private readonly leafRouteData = toSignal(
|
||||||
this.router.events.pipe(
|
this.router.events.pipe(
|
||||||
@@ -30,13 +33,32 @@ export class App {
|
|||||||
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
|
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
|
||||||
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
|
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
|
||||||
readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
|
readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
|
||||||
|
/** The login screen (`data.sinCromo`) owns the whole window: no header, no footer. */
|
||||||
|
readonly sinCromo = computed(() => !!this.leafRouteData()['sinCromo']);
|
||||||
|
|
||||||
|
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. */
|
||||||
protected readonly activeDomain = computed(() =>
|
protected readonly activeDomain = computed(() =>
|
||||||
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
|
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
|
||||||
protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain()));
|
/** Only the domains the account may see: the header never offers a forbidden one. */
|
||||||
|
private readonly permitidos = computed<readonly Dominio[]>(() => {
|
||||||
|
const sesion = this.auth.usuario();
|
||||||
|
return sesion ? DOMINIOS.filter(dominio => sesion.dominios.includes(dominio)) : DOMINIOS;
|
||||||
|
});
|
||||||
|
protected readonly otherDomains = computed(() =>
|
||||||
|
this.permitidos().filter(domain => domain !== this.activeDomain()));
|
||||||
|
|
||||||
|
protected salir(): void {
|
||||||
|
// Whether the server session was already gone, the browser ends up at the login screen.
|
||||||
|
this.auth.logout().subscribe({
|
||||||
|
next: () => void this.router.navigate(['/login']),
|
||||||
|
error: () => void this.router.navigate(['/login']),
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { CanActivateFn, Router } from '@angular/router';
|
||||||
|
import { map } from 'rxjs';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sin sesión no hay ruta protegida: se manda al inicio de sesión y se recuerda
|
||||||
|
* `returnUrl` para volver a donde iba el usuario.
|
||||||
|
*/
|
||||||
|
export const authGuard: CanActivateFn = (_ruta, estado) => {
|
||||||
|
const auth = inject(AuthService);
|
||||||
|
const router = inject(Router);
|
||||||
|
return auth
|
||||||
|
.sesion()
|
||||||
|
.pipe(
|
||||||
|
map(
|
||||||
|
(usuario) =>
|
||||||
|
usuario !== null ||
|
||||||
|
router.createUrlTree(['/login'], { queryParams: { returnUrl: estado.url } }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// La sesión vive en el navegador (la WebApi no autentica): estas pruebas fijan
|
||||||
|
// el contrato del servicio —quién entra, qué dominios ve y qué queda guardado—
|
||||||
|
// porque de él dependen el guard de rutas y el recorte de los selectores.
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
describe('AuthService', () => {
|
||||||
|
let auth: AuthService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
sessionStorage.clear();
|
||||||
|
TestBed.configureTestingModule({});
|
||||||
|
auth = TestBed.inject(AuthService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('entra con la contraseña correcta y deja al usuario en la señal', () => {
|
||||||
|
auth.login('cama', 'cama2026').subscribe();
|
||||||
|
|
||||||
|
expect(auth.usuario()).toEqual({ usuario: 'cama', nombre: 'Equipo CaMa', dominios: ['cama'] });
|
||||||
|
expect(auth.autenticado()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rechaza una contraseña incorrecta sin abrir sesión', () => {
|
||||||
|
let error: Error | undefined;
|
||||||
|
auth.login('cama', 'otra').subscribe({ error: (e: Error) => (error = e) });
|
||||||
|
|
||||||
|
expect(error?.message).toContain('incorrectos');
|
||||||
|
expect(auth.autenticado()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dice qué dominios puede ver la cuenta', () => {
|
||||||
|
auth.login('cama', 'cama2026').subscribe();
|
||||||
|
|
||||||
|
expect(auth.puedeVer('cama')).toBe(true);
|
||||||
|
expect(auth.puedeVer('cacu')).toBe(false);
|
||||||
|
expect(auth.puedeVer('tea')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el administrador ve los tres dominios', () => {
|
||||||
|
auth.login('admin', 'admin2026').subscribe();
|
||||||
|
expect(['cacu', 'cama', 'tea'].every((dominio) => auth.puedeVer(dominio))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cerrar sesión borra al usuario y lo guardado', () => {
|
||||||
|
auth.login('tea', 'tea2026').subscribe();
|
||||||
|
auth.logout().subscribe();
|
||||||
|
|
||||||
|
expect(auth.autenticado()).toBe(false);
|
||||||
|
expect(sessionStorage.getItem('isssteleon.sesion')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('la sesión sobrevive a una recarga de la pestaña', () => {
|
||||||
|
// Fails if the login is kept only in memory: a refresh would log the team out mid-task.
|
||||||
|
auth.login('cacu', 'cacu2026').subscribe();
|
||||||
|
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
TestBed.configureTestingModule({});
|
||||||
|
expect(TestBed.inject(AuthService).usuario()?.usuario).toBe('cacu');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { Injectable, computed, signal } from '@angular/core';
|
||||||
|
import { Observable, of, throwError } from 'rxjs';
|
||||||
|
|
||||||
|
/** El usuario de la sesión, con los dominios que la interfaz le deja ver. */
|
||||||
|
export interface Usuario {
|
||||||
|
readonly usuario: string;
|
||||||
|
readonly nombre: string;
|
||||||
|
readonly dominios: readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cuentas de la interfaz. La WebApi no tiene autenticación: el inicio de sesión
|
||||||
|
* y el recorte por dominio viven aquí, en el navegador, para ordenar el trabajo
|
||||||
|
* de cada equipo. No son seguridad: cualquiera puede leer esta lista en el
|
||||||
|
* paquete de la aplicación y la API responde a quien la llame.
|
||||||
|
*/
|
||||||
|
const CUENTAS: readonly (Usuario & { contrasena: string })[] = [
|
||||||
|
{ usuario: 'admin', contrasena: 'admin2026', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] },
|
||||||
|
{ usuario: 'cacu', contrasena: 'cacu2026', nombre: 'Equipo CaCu', dominios: ['cacu'] },
|
||||||
|
{ usuario: 'cama', contrasena: 'cama2026', nombre: 'Equipo CaMa', dominios: ['cama'] },
|
||||||
|
{ usuario: 'tea', contrasena: 'tea2026', nombre: 'Equipo TEA', dominios: ['tea'] },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** La sesión se guarda por pestaña: cerrar el navegador pide entrar de nuevo. */
|
||||||
|
const CLAVE = 'isssteleon.sesion';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sesión local de la aplicación. Es la única fuente de verdad del usuario: el
|
||||||
|
* guard pregunta aquí, los paneles filtran dominios con `puedeVer` y salir solo
|
||||||
|
* borra el registro del navegador.
|
||||||
|
*/
|
||||||
|
@Injectable({ providedIn: 'root' })
|
||||||
|
export class AuthService {
|
||||||
|
private readonly usuarioActual = signal<Usuario | null>(this.leer());
|
||||||
|
readonly usuario = this.usuarioActual.asReadonly();
|
||||||
|
readonly autenticado = computed(() => this.usuarioActual() !== null);
|
||||||
|
|
||||||
|
/** Si la cuenta puede ver ese dominio. Sin sesión no se opina (los guards deciden). */
|
||||||
|
puedeVer(dominio: string): boolean {
|
||||||
|
const sesion = this.usuarioActual();
|
||||||
|
return sesion ? sesion.dominios.includes(dominio) : true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** La sesión guardada en esta pestaña; se resuelve al instante, sin servidor. */
|
||||||
|
sesion(): Observable<Usuario | null> {
|
||||||
|
return of(this.usuarioActual());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valida contra la lista local; un error marca las credenciales como incorrectas. */
|
||||||
|
login(usuario: string, contrasena: string): Observable<Usuario> {
|
||||||
|
const cuenta = CUENTAS.find((c) => c.usuario === usuario.trim() && c.contrasena === contrasena);
|
||||||
|
if (!cuenta) return throwError(() => new Error('usuario o contraseña incorrectos'));
|
||||||
|
const sesion: Usuario = { usuario: cuenta.usuario, nombre: cuenta.nombre, dominios: [...cuenta.dominios] };
|
||||||
|
this.establecer(sesion);
|
||||||
|
return of(sesion);
|
||||||
|
}
|
||||||
|
|
||||||
|
logout(): Observable<void> {
|
||||||
|
this.limpiar();
|
||||||
|
return of(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
limpiar(): void {
|
||||||
|
this.usuarioActual.set(null);
|
||||||
|
try {
|
||||||
|
sessionStorage.removeItem(CLAVE);
|
||||||
|
} catch {
|
||||||
|
// Almacenamiento deshabilitado: la sesión dura lo que la pestaña en memoria.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private establecer(sesion: Usuario): void {
|
||||||
|
this.usuarioActual.set(sesion);
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(CLAVE, JSON.stringify(sesion));
|
||||||
|
} catch {
|
||||||
|
// Idem: sin almacenamiento, la sesión no sobrevive a una recarga.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private leer(): Usuario | null {
|
||||||
|
try {
|
||||||
|
const crudo = sessionStorage.getItem(CLAVE);
|
||||||
|
if (!crudo) return null;
|
||||||
|
const sesion = JSON.parse(crudo) as Usuario;
|
||||||
|
return typeof sesion?.usuario === 'string' && Array.isArray(sesion.dominios) ? sesion : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { Usuario } from './auth.service';
|
||||||
|
|
||||||
|
/** Same key AuthService persists the visual session under. */
|
||||||
|
const CLAVE_SESION = 'isssteleon.sesion';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seeds the browser-only visual session before the router and AuthService are created,
|
||||||
|
* so routes behind authGuard render instead of redirecting to /login. Pair every call
|
||||||
|
* with `limpiarSesionVisual()` in afterEach so the session never leaks between tests.
|
||||||
|
*/
|
||||||
|
export function iniciarSesionVisual(sesion: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] }): void {
|
||||||
|
sessionStorage.setItem(CLAVE_SESION, JSON.stringify(sesion));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function limpiarSesionVisual(): void {
|
||||||
|
sessionStorage.removeItem(CLAVE_SESION);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { inject } from '@angular/core';
|
||||||
|
import { CanActivateFn, Router } from '@angular/router';
|
||||||
|
import { map } from 'rxjs';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cada cuenta ve solo sus dominios: una ruta con `data.dominio` ajeno manda a la
|
||||||
|
* cuenta a su primer dominio. Sin sesión no decide nada (`authGuard` ya la
|
||||||
|
* mandó al inicio de sesión).
|
||||||
|
*/
|
||||||
|
export const dominioGuard: CanActivateFn = (ruta) => {
|
||||||
|
const auth = inject(AuthService);
|
||||||
|
const router = inject(Router);
|
||||||
|
const pedido = ruta.data?.['dominio'] as string | undefined;
|
||||||
|
return auth.sesion().pipe(
|
||||||
|
map((usuario) => {
|
||||||
|
if (!usuario || !pedido || usuario.dominios.includes(pedido)) return true;
|
||||||
|
const propio = usuario.dominios[0];
|
||||||
|
return propio ? router.createUrlTree(['/indicadores', propio]) : router.createUrlTree(['/']);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helpers for the screens that list domains (cargar información, gobernanza):
|
||||||
|
* an account only ever sees its own, and «Todos» only belongs to one that
|
||||||
|
* reaches every domain — the administrator.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** De la lista dada, las entradas cuyo dominio alcanza la cuenta. */
|
||||||
|
export function dominiosPermitidos<T extends { id: string }>(auth: AuthService, dominios: readonly T[]): T[] {
|
||||||
|
return dominios.filter((dominio) => auth.puedeVer(dominio.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Si la cuenta alcanza todos: solo entonces tiene sentido ofrecer «Todos». */
|
||||||
|
export function alcanzaTodos(auth: AuthService, dominios: readonly { id: string }[]): boolean {
|
||||||
|
return dominios.every((dominio) => auth.puedeVer(dominio.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El dominio con el que abre una pantalla: el único que alcanza la cuenta, o
|
||||||
|
* `null` («Todos») cuando alcanza varios. Sin sesión resuelta devuelve `null`,
|
||||||
|
* que es el comportamiento de siempre.
|
||||||
|
*/
|
||||||
|
export function dominioInicial<T extends string>(auth: AuthService, dominios: readonly { id: T }[]): T | null {
|
||||||
|
const propios = dominiosPermitidos(auth, dominios);
|
||||||
|
return propios.length === 1 ? propios[0].id : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<section class="login" aria-labelledby="login-titulo">
|
||||||
|
<div class="login__caja">
|
||||||
|
<img class="login__logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||||
|
|
||||||
|
<h1 class="login__titulo" id="login-titulo">Inicio de sesión</h1>
|
||||||
|
|
||||||
|
<form class="login__formulario" (ngSubmit)="ingresar()" novalidate>
|
||||||
|
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
|
||||||
|
<input
|
||||||
|
matInput
|
||||||
|
name="usuario"
|
||||||
|
[(ngModel)]="usuario"
|
||||||
|
placeholder="Usuario"
|
||||||
|
aria-label="Usuario"
|
||||||
|
autocomplete="username"
|
||||||
|
autocapitalize="none"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
|
||||||
|
<input
|
||||||
|
matInput
|
||||||
|
name="contrasena"
|
||||||
|
[(ngModel)]="contrasena"
|
||||||
|
[type]="verContrasena() ? 'text' : 'password'"
|
||||||
|
placeholder="Contraseña"
|
||||||
|
aria-label="Contraseña"
|
||||||
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
mat-icon-button
|
||||||
|
matSuffix
|
||||||
|
type="button"
|
||||||
|
class="login__ojo"
|
||||||
|
(click)="mostrarContrasena()"
|
||||||
|
[attr.aria-label]="verContrasena() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
|
||||||
|
[attr.aria-pressed]="verContrasena()"
|
||||||
|
>
|
||||||
|
<mat-icon>{{ verContrasena() ? 'visibility_off' : 'visibility' }}</mat-icon>
|
||||||
|
</button>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
@if (error(); as mensaje) {
|
||||||
|
<p class="login__error" role="alert">{{ mensaje }}</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="login__ingresar"
|
||||||
|
[disabled]="!usuario.trim() || !contrasena || enviando()"
|
||||||
|
>
|
||||||
|
{{ enviando() ? 'Ingresando…' : 'Ingresar' }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="login__legal">©{{ anio }} Todos los derechos reservados.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
:host {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
|
||||||
|
/* The button borrows the home actions' palette: white with a thin gray border
|
||||||
|
until the form is complete, then `--color-action` (see styles.scss). */
|
||||||
|
--login-fondo: #f8f9fa;
|
||||||
|
--login-borde: #e9ecef;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login {
|
||||||
|
align-items: center;
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
justify-content: center;
|
||||||
|
/* The whole block sits a little below the middle: the logo above it gives the screen its weight. */
|
||||||
|
padding: var(--space-9) var(--space-5) var(--space-8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__caja {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-4);
|
||||||
|
max-width: 340px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The brand opens the screen and is the biggest thing on it: it is what fills the empty space. */
|
||||||
|
.login__logo {
|
||||||
|
align-self: center;
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0;
|
||||||
|
width: 260px;
|
||||||
|
animation: login-logo-entrada 600ms ease-out both;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes login-logo-entrada {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-8px);
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.login__logo {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__titulo {
|
||||||
|
align-items: center;
|
||||||
|
color: var(--color-text);
|
||||||
|
display: flex;
|
||||||
|
font-family: var(--font-heading);
|
||||||
|
font-size: 1.375rem;
|
||||||
|
font-weight: 600;
|
||||||
|
gap: var(--space-4);
|
||||||
|
margin: 0 0 var(--space-2);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The two rules that flank the title, as in the reference screen. */
|
||||||
|
.login__titulo::before,
|
||||||
|
.login__titulo::after {
|
||||||
|
background: var(--color-border);
|
||||||
|
content: '';
|
||||||
|
flex: 1;
|
||||||
|
height: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__formulario {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__campo {
|
||||||
|
width: 100%;
|
||||||
|
--mat-form-field-container-height: 44px;
|
||||||
|
--mat-form-field-container-vertical-padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__ojo {
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Edge paints its own reveal control over the password field; the eye in the field is ours. */
|
||||||
|
.login__campo input::-ms-reveal,
|
||||||
|
.login__campo input::-ms-clear {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__error {
|
||||||
|
color: var(--mat-sys-error);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
margin: calc(-1 * var(--space-1)) 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The button shares the fields' width: one column, one border, no icon and no underline.
|
||||||
|
Its border turns teal when the form is complete, and it fades in instead of switching. */
|
||||||
|
.login__ingresar {
|
||||||
|
align-items: center;
|
||||||
|
background: var(--login-fondo);
|
||||||
|
border: 1px solid var(--login-borde);
|
||||||
|
border-radius: 10px;
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
cursor: default;
|
||||||
|
display: flex;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
font-weight: 500;
|
||||||
|
justify-content: center;
|
||||||
|
margin-top: var(--space-2);
|
||||||
|
min-height: 46px;
|
||||||
|
padding: 0 var(--space-5);
|
||||||
|
text-decoration: none;
|
||||||
|
transition:
|
||||||
|
background-color 260ms ease,
|
||||||
|
border-color 260ms ease,
|
||||||
|
color 260ms ease;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__ingresar:not(:disabled) {
|
||||||
|
border-color: var(--color-action);
|
||||||
|
color: var(--color-text);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__ingresar:hover:not(:disabled) {
|
||||||
|
background: var(--color-action-hover);
|
||||||
|
border-color: var(--color-action);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__ingresar:focus-visible {
|
||||||
|
outline: 2px solid var(--color-action);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__ingresar:disabled {
|
||||||
|
background: var(--login-fondo);
|
||||||
|
border-color: var(--login-borde);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__legal {
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
margin: var(--space-4) 0 0;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.login {
|
||||||
|
padding: var(--space-7) var(--space-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__caja {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login__logo {
|
||||||
|
width: 208px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatInputModule } from '@angular/material/input';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inicio de sesión: valida contra las cuentas locales de `AuthService` y, si el
|
||||||
|
* usuario ya tiene sesión, salta al destino. `returnUrl` lo pone el guard cuando
|
||||||
|
* una ruta protegida lo trajo aquí.
|
||||||
|
*/
|
||||||
|
@Component({
|
||||||
|
selector: 'app-login-page',
|
||||||
|
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
|
||||||
|
styleUrl: './login-page.scss',
|
||||||
|
templateUrl: './login-page.html',
|
||||||
|
})
|
||||||
|
export class LoginPage implements OnInit {
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
private readonly ruta = inject(ActivatedRoute);
|
||||||
|
|
||||||
|
protected usuario = '';
|
||||||
|
protected contrasena = '';
|
||||||
|
protected readonly verContrasena = signal(false);
|
||||||
|
protected readonly enviando = signal(false);
|
||||||
|
protected readonly error = signal<string | null>(null);
|
||||||
|
protected readonly anio = new Date().getFullYear();
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
// Quien ya inició sesión y abre /login vuelve derecho a la aplicación.
|
||||||
|
this.auth.sesion().subscribe((usuario) => {
|
||||||
|
if (usuario) void this.router.navigateByUrl(this.destino());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected ingresar(): void {
|
||||||
|
if (!this.usuario.trim() || !this.contrasena || this.enviando()) return;
|
||||||
|
this.enviando.set(true);
|
||||||
|
this.error.set(null);
|
||||||
|
this.auth.login(this.usuario.trim(), this.contrasena).subscribe({
|
||||||
|
next: () => void this.router.navigateByUrl(this.destino()),
|
||||||
|
error: () => {
|
||||||
|
this.enviando.set(false);
|
||||||
|
this.error.set('Usuario o contraseña incorrectos.');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected mostrarContrasena(): void {
|
||||||
|
this.verContrasena.update((visible) => !visible);
|
||||||
|
}
|
||||||
|
|
||||||
|
private destino(): string {
|
||||||
|
const pedido = this.ruta.snapshot.queryParamMap.get('returnUrl');
|
||||||
|
return pedido?.startsWith('/') && !pedido.startsWith('/login') ? pedido : '/';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
aria-label="Base de datos destino"
|
aria-label="Base de datos destino"
|
||||||
[matTooltip]="store.domainLocked() ? 'Una carga va a una sola base; quita los flujos para cambiarla' : 'Base de datos destino'"
|
[matTooltip]="store.domainLocked() ? 'Una carga va a una sola base; quita los flujos para cambiarla' : 'Base de datos destino'"
|
||||||
>
|
>
|
||||||
@for (domain of domains; track domain.id) {
|
@for (domain of domains(); track domain.id) {
|
||||||
<mat-button-toggle [value]="domain.id" [attr.aria-label]="domain.description">{{ domain.label }}</mat-button-toggle>
|
<mat-button-toggle [value]="domain.id" [attr.aria-label]="domain.description">{{ domain.label }}</mat-button-toggle>
|
||||||
}
|
}
|
||||||
</mat-button-toggle-group>
|
</mat-button-toggle-group>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { DragDropModule } from '@angular/cdk/drag-drop';
|
import { DragDropModule } from '@angular/cdk/drag-drop';
|
||||||
import { DecimalPipe } from '@angular/common';
|
import { DecimalPipe } from '@angular/common';
|
||||||
import { Component, Injector, inject, signal } from '@angular/core';
|
import { Component, Injector, computed, inject, signal } from '@angular/core';
|
||||||
import { MatBadgeModule } from '@angular/material/badge';
|
import { MatBadgeModule } from '@angular/material/badge';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||||
@@ -12,6 +12,8 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
|||||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
import { Domain, TargetMeta } from '../../api/api.types';
|
import { Domain, TargetMeta } from '../../api/api.types';
|
||||||
|
import { AuthService } from '../../../auth/auth.service';
|
||||||
|
import { dominiosPermitidos } from '../../../auth/dominios';
|
||||||
import { DataConnection, SourceTable } from '../../domain/data-source';
|
import { DataConnection, SourceTable } from '../../domain/data-source';
|
||||||
import { PdfConnection } from '../../domain/pdf-source';
|
import { PdfConnection } from '../../domain/pdf-source';
|
||||||
import { SqlConnection } from '../../domain/sql-source';
|
import { SqlConnection } from '../../domain/sql-source';
|
||||||
@@ -59,11 +61,13 @@ import { SqlQueryDialog, SqlQueryResult } from '../sql-query-dialog/sql-query-di
|
|||||||
})
|
})
|
||||||
export class ConnectPage {
|
export class ConnectPage {
|
||||||
readonly store = inject(ConnectWorkspaceStore);
|
readonly store = inject(ConnectWorkspaceStore);
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
private readonly dialog = inject(MatDialog);
|
private readonly dialog = inject(MatDialog);
|
||||||
private readonly snackBar = inject(MatSnackBar);
|
private readonly snackBar = inject(MatSnackBar);
|
||||||
private readonly injector = inject(Injector);
|
private readonly injector = inject(Injector);
|
||||||
|
|
||||||
readonly domains = DOMAINS;
|
/** Only the account's own databases: the picker never offers a domain the server will reject. */
|
||||||
|
readonly domains = computed(() => dominiosPermitidos(this.auth, DOMAINS));
|
||||||
readonly paneOpen = signal(true);
|
readonly paneOpen = signal(true);
|
||||||
readonly validatingAll = signal(false);
|
readonly validatingAll = signal(false);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { Observable, firstValueFrom, of } from 'rxjs';
|
import { Observable, firstValueFrom, of } from 'rxjs';
|
||||||
|
import { AuthService } from '../../auth/auth.service';
|
||||||
import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types';
|
import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types';
|
||||||
import { ImportsApi } from '../api/imports.api';
|
import { ImportsApi } from '../api/imports.api';
|
||||||
import { SourceGateway } from '../api/source-gateway';
|
import { SourceGateway } from '../api/source-gateway';
|
||||||
@@ -32,6 +33,8 @@ describe('ConnectWorkspaceStore', () => {
|
|||||||
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
|
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
|
||||||
{ provide: ImportsApi, useValue: imports },
|
{ provide: ImportsApi, useValue: imports },
|
||||||
{ provide: SourceGateway, useValue: {} },
|
{ provide: SourceGateway, useValue: {} },
|
||||||
|
// Sin sesión resuelta el alcance es todo; el caso restringido se arma en su propia prueba.
|
||||||
|
{ provide: AuthService, useValue: { puedeVer: () => true } },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
store = TestBed.inject(ConnectWorkspaceStore);
|
store = TestBed.inject(ConnectWorkspaceStore);
|
||||||
@@ -52,6 +55,25 @@ describe('ConnectWorkspaceStore', () => {
|
|||||||
expect(store.domain()).toBe('cacu');
|
expect(store.domain()).toBe('cacu');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('opens on the account\'s own domain and refuses the others', () => {
|
||||||
|
// Fails if the destination database ignores the session: a CaMa team could load into CaCu's database.
|
||||||
|
TestBed.resetTestingModule();
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
ConnectWorkspaceStore,
|
||||||
|
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
|
||||||
|
{ provide: ImportsApi, useValue: imports },
|
||||||
|
{ provide: SourceGateway, useValue: {} },
|
||||||
|
{ provide: AuthService, useValue: { puedeVer: (dominio: string) => dominio === 'cama' } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const restringido = TestBed.inject(ConnectWorkspaceStore);
|
||||||
|
|
||||||
|
expect(restringido.domain()).toBe('cama');
|
||||||
|
restringido.setDomain('cacu');
|
||||||
|
expect(restringido.domain()).toBe('cama');
|
||||||
|
});
|
||||||
|
|
||||||
it('removing a connection removes the flows built on its tables', () => {
|
it('removing a connection removes the flows built on its tables', () => {
|
||||||
const { connection } = flowFrom('a.csv', PACIENTE);
|
const { connection } = flowFrom('a.csv', PACIENTE);
|
||||||
flowFrom('b.csv', PACIENTE);
|
flowFrom('b.csv', PACIENTE);
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { Injectable, computed, inject, signal } from '@angular/core';
|
|||||||
import { toSignal } from '@angular/core/rxjs-interop';
|
import { toSignal } from '@angular/core/rxjs-interop';
|
||||||
import { Observable, catchError, from, of, switchMap, tap } from 'rxjs';
|
import { Observable, catchError, from, of, switchMap, tap } from 'rxjs';
|
||||||
import { BatchResult, ConflictStrategy, ConnectorInfo, Domain, TargetMeta, apiErrorMessage } from '../api/api.types';
|
import { BatchResult, ConflictStrategy, ConnectorInfo, Domain, TargetMeta, apiErrorMessage } from '../api/api.types';
|
||||||
|
import { AuthService } from '../../auth/auth.service';
|
||||||
|
import { dominiosPermitidos } from '../../auth/dominios';
|
||||||
import { ConnectorsApi } from '../api/connectors.api';
|
import { ConnectorsApi } from '../api/connectors.api';
|
||||||
import { ImportsApi } from '../api/imports.api';
|
import { ImportsApi } from '../api/imports.api';
|
||||||
import { SourceGateway } from '../api/source-gateway';
|
import { SourceGateway } from '../api/source-gateway';
|
||||||
@@ -11,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' },
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,6 +31,7 @@ export const DOMAINS: { id: Domain; label: string; description: string }[] = [
|
|||||||
export class ConnectWorkspaceStore {
|
export class ConnectWorkspaceStore {
|
||||||
private readonly gateway = inject(SourceGateway);
|
private readonly gateway = inject(SourceGateway);
|
||||||
private readonly importsApi = inject(ImportsApi);
|
private readonly importsApi = inject(ImportsApi);
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
|
|
||||||
private readonly targetsError = signal<string | null>(null);
|
private readonly targetsError = signal<string | null>(null);
|
||||||
readonly allTargets = toSignal(
|
readonly allTargets = toSignal(
|
||||||
@@ -50,7 +53,8 @@ export class ConnectWorkspaceStore {
|
|||||||
});
|
});
|
||||||
readonly acceptedExtensions = computed(() => acceptedExtensions(this.connectors()));
|
readonly acceptedExtensions = computed(() => acceptedExtensions(this.connectors()));
|
||||||
|
|
||||||
private readonly _domain = signal<Domain>('cacu');
|
/** The destination database: the account's own when it only reaches one. */
|
||||||
|
private readonly _domain = signal<Domain>(this.dominioInicial());
|
||||||
private readonly _connections = signal<DataConnection[]>([]);
|
private readonly _connections = signal<DataConnection[]>([]);
|
||||||
private readonly _flows = signal<ImportFlow[]>([]);
|
private readonly _flows = signal<ImportFlow[]>([]);
|
||||||
private readonly _selectedFlowId = signal<string | null>(null);
|
private readonly _selectedFlowId = signal<string | null>(null);
|
||||||
@@ -128,7 +132,12 @@ export class ConnectWorkspaceStore {
|
|||||||
});
|
});
|
||||||
|
|
||||||
setDomain(domain: Domain): void {
|
setDomain(domain: Domain): void {
|
||||||
if (!this.domainLocked()) this._domain.set(domain);
|
if (!this.domainLocked() && this.auth.puedeVer(domain)) this._domain.set(domain);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first domain the account may see; every account has at least one (`WebApi` gives none other). */
|
||||||
|
private dominioInicial(): Domain {
|
||||||
|
return dominiosPermitidos(this.auth, DOMAINS)[0]?.id ?? 'cacu';
|
||||||
}
|
}
|
||||||
|
|
||||||
setOnConflict(strategy: ConflictStrategy): void {
|
setOnConflict(strategy: ConflictStrategy): void {
|
||||||
|
|||||||
@@ -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; }
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
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; }
|
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; 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 {
|
||||||
@@ -9,13 +11,20 @@ export interface SeguimientoPaciente {
|
|||||||
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;
|
||||||
}
|
}
|
||||||
|
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 };
|
filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number };
|
||||||
|
/** 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 };
|
||||||
@@ -29,3 +38,15 @@ export function isoDate(value: unknown): value is string {
|
|||||||
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',
|
||||||
|
};
|
||||||
|
|||||||
@@ -3,11 +3,20 @@ import { HttpClient, HttpParams } from '@angular/common/http';
|
|||||||
import { map } from 'rxjs';
|
import { map } from 'rxjs';
|
||||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||||
import { identidadDe, identidadesDe } from './paciente-identidad';
|
import { identidadDe, identidadesDe } from './paciente-identidad';
|
||||||
|
import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
const 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'];
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||||
// The current authorization covers demonstration records only. Validate this
|
// The current authorization covers demonstration records only. Validate this
|
||||||
@@ -16,15 +25,18 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
|||||||
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['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' || !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']);
|
||||||
}) || !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;
|
||||||
}
|
}
|
||||||
@@ -36,6 +48,8 @@ export class CacuSeguimientoService {
|
|||||||
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);
|
||||||
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,12 +36,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 +78,76 @@ 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);
|
||||||
});
|
});
|
||||||
|
it('busca parcialmente por identificador en la página, conserva la búsqueda al paginar y permite limpiarla', () => {
|
||||||
|
const items = fixtureData.items.slice(0, 2).map((item, i) => ({ ...item, id_seudonimo: ['PRUEBA-Á42', 'PRUEBA-73'][i] }));
|
||||||
|
const pagina = { ...fixtureData, items };
|
||||||
|
open().flush(pagina);
|
||||||
|
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
|
||||||
|
fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
const escribir = (texto: string) => {
|
||||||
|
const input = root.querySelector<HTMLInputElement>('input[type="search"]')!;
|
||||||
|
input.value = texto;
|
||||||
|
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
fixture.detectChanges();
|
||||||
|
};
|
||||||
|
escribir(' a42 ');
|
||||||
|
expect(root.querySelectorAll('tr[data-paciente]')).toHaveLength(1);
|
||||||
|
expect(root.querySelector('tr[data-paciente]')?.textContent).toContain('PRUEBA-Á42');
|
||||||
|
expect(root.querySelector('#alcance-busqueda-cacu')?.textContent).toContain('1 de 2 registros de esta página');
|
||||||
|
http.expectNone(() => true);
|
||||||
|
|
||||||
|
root.querySelectorAll<HTMLButtonElement>('nav button')[1].click();
|
||||||
|
const siguiente = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page') === '2');
|
||||||
|
expect(siguiente.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
||||||
|
siguiente.flush({ ...pagina, items: items.slice(1), paginacion: { ...pagina.paginacion, page: 2 } });
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(root.textContent).toContain('No hay coincidencias en esta página.');
|
||||||
|
expect(root.querySelector<HTMLInputElement>('input[type="search"]')?.value).toBe(' a42 ');
|
||||||
|
[...root.querySelectorAll('button')].find(button => button.textContent === 'Limpiar búsqueda')!.click();
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(root.querySelectorAll('tr[data-paciente]')).toHaveLength(1);
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('muestra el grupo de edad y señala la ausencia de edad exacta y fecha de nacimiento', () => {
|
||||||
|
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(root.querySelector('td small')?.textContent).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).toBe('No disponible');
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it.each(['Excel', 'PDF'])('la exportación %s usa el contrato y los filtros aplicados de CaCu, incluso con la búsqueda de página activa', 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.componentInstance.busquedaCaCu = 'no coincide';
|
||||||
|
fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect(root.querySelector('tr[data-paciente]')).toBeNull();
|
||||||
|
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');
|
||||||
@@ -96,4 +167,50 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
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,70 @@
|
|||||||
|
import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, 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']),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
): SeguimientoTablaResponse {
|
||||||
|
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: true,
|
||||||
|
corte: respuesta.corte,
|
||||||
|
ventana: respuesta.ventana,
|
||||||
|
paginacion: respuesta.paginacion,
|
||||||
|
filtros: { estatus, orden: orden ?? 'reciente', horizonte: horizonte?.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'}` })) },
|
||||||
|
],
|
||||||
|
columnas: [
|
||||||
|
{ clave: identidad, etiqueta: ETIQUETA_IDENTIDAD[identidad] },
|
||||||
|
{ clave: 'grupo_edad', etiqueta: 'Grupo de 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: 'reciente', etiqueta: 'Estudio más reciente' },
|
||||||
|
{ clave: 'dias', etiqueta: 'Días de toma a diagnóstico' },
|
||||||
|
{ clave: 'prioridad', etiqueta: 'Prioridad' },
|
||||||
|
],
|
||||||
|
items: respuesta.items.map(item => ({
|
||||||
|
[identidad]: identidadDe(item)!.id,
|
||||||
|
grupo_edad: item.grupo_edad === 'sin_dato' ? null : item.grupo_edad,
|
||||||
|
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)])),
|
||||||
|
reciente: latestStudy(item),
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
|||||||
@@ -24,17 +24,21 @@ 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, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||||
template: `
|
template: `
|
||||||
<mat-card>
|
<mat-card>
|
||||||
<header>
|
@if (!conteos) {
|
||||||
<div class="card-identity">
|
<header>
|
||||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
<div class="card-identity">
|
||||||
</div>
|
<h2 [id]="titleId" tabindex="-1" [class.con-ayuda]="dominio === 'tea'">{{ indicador.titulo }}</h2>
|
||||||
</header>
|
</div>
|
||||||
|
</header>
|
||||||
|
}
|
||||||
@if (!sobrio) {
|
@if (!sobrio) {
|
||||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
||||||
@@ -42,7 +46,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||||
</button>
|
</button>
|
||||||
}
|
}
|
||||||
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
|
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="conteos ? null : titleId">
|
||||||
@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">
|
||||||
@@ -62,7 +66,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
</div>
|
</div>
|
||||||
} @else if (conteos; as par) {
|
} @else if (conteos; as par) {
|
||||||
<div #visibilityRegion class="conteos-region">
|
<div #visibilityRegion class="conteos-region">
|
||||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
|
||||||
</div>
|
</div>
|
||||||
} @else if (selectedFigure) {
|
} @else if (selectedFigure) {
|
||||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||||
@@ -79,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; }
|
||||||
@@ -106,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; }
|
||||||
@@ -133,15 +139,17 @@ 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); }
|
||||||
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 ?? ''); }
|
||||||
@@ -168,6 +176,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
|||||||
@Input({ required: true }) applied!: GlobalApplied;
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
@Input() independentPeriods = false;
|
@Input() independentPeriods = false;
|
||||||
@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>;
|
||||||
|
|||||||
@@ -33,15 +33,20 @@
|
|||||||
@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 {
|
||||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista 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>
|
||||||
|
|||||||
@@ -5,6 +5,15 @@ p, h3, summary { overflow-wrap: anywhere; }
|
|||||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
.selection-status { font-weight: 600; }
|
.selection-status { font-weight: 600; }
|
||||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||||
|
.families { display: flex; flex-wrap: wrap; gap: .75rem; }
|
||||||
|
.family { flex: 1 1 16rem; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--issste-border); border-radius: 1rem; background: var(--issste-surface); }
|
||||||
|
.family button { display: inline-flex; align-items: center; gap: .55rem; }
|
||||||
|
.family .parent { width: 100%; justify-content: flex-start; border: 0; border-radius: 0; border-bottom: 1px solid var(--issste-border); font-weight: 650; background: color-mix(in srgb, var(--swatch) 14%, var(--issste-surface)); }
|
||||||
|
.family .children { display: flex; flex-wrap: wrap; gap: .4rem; padding: .55rem; }
|
||||||
|
.family .child { flex: 1 1 8rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); }
|
||||||
|
.family .parent[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 24%, var(--issste-surface)); box-shadow: inset 0 -3px 0 var(--swatch); }
|
||||||
|
.family .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); transform: scale(1.03); }
|
||||||
|
.family .swatch { width: .35rem; height: 1.15rem; border: 0; border-radius: .2rem; background: var(--swatch); }
|
||||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||||
.legend > button { justify-self: start; }
|
.legend > button { justify-self: start; }
|
||||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||||
@@ -26,6 +35,23 @@ 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; }
|
||||||
|
.histo-meta { display: flex; justify-content: flex-end; align-items: flex-start; gap: .75rem; margin: -.85rem -.65rem 0 0; }
|
||||||
|
.view-context { display: flex; flex-direction: column; align-items: flex-end; gap: .1rem; margin: .2rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; }
|
||||||
|
.histo .figure { border-top: 0; }
|
||||||
|
.histo .figure + .figure { border-top: 1px solid var(--issste-border); padding-top: .25rem; }
|
||||||
|
.histo .help { position: relative; display: flex; justify-content: flex-end; padding-bottom: 0; }
|
||||||
|
.histo .help .methodology-toggle { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; font-weight: 800; font-size: 1rem; line-height: 1; background: var(--issste-accent); color: var(--issste-on-accent); }
|
||||||
|
.histo .help .methodology { position: absolute; z-index: 8; top: 100%; right: 0; width: min(34rem, calc(100vw - 2rem)); max-height: 18rem; overflow: auto; background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
|
||||||
|
.histo .legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
|
||||||
|
.histo .tab-bar { display: flex; align-items: flex-end; gap: .5rem; border-bottom: 1px solid var(--issste-border); }
|
||||||
|
.histo .tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
|
||||||
|
.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; }
|
||||||
|
.histo .tabs .tab[aria-selected=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; }
|
||||||
|
.histo .child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
|
||||||
|
.histo .tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
|
||||||
|
.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); }
|
||||||
|
.histo .tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); }
|
||||||
|
.histo .tab .swatch, .histo .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
|
||||||
.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; }
|
||||||
@@ -34,4 +60,20 @@ 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). */
|
/* Rates on the left, donut on the right (the reverse of EU7). */
|
||||||
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); } }
|
@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; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.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; }
|
||||||
|
|||||||
@@ -1,21 +1,4 @@
|
|||||||
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
|
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
|
||||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
|
||||||
@if (helpOpen) {
|
|
||||||
<div class="methodology">
|
|
||||||
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
|
|
||||||
<h3>Dona por categoría</h3>
|
|
||||||
@if (donutGuide; as guide) {
|
|
||||||
@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> }
|
|
||||||
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
|
||||||
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
|
|
||||||
</section>
|
|
||||||
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
|
|
||||||
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
|
|
||||||
<p>Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
|
|
||||||
</section>
|
|
||||||
</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" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
|
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
|
||||||
@@ -24,6 +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 BI-RADS 4, 5 ó 6 en ' + 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>
|
||||||
@@ -32,22 +17,43 @@
|
|||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
<div class="figures">
|
<div class="figures">
|
||||||
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
<section class="figure">
|
||||||
|
<div class="figure-head">
|
||||||
|
<h3>{{ tituloMastografias }}</h3>
|
||||||
|
<div class="help" (mouseenter)="openHelp('examenes')" (mouseleave)="hideHelp('examenes')" (focusin)="openHelp('examenes')" (focusout)="onHelpFocusOut('examenes', $event)">
|
||||||
|
<button type="button" class="help-icon" aria-label="Cómo leer, mastografías por categoría" [attr.aria-expanded]="helpWhich === 'examenes'"
|
||||||
|
[attr.aria-describedby]="helpWhich === 'examenes' ? 'cama-birads-ayuda-mastografias' : null" (click)="toggleHelp('examenes')"><span aria-hidden="true">!</span></button>
|
||||||
|
@if (helpWhich === 'examenes') {
|
||||||
|
<div class="methodology" id="cama-birads-ayuda-mastografias" role="tooltip">Cada mastografía cuenta en su propia categoría.</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@if (total) {
|
@if (total) {
|
||||||
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="tituloMastografias" />
|
||||||
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
||||||
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||||
</section>
|
</section>
|
||||||
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
|
<section class="figure">
|
||||||
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
|
<div class="figure-head">
|
||||||
|
<h3>{{ tituloPacientes }}</h3>
|
||||||
|
<div class="help" (mouseenter)="openHelp('pacientes')" (mouseleave)="hideHelp('pacientes')" (focusin)="openHelp('pacientes')" (focusout)="onHelpFocusOut('pacientes', $event)">
|
||||||
|
<button type="button" class="help-icon" aria-label="Cómo leer, pacientes por categoría" [attr.aria-expanded]="helpWhich === 'pacientes'"
|
||||||
|
[attr.aria-describedby]="helpWhich === 'pacientes' ? 'cama-birads-ayuda-pacientes' : null" (click)="toggleHelp('pacientes')"><span aria-hidden="true">!</span></button>
|
||||||
|
@if (helpWhich === 'pacientes') {
|
||||||
|
<div class="methodology" id="cama-birads-ayuda-pacientes" role="tooltip">La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@if (totalPacientes) {
|
||||||
|
<app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="tituloPacientes" />
|
||||||
|
} @else { <p role="status">{{ !m.pacientesVerificados ? 'Dona de pacientes no disponible hasta verificar la definición publicada.' : totalPacientes === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.pacientes + ' en el periodo.' }}</p> }
|
||||||
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
|
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<p class="note">Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.</p>
|
|
||||||
@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>
|
||||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||||
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
|
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más alta) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
|
||||||
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
|
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
|
||||||
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
|
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
@@ -3,16 +3,25 @@
|
|||||||
p, h3, summary { overflow-wrap: anywhere; }
|
p, h3, summary { overflow-wrap: anywhere; }
|
||||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
.figure-head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
|
||||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
.figure-head h3 { margin: 0; }
|
||||||
|
.help { display: flex; flex: none; justify-content: flex-end; }
|
||||||
|
.help .methodology { position: absolute; z-index: 8; inset-block-start: calc(100% + .35rem); inset-inline-end: 0;
|
||||||
|
box-sizing: border-box; inline-size: min(34rem, 100%); background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
|
||||||
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||||
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
||||||
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
|
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
|
||||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
|
||||||
.periods button:disabled { opacity: .5; cursor: default; }
|
.periods button:disabled { opacity: .5; cursor: default; }
|
||||||
// The two figures share the card in equal halves; one above the other on a narrow card.
|
// The two figures share the card in equal halves; one above the other on a narrow card.
|
||||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
.help-icon { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; background: var(--issste-accent); color: var(--issste-on-accent); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
|
||||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
.help-icon:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
|
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; }
|
||||||
|
.figure + .figure { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-4); padding-top: var(--issste-space-4); }
|
||||||
|
@media (min-width: 1100px) {
|
||||||
|
.figures { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||||
|
.figure + .figure { border-top: 0; margin-top: 0; padding-top: 0; border-inline-start: 1px solid var(--issste-border); padding-inline-start: var(--issste-space-6); }
|
||||||
|
}
|
||||||
app-plotly-chart { --plot-height: 400px; }
|
app-plotly-chart { --plot-height: 400px; }
|
||||||
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
|
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
|
||||||
.donut-chart { --plot-min-width: 230px; }
|
.donut-chart { --plot-min-width: 230px; }
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||||
import { HttpErrorResponse } from '@angular/common/http';
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { TitleCasePipe } from '@angular/common';
|
import { TitleCasePipe } from '@angular/common';
|
||||||
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 { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models';
|
||||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
import { 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 { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
|
import { ConteosIncompatibles, donaConteos, donaPacientes, ModeloConteos, modelosConteos, ParConteos, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-conteos-pareados',
|
selector: 'app-indicador-conteos-pareados',
|
||||||
@@ -25,35 +25,45 @@ export class IndicadorConteosPareados 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;
|
||||||
@Input() metadata?: IndicadorMetadatos;
|
|
||||||
readonly metadataRequested = output<void>();
|
|
||||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||||
message = '';
|
message = '';
|
||||||
periodIndex = 0;
|
periodIndex = 0;
|
||||||
pages: ModeloConteos[] = [];
|
pages: ModeloConteos[] = [];
|
||||||
donutFigure?: PlotlyFigure;
|
donutFigure?: PlotlyFigure;
|
||||||
barsFigure?: PlotlyFigure;
|
patientsFigure?: PlotlyFigure;
|
||||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||||
private subscription?: Subscription;
|
private subscription?: Subscription;
|
||||||
private key = '';
|
private key = '';
|
||||||
private loaded = false;
|
private loaded = false;
|
||||||
private anchoDona = 390;
|
private anchoDona = 390;
|
||||||
|
private anchoPacientes = 390;
|
||||||
|
|
||||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
get total() { return this.model ? totalExamenes(this.model) : null; }
|
||||||
|
get totalPacientes() { return this.model ? totalPacientes(this.model) : null; }
|
||||||
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
|
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
|
||||||
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
|
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
|
||||||
helpOpen = false;
|
helpWhich: 'examenes' | 'pacientes' | null = null;
|
||||||
// "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's
|
private helpPinned: 'examenes' | 'pacientes' | null = null;
|
||||||
// description of its own bars does not apply to them and is not used.
|
toggleHelp(which: 'examenes' | 'pacientes') {
|
||||||
get donutGuide() {
|
if (this.helpPinned === which) { this.helpPinned = null; this.helpWhich = null; return; }
|
||||||
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
|
this.helpPinned = which;
|
||||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
this.openHelp(which);
|
||||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
}
|
||||||
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
|
openHelp(which: 'examenes' | 'pacientes') {
|
||||||
|
this.helpWhich = which;
|
||||||
|
}
|
||||||
|
hideHelp(which: 'examenes' | 'pacientes') {
|
||||||
|
if (this.helpPinned === which) return;
|
||||||
|
if (this.helpWhich === which) this.helpWhich = null;
|
||||||
|
}
|
||||||
|
onHelpFocusOut(which: 'examenes' | 'pacientes', event: FocusEvent) {
|
||||||
|
const next = event.relatedTarget;
|
||||||
|
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
|
||||||
|
if (this.helpPinned === which) this.helpPinned = null;
|
||||||
|
if (this.helpWhich === which) this.helpWhich = null;
|
||||||
}
|
}
|
||||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges) {
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
||||||
@@ -65,7 +75,7 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
|||||||
else if (this.model && changes['tema']) this.draw();
|
else if (this.model && changes['tema']) this.draw();
|
||||||
}
|
}
|
||||||
retry() { if (this.visible) this.load(); }
|
retry() { if (this.visible) this.load(); }
|
||||||
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
|
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.patientsFigure = undefined; }
|
||||||
private load() {
|
private load() {
|
||||||
this.subscription?.unsubscribe();
|
this.subscription?.unsubscribe();
|
||||||
this.loaded = true; this.clear();
|
this.loaded = true; this.clear();
|
||||||
@@ -111,11 +121,17 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
|||||||
const m = this.model;
|
const m = this.model;
|
||||||
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
|
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
|
||||||
}
|
}
|
||||||
|
ajustarAnchoPacientes(ancho: number) {
|
||||||
|
if (ancho === this.anchoPacientes) return;
|
||||||
|
this.anchoPacientes = ancho;
|
||||||
|
const m = this.model;
|
||||||
|
if (m) this.patientsFigure = donaPacientes(m, this.par, this.tema, ancho);
|
||||||
|
}
|
||||||
private draw() {
|
private draw() {
|
||||||
const m = this.model;
|
const m = this.model;
|
||||||
if (!m) return;
|
if (!m) return;
|
||||||
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
|
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
|
||||||
this.barsFigure = barrasConteos(m, this.par, this.tema);
|
this.patientsFigure = donaPacientes(m, this.par, this.tema, this.anchoPacientes);
|
||||||
this.changeDetector.markForCheck();
|
this.changeDetector.markForCheck();
|
||||||
}
|
}
|
||||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||||
|
|||||||
@@ -33,15 +33,20 @@
|
|||||||
@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 {
|
||||||
<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 EU7">
|
||||||
<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>
|
||||||
@@ -53,7 +58,7 @@
|
|||||||
<p>{{ sinDatoNote }}</p>
|
<p>{{ sinDatoNote }}</p>
|
||||||
</section>
|
</section>
|
||||||
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
|
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
|
||||||
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
|
<p>Número de pacientes por categoría en cada escenario, en una escala común; excluye «Sin dato».</p>
|
||||||
@if (m.escenarios.length && barsFigure) {
|
@if (m.escenarios.length && barsFigure) {
|
||||||
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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; }
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
|
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
|
||||||
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
|
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
|
||||||
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
|
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
|
||||||
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
|
expect((f.componentInstance.barsFigure!.layout['yaxis'] as { categoryarray: string[] }).categoryarray[0]).not.toContain('Total válido');
|
||||||
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');
|
||||||
@@ -63,6 +63,21 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839');
|
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.donutFigure!.data[2]['values'] as number[])[0]).toBe(0);
|
||||||
|
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]) {
|
||||||
@@ -75,7 +90,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
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.componentInstance.barsFigure!.layout['barmode']).toBe('group');
|
||||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
|
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
|
||||||
expect(charts.map(chart => chart.animated())).toEqual([true, true]);
|
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');
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
|
|||||||
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 { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||||
|
|
||||||
@@ -101,7 +101,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,9 +10,11 @@ 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';
|
||||||
|
import { recolorFigure } from './indicadores-c2-palette';
|
||||||
|
|
||||||
// The panel owns requests; the card receives the original and its presentation copy.
|
// The panel owns requests; the card receives the original and its presentation copy.
|
||||||
export interface FigureState {
|
export interface FigureState {
|
||||||
@@ -40,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',
|
||||||
})
|
})
|
||||||
@@ -62,7 +64,8 @@ export class IndicadorFigureCard implements OnChanges {
|
|||||||
}
|
}
|
||||||
get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; }
|
get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; }
|
||||||
legendColor(label: string, parent: boolean): string {
|
legendColor(label: string, parent: boolean): string {
|
||||||
const trace = this.chartFigure?.data[parent && this.activeParent ? 1 : 0];
|
const painted = this.chartFigure ? recolorFigure(this.chartFigure) : undefined;
|
||||||
|
const trace = painted?.data[parent && this.activeParent ? 1 : 0];
|
||||||
const labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined;
|
const labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined;
|
||||||
const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : undefined;
|
const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : undefined;
|
||||||
return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor';
|
return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor';
|
||||||
@@ -140,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';
|
||||||
|
|||||||
@@ -1,20 +1,27 @@
|
|||||||
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS">
|
<section class="confirmacion histo" aria-label="Resultado histopatológico por categoría BI-RADS">
|
||||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
<div class="histo-meta">
|
||||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
<p class="view-context">
|
||||||
@if (helpOpen) {
|
<span>{{ intervalLabel }}</span>
|
||||||
<div class="methodology">
|
@if (contextPeriod) { <span>Periodo {{ contextPeriod }}</span> }
|
||||||
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
|
</p>
|
||||||
@if (metadata) {
|
<div class="help" (mouseenter)="showHelp()" (mouseleave)="hideHelp()" (focusin)="showHelp()" (focusout)="onHelpFocusOut($event)">
|
||||||
@for (guide of readingGuide; track guide.figura) {
|
<button type="button" class="methodology-toggle" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" [attr.aria-describedby]="helpOpen ? 'histo-como-leer' : null" (click)="toggleHelp()"><span aria-hidden="true">!</span></button>
|
||||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
@if (helpOpen) {
|
||||||
<h3>{{ guide.nombre }}</h3>
|
<div class="methodology" id="histo-como-leer" role="tooltip">
|
||||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
|
||||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
@if (metadata) {
|
||||||
</section>
|
@for (guide of readingGuide; track guide.figura) {
|
||||||
|
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||||
|
<h3>{{ guide.nombre }}</h3>
|
||||||
|
@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> }
|
||||||
|
</section>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
</div>
|
||||||
</div>
|
}
|
||||||
}
|
</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 la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||||
@@ -32,36 +39,39 @@
|
|||||||
@if (model; as m) {
|
@if (model; as m) {
|
||||||
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
|
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
|
||||||
@else {
|
@else {
|
||||||
|
<div class="legend">
|
||||||
|
<div class="tab-bar">
|
||||||
|
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
|
||||||
|
@for (g of m.grupos; track g.id; let gi = $index) {
|
||||||
|
<button type="button" role="tab" class="tab" [id]="'histo-tab-' + g.id" [style.--swatch]="g.color" [attr.aria-selected]="selection?.grupo === g.id" [attr.aria-controls]="'histo-panel-' + g.id" (click)="select('grupos', gi)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="child-groups">
|
||||||
|
@for (g of m.grupos; track g.id) {
|
||||||
|
<div class="tab-panel" role="group" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + g.id">
|
||||||
|
@for (c of m.categorias; track c.id; let ci = $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', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="figures">
|
<div class="figures">
|
||||||
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
|
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
|
||||||
@if (ratesFigure) {
|
@if (ratesFigure) {
|
||||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
|
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
|
||||||
}
|
}
|
||||||
<ul class="rate-states">
|
|
||||||
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
|
||||||
</ul>
|
|
||||||
</section>
|
</section>
|
||||||
<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.conResultado !== null && m.conResultado > 0 && donutFigure) {
|
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
|
||||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||||
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
|
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
|
||||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
|
|
||||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
|
||||||
@for (g of m.grupos; track g.id; let i = $index) {
|
|
||||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
|
||||||
@for (c of m.categorias; track c.id; let i = $index) {
|
|
||||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
}
|
}
|
||||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
|
||||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
@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>
|
||||||
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
|
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ 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 { 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 { 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 { Celda } from './indicadores-confirmacion-citologia';
|
import { Celda } from './indicadores-confirmacion-citologia';
|
||||||
@@ -43,6 +43,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
donutFigure?: PlotlyFigure;
|
donutFigure?: PlotlyFigure;
|
||||||
ratesFigure?: PlotlyFigure;
|
ratesFigure?: PlotlyFigure;
|
||||||
helpOpen = false;
|
helpOpen = false;
|
||||||
|
private helpPinned = false;
|
||||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||||
private subscription?: Subscription;
|
private subscription?: Subscription;
|
||||||
@@ -54,7 +55,11 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
private readonly alCambiarAncho = () => this.draw();
|
private readonly alCambiarAncho = () => this.draw();
|
||||||
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
|
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
|
||||||
|
|
||||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
get intervalLabel() { return this.applied?.tipo === 'mes' ? 'Intervalo mensual' : 'Intervalo semestral'; }
|
||||||
|
get contextPeriod() {
|
||||||
|
return this.model?.periodo ?? this.periods[this.periodIndex]
|
||||||
|
?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : '');
|
||||||
|
}
|
||||||
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 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; }
|
||||||
@@ -71,7 +76,23 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
toggleHelp() {
|
||||||
|
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
|
||||||
|
this.helpPinned = true;
|
||||||
|
this.showHelp();
|
||||||
|
}
|
||||||
|
showHelp() {
|
||||||
|
if (this.helpOpen) return;
|
||||||
|
this.helpOpen = true;
|
||||||
|
this.metadataRequested.emit();
|
||||||
|
}
|
||||||
|
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
|
||||||
|
onHelpFocusOut(event: FocusEvent) {
|
||||||
|
const next = event.relatedTarget;
|
||||||
|
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
|
||||||
|
this.helpPinned = false;
|
||||||
|
this.helpOpen = false;
|
||||||
|
}
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges) {
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ import { IndicadorKpiCard } from './indicador-kpi-card';
|
|||||||
expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba');
|
expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba');
|
||||||
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
|
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
|
||||||
expect(fixture.nativeElement.textContent).toContain('Referencia de prueba');
|
expect(fixture.nativeElement.textContent).toContain('Referencia de prueba');
|
||||||
|
expect(fixture.nativeElement.querySelector('.period-label')).toBeNull();
|
||||||
|
fixture.componentRef.setInput('temporalReference', '2025-S2'); fixture.detectChanges();
|
||||||
|
expect(fixture.nativeElement.querySelector('.period-label').textContent).toBe('Periodo:');
|
||||||
|
expect(fixture.nativeElement.querySelector('.kpi-foot').textContent).toContain('2025-S2');
|
||||||
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba');
|
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba');
|
||||||
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
|
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||||
|
|||||||
@@ -12,16 +12,23 @@ import { MatCardModule } from '@angular/material/card';
|
|||||||
@if (value !== null && value !== undefined) {
|
@if (value !== null && value !== undefined) {
|
||||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||||
}
|
}
|
||||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
<div class="kpi-foot">
|
||||||
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
|
@if (showPeriod && temporalReference) {
|
||||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
<p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p>
|
||||||
|
}
|
||||||
|
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
|
||||||
|
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||||
|
</div>
|
||||||
</mat-card>
|
</mat-card>
|
||||||
`,
|
`,
|
||||||
styles: `
|
styles: `
|
||||||
:host { display: block; min-width: 0; }
|
:host { display: flex; flex-direction: column; height: 100%; min-width: 0; }
|
||||||
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
|
mat-card { box-sizing: border-box; display: flex; flex-direction: column; flex: 1 1 auto; height: auto; min-height: 100%; padding: var(--issste-space-6);
|
||||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
||||||
border-radius: var(--issste-radius); box-shadow: none; }
|
border-radius: var(--issste-radius); box-shadow: none; }
|
||||||
|
.kpi-foot { margin-top: auto; }
|
||||||
|
.period { display: flex; flex-wrap: wrap; align-items: baseline; gap: .35rem; }
|
||||||
|
.period-label { font-weight: 600; }
|
||||||
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
||||||
h3, p { overflow-wrap: anywhere; }
|
h3, p { overflow-wrap: anywhere; }
|
||||||
p { margin: var(--issste-space-3) 0 0; }
|
p { margin: var(--issste-space-3) 0 0; }
|
||||||
@@ -30,9 +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; }
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
export class IndicadorKpiCard {
|
export class IndicadorKpiCard {
|
||||||
@@ -40,12 +47,18 @@ 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;
|
||||||
|
// The opportunity strip shares one period, shown by the parent instead of on every card.
|
||||||
|
@Input() showPeriod = true;
|
||||||
@Input() loading = false;
|
@Input() loading = false;
|
||||||
@Input() notes: string[] = [];
|
@Input() notes: string[] = [];
|
||||||
@Input() state = 'Pendiente de definición';
|
@Input() state = 'Pendiente de definición';
|
||||||
// A card that shows its value needs no "Disponible" line.
|
// A card that shows its value needs no "Disponible" line.
|
||||||
@Input() quietWhenAvailable = false;
|
@Input() quietWhenAvailable = false;
|
||||||
@Input() additionalInfo?: string;
|
@Input() additionalInfo?: string;
|
||||||
|
get labeledPeriod(): boolean {
|
||||||
|
const text = this.temporalReference?.trim();
|
||||||
|
return !!text && text.split(',').every(part => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(part.trim()));
|
||||||
|
}
|
||||||
get informationLine(): string | undefined {
|
get informationLine(): string | undefined {
|
||||||
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
||||||
return [...new Set(lines)].join(' ');
|
return [...new Set(lines)].join(' ');
|
||||||
|
|||||||
@@ -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,15 +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(domain === 'cacu' ? 5 : 4);
|
expect(cards).toHaveLength(5);
|
||||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', 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(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined]);
|
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
|
||||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
|
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
|
||||||
|
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Integración pendiente', 'Integración pendiente']
|
||||||
|
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
||||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||||
expect.stringContaining('2025-S1'),
|
|
||||||
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.'),
|
||||||
]));
|
]));
|
||||||
|
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||||
|
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);
|
||||||
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,14 +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]="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 {
|
||||||
@@ -36,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);
|
||||||
@@ -43,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');
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
<section aria-label="Editor de filtros generales del proyecto">
|
<section aria-label="Editor de filtros generales del proyecto">
|
||||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||||
<div class="fields compact">
|
<div class="fields compact">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
<div class="interval">
|
||||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
|
||||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||||
</mat-select>
|
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||||
</mat-form-field>
|
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
||||||
|
</mat-button-toggle-group>
|
||||||
|
</div>
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||||
@@ -51,11 +53,13 @@
|
|||||||
<section aria-label="Editor de filtros generales del proyecto">
|
<section aria-label="Editor de filtros generales del proyecto">
|
||||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||||
<div class="fields">
|
<div class="fields">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
<div class="interval">
|
||||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
|
||||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||||
</mat-select>
|
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||||
</mat-form-field>
|
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
||||||
|
</mat-button-toggle-group>
|
||||||
|
</div>
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||||
|
|||||||
@@ -2,13 +2,30 @@
|
|||||||
|
|
||||||
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
|
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
|
||||||
// CaMa's compact row: tighter fields and buttons, one line of text under it.
|
// CaMa's compact row: tighter fields and buttons, one line of text under it.
|
||||||
:host(.compacto) { margin: 0; @include mat.theme((density: -4)); }
|
:host(.compacto) {
|
||||||
|
margin: 0;
|
||||||
|
@include mat.theme((density: -4));
|
||||||
|
// That theme also rewrites the corner scale, which turns this switch into a pill.
|
||||||
|
// The history switch keeps the slight rounding of the indicators pages.
|
||||||
|
--mat-sys-corner-extra-small: 2px;
|
||||||
|
--mat-sys-corner-small: 2px;
|
||||||
|
--mat-sys-corner-medium: 4px;
|
||||||
|
--mat-sys-corner-large: 4px;
|
||||||
|
--mat-sys-corner-extra-large: 6px;
|
||||||
|
--mat-sys-corner-full: 4px;
|
||||||
|
}
|
||||||
|
:host(.compacto) .interval mat-button-toggle-group {
|
||||||
|
--mat-button-toggle-height: 40px;
|
||||||
|
--mat-button-toggle-shape: 6px;
|
||||||
|
}
|
||||||
:host(.compacto) p { line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
|
:host(.compacto) p { line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
|
||||||
:host(.compacto) .pending { color: var(--issste-text); border-left-color: var(--issste-accent); padding-left: var(--issste-space-2); }
|
:host(.compacto) .pending { color: var(--issste-text); border-left-color: var(--issste-accent); padding-left: var(--issste-space-2); }
|
||||||
:host(.compacto) .apply-button { min-height: 40px; }
|
:host(.compacto) .apply-button { min-height: 40px; }
|
||||||
:host(.compacto) .period-builder button { min-height: 40px; }
|
:host(.compacto) .period-builder button { min-height: 40px; }
|
||||||
section { min-width: 0; }
|
section { min-width: 0; }
|
||||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
|
.fields { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
|
||||||
|
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
|
||||||
|
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
|
||||||
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
|
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
|
||||||
.period-builder mat-form-field { flex: 0 1 10rem; }
|
.period-builder mat-form-field { flex: 0 1 10rem; }
|
||||||
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
|
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
|
||||||
@@ -21,7 +38,7 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
|
|||||||
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
||||||
.remove button { min-height: 44px; }
|
.remove button { min-height: 44px; }
|
||||||
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
|
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
|
||||||
.fields.compact { align-items: center; }
|
.fields.compact { align-items: end; }
|
||||||
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
||||||
.fields.compact .apply-button { margin-top: 0; }
|
.fields.compact .apply-button { margin-top: 0; }
|
||||||
@media (max-width: 550px) {
|
@media (max-width: 550px) {
|
||||||
|
|||||||
@@ -138,16 +138,11 @@ describe('UX-04 control asistido', () => {
|
|||||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||||
expect(apply).toHaveBeenCalledTimes(1);
|
expect(apply).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
|
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', () => {
|
||||||
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
|
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
|
||||||
expect(labels).toContain('Intervalo de análisis');
|
expect(fixture.nativeElement.querySelector('.field-label').textContent).toBe('Intervalo de análisis');
|
||||||
expect(labels).not.toContain('Modalidad');
|
expect(labels).not.toContain('Modalidad');
|
||||||
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
|
expect([...fixture.nativeElement.querySelectorAll('mat-button-toggle')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(['Mensual', 'Semestral']);
|
||||||
.find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
|
|
||||||
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
|
|
||||||
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
|
|
||||||
expect(options).toEqual(['Semestral', 'Mensual']);
|
|
||||||
select.componentInstance.close();
|
|
||||||
});
|
});
|
||||||
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
||||||
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core';
|
import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
import { MatInputModule } from '@angular/material/input';
|
import { MatInputModule } from '@angular/material/input';
|
||||||
import { MatSelectModule } from '@angular/material/select';
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
@@ -10,7 +11,7 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-period-filters',
|
selector: 'app-indicador-period-filters',
|
||||||
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
|
imports: [FormsModule, MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatInputModule, MatSelectModule],
|
||||||
host: { '[class.compacto]': 'compact' },
|
host: { '[class.compacto]': 'compact' },
|
||||||
templateUrl: './indicador-period-filters.html',
|
templateUrl: './indicador-period-filters.html',
|
||||||
styleUrl: './indicador-period-filters.scss',
|
styleUrl: './indicador-period-filters.scss',
|
||||||
|
|||||||
@@ -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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
|||||||
@@ -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']]));
|
||||||
@@ -161,14 +189,16 @@ describe('paleta C2 institucional y semántica', () => {
|
|||||||
it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => {
|
it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => {
|
||||||
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
||||||
const figure = supported(data, { ...selection, tema }).figure;
|
const figure = supported(data, { ...selection, tema }).figure;
|
||||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||||
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||||
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
|
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
|
||||||
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
||||||
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
|
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
|
||||||
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
|
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
|
||||||
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
|
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
|
||||||
expect(c2Color('#D98E4A', 0)).toBe('#D98E4A');
|
expect(c2Color('#D98E4A', 0)).toBe(C2_PALETTE.series[0]);
|
||||||
|
expect(c2Color('#B55A1F', 2)).toBe(C2_PALETTE.series[2]);
|
||||||
|
expect(c2Color('#9DBFE3', 1)).toBe('#9DBFE3');
|
||||||
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
|
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
|
||||||
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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 { c2Theme, groupBase, 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,7 +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));
|
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 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 },
|
||||||
@@ -93,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,
|
||||||
@@ -104,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((_, i) => groupBase(i)), 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
|
||||||
|
|||||||
@@ -8,19 +8,22 @@ describe('paleta del logo ISSSTELEON', () => {
|
|||||||
expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]);
|
expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('reemplaza mezclas de partido por entradas distintas y conserva el gris de sin dato', () => {
|
it('cambia el café y el anaranjado por la serie, y deja azul, rojo, gris y edad', () => {
|
||||||
const [azul, rojo, naranja, amarillo, guinda, sinDato, edad] = institutionalize([
|
const [cafe, otroCafe, rojo, azul, sinDato, edad] = institutionalize([
|
||||||
'#0044CC', '#C41E3A', '#FF6B00', '#FFD100', '#7A2E0E', '#C9CDD2', '#2F6DB3',
|
'#B55A1F', '#D9822B', '#C41E3A', '#0044CC', '#C9CDD2', '#2F6DB3',
|
||||||
]);
|
]);
|
||||||
expect([azul, rojo, naranja, amarillo, guinda]).toEqual(C2_PALETTE.series.slice(0, 5));
|
expect([cafe, otroCafe]).toEqual(C2_PALETTE.series.slice(0, 2));
|
||||||
expect(edad).toBe('#2F6DB3');
|
expect(rojo).toBe('#C41E3A');
|
||||||
|
expect(azul).toBe('#0044CC');
|
||||||
expect(sinDato).toBe('#C9CDD2');
|
expect(sinDato).toBe('#C9CDD2');
|
||||||
|
expect(edad).toBe('#2F6DB3');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
|
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
|
||||||
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
|
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
|
||||||
expect(new Set(colors.slice(0, 3)).size).toBe(3);
|
expect(new Set(colors.slice(0, 3)).size).toBe(3);
|
||||||
expect(colors[3]).toBe(groupBase(1));
|
expect(colors[3]).toBe(C2_PALETTE.calidos[0]);
|
||||||
|
expect(colors[0]).not.toBe(C2_PALETTE.calidos[0]);
|
||||||
expect(colors[0]).not.toBe(colors[3]);
|
expect(colors[0]).not.toBe(colors[3]);
|
||||||
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
|
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
|
||||||
});
|
});
|
||||||
@@ -34,8 +37,7 @@ describe('paleta del logo ISSSTELEON', () => {
|
|||||||
layout: { font: { color: '#081839' }, paper_bgcolor: '#FFFFFF', colorway: ['#EF553B', '#636efa'] },
|
layout: { font: { color: '#081839' }, paper_bgcolor: '#FFFFFF', colorway: ['#EF553B', '#636efa'] },
|
||||||
});
|
});
|
||||||
expect((figure.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]);
|
expect((figure.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]);
|
||||||
expect(figure.data[0]['error_x']).toMatchObject({ color: expect.stringMatching(/^rgba\(\d+,\d+,\d+,0\.4\)$/) });
|
expect((figure.data[0]['error_x'] as { color: string }).color).toBe('rgba(0,68,204,0.4)');
|
||||||
expect((figure.data[0]['error_x'] as { color: string }).color).not.toContain('0,68,204');
|
|
||||||
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
|
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
|
||||||
const scale = figure.data[0]['colorscale'] as [number, string][];
|
const scale = figure.data[0]['colorscale'] as [number, string][];
|
||||||
expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]);
|
expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]);
|
||||||
@@ -43,11 +45,7 @@ describe('paleta del logo ISSSTELEON', () => {
|
|||||||
expect(scale[0][1]).not.toBe(scale[1][1]);
|
expect(scale[0][1]).not.toBe(scale[1][1]);
|
||||||
expect(figure.layout['font']).toEqual({ color: '#081839' });
|
expect(figure.layout['font']).toEqual({ color: '#081839' });
|
||||||
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
|
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
|
||||||
expect(figure.layout['colorway']).toEqual(C2_PALETTE.series.slice(2, 4));
|
expect(figure.layout['colorway']).toEqual([C2_PALETTE.series[1], '#636efa']);
|
||||||
expect(new Set([
|
|
||||||
(figure.data[0]['marker'] as { color: string }).color,
|
|
||||||
...(figure.layout['colorway'] as string[]),
|
|
||||||
]).size).toBe(3);
|
|
||||||
expect(recolorFigure(figure)).toBe(figure);
|
expect(recolorFigure(figure)).toBe(figure);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,17 +1,20 @@
|
|||||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||||
|
|
||||||
// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0).
|
// Logo lime plus the analogous and complementary hues chosen for the charts.
|
||||||
// Neighboring entries differ in hue so series stay distinct, and none is a party colour:
|
// Cool greens, teal and blue are the normal side. Rose, violet and purple are the abnormal side.
|
||||||
// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral.
|
// Neutrals stay neutral. Sequential fills run from pale lime to deep teal.
|
||||||
// Sequential fills (heatmaps) use SCALE, from pale lime to deep teal.
|
const OWNED = new Set<string>();
|
||||||
|
function own(hex: string): string { OWNED.add(hex.toLowerCase()); return hex; }
|
||||||
export const C2_PALETTE = Object.freeze({
|
export const C2_PALETTE = Object.freeze({
|
||||||
|
frios: Object.freeze([own('#A8C243'), own('#69C242'), own('#42C25C'), own('#42C29C'), own('#4269C2')]),
|
||||||
|
calidos: Object.freeze([own('#C24269'), own('#9C42C2'), own('#5C42C2'), own('#C2429C'), own('#8E2F62'), own('#7A3496')]),
|
||||||
series: Object.freeze([
|
series: Object.freeze([
|
||||||
'#5c7014', '#0e7568', '#6a6448', '#3d6b38',
|
'#A8C243', '#42C29C', '#C24269', '#9C42C2',
|
||||||
'#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38',
|
'#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' }),
|
||||||
@@ -23,17 +26,56 @@ export function isAgeColor(color: string): boolean {
|
|||||||
const key = parseColor(color)?.key;
|
const key = parseColor(color)?.key;
|
||||||
return !!key && ageKeys.has(key);
|
return !!key && ageKeys.has(key);
|
||||||
}
|
}
|
||||||
export function c2Color(published: string | undefined, index: number): string {
|
/** Orange, tan and coffee. Age gold and the palette's own stone are not included. */
|
||||||
// A published swatch stays. The series only fills a category that arrived without one.
|
function isCoffeeParsed(item: Parsed | undefined): boolean {
|
||||||
if (published && (/^#[0-9a-f]{6}$/i.test(published) || isAgeColor(published))) return published;
|
if (!item || item.kind === 'neutral' || ageKeys.has(item.key)) return false;
|
||||||
return C2_PALETTE.series[index % C2_PALETTE.series.length];
|
return item.hue >= 8 && item.hue <= 46 && item.sat >= 0.28;
|
||||||
|
}
|
||||||
|
export function isCoffeeColor(color: string): boolean {
|
||||||
|
return isCoffeeParsed(parseColor(color));
|
||||||
|
}
|
||||||
|
export type Tono = 'frio' | 'calido' | 'neutro';
|
||||||
|
/** Metadata id: cool for normal groups, warm for abnormal ones. Unknown ids stay neutral. */
|
||||||
|
export function tonoDe(clave: string | undefined | null): Tono {
|
||||||
|
if (!clave) return 'neutro';
|
||||||
|
const id = clave.normalize('NFD').replace(/\p{M}/gu, '').toUpperCase().replace(/[^A-Z0-9]+/g, '_');
|
||||||
|
if (id.includes('SIN_DATO') || id.includes('SIN_BIOPSIA')) return 'neutro';
|
||||||
|
if (id.includes('NO_METAST') || id.includes('SIN_METAST') || id.includes('NO_ANORMAL') || id.includes('NO_MALIG') || id.includes('BENIGN') || id.includes('NO_ALTER')) return 'frio';
|
||||||
|
if (id.includes('METAST') || id.includes('CARCINOMA') || id.includes('ANORMAL') || id.includes('MALIG') || id.includes('INVAS') || id.includes('IN_SITU') || id.includes('LIEAG') || id.includes('ALTER')) return 'calido';
|
||||||
|
if (/^(B4|B4A|B4B|B4C|B5|B6)$/.test(id) || /^BIRADS_[456]/.test(id)) return 'calido';
|
||||||
|
return 'neutro';
|
||||||
|
}
|
||||||
|
function poolDe(tono: Tono): readonly string[] {
|
||||||
|
if (tono === 'calido') return C2_PALETTE.calidos;
|
||||||
|
if (tono === 'frio') return C2_PALETTE.frios;
|
||||||
|
return C2_PALETTE.series;
|
||||||
|
}
|
||||||
|
export function c2Color(published: string | undefined, index: number, tono: Tono = 'neutro'): string {
|
||||||
|
// Coffee takes the cool or warm pool when the category metadata says which. Other published colours stay.
|
||||||
|
if (published && isAgeColor(published)) return published;
|
||||||
|
if (published && isNeutralColor(published)) return published;
|
||||||
|
const pool = poolDe(tono);
|
||||||
|
if (published && isCoffeeColor(published)) return pool[index % pool.length];
|
||||||
|
if (published && /^#[0-9a-f]{6}$/i.test(published)) return published;
|
||||||
|
return pool[index % pool.length];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One base hue per group, then lighter and darker steps so siblings stay related but distinct. */
|
/** One base per group: cool if the id is normal, warm if it is abnormal, then steps so siblings differ. */
|
||||||
|
export function basesPorGrupo(groups: readonly string[]): ReadonlyMap<string, string> {
|
||||||
|
const seen = { frio: 0, calido: 0, neutro: 0 };
|
||||||
|
const base = new Map<string, string>();
|
||||||
|
for (const id of [...new Set(groups)]) {
|
||||||
|
const tono = tonoDe(id);
|
||||||
|
const pool = poolDe(tono);
|
||||||
|
base.set(id, pool[seen[tono] % pool.length]);
|
||||||
|
seen[tono] += 1;
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
export function paintByGroup(groups: readonly string[]): string[] {
|
export function paintByGroup(groups: readonly string[]): string[] {
|
||||||
const order = [...new Set(groups)];
|
const bases = basesPorGrupo(groups);
|
||||||
const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length]));
|
const counts = new Map([...bases.keys()].map(id => [id, groups.filter(g => g === id).length]));
|
||||||
const stairs = new Map(order.map((id, i) => [id, steps(C2_PALETTE.series[i % C2_PALETTE.series.length], counts.get(id)!)]));
|
const stairs = new Map([...bases].map(([id, color]) => [id, steps(color, counts.get(id)!)]));
|
||||||
const cursor = new Map<string, number>();
|
const cursor = new Map<string, number>();
|
||||||
return groups.map(id => {
|
return groups.map(id => {
|
||||||
const index = cursor.get(id) ?? 0;
|
const index = cursor.get(id) ?? 0;
|
||||||
@@ -51,7 +93,7 @@ export function institutionalize(colors: readonly string[]): string[] {
|
|||||||
const foreign: string[] = [];
|
const foreign: string[] = [];
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
for (const item of parsed) {
|
for (const item of parsed) {
|
||||||
if (!item || item.kind !== 'foreign' || ageKeys.has(item.key) || seen.has(item.key)) continue;
|
if (!item || !isCoffeeParsed(item) || seen.has(item.key)) continue;
|
||||||
seen.add(item.key);
|
seen.add(item.key);
|
||||||
foreign.push(item.key);
|
foreign.push(item.key);
|
||||||
}
|
}
|
||||||
@@ -63,9 +105,14 @@ export function institutionalize(colors: readonly string[]): string[] {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Keep a published colour; only a missing one takes the next series entry. */
|
/** Coffee published colours take the cool or warm pool of their metadata id. */
|
||||||
export function seriesColors(published: readonly (string | undefined)[]): string[] {
|
export function seriesColors(published: readonly (string | undefined)[], claves?: readonly (string | undefined)[]): string[] {
|
||||||
return published.map((color, index) => c2Color(color, index));
|
const seen = { frio: 0, calido: 0, neutro: 0 };
|
||||||
|
return published.map((color, index) => {
|
||||||
|
const tono = tonoDe(claves?.[index]);
|
||||||
|
const slot = tono === 'neutro' ? index : seen[tono]++;
|
||||||
|
return c2Color(color, slot, tono);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const NAMED: Record<string, [number, number, number]> = {
|
const NAMED: Record<string, [number, number, number]> = {
|
||||||
@@ -101,10 +148,13 @@ function parseColor(input: string): Parsed | undefined {
|
|||||||
}
|
}
|
||||||
const lum = luminance({ r, g, b });
|
const lum = luminance({ r, g, b });
|
||||||
const neutral = sat < 0.18;
|
const neutral = sat < 0.18;
|
||||||
const harmonious = !neutral && (
|
const swatch = '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
|
||||||
(hue >= 64 && hue <= 188 && sat >= 0.22)
|
const harmonious = OWNED.has(swatch) || (!neutral && (
|
||||||
|
(hue >= 64 && hue <= 175 && sat >= 0.22)
|
||||||
|
|| (hue >= 200 && hue <= 320 && sat >= 0.22)
|
||||||
|
|| (hue >= 320 && hue < 356 && sat >= 0.28 && sat <= 0.78)
|
||||||
|| (hue > 188 && hue <= 230 && sat <= 0.5)
|
|| (hue > 188 && hue <= 230 && sat <= 0.5)
|
||||||
|| (hue >= 40 && hue < 64 && sat <= 0.42));
|
|| (hue >= 40 && hue < 64 && sat <= 0.42)));
|
||||||
return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' };
|
return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' };
|
||||||
}
|
}
|
||||||
function steps(base: string, count: number): string[] {
|
function steps(base: string, count: number): string[] {
|
||||||
|
|||||||
@@ -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,168 @@
|
|||||||
|
// 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('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,22 @@
|
|||||||
|
// 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',
|
||||||
|
'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,40 @@
|
|||||||
|
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',
|
||||||
|
});
|
||||||
|
|
||||||
|
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: Distribución de resultados citológicos', '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: Distribución de resultados citológicos', '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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -10,6 +10,7 @@ import { provideRouter } from '@angular/router';
|
|||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { MatDialog } from '@angular/material/dialog';
|
import { MatDialog } from '@angular/material/dialog';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||||
import tasaVisible from './fixtures/cama_tasa_deteccion_visible.json';
|
import tasaVisible from './fixtures/cama_tasa_deteccion_visible.json';
|
||||||
import tasaSuprimida from './fixtures/cama_tasa_deteccion_suprimido.json';
|
import tasaSuprimida from './fixtures/cama_tasa_deteccion_suprimido.json';
|
||||||
import diasVisible from './fixtures/cama_dias_resultado_visible.json';
|
import diasVisible from './fixtures/cama_dias_resultado_visible.json';
|
||||||
@@ -31,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 resultado maligno.' });
|
.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);
|
||||||
@@ -86,7 +87,7 @@ describe('CAM-01, CAM-02 y CAM-03: histórico con las respuestas reales', () =>
|
|||||||
expect(f.contrato).toBe('C2'); expect(f.suprimidos).toEqual([]); expect(f.sinDato).toEqual([]);
|
expect(f.contrato).toBe('C2'); expect(f.suprimidos).toEqual([]); expect(f.sinDato).toEqual([]);
|
||||||
expect(f.figure.data.map(t => [t['name'], (t['y'] as number[])[0]])).toEqual([
|
expect(f.figure.data.map(t => [t['name'], (t['y'] as number[])[0]])).toEqual([
|
||||||
['Benigno', 7], ['Lesión de riesgo (B3)', 5], ['Carcinoma in situ', 6], ['Carcinoma invasor', 7], ['Sin biopsia reportada', 6], ['Sin dato', 6]]);
|
['Benigno', 7], ['Lesión de riesgo (B3)', 5], ['Carcinoma in situ', 6], ['Carcinoma invasor', 7], ['Sin biopsia reportada', 6], ['Sin dato', 6]]);
|
||||||
expect(f.figure.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', '#D9822B', '#B5482E', '#C9CDD2', '#C9CDD2']);
|
expect(f.figure.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', C2_PALETTE.calidos[0], C2_PALETTE.calidos[1], '#C9CDD2', '#C9CDD2']);
|
||||||
expect(f.figure.layout['barmode']).toBe('stack');
|
expect(f.figure.layout['barmode']).toBe('stack');
|
||||||
expect(f.comoLeer).toContain('pacientes');
|
expect(f.comoLeer).toContain('pacientes');
|
||||||
});
|
});
|
||||||
@@ -112,9 +113,10 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
|||||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', REALES);
|
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', REALES);
|
||||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true);
|
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true);
|
||||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges();
|
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges();
|
||||||
const respuestas: Record<string, unknown> = visibles
|
const respuestas: Record<string, unknown> = {
|
||||||
? { cama_tasa_deteccion_histopatologica: tasaVisible, cama_dias_resultado_diagnostico: diasVisible, cama_histopatologia_birads: generalFixture }
|
cama_dias_resultado_diagnostico: visibles ? diasVisible : diasSuprimido,
|
||||||
: { cama_tasa_deteccion_histopatologica: tasaSuprimida, cama_dias_resultado_diagnostico: diasSuprimido, cama_histopatologia_birads: generalFixture };
|
cama_histopatologia_birads: generalFixture,
|
||||||
|
};
|
||||||
const pedidos: string[] = [];
|
const pedidos: string[] = [];
|
||||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||||
for (const r of ola) {
|
for (const r of ola) {
|
||||||
@@ -131,28 +133,29 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
|||||||
const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
|
const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
|
||||||
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);
|
||||||
|
|
||||||
it('los tres indicadores publicados se piden y se dibujan; los cinco restantes de la lista siguen pendientes', () => {
|
it('omite el panel y las consultas de detección aunque la medida figure en el catálogo', () => {
|
||||||
const pedidos = montar(true);
|
const pedidos = montar(true);
|
||||||
|
expect(REALES.map(i => i.id)).toContain('cama_tasa_deteccion_histopatologica');
|
||||||
|
expect(pedidos.some(p => p.includes('cama_tasa_deteccion_histopatologica'))).toBe(false);
|
||||||
expect(pedidos.filter(p => p.includes('/datos'))).toEqual([
|
expect(pedidos.filter(p => p.includes('/datos'))).toEqual([
|
||||||
'/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1',
|
'/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1',
|
||||||
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1',
|
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
|
||||||
'/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
|
|
||||||
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
||||||
expect(titulos.filter(([t]) => ['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
|
expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
|
||||||
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
|
expect(titulos.filter(([, estado]) => estado === 'dibujado'))
|
||||||
expect(graficas()).toHaveLength(3);
|
.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, 2]);
|
expect(graficas().map(g => g.figure!.data.length)).toEqual([2, 6]);
|
||||||
});
|
});
|
||||||
it('con el umbral normal los dos paneles C1 y C3r avisan 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);
|
||||||
const texto = paneles().map(p => p.textContent!);
|
const texto = paneles().map(p => p.textContent!);
|
||||||
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(2);
|
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(1);
|
||||||
expect(graficas()).toHaveLength(3);
|
expect(graficas()).toHaveLength(2);
|
||||||
});
|
});
|
||||||
it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => {
|
it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => {
|
||||||
montar(false);
|
montar(false);
|
||||||
const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[];
|
const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[];
|
||||||
expect(notas).toHaveLength(2);
|
expect(notas).toHaveLength(1);
|
||||||
for (const nota of notas) {
|
for (const nota of notas) {
|
||||||
expect(nota.open).toBe(false);
|
expect(nota.open).toBe(false);
|
||||||
expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos');
|
expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos');
|
||||||
@@ -160,7 +163,6 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
|||||||
}
|
}
|
||||||
notas[0].open = true;
|
notas[0].open = true;
|
||||||
expect(notas[0].open).toBe(true);
|
expect(notas[0].open).toBe(true);
|
||||||
expect(notas[1].open).toBe(false);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -197,21 +199,27 @@ 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('las cuatro tarjetas de oportunidad tienen datos, ninguna pendiente, con los valores publicados', () => {
|
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
|
||||||
cargar(completo());
|
// Fails if the unavailable slot displays a value or displaces the published measures.
|
||||||
expect(kpis()).toHaveLength(4);
|
const pedidos = cargar(completo());
|
||||||
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
expect(kpis()).toHaveLength(5);
|
||||||
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.');
|
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(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()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.');
|
expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.');
|
||||||
|
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
|
||||||
|
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');
|
||||||
@@ -231,6 +239,6 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
|||||||
});
|
});
|
||||||
it('solo CAM-01 y CAM-02 sin CAM-03: dos tarjetas con datos y la de histopatología pendiente', () => {
|
it('solo CAM-01 y CAM-02 sin CAM-03: dos tarjetas con datos y la de histopatología pendiente', () => {
|
||||||
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||||
expect(kpis()).toHaveLength(4); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente');
|
expect(kpis()).toHaveLength(5); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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', () => {
|
||||||
@@ -308,3 +308,33 @@ describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () =>
|
|||||||
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
|
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Conteos publicados de CaMa en la ruta FHIR', () => {
|
||||||
|
let http: HttpTestingController;
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
afterEach(() => http.verify());
|
||||||
|
function pedir(id: string, fhirId: string) {
|
||||||
|
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).datos('cama', id, 'semestre', ['2025-S2']));
|
||||||
|
http.expectOne('/cama/fhir/Measure').flush(measuresData);
|
||||||
|
http.expectOne(r => r.url === '/cama/fhir/MeasureReport').flush({ ...answers[fhirId].semestre, entry: reportsOf(fhirId, 'semestre', '2025-07-01').map(resource => ({ resource })) });
|
||||||
|
return answer;
|
||||||
|
}
|
||||||
|
it('las mastografías llegan a la tarjeta con los conteos publicados', async () => {
|
||||||
|
const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS);
|
||||||
|
const mostrado = await pedir('cama_birads_456_mastografia', 'CAMA-BIRADS456-MASTOGRAFIA');
|
||||||
|
expect(mostrado.filas).toEqual(publicado.filas);
|
||||||
|
const pacientes = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
|
||||||
|
const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre');
|
||||||
|
expect(totalExamenes(model)).toBe(39);
|
||||||
|
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
|
||||||
|
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
|
||||||
|
});
|
||||||
|
it('los pacientes conservan sus conteos publicados', async () => {
|
||||||
|
const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
|
||||||
|
const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE');
|
||||||
|
expect(pacientes.filas).toEqual(publicado.filas);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ describe('Tasa de detección histopatológica (C1)', () => {
|
|||||||
expect(d['grupos']).toEqual({ total: 'Total' });
|
expect(d['grupos']).toEqual({ total: 'Total' });
|
||||||
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
|
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
|
||||||
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
|
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
|
||||||
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` });
|
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con riesgo a carcinoma.` });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
|
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user