Compare commits
56 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 04795a09cc |
@@ -14,30 +14,3 @@ 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`
|
||||
(`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`.
|
||||
|
||||
## Fuente de histopatología BI-RADS
|
||||
|
||||
La compilación estándar incorpora la fuente sintética de la tarjeta de
|
||||
histopatología en **CaMa → Resumen**. La dona y las barras usan el mismo
|
||||
fixture. El catálogo, los filtros generales y los demás indicadores siguen
|
||||
usando WebApi. Si el catálogo carga sin la medida de histopatología, Resumen
|
||||
incluye la tarjeta con su fuente local.
|
||||
|
||||
El archivo
|
||||
`src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json`
|
||||
contiene conteos inventados, sin validez clínica. Define los 12 subtipos en orden
|
||||
con sus identificadores y colores. Cada mes remite a un perfil de conteos por
|
||||
estrato BI-RADS que incluye resultados benignos, subtipos, casos sin biopsia
|
||||
reportada y casos sin dato. Abarca enero de 2025 a diciembre de 2026. Los semestres
|
||||
suman esos mismos meses. Un periodo fuera de cobertura queda sin resultados.
|
||||
|
||||
El anillo interior usa el total con resultado de biopsia. El exterior reparte
|
||||
el grupo «Riesgo a carcinoma» entre sus 12 subtipos. Las barras y el centro
|
||||
muestran el subconjunto elegido sobre el total con resultado, por BI-RADS y del
|
||||
periodo completo, respectivamente. La leyenda permite elegir subtipos incluso
|
||||
cuando el sector es demasiado pequeño.
|
||||
|
||||
Cuando se valide la matriz clínica de subtipos, el adaptador FHIR podrá construir
|
||||
el mismo modelo de presentación con los conteos, estratos, denominadores y
|
||||
reglas de supresión aprobados. Los componentes de visualización ya consumen
|
||||
ese modelo tanto para las tasas como para los anillos.
|
||||
|
||||
@@ -62,6 +62,17 @@
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
},
|
||||
"simulado": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true,
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/app/app.config.ts",
|
||||
"with": "src/app/app.config.simulado.ts"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "production"
|
||||
@@ -77,6 +88,10 @@
|
||||
},
|
||||
"development": {
|
||||
"buildTarget": "WebApp:build:development"
|
||||
},
|
||||
"simulado": {
|
||||
"buildTarget": "WebApp:build:simulado",
|
||||
"proxyConfig": "simulado/proxy.simulado.json"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Modo simulado (solo nuestra copia local, rama `ulises/tea-seguimiento`)
|
||||
|
||||
Para ver y modificar la página de seguimiento de TEA sin la plataforma completa ni su preproceso.
|
||||
Todo es **inventado**. No forma parte de la WebApp que se entrega.
|
||||
|
||||
| Archivo | Qué es |
|
||||
|---|---|
|
||||
| `datos_tea.json` | 120 niños inventados: lista, ficha y la relación con el ADOS-2 (modelo de OR de E27). Se genera; no se versiona |
|
||||
| `servidor.py` | Servidor de prueba (Python, sin instalar nada) en `localhost:5051` |
|
||||
| `proxy.simulado.json` | Las rutas de la API, al servidor de prueba |
|
||||
| `../src/app/app.config.simulado.ts` | Igual que `app.config.ts`, pero el seguimiento de TEA lee el contrato JSON (`/tea/seguimiento`) |
|
||||
|
||||
## Cómo se usa
|
||||
|
||||
1. Generar los datos (una vez, o cuando cambie el modelo), desde `biomarcadores-tea/`:
|
||||
```
|
||||
python experimentos/E27_modelo_or/simulado_plataforma.py
|
||||
```
|
||||
2. Levantar el servidor de prueba, desde `webapp-tea/`:
|
||||
```
|
||||
python simulado/servidor.py
|
||||
```
|
||||
3. En otra terminal, la página, desde `webapp-tea/`:
|
||||
```
|
||||
npx ng serve --configuration simulado --port 4300
|
||||
```
|
||||
4. Abrir `http://localhost:4300/indicadores/tea`, entrar a **Seguimiento** y abrir un paciente.
|
||||
|
||||
## El panel nuevo: «Relación con el ADOS-2»
|
||||
|
||||
En la ficha del paciente (`tea-paciente-resumen.*`) muestra, por cada asociación clara de la cohorte (q < 0.05):
|
||||
- la zona del EEG y el z del paciente, marcada si está alterada (|z| ≥ 2);
|
||||
- el aspecto del ADOS-2 (reactivo o dominio);
|
||||
- el OR de la cohorte con su intervalo y su q;
|
||||
- la probabilidad que el modelo da a este paciente (con su edad y módulo) frente a la de un niño con z = 0;
|
||||
- lo que muestra su ADOS-2.
|
||||
|
||||
El campo `relacion_ados2` es opcional: sin él (la plataforma real hoy), el panel no aparece.
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"/api": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/imports": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/data": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/health": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/cacu": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/cama": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/tea": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/governance": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/reportes": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
servidor.py — Servidor de prueba con datos SIMULADOS para ver la página de TEA sin la plataforma completa.
|
||||
|
||||
Solo para nuestra copia local (rama ulises/tea-seguimiento): no forma parte de la WebApp que se entrega.
|
||||
Responde lo que pide la sección de seguimiento de TEA en su contrato JSON:
|
||||
- `/tea/seguimiento`: la lista, con filtros y páginas;
|
||||
- `/tea/seguimiento/<id>`: la ficha, incluido el campo nuevo `relacion_ados2`.
|
||||
|
||||
A lo demás de `/tea/...` contesta vacío, para que la página cargue.
|
||||
|
||||
Los datos los escribe `biomarcadores-tea/experimentos/E27_modelo_or/simulado_plataforma.py` en `datos_tea.json`.
|
||||
|
||||
python simulado/servidor.py # http://localhost:5051
|
||||
npx ng serve --configuration simulado --port 4300
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from datetime import date, timedelta
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, unquote, urlparse
|
||||
|
||||
PUERTO = 5051
|
||||
DATOS = json.loads((Path(__file__).with_name("datos_tea.json")).read_text(encoding="utf-8"))
|
||||
VACIO_FHIR = {"resourceType": "Bundle", "type": "searchset", "total": 0, "entry": []}
|
||||
|
||||
|
||||
def _num(q, k):
|
||||
v = q.get(k, [None])[0]
|
||||
try:
|
||||
return float(v) if v is not None else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def lista(q: dict) -> dict:
|
||||
meses = int(q.get("meses", ["12"])[0]) if q.get("meses", ["12"])[0] in ("1", "3", "6", "12") else 12
|
||||
corte = q.get("corte", [date.today().isoformat()])[0]
|
||||
page = max(1, int(q.get("page", ["1"])[0]))
|
||||
size = min(200, max(1, int(q.get("page_size", ["25"])[0])))
|
||||
filtro = q.get("alteraciones_eeg", [None])[0]
|
||||
ps = DATOS["pacientes"]
|
||||
if filtro in ("normal", "anormal"):
|
||||
ps = [p for p in ps if p["alteraciones_eeg"] == filtro]
|
||||
elif filtro == "sin_eeg_valido":
|
||||
ps = [p for p in ps if p["ultimo_eeg"] is None]
|
||||
if q.get("grupo_edad"):
|
||||
ps = [p for p in ps if p["grupo_edad"].startswith(q["grupo_edad"][0].replace("_", "-"))]
|
||||
for campo, lo, hi in (("mchat", "mchat_min", "mchat_max"), ("css_ados2", "css_min", "css_max")):
|
||||
a, b = _num(q, lo), _num(q, hi)
|
||||
if a is not None:
|
||||
ps = [p for p in ps if p[campo] is not None and a <= p[campo] <= (b if b is not None else 99)]
|
||||
if q.get("estado_caso"):
|
||||
ps = [p for p in ps if p["estado_caso"] == q["estado_caso"][0]]
|
||||
if q.get("alteracion"):
|
||||
ps = [p for p in ps if q["alteracion"][0] in p["alteraciones"]]
|
||||
total = len(ps)
|
||||
por_alt = [{"codigo": t["codigo"], "etiqueta": t["etiqueta"], "n": sum(t["codigo"] in p["alteraciones"] for p in ps)}
|
||||
for t in DATOS["tipos_alteracion"]]
|
||||
hasta = date.fromisoformat(corte)
|
||||
return {
|
||||
"simulado": True, "corte": corte,
|
||||
"ventana": {"meses": meses, "desde": (hasta - timedelta(days=30 * meses)).isoformat(), "hasta": corte},
|
||||
"filtros": {"alteraciones_eeg": filtro},
|
||||
"paginacion": {"page": page, "page_size": size, "total_items": total, "total_pages": max(1, math.ceil(total / size))},
|
||||
"items": ps[(page - 1) * size: page * size],
|
||||
"tipos_alteracion": DATOS["tipos_alteracion"],
|
||||
"resumen_eeg": {"validadas": True, "con_eeg_valido": total,
|
||||
"normales": sum(p["alteraciones_eeg"] == "normal" for p in ps),
|
||||
"anormales": sum(p["alteraciones_eeg"] == "anormal" for p in ps), "sin_eeg": 0,
|
||||
"por_alteracion": por_alt},
|
||||
}
|
||||
|
||||
|
||||
class Manejador(BaseHTTPRequestHandler):
|
||||
def _json(self, cuerpo, codigo=200):
|
||||
datos = json.dumps(cuerpo, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(codigo)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(datos)))
|
||||
self.end_headers()
|
||||
self.wfile.write(datos)
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
u = urlparse(self.path)
|
||||
ruta, q = u.path.rstrip("/"), parse_qs(u.query)
|
||||
if ruta == "/tea/seguimiento":
|
||||
return self._json(lista(q))
|
||||
if ruta.startswith("/tea/seguimiento/"):
|
||||
d = DATOS["detalles"].get(unquote(ruta.rsplit("/", 1)[1]))
|
||||
return self._json(d) if d else self._json({"error": "no encontrado"}, 404)
|
||||
if "/fhir/" in ruta:
|
||||
return self._json(VACIO_FHIR)
|
||||
if ruta.endswith("/indicadores"):
|
||||
return self._json([])
|
||||
if ruta == "/health":
|
||||
return self._json({"status": "ok", "simulado": True})
|
||||
return self._json({"error": "sin datos simulados para esta ruta"}, 404)
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
sys.stderr.write(" " + fmt % args + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"Servidor simulado en http://localhost:{PUERTO} ({len(DATOS['pacientes'])} niños inventados)")
|
||||
ThreadingHTTPServer(("127.0.0.1", PUERTO), Manejador).serve_forever()
|
||||
@@ -41,7 +41,7 @@ describe('Encabezado del marco', () => {
|
||||
const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.path)]);
|
||||
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);
|
||||
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
|
||||
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
|
||||
@@ -60,7 +60,7 @@ describe('Encabezado del marco', () => {
|
||||
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
|
||||
await ir('/indicadores/cama');
|
||||
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(selector()!.getAttribute('aria-expanded')).toBe('true');
|
||||
});
|
||||
@@ -69,7 +69,7 @@ describe('Encabezado del marco', () => {
|
||||
const items = await abrirMenu();
|
||||
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
|
||||
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.
|
||||
const ubicacion = TestBed.inject(Location);
|
||||
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
|
||||
@@ -80,7 +80,8 @@ describe('Encabezado del marco', () => {
|
||||
await ir(url);
|
||||
expect(selector()).toBeNull();
|
||||
expect(root().querySelector('.platform-title')).toBeNull();
|
||||
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
|
||||
expect(root().querySelector('.site-header__section')).toBeNull();
|
||||
expect(root().querySelector('.site-header__nav')?.textContent).not.toContain('Análisis de información');
|
||||
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
|
||||
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { routes } from './app.routes';
|
||||
import { IndicadoresService } from './features/indicadores/indicadores.service';
|
||||
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
|
||||
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
|
||||
|
||||
// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento
|
||||
// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`).
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
||||
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
||||
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
|
||||
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
|
||||
]
|
||||
};
|
||||
+1
-2
@@ -20,9 +20,8 @@
|
||||
}
|
||||
} @else {
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
<span class="site-header__crumb" aria-current="page">{{ crumb }}</span>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
|
||||
+29
-19
@@ -41,14 +41,6 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.site-header__section {
|
||||
text-decoration: none;
|
||||
color: var(--color-text);
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
@@ -89,11 +81,6 @@
|
||||
width: clamp(132px, 42vw, 170px);
|
||||
}
|
||||
|
||||
.site-header__section {
|
||||
font-size: 13px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.site-footer__content {
|
||||
min-height: 76px;
|
||||
padding: 0 20px;
|
||||
@@ -117,7 +104,8 @@
|
||||
|
||||
.domain-selector--espera {
|
||||
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
|
||||
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||
max-width: 100%; background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; line-height: 1.2;
|
||||
min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Session exit: the same action look as the home buttons, in header size. */
|
||||
@@ -160,9 +148,31 @@
|
||||
width: 18px;
|
||||
}
|
||||
|
||||
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
||||
@media (max-width: 599px) {
|
||||
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
||||
.app-shell--indicadores .brand { margin-inline-end: auto; }
|
||||
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
|
||||
// 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; }
|
||||
}
|
||||
|
||||
+10
-1
@@ -60,6 +60,15 @@ describe('App', () => {
|
||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('home shows only the brand name as eyebrow and names the risk models action', async () => {
|
||||
// Fails if the eyebrow regains the section text or the action goes back to «Indicadores».
|
||||
const page = await render('/');
|
||||
expect(page.querySelector('.home__eyebrow')?.textContent?.trim()).toBe('ISSSTELEON');
|
||||
const acciones = Array.from(page.querySelectorAll('.home__action')).map(a => a.textContent?.replace(/\s+/g, ' ').trim());
|
||||
expect(acciones.some(t => t?.endsWith('Modelos predictivos de riesgo'))).toBe(true);
|
||||
expect(acciones.some(t => t?.endsWith('Indicadores'))).toBe(false);
|
||||
});
|
||||
|
||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||
const page = await render('/conectar');
|
||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||
@@ -93,7 +102,7 @@ describe('App', () => {
|
||||
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('CaCu');
|
||||
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('Cáncer cervicouterino');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+3
-1
@@ -38,7 +38,9 @@ export class App {
|
||||
|
||||
protected readonly usuario = this.auth.usuario;
|
||||
protected readonly 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(
|
||||
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. */
|
||||
|
||||
@@ -13,9 +13,9 @@ import { DataConnection, SourceTable } from '../domain/data-source';
|
||||
import { ImportFlow } from '../domain/import-flow';
|
||||
|
||||
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: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' },
|
||||
{ id: 'tea', label: 'Trastorno del espectro autista', description: 'Trastorno del espectro autista' },
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
:host { display: contents; }
|
||||
.domain-selector {
|
||||
flex: 0 0 auto;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
min-height: 40px;
|
||||
background-color: var(--issste-accent);
|
||||
color: var(--issste-text);
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
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:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
|
||||
@@ -7,14 +7,19 @@ const HISTOLOGIA: Readonly<Record<string, string>> = {
|
||||
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
|
||||
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
|
||||
};
|
||||
const ESCENARIOS: Readonly<Record<string, string>> = { POST_TRATAMIENTO: 'Post-tratamiento', EN_OBSERVACION: 'En observación' };
|
||||
|
||||
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
|
||||
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
|
||||
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
|
||||
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
|
||||
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
|
||||
/** The patient's clinical scenario at the cut-off: «Post-tratamiento» or «En observación». */
|
||||
export const etiquetaEscenario = (codigo: string) => ESCENARIOS[codigo] ?? codigo;
|
||||
|
||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
|
||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = {
|
||||
birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia, escenario_clinico: etiquetaEscenario,
|
||||
};
|
||||
|
||||
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
|
||||
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
|
||||
|
||||
@@ -6,7 +6,7 @@ export interface Concept { coding?: Coding[]; text?: string }
|
||||
export interface Quantity { value?: number; unit?: string }
|
||||
export interface Extension {
|
||||
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 };
|
||||
extension?: Extension[];
|
||||
}
|
||||
@@ -30,9 +30,9 @@ export function code(concept: Concept | undefined): string | undefined {
|
||||
export function display(concept: Concept | undefined): string | undefined {
|
||||
return concept?.coding?.[0]?.display ?? concept?.text;
|
||||
}
|
||||
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
|
||||
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URI such as a URN).
|
||||
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
|
||||
const url = system.includes('://') ? system : CODE_SYSTEM + system;
|
||||
const url = system.includes(':') ? system : CODE_SYSTEM + system;
|
||||
return concept?.coding?.find(c => c.system === url)?.code;
|
||||
}
|
||||
// The extensions named `name` (the last segment of their URL).
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,41 +0,0 @@
|
||||
{
|
||||
"origen": "Sintético (WebApp). Conteos inventados para demostrar la visualización; sin significado clínico.",
|
||||
"categorias": [
|
||||
{ "id": "DUCTAL_NST", "etiqueta": "Ductal (NST)", "color": "#AD386D" },
|
||||
{ "id": "LOBULILLAR", "etiqueta": "Lobulillar", "color": "#5C55BB" },
|
||||
{ "id": "OTROS", "etiqueta": "Otros", "color": "#007F86" },
|
||||
{ "id": "DUCTAL_LOBULILLAR", "etiqueta": "Ductal-lobulillar mixto", "color": "#8767C9" },
|
||||
{ "id": "MUCINOSO", "etiqueta": "Mucinoso", "color": "#3274BF" },
|
||||
{ "id": "PAGET", "etiqueta": "Paget", "color": "#D35C91" },
|
||||
{ "id": "PAPILAR", "etiqueta": "Papilar", "color": "#537723" },
|
||||
{ "id": "TUBULAR_CRIBIFORME", "etiqueta": "Tubular / cribiforme", "color": "#9454AA" },
|
||||
{ "id": "MICROPAPILAR", "etiqueta": "Micropapilar", "color": "#C24938" },
|
||||
{ "id": "SIN_MAPEAR", "etiqueta": "SIN MAPEAR", "color": "#68778B" },
|
||||
{ "id": "INFLAMATORIO", "etiqueta": "Inflamatorio", "color": "#A4932A" },
|
||||
{ "id": "MEDULAR", "etiqueta": "Medular", "color": "#438573" }
|
||||
],
|
||||
"meses": {
|
||||
"2025-01": "A", "2025-02": "B", "2025-03": "A", "2025-04": "B", "2025-05": "B", "2025-06": "A",
|
||||
"2025-07": "B", "2025-08": "A", "2025-09": "B", "2025-10": "A", "2025-11": "B", "2025-12": "B",
|
||||
"2026-01": "A", "2026-02": "B", "2026-03": "A", "2026-04": "A", "2026-05": "B", "2026-06": "A",
|
||||
"2026-07": "A", "2026-08": "B", "2026-09": "B", "2026-10": "B", "2026-11": "A", "2026-12": "B"
|
||||
},
|
||||
"perfiles": {
|
||||
"A": {
|
||||
"BIRADS_4": { "benignos": 54, "subtipos": [8, 3, 2, 1, 1, 0, 1, 0, 0, 1, 0, 0], "sinBiopsia": 5, "sinDato": 1 },
|
||||
"BIRADS_4A": { "benignos": 93, "subtipos": [5, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0], "sinBiopsia": 9, "sinDato": 2 },
|
||||
"BIRADS_4B": { "benignos": 67, "subtipos": [19, 5, 3, 2, 1, 1, 1, 1, 0, 1, 0, 1], "sinBiopsia": 6, "sinDato": 2 },
|
||||
"BIRADS_4C": { "benignos": 30, "subtipos": [33, 9, 5, 4, 3, 1, 2, 2, 1, 2, 1, 1], "sinBiopsia": 4, "sinDato": 1 },
|
||||
"BIRADS_5": { "benignos": 10, "subtipos": [48, 12, 8, 6, 4, 3, 3, 2, 2, 2, 2, 1], "sinBiopsia": 3, "sinDato": 1 },
|
||||
"BIRADS_6": { "benignos": 0, "subtipos": [15, 4, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0], "sinBiopsia": 0, "sinDato": 1 }
|
||||
},
|
||||
"B": {
|
||||
"BIRADS_4": { "benignos": 49, "subtipos": [7, 2, 2, 1, 0, 0, 1, 0, 0, 2, 0, 1], "sinBiopsia": 6, "sinDato": 2 },
|
||||
"BIRADS_4A": { "benignos": 86, "subtipos": [6, 2, 0, 1, 0, 0, 1, 1, 0, 2, 0, 0], "sinBiopsia": 7, "sinDato": 1 },
|
||||
"BIRADS_4B": { "benignos": 66, "subtipos": [15, 4, 4, 2, 2, 0, 1, 1, 1, 1, 0, 0], "sinBiopsia": 4, "sinDato": 1 },
|
||||
"BIRADS_4C": { "benignos": 35, "subtipos": [31, 8, 5, 3, 2, 1, 3, 2, 1, 1, 1, 1], "sinBiopsia": 5, "sinDato": 2 },
|
||||
"BIRADS_5": { "benignos": 9, "subtipos": [44, 14, 7, 7, 5, 4, 3, 2, 2, 1, 2, 1], "sinBiopsia": 2, "sinDato": 2 },
|
||||
"BIRADS_6": { "benignos": 0, "subtipos": [17, 5, 3, 1, 2, 1, 0, 1, 1, 2, 1, 1], "sinBiopsia": 0, "sinDato": 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"cacu/CACU-CONFIRMACION-CITOLOGIA": {
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"indicador": {
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"version": "0.1.2",
|
||||
"titulo": "Tasa de confirmación histopatológica",
|
||||
"contrato": "C2",
|
||||
@@ -19,7 +19,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"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.",
|
||||
"ficha": {
|
||||
@@ -41,7 +41,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"titulo": "Tasa de confirmación histopatológica",
|
||||
"version": "0.1.2",
|
||||
"contrato": "C2",
|
||||
@@ -80,51 +80,14 @@
|
||||
"filas": []
|
||||
},
|
||||
"citologia_alto_grado": {
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"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": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
}
|
||||
}
|
||||
},
|
||||
"cacu/CACU-DIAS-TOMA-DIAGNOSTICO": {
|
||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"id": "cacu_dias_toma_diagnostico",
|
||||
"indicador": {
|
||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"id": "cacu_dias_toma_diagnostico",
|
||||
"version": "0.2.3",
|
||||
"titulo": "Tiempo de tamizaje a diagnóstico",
|
||||
"contrato": "C3r",
|
||||
@@ -139,7 +102,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"id": "cacu_dias_toma_diagnostico",
|
||||
"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.",
|
||||
"ficha": {
|
||||
@@ -171,7 +134,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
|
||||
"id": "cacu_dias_toma_diagnostico",
|
||||
"titulo": "Tiempo de tamizaje a diagnóstico",
|
||||
"version": "0.2.3",
|
||||
"contrato": "C3r",
|
||||
@@ -239,9 +202,9 @@
|
||||
}
|
||||
},
|
||||
"cacu/CACU-EU-TIEMPO-REPORTE": {
|
||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
||||
"id": "cacu_eu_tiempo_reporte",
|
||||
"indicador": {
|
||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
||||
"id": "cacu_eu_tiempo_reporte",
|
||||
"version": "0.2.1",
|
||||
"titulo": "Días de la toma de la citología a su resultado",
|
||||
"contrato": "C3r",
|
||||
@@ -256,7 +219,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
||||
"id": "cacu_eu_tiempo_reporte",
|
||||
"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.",
|
||||
"ficha": {
|
||||
@@ -288,7 +251,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_EU_TIEMPO_REPORTE",
|
||||
"id": "cacu_eu_tiempo_reporte",
|
||||
"titulo": "Días de la toma de la citología a su resultado",
|
||||
"version": "0.2.1",
|
||||
"contrato": "C3r",
|
||||
@@ -356,9 +319,9 @@
|
||||
}
|
||||
},
|
||||
"cacu/CACU-EU13": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"indicador": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"version": "0.3.2",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"contrato": "C1",
|
||||
@@ -376,7 +339,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"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.",
|
||||
"ficha": {
|
||||
@@ -408,7 +371,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -474,7 +437,7 @@
|
||||
]
|
||||
},
|
||||
"grupo_edad": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -592,7 +555,7 @@
|
||||
]
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -652,9 +615,9 @@
|
||||
}
|
||||
},
|
||||
"cacu/CACU-EU7": {
|
||||
"id": "CACU_EU7",
|
||||
"id": "cacu_eu7",
|
||||
"indicador": {
|
||||
"id": "CACU_EU7",
|
||||
"id": "cacu_eu7",
|
||||
"version": "0.3.3",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"contrato": "C2",
|
||||
@@ -672,7 +635,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "CACU_EU7",
|
||||
"id": "cacu_eu7",
|
||||
"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.",
|
||||
"ficha": {
|
||||
@@ -694,7 +657,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_EU7",
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
@@ -733,91 +696,17 @@
|
||||
"filas": []
|
||||
},
|
||||
"grupo_edad": {
|
||||
"id": "CACU_EU7",
|
||||
"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": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"id": "CACU_EU7",
|
||||
"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": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
}
|
||||
}
|
||||
},
|
||||
"cacu/CACU-RIESGO-BANDA": {
|
||||
"id": "CACU_RIESGO_BANDA",
|
||||
"id": "cacu_riesgo_banda",
|
||||
"indicador": {
|
||||
"id": "CACU_RIESGO_BANDA",
|
||||
"id": "cacu_riesgo_banda",
|
||||
"version": "0.1.0",
|
||||
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
|
||||
"contrato": "C2",
|
||||
@@ -831,7 +720,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "CACU_RIESGO_BANDA",
|
||||
"id": "cacu_riesgo_banda",
|
||||
"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.",
|
||||
"ficha": {
|
||||
@@ -853,7 +742,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_RIESGO_BANDA",
|
||||
"id": "cacu_riesgo_banda",
|
||||
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
@@ -894,9 +783,9 @@
|
||||
}
|
||||
},
|
||||
"cacu/IND1": {
|
||||
"id": "IND1",
|
||||
"id": "ind1",
|
||||
"indicador": {
|
||||
"id": "IND1",
|
||||
"id": "ind1",
|
||||
"version": "0.3.2",
|
||||
"titulo": "Pacientes con citología anómala",
|
||||
"contrato": "C1",
|
||||
@@ -911,7 +800,7 @@
|
||||
"filtros": []
|
||||
},
|
||||
"metadatos": {
|
||||
"id": "IND1",
|
||||
"id": "ind1",
|
||||
"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.",
|
||||
"ficha": {
|
||||
@@ -943,7 +832,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "IND1",
|
||||
"id": "ind1",
|
||||
"titulo": "Pacientes con citología anómala",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { modelosHistopatologiaDemo } from './histopatologia-cama-demo';
|
||||
import { recolorFigure } from './indicadores-c2-palette';
|
||||
import { categoriasExteriores, donaHistopatologia, figuraTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
|
||||
const nombres = [
|
||||
'Ductal (NST)', 'Lobulillar', 'Otros', 'Ductal-lobulillar mixto', 'Mucinoso', 'Paget', 'Papilar',
|
||||
'Tubular / cribiforme', 'Micropapilar', 'SIN MAPEAR', 'Inflamatorio', 'Medular',
|
||||
];
|
||||
const [modelo] = modelosHistopatologiaDemo('mes', ['2025-02']);
|
||||
const suma = (valores: number[]) => valores.reduce((a, b) => a + b, 0);
|
||||
|
||||
describe('Fuente sintética de histopatología CaMa', () => {
|
||||
it('dibuja los 12 subtipos en orden, con colores distintos y con el subtotal del grupo exterior', () => {
|
||||
const seleccion = seleccionBase(modelo);
|
||||
const [, interior, exterior] = recolorFigure(donaHistopatologia(modelo, seleccion, 'claro')).data;
|
||||
expect(exterior['labels']).toEqual(nombres);
|
||||
expect(categoriasExteriores(modelo).map(c => c.etiqueta)).toEqual(nombres);
|
||||
const colores = categoriasExteriores(modelo).map(c => c.color);
|
||||
expect(new Set(colores).size).toBe(12);
|
||||
expect(exterior['marker']).toMatchObject({ colors: colores });
|
||||
expect(interior['labels']).toEqual(['No maligno', 'Riesgo a carcinoma']);
|
||||
expect(suma(exterior['values'] as number[])).toBe((interior['values'] as number[])[1]);
|
||||
expect(suma(interior['values'] as number[])).toBe(modelo.conResultado);
|
||||
expect((exterior['values'] as number[]).every(n => n > 0)).toBe(true);
|
||||
});
|
||||
|
||||
it('mantiene SIN MAPEAR en mayúsculas y evita porcentajes indefinidos en un anillo sin casos', () => {
|
||||
const figura = figuraTasas(modelo, { grupo: modelo.base, categoria: 'SIN_MAPEAR' }, 'claro');
|
||||
expect(figura.layout['xaxis']).toMatchObject({ title: { text: 'Porcentaje con SIN MAPEAR' } });
|
||||
const benignos = modelo.totales['BENIGNO'];
|
||||
const totales = { ...modelo.totales, ...Object.fromEntries(categoriasExteriores(modelo).map(c => [c.id, 0])) };
|
||||
const sinCasos = { ...modelo, totales, conResultado: benignos };
|
||||
const exterior = donaHistopatologia(sinCasos, seleccionBase(sinCasos), 'claro').data[2];
|
||||
expect(exterior['customdata']).toEqual(nombres.map(() => ['0', '—']));
|
||||
});
|
||||
|
||||
it('reconcilia barras, anillos y tabla para cada selección, incluidos los ceros', () => {
|
||||
for (const { id, grupo } of modelo.categorias) {
|
||||
const seleccion = { grupo, categoria: id };
|
||||
const valores = tasas(modelo, seleccion);
|
||||
expect(suma(valores.map(t => t.k!))).toBe(modelo.totales[id]);
|
||||
for (const { fila, k, valor, bajo, alto } of valores) {
|
||||
expect(k).toBe(fila.celdas[id].n);
|
||||
expect(valor).toBe(100 * k! / fila.den!);
|
||||
expect(bajo).toBeGreaterThanOrEqual(0);
|
||||
expect(alto).toBeLessThanOrEqual(100);
|
||||
expect(fila.total.n).toBe(fila.den! + fila.aparte['SIN_BIOPSIA'].n! + fila.aparte['SIN_DATO'].n!);
|
||||
}
|
||||
const [barra] = figuraTasas(modelo, seleccion, 'oscuro', true).data;
|
||||
expect(barra['type']).toBe('bar');
|
||||
expect(barra['x']).toEqual(valores.map(t => t.valor));
|
||||
}
|
||||
expect(tasas(modelo, { grupo: modelo.base, categoria: 'MICROPAPILAR' })[0].valor).toBe(0);
|
||||
});
|
||||
|
||||
it('agrega los mismos meses en cada semestre y devuelve vacío fuera de cobertura', () => {
|
||||
const semestres = modelosHistopatologiaDemo('semestre');
|
||||
expect(semestres.map(m => m.periodo)).toEqual(['2025-S1', '2025-S2', '2026-S1', '2026-S2']);
|
||||
const primerSemestre = modelosHistopatologiaDemo('mes').filter(m => m.periodo <= '2025-06');
|
||||
for (const { id } of modelo.categorias) {
|
||||
expect(semestres[0].totales[id]).toBe(suma(primerSemestre.map(m => m.totales[id]!)));
|
||||
}
|
||||
expect(modelosHistopatologiaDemo('mes', ['2025-03', '2025-02']).map(m => m.periodo)).toEqual(['2025-03', '2025-02']);
|
||||
expect(modelosHistopatologiaDemo('mes', ['2024-10'])).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([true, false])('Resumen usa los datos incorporados con medida publicada = %s', publicada => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [
|
||||
provideRouter([]), provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PLOTLY_LOADER, useValue: () => new Promise(() => {}) },
|
||||
] });
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
const memory = TestBed.inject(IndicadoresMemory);
|
||||
for (const dominio of ['cama', 'cacu', 'tea'] as const) memory.finishInitialKpiPresentation(dominio);
|
||||
const f = TestBed.createComponent(IndicadoresPage);
|
||||
const catalogo = (id: string) => [{ id, titulo: 'Indicador publicado', contrato: 'C2', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
|
||||
http.expectOne('/tea/indicadores').flush(catalogo('tea_prueba'));
|
||||
f.componentInstance.changeDominio('cama');
|
||||
const idsCama = ['cama_birads_456_mastografia', 'cama_birads_456_paciente'];
|
||||
if (publicada) idsCama.push('cama_histopatologia_birads');
|
||||
http.expectOne('/cama/indicadores').flush(idsCama.flatMap(catalogo));
|
||||
f.detectChanges();
|
||||
const tarjeta = f.debugElement.query(node => node.componentInstance instanceof IndicadorHistopatologiaCama);
|
||||
expect(tarjeta).toBeTruthy();
|
||||
const histo = tarjeta.componentInstance as IndicadorHistopatologiaCama;
|
||||
const card = f.debugElement.queryAll(By.directive(IndicadorCatalogCard))
|
||||
.map(node => node.componentInstance as IndicadorCatalogCard)
|
||||
.find(item => item.indicador.id === 'cama_histopatologia_birads')!;
|
||||
card.setVisible(true);
|
||||
f.detectChanges();
|
||||
expect(histo.status()).toBe('ready');
|
||||
expect(histo.contextPeriod).toBe('2026-S2');
|
||||
expect(f.nativeElement.textContent).toContain('Tiempo de diagnóstico a tratamiento');
|
||||
expect(f.componentInstance.catalog().map(item => item.id)).toEqual(idsCama);
|
||||
expect(f.nativeElement.querySelector('app-indicador-conteos-pareados')).not.toBeNull();
|
||||
expect([...tarjeta.nativeElement.querySelectorAll('.child')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(nombres);
|
||||
expect(histo.selectionLabel).toBe('Riesgo a carcinoma');
|
||||
|
||||
histo.plotClicked({ points: [{ data: { name: 'categorias' }, pointNumber: 9 }] });
|
||||
f.detectChanges();
|
||||
expect(histo.selectionLabel).toBe('SIN MAPEAR');
|
||||
expect(histo.ratesFigure!.data[0]['x']).toEqual(tasas(histo.model!, histo.selection!).map(t => t.valor));
|
||||
expect(tarjeta.nativeElement.querySelector('.child[aria-pressed=true]').textContent.trim()).toBe('SIN MAPEAR');
|
||||
histo.plotClicked({ points: [{ data: { name: 'grupos' }, pointNumber: 0 }] });
|
||||
expect(histo.selectionLabel).toBe('No maligno');
|
||||
histo.plotClicked({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] });
|
||||
expect(histo.selectionLabel).toBe('Riesgo a carcinoma');
|
||||
histo.changePeriod(-1);
|
||||
expect(histo.contextPeriod).toBe('2026-S1');
|
||||
histo.showHelp();
|
||||
f.detectChanges();
|
||||
expect(tarjeta.nativeElement.querySelector('.methodology').textContent).toContain('El exterior muestra solo la distribución de los subtipos');
|
||||
http.expectNone(req => /cama_histopatologia_birads\/(datos|metadatos)$/.test(req.url));
|
||||
|
||||
for (const dominio of ['cacu', 'tea'] as const) {
|
||||
f.componentInstance.changeDominio(dominio);
|
||||
http.expectOne('/' + dominio + '/indicadores').flush(catalogo(dominio + '_prueba'));
|
||||
f.detectChanges();
|
||||
expect(f.nativeElement.querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
||||
expect(f.nativeElement.querySelector('.catalog-grid').textContent).toContain('Indicador publicado');
|
||||
}
|
||||
f.destroy();
|
||||
http.match(() => true);
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
@@ -1,53 +0,0 @@
|
||||
import fixture from './fixtures/cama_histopatologia_birads_demo_sintetica.json';
|
||||
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { Celda } from './indicadores-confirmacion-citologia';
|
||||
import {
|
||||
APARTE, ESTRATOS_BIRADS, ETIQUETA_ESTRATO, FilaBirads, ModeloHistopatologia,
|
||||
} from './indicadores-histopatologia-cama';
|
||||
import { TipoPeriodo } from './indicadores.models';
|
||||
|
||||
const RIESGO = 'RIESGO_CARCINOMA';
|
||||
const NO_MALIGNO = 'NO_MALIGNO';
|
||||
const BENIGNO = 'BENIGNO';
|
||||
const subtipos = fixture.categorias.map(c => ({ ...c, grupo: RIESGO }));
|
||||
const categorias = [
|
||||
...subtipos,
|
||||
{ id: BENIGNO, etiqueta: 'Benigno', color: C2_PALETTE.frios[0], grupo: NO_MALIGNO },
|
||||
];
|
||||
const grupos = [
|
||||
{ id: NO_MALIGNO, etiqueta: 'No maligno', color: C2_PALETTE.frios[3], categorias: [BENIGNO] },
|
||||
{ id: RIESGO, etiqueta: 'Riesgo a carcinoma', color: C2_PALETTE.calidos[0], categorias: subtipos.map(c => c.id) },
|
||||
];
|
||||
|
||||
const meses = Object.entries(fixture.meses).map(([mes, perfil]) => ({
|
||||
mes,
|
||||
semestre: mes.slice(0, 4) + (mes.slice(5) <= '06' ? '-S1' : '-S2'),
|
||||
perfil: fixture.perfiles[perfil as keyof typeof fixture.perfiles],
|
||||
}));
|
||||
const sumar = (valores: number[]) => valores.reduce((total, n) => total + n, 0);
|
||||
const publicada = (n: number) => ({ n, estado: 'Publicado' as const });
|
||||
|
||||
export function modelosHistopatologiaDemo(tipo: TipoPeriodo, solicitados?: readonly string[]): ModeloHistopatologia[] {
|
||||
const disponibles = [...new Set(meses.map(mes => mes[tipo]))].sort();
|
||||
const periodos = solicitados ? solicitados.filter(p => disponibles.includes(p)) : disponibles;
|
||||
return periodos.map(periodo => {
|
||||
const enPeriodo = meses.filter(mes => mes[tipo] === periodo);
|
||||
const filas: FilaBirads[] = ESTRATOS_BIRADS.map(id => {
|
||||
const datos = enPeriodo.map(mes => mes.perfil[id]);
|
||||
const celdas: Record<string, Celda> = Object.fromEntries(subtipos.map((subtipo, i) =>
|
||||
[subtipo.id, publicada(sumar(datos.map(d => d.subtipos[i])))]
|
||||
));
|
||||
celdas[BENIGNO] = publicada(sumar(datos.map(d => d.benignos)));
|
||||
const den = sumar(Object.values(celdas).map(celda => celda.n!));
|
||||
const sinBiopsia = sumar(datos.map(d => d.sinBiopsia));
|
||||
const sinDato = sumar(datos.map(d => d.sinDato));
|
||||
return { id, etiqueta: ETIQUETA_ESTRATO[id], celdas, den, estado: 'Publicado',
|
||||
aparte: { SIN_BIOPSIA: publicada(sinBiopsia), SIN_DATO: publicada(sinDato) },
|
||||
total: publicada(den + sinBiopsia + sinDato) };
|
||||
});
|
||||
const totales = Object.fromEntries(categorias.map(c => [c.id, sumar(filas.map(fila => fila.celdas[c.id].n!))]));
|
||||
return { periodo, categorias, grupos, base: RIESGO, filas, totales,
|
||||
conResultado: sumar(Object.values(totales)), aparte: [...APARTE], vacio: false, notas: [],
|
||||
grupoAnilloExterior: RIESGO };
|
||||
});
|
||||
}
|
||||
@@ -36,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
|
||||
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.
|
||||
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
|
||||
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
|
||||
|
||||
@@ -56,7 +56,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
</div>
|
||||
} @else if (isHistopatologia) {
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
|
||||
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (tiempos; as par) {
|
||||
<div #visibilityRegion class="tiempos-region">
|
||||
@@ -135,8 +135,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
|
||||
});
|
||||
}
|
||||
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
|
||||
get sobrio() { return this.dominio === 'cama'; }
|
||||
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
|
||||
get sobrio() { return true; }
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
@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) {
|
||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, ' + m.periodo;
|
||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
|
||||
@@ -9,7 +9,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
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,
|
||||
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);
|
||||
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')
|
||||
|| !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.status.set('incompatible'); return;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified';
|
||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
@@ -25,8 +25,48 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
selector: 'app-indicador-figure-panel',
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section class="figure-panel" [attr.aria-labelledby]="titleId">
|
||||
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
@if (sidebar) {
|
||||
<aside class="strata-sidebar" aria-label="Estratificación">
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Estratificar por</legend>
|
||||
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
|
||||
(click)="changeDimension('')">Sin estratificar</button>
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
|
||||
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||
}
|
||||
</div>
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
|
||||
@if (dimension && estratos.length > 1) {
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Mostrar</legend>
|
||||
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
|
||||
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
|
||||
@for (e of estratos; track e.valor) {
|
||||
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
|
||||
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
|
||||
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
|
||||
</fieldset>
|
||||
}
|
||||
@if (dimension) {
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Medida</legend>
|
||||
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
}
|
||||
</aside>
|
||||
}
|
||||
<header class="panel-controls">
|
||||
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
|
||||
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
|
||||
@@ -36,7 +76,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
|
||||
</span>
|
||||
}
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
|
||||
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
||||
<legend>Distribución</legend>
|
||||
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
|
||||
@@ -49,10 +89,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
|
||||
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (dimension) {
|
||||
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||
}
|
||||
@@ -71,8 +117,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
|
||||
</tbody></table></div>
|
||||
</details>
|
||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||
@@ -117,6 +163,30 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
|
||||
.donut-periods button:disabled { opacity: .45; }
|
||||
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
|
||||
shared with the neighbouring panel, so the bars line up with the donut. */
|
||||
:host { container-type: inline-size; }
|
||||
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
|
||||
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
|
||||
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
|
||||
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
|
||||
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
|
||||
.sidebar-list { display: grid; gap: .25rem; }
|
||||
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
|
||||
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
|
||||
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.sidebar-reset { margin-top: .5rem; }
|
||||
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
@container (max-width: 559px) {
|
||||
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
|
||||
.strata-sidebar { position: static; }
|
||||
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
|
||||
}
|
||||
.visually-hidden {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
@@ -165,7 +235,39 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||
}
|
||||
dimension: DimensionEstrato | '' = '';
|
||||
readonly etiquetaDimension = etiquetaDimension;
|
||||
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
|
||||
private medidaElegida?: MedidaEstrato;
|
||||
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
|
||||
changeMedida(medida: MedidaEstrato) {
|
||||
if (medida === this.medida) return;
|
||||
this.medidaElegida = medida;
|
||||
this.representStratified();
|
||||
}
|
||||
cells: StratifiedCell[] = [];
|
||||
/** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */
|
||||
get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; }
|
||||
estratos: StratumOption[] = [];
|
||||
ocultos = new Set<string>();
|
||||
toggleEstrato(valor: string) {
|
||||
const ocultos = new Set(this.ocultos);
|
||||
if (ocultos.has(valor)) ocultos.delete(valor);
|
||||
else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor);
|
||||
else return;
|
||||
this.ocultos = ocultos;
|
||||
this.representStratified();
|
||||
}
|
||||
mostrarTodos() {
|
||||
if (!this.ocultos.size) return;
|
||||
this.ocultos = new Set();
|
||||
this.representStratified();
|
||||
}
|
||||
private representStratified() {
|
||||
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||
try { this.result.set(this.presentStratified(this.stratifiedData)); }
|
||||
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
|
||||
}
|
||||
}
|
||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||
private stratifiedData?: IndicadorDatos;
|
||||
@@ -177,14 +279,18 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
changeDimension(value: DimensionEstrato | '') {
|
||||
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
|
||||
if (this.dimension === value) return;
|
||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
|
||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set();
|
||||
this.requestFigure();
|
||||
}
|
||||
chooseStratified() {
|
||||
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
|
||||
}
|
||||
private presentStratified(data: IndicadorDatos): FigureState {
|
||||
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
|
||||
this.estratos = stratumOptions(data);
|
||||
const publicados = new Set(this.estratos.map(e => e.valor));
|
||||
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos);
|
||||
this.cells = adapted.cells;
|
||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||
@@ -349,7 +455,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
}
|
||||
}
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) {
|
||||
this.dimension = ''; this.estratos = []; this.ocultos = new Set();
|
||||
}
|
||||
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
||||
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
|
||||
this.titleId = identityElementId(identity) + '-title';
|
||||
|
||||
@@ -8,20 +8,27 @@
|
||||
<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>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology" id="histo-como-leer" role="tooltip">
|
||||
<p>Cada barra muestra el porcentaje de pacientes con resultado de biopsia en la categoría BI-RADS que corresponde a la selección. La línea indica el intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» se muestran aparte en la tabla.</p>
|
||||
<p>El anillo interior compara los grupos entre todas las pacientes con resultado. El exterior muestra solo la distribución de los subtipos dentro de «Riesgo a carcinoma». Selecciona un sector o su etiqueta para actualizar las barras.</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 (metadata) {
|
||||
@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>
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('incompatible') { <p role="alert">{{ message }}</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 ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'empty') {
|
||||
<p role="status">No hay resultados de biopsia para el periodo seleccionado.</p>
|
||||
}
|
||||
@if (status() === 'ready') {
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" aria-label="Periodos de la histopatología por BI-RADS">
|
||||
<button type="button" aria-label="Periodo anterior de la histopatología" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
@@ -30,6 +37,8 @@
|
||||
</nav>
|
||||
}
|
||||
@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> }
|
||||
@else {
|
||||
<div class="legend">
|
||||
<div class="tab-bar">
|
||||
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
|
||||
@@ -41,7 +50,7 @@
|
||||
<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 categoriasExteriores(m); track c.id; let ci = $index) {
|
||||
@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>
|
||||
}
|
||||
@@ -62,8 +71,9 @@
|
||||
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Ver valores</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">
|
||||
<table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead>
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { snapshotKey } from './indicadores-snapshots';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { Celda } from './indicadores-confirmacion-citologia';
|
||||
import { categoriasExteriores, clicHistopatologia, donaHistopatologia, figuraTasas, ID_HISTOPATOLOGIA,
|
||||
ModeloHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta } from './indicadores-histopatologia-cama';
|
||||
import { modelosHistopatologiaDemo } from './histopatologia-cama-demo';
|
||||
import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA,
|
||||
lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama';
|
||||
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const;
|
||||
|
||||
/**
|
||||
* CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the
|
||||
* result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service
|
||||
* for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-indicador-histopatologia-cama',
|
||||
imports: [PlotlyChart],
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-histopatologia-cama.html',
|
||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||
})
|
||||
@@ -19,7 +32,9 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
readonly status = signal<'deferred' | 'ready' | 'empty' | 'incompatible'>('deferred');
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
selection?: SeleccionHistopatologia;
|
||||
periods: string[] = [];
|
||||
@@ -28,9 +43,10 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
donutFigure?: PlotlyFigure;
|
||||
ratesFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
readonly categoriasExteriores = categoriasExteriores;
|
||||
private helpPinned = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: ModeloHistopatologia[] = [];
|
||||
@@ -45,8 +61,21 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
?? (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 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 rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||
readonly estadoTasa = estadoTasa;
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() {
|
||||
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
|
||||
this.helpPinned = true;
|
||||
@@ -55,6 +84,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
showHelp() {
|
||||
if (this.helpOpen) return;
|
||||
this.helpOpen = true;
|
||||
this.metadataRequested.emit();
|
||||
}
|
||||
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
|
||||
onHelpFocusOut(event: FocusEvent) {
|
||||
@@ -65,32 +95,53 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied)
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]);
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
||||
if (key !== this.key) {
|
||||
this.key = key; this.loaded = false;
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() {
|
||||
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
||||
this.donutFigure = undefined; this.ratesFigure = undefined;
|
||||
}
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const { tipo, selection } = this.applied;
|
||||
this.pages = modelosHistopatologiaDemo(tipo, selection.mode === 'explicit' ? selection.periodos : undefined);
|
||||
this.periods = this.pages.map(modelo => modelo.periodo);
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1);
|
||||
this.activatePeriod();
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
||||
{ estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosHistopatologia(datos, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloHistopatologia(datos, p));
|
||||
// The most recent period first; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex];
|
||||
@@ -115,5 +166,5 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Component, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
|
||||
/**
|
||||
* CaMa's histopathological result by BI-RADS category, while the catalog does not publish its indicator
|
||||
* (`cama_histopatologia_birads`). It keeps the card's place and structure, with no figure and no number.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-indicador-histopatologia-pendiente',
|
||||
host: { class: 'dual-card' },
|
||||
imports: [MatButtonModule, MatCardModule],
|
||||
template: `
|
||||
<mat-card>
|
||||
<h2>Resultado histopatológico por categoría BI-RADS</h2>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="ayuda()" (click)="ayuda.set(!ayuda())">Cómo leer</button>
|
||||
@if (ayuda()) {
|
||||
<div class="methodology">
|
||||
<p>Cuando el catálogo publique el indicador, esta tarjeta mostrará, por categoría BI-RADS, el porcentaje de biopsias con resultado maligno y su intervalo de confianza, y la distribución del resultado de la biopsia en una dona que se puede recorrer por grupo y por resultado.</p>
|
||||
</div>
|
||||
}
|
||||
<p class="estado" role="status"><strong>Integración pendiente.</strong> Este indicador aún no está publicado por el catálogo institucional.</p>
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Por categoría BI-RADS</h3><div class="vacio">Sin datos publicados</div></section>
|
||||
<section class="figure"><h3>Resultado de la biopsia</h3><div class="vacio">Sin datos publicados</div></section>
|
||||
</div>
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; grid-column: 1 / -1; }
|
||||
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; }
|
||||
h3 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.estado { color: var(--issste-text-secondary); }
|
||||
.methodology { margin-top: var(--issste-space-3); padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.methodology p { margin: 0; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); margin-top: var(--issste-space-3); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.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); }
|
||||
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorHistopatologiaPendiente {
|
||||
readonly ayuda = signal(false);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
<div class="kpi-foot">
|
||||
@if (temporalReference) {
|
||||
@if (showPeriod && temporalReference) {
|
||||
<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>
|
||||
@@ -37,9 +37,9 @@ import { MatCardModule } from '@angular/material/card';
|
||||
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
// CaMa's cards are as tall as their grid row.
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
|
||||
:host-context(.kpi-section) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section) mat-card { flex: 1 1 auto; height: auto; }
|
||||
:host-context(.kpi-section) .value { font-size: 1.65rem; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiCard {
|
||||
@@ -47,6 +47,8 @@ export class IndicadorKpiCard {
|
||||
@Input() value?: string | number | null;
|
||||
@Input() unit?: 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() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
|
||||
@@ -39,7 +39,8 @@ describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
latest.flush(data(periods[0], 'suppressed'));
|
||||
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
|
||||
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.');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
@@ -190,9 +190,11 @@ describe('KPI integración con autoridad global', () => {
|
||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
|
||||
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
||||
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(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');
|
||||
// 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);
|
||||
|
||||
@@ -19,14 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[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]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="true"
|
||||
[showPeriod]="false" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
|
||||
:host-context(.kpi-section) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section) app-indicador-kpi-card { flex: 1 1 auto; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
|
||||
@@ -38,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 button { min-height: 44px; }
|
||||
.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 .apply-button { margin-top: 0; }
|
||||
@media (max-width: 550px) {
|
||||
|
||||
@@ -97,13 +97,13 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
|
||||
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
|
||||
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
|
||||
<tbody>@for (i of d.items; track i.codigo) {
|
||||
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
|
||||
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
|
||||
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
|
||||
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
|
||||
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
|
||||
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Análisis de riesgos'">Ver pacientes</button> }</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
|
||||
@@ -155,7 +155,7 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
|
||||
}
|
||||
@if (m(); as mm) {
|
||||
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
|
||||
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
|
||||
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Análisis de riesgos.</p>
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
|
||||
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
|
||||
|
||||
@@ -127,7 +127,7 @@ describe('Pestaña Análisis epidemiológico', () => {
|
||||
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
|
||||
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
|
||||
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
|
||||
expect(text()).toContain('abrir la lista en Seguimiento');
|
||||
expect(text()).toContain('abrir la lista en Análisis de riesgos');
|
||||
});
|
||||
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
|
||||
// Fails if the cards stay on screen without an answer with categories.
|
||||
@@ -177,7 +177,7 @@ describe('Pestaña Análisis epidemiológico', () => {
|
||||
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
|
||||
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
|
||||
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
|
||||
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
|
||||
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Análisis de riesgos');
|
||||
});
|
||||
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
|
||||
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
|
||||
|
||||
@@ -93,18 +93,18 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
|
||||
<p class="aviso" role="status">{{ aviso() }}</p>
|
||||
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
|
||||
label="Pacientes por categoría BI-RADS" />
|
||||
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
|
||||
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Análisis de riesgos. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
|
||||
<table>
|
||||
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
|
||||
<tbody>
|
||||
@for (g of d.grupos; track g.codigo) {
|
||||
<tr [attr.data-grupo]="g.codigo">
|
||||
<th scope="row">{{ etiqueta(g.codigo) }}</th>
|
||||
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
|
||||
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
|
||||
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
|
||||
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Análisis de riesgos'">Ver pacientes</button> }</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
|
||||
@@ -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,133 @@
|
||||
// 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';
|
||||
|
||||
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 two 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_toma_diagnostico: ['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');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
// 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-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
|
||||
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
|
||||
'CACU-EU13': 'cacu_eu13',
|
||||
'CACU-EU7': 'cacu_eu7',
|
||||
'CACU-RIESGO-BANDA': 'cacu_riesgo_banda',
|
||||
'IND1': 'ind1',
|
||||
};
|
||||
@@ -101,12 +101,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(before[0].indicador.id).toBe('cacu_eu7');
|
||||
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();
|
||||
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));
|
||||
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(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
|
||||
@@ -32,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () =>
|
||||
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
|
||||
// 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))
|
||||
.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.' });
|
||||
});
|
||||
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);
|
||||
@@ -210,13 +210,14 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
expect(root().querySelector('.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 resultado maligno.');
|
||||
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()[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', () => {
|
||||
const pedidos = cargar(completo());
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
const primera = tarjetas()[0];
|
||||
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
@@ -230,10 +231,13 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_tasa_deteccion_histopatologica');
|
||||
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico');
|
||||
});
|
||||
it('sin CAM-03 en el catálogo conserva el KPI y la tarjeta con fuente local', () => {
|
||||
const pedidos = cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||
expect(kpis()).toHaveLength(5);
|
||||
expect(root().querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
expect(pedidos).not.toContain('cama_histopatologia_birads');
|
||||
it('sin CAM-03 en el catálogo la tarjeta sigue pendiente, como antes', () => {
|
||||
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).not.toBeNull();
|
||||
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
||||
});
|
||||
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')]);
|
||||
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', () => {
|
||||
// Pins down: only CaMa's measures use the table; TEA's and CaCu's keep `-` to `_`. Fails if the table captures
|
||||
// ids of other domains or the generic rule changes.
|
||||
// Pins down: only CaMa's table maps CaMa's measures, and TEA's keep `-` to `_` (CaCu has a table of its own, see
|
||||
// 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('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', () => {
|
||||
@@ -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]);
|
||||
});
|
||||
});
|
||||
|
||||
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.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
|
||||
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
|
||||
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` });
|
||||
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', () => {
|
||||
|
||||
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
|
||||
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
|
||||
]);
|
||||
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
|
||||
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
|
||||
});
|
||||
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
|
||||
@@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => {
|
||||
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
|
||||
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
|
||||
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con resultado maligno.' });
|
||||
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
|
||||
});
|
||||
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
|
||||
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
@@ -213,8 +213,10 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
|
||||
expect(cards().map(card => text(card, 'h3'))).toEqual([
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica',
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica',
|
||||
'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']);
|
||||
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]);
|
||||
expect(cards().map(card => text(card, '.kpi-state'))).toEqual([
|
||||
@@ -234,7 +236,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
expect(text(cards()[4], '.kpi-state')).toBe('Indicador no disponible');
|
||||
expect(text(cards()[4], '.value')).toBeUndefined();
|
||||
expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false);
|
||||
expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.');
|
||||
expect(cards()[1].textContent).toContain('2 de 5 biopsias con riesgo a carcinoma.');
|
||||
});
|
||||
it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => {
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
@@ -254,7 +256,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
|
||||
expect(text(cards()[0], '.value')).toBe('5pacientes');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía interpretación radiológica"]')).not.toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía a interpretación radiológica"]')).not.toBeNull();
|
||||
});
|
||||
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
|
||||
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Covers the clinical section of CaMa's summary: its heading and counter, and the controls the mockup does not
|
||||
// have (search, pins, floating navigation, representation selector, figure count), which CaCu and TEA keep.
|
||||
// Covers the clinical section: its heading, and the controls the mockup does not have
|
||||
// (search, pins, floating navigation, representation selector, figure count) in every domain.
|
||||
// Fixtures are catalogs shaped like /<dominio>/indicadores; no figure is requested (the cards stay out of view).
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -53,8 +53,8 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
expect(titles()).not.toContain('Distribución de resultados de biopsia');
|
||||
// The patients' counts go on the exams' card, so the partner indicator has no card of its own.
|
||||
expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6');
|
||||
// The paired card has no card title; each donut names itself.
|
||||
expect(titles()).toEqual(['Resultado histopatológico por categoría BI-RADS']);
|
||||
// The paired card has no card title; each donut names itself. The other three indicators are in Histórico.
|
||||
expect(titles()).toEqual([]);
|
||||
expect(root().querySelector('app-indicador-conteos-pareados')).not.toBeNull();
|
||||
expect(section().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6');
|
||||
expect(root().textContent).not.toContain('indicador publicado');
|
||||
@@ -73,21 +73,26 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6');
|
||||
expect(nombres).not.toContain(CAMA[1].titulo);
|
||||
});
|
||||
it('CaMa: la tarjeta de histopatología tiene su lugar aunque la medida no figure en el catálogo', () => {
|
||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
||||
open('cama', CAMA);
|
||||
const primera = root().querySelector('.catalog-grid')!.firstElementChild!;
|
||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
expect(primera.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
|
||||
expect(fixture.componentInstance.catalog().map(item => item.id)).not.toContain('cama_histopatologia_birads');
|
||||
const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement;
|
||||
expect(tarjeta).not.toBeNull();
|
||||
expect(tarjeta.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
|
||||
expect(tarjeta.querySelector('[role=status]')?.textContent).toContain('Integración pendiente');
|
||||
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
|
||||
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
|
||||
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
|
||||
// It comes first, as in the reference, and is not counted as a published indicator.
|
||||
expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta);
|
||||
});
|
||||
it('CaMa: si el catálogo publica la medida, Resumen dibuja una sola tarjeta de histopatología', () => {
|
||||
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
|
||||
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
||||
expect(root().querySelectorAll('app-indicador-histopatologia-cama')).toHaveLength(1);
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
expect(titles()).toContain('Resultado histopatológico por categoría BI-RADS');
|
||||
});
|
||||
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica de CaMa', domain => {
|
||||
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica pendiente', domain => {
|
||||
open(domain, OTRO(domain));
|
||||
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
});
|
||||
it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => {
|
||||
// Fails if any of the controls the mockup does not have comes back to CaMa's summary.
|
||||
@@ -108,18 +113,14 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
|
||||
expect(titles()).toEqual(before);
|
||||
});
|
||||
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados y conteo de figuras', domain => {
|
||||
// Fails if CaMa's simplified section leaks into the other domains.
|
||||
it.each(['tea', 'cacu'] as const)('%s usa el mismo resumen clínico que CaMa: sin buscador, fijados ni conteo de figuras', domain => {
|
||||
open(domain, OTRO(domain));
|
||||
expect(root().querySelector('.catalog-search')).not.toBeNull();
|
||||
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||
expect(section().textContent).toContain('2 figuras publicadas');
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
expect(root().querySelector('#dashboard-title')?.textContent?.trim()).toBe(domain === 'tea' ? 'Trastorno del espectro autista' : 'Cáncer cervicouterino');
|
||||
expect(root().querySelector('header .domain')).toBeNull();
|
||||
expect(root().querySelector('.catalog-search')).toBeNull();
|
||||
expect(root().querySelector('.pin-toggle')).toBeNull();
|
||||
expect(section().textContent).not.toContain('figuras publicadas');
|
||||
expect(root().textContent).not.toContain('indicadores publicados');
|
||||
});
|
||||
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
|
||||
open('cacu', OTRO('cacu'));
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
open('tea', OTRO('tea'));
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores gráficos');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -33,8 +33,7 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
||||
fixture.detectChanges();
|
||||
expect(text()).not.toContain('Indicador de CaMa');
|
||||
});
|
||||
it('los controles propios de cada dominio se conservan al ir y volver', () => {
|
||||
// CaCu keeps its multiple selection, search and pins; CaMa does not have them; neither state contaminates the other.
|
||||
it('el resumen clínico es el mismo al ir y volver, y el catálogo no se mezcla', () => {
|
||||
const abrir = (d: 'cacu' | 'cama', n: number) => {
|
||||
fixture.componentInstance.changeDominio(d); fixture.detectChanges();
|
||||
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
|
||||
@@ -42,8 +41,9 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
||||
};
|
||||
const el = () => fixture.nativeElement as HTMLElement;
|
||||
abrir('cacu', 6);
|
||||
expect(el().querySelector('.catalog-search')).not.toBeNull();
|
||||
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||
expect(el().querySelector('.catalog-search')).toBeNull();
|
||||
expect(el().querySelector('.pin-toggle')).toBeNull();
|
||||
expect(el().querySelector('#dashboard-title')?.textContent?.trim()).toBe('Cáncer cervicouterino');
|
||||
expect(el().textContent).toContain('Intervalo de análisis');
|
||||
abrir('cama', 6);
|
||||
expect(el().querySelector('.catalog-search')).toBeNull();
|
||||
@@ -51,9 +51,8 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
||||
expect(el().textContent).not.toContain('Buscar indicadores');
|
||||
expect(el().textContent).not.toContain('cacu_');
|
||||
abrir('cacu', 6);
|
||||
// On the way back the page state (not only the DOM) says CaCu has its search again.
|
||||
expect(fixture.componentInstance.dominio).toBe('cacu');
|
||||
expect(fixture.componentInstance.searchVisible()).toBe(true);
|
||||
expect(fixture.componentInstance.searchVisible()).toBe(false);
|
||||
expect(el().textContent).toContain('Intervalo de análisis');
|
||||
expect(el().textContent).not.toContain('cama_');
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ import { strFromU8, unzipSync } from 'fflate';
|
||||
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
|
||||
import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf';
|
||||
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
|
||||
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte';
|
||||
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaEscenario, etiquetaHistologia } from './etiquetas-cohorte';
|
||||
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
|
||||
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
|
||||
@@ -33,6 +33,17 @@ describe('Etiquetas de la cohorte', () => {
|
||||
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
|
||||
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
|
||||
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
|
||||
expect(['POST_TRATAMIENTO', 'EN_OBSERVACION', 'CONTROL'].map(etiquetaEscenario)).toEqual(['Post-tratamiento', 'En observación', 'CONTROL']);
|
||||
});
|
||||
it('el escenario clínico de una fila se lee «Post-tratamiento» o «En observación» en la lista y en la ficha, con su código guardado', () => {
|
||||
// Fails if the list or the record show the scenario's code, or the code the filter sends is lost.
|
||||
const cruda = listaCohorte();
|
||||
const items = cruda['items'] as Record<string, unknown>[];
|
||||
items[0]['escenario_clinico'] = 'POST_TRATAMIENTO'; items[1]['escenario_clinico'] = 'EN_OBSERVACION';
|
||||
const r = seguimientoTablaResponse(cruda);
|
||||
expect(r.items[0]).toMatchObject({ escenario_clinico: 'Post-tratamiento', escenario_clinico_codigo: 'POST_TRATAMIENTO' });
|
||||
expect(r.items[1]).toMatchObject({ escenario_clinico: 'En observación', escenario_clinico_codigo: 'EN_OBSERVACION' });
|
||||
expect(toCamaPatientSummary(r.items[0], '2026-01-01')?.clinicalScenario).toBe('Post-tratamiento');
|
||||
});
|
||||
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
|
||||
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
|
||||
|
||||
@@ -228,17 +228,18 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
||||
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
|
||||
const exterior = m.grados.map(g => m.totales[g.id]!);
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia, %{customdata[1]}<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
// A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
|
||||
const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
|
||||
const hoverText = (values: number[]) => values.map(n => `${miles(n)} mujeres con biopsia, ${shareText(n, total)}`);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior),
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
|
||||
@@ -204,7 +204,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
// Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary.
|
||||
// The pair has no card title; each donut has its own heading.
|
||||
expect(titulos).toEqual(['Resultado histopatológico por categoría BI-RADS']);
|
||||
expect(titulos).toEqual([]);
|
||||
expect(root().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6');
|
||||
expect(root().textContent).not.toContain('indicador publicado');
|
||||
});
|
||||
@@ -213,7 +213,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
|
||||
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
|
||||
expect(h3).toEqual([
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, 2025-S2',
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, 2025-S2',
|
||||
'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 2025-S2',
|
||||
]);
|
||||
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
|
||||
|
||||
@@ -19,7 +19,9 @@ export class IndicadoresDefinitions {
|
||||
@Input() loading = false;
|
||||
@Input() error = '';
|
||||
readonly retry = output<void>();
|
||||
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
|
||||
readonly domainNames: Record<Dominio, string> = {
|
||||
tea: 'trastorno del espectro autista', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama',
|
||||
};
|
||||
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
|
||||
@@ -119,8 +119,12 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
return active[0];
|
||||
};
|
||||
const rg = reporte(general), re = reporte(porEscenario);
|
||||
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha']
|
||||
.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
||||
// With a report id on both sides, the report is identified by it and its cut-off and versions: a FHIR report's
|
||||
// `date` (`generado_en`) is when the answer was served, so the same stored report served twice differs only there.
|
||||
// Without ids, the generation time is still part of the provenance.
|
||||
const identificados = rg?.['report_id'] != null && re?.['report_id'] != null;
|
||||
const procedencia = ['report_id', 'fecha_corte', ...(identificados ? [] : ['generado_en']), 'kit_version', 'toml_sha', 'parametros_sha'];
|
||||
if (!!rg !== !!re || (rg && re && procedencia.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
||||
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
|
||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
||||
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||
@@ -145,17 +149,20 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
|
||||
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
|
||||
});
|
||||
// A period without patients may publish its general distribution as explicit zeros (FHIR's complete report) and no
|
||||
// scenario at all: that's an empty period, not a mismatch. A null or positive count without scenarios still is one.
|
||||
const generalEnCeros = g.size > 0 && [...g.values()].every(row => row['n'] === 0);
|
||||
// Compare only fully published sums. Never derive a hidden value by subtraction.
|
||||
if (escenarios.length) {
|
||||
for (const c of cats) {
|
||||
const total = suma(escenarios.map(s => s.celdas[c.id]));
|
||||
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
|
||||
}
|
||||
} else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||
} else if (g.size && !generalEnCeros) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
|
||||
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
|
||||
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
|
||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size,
|
||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size || (generalEnCeros && !escenarios.length),
|
||||
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
|
||||
}
|
||||
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
|
||||
@@ -193,19 +200,20 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
};
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
|
||||
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % del total con resultado<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]);
|
||||
// A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
|
||||
const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
|
||||
const hoverText = (values: number[]) => values.map(n => `${miles(n)} pacientes, ${percentNumber(100 * n / m.total!)} % del total con resultado`);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
||||
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
|
||||
textfont: { color: '#FFFFFF' }, hovertext: hoverText(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
|
||||
textfont: { size: 11 }, customdata: custom(exterior),
|
||||
textfont: { size: 11 }, hovertext: hoverText(exterior),
|
||||
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,12 +2,14 @@
|
||||
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
|
||||
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
|
||||
// the shapes the page reads and passed through the same checks.
|
||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
|
||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database; `conModelo`
|
||||
// below adds to its patient summary the age at the EEG, a metric's age-norm curve and the ADOS-2 association model,
|
||||
// in the shape `webapi/fhir/tea.py` emits them.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { Bundle, Resource, resources } from './fhir';
|
||||
import {
|
||||
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
|
||||
periodosDesde, Report,
|
||||
@@ -20,6 +22,49 @@ import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-f
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
|
||||
const SD = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
const CURVA = `${SD}/curva-referencia`;
|
||||
const curva = {
|
||||
url: CURVA, extension: [
|
||||
{ url: `${CURVA}/fuente`, valueString: 'tea-ritmo_posterior/3' }, { url: `${CURVA}/estado`, valueString: 'validada' },
|
||||
...[12, 24, 36].map(v => ({ url: `${CURVA}/edad-meses`, valueDecimal: v })),
|
||||
...([['p5', [4, 4.5, 5]], ['p25', [5, 5.5, 6]], ['mediana', [5.5, 6, 6.5]], ['p75', [6, 6.5, 7]], ['p95', [6.5, 7, 7.5]]] as [string, number[]][])
|
||||
.flatMap(([p, vs]) => vs.map(v => ({ url: `${CURVA}/${p}`, valueDecimal: v }))),
|
||||
],
|
||||
};
|
||||
const prediccion = (zona: string, z: number | null) => ({
|
||||
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] },
|
||||
probabilityDecimal: 0.41,
|
||||
extension: [
|
||||
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
|
||||
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' },
|
||||
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
|
||||
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
|
||||
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
|
||||
],
|
||||
});
|
||||
// The fixture's patient summary with what the WebApi adds when the analysis and the association model have data.
|
||||
function conModelo(): Bundle {
|
||||
const bundle = structuredClone(fx.resumenPaciente) as Bundle;
|
||||
for (const r of resources(bundle)) {
|
||||
if (r.resourceType === 'DiagnosticReport') r.extension = [...(r.extension ?? []), { url: `${SD}/edad-meses`, valueDecimal: 23.6 }];
|
||||
const codigo = (r['code'] as { coding?: { code?: string }[] } | undefined)?.coding?.[0]?.code;
|
||||
if (r.resourceType === 'Observation' && codigo === 'ritmo_posterior' && !r.id?.startsWith('electrodos-'))
|
||||
r.extension = [...(r.extension ?? []), curva];
|
||||
}
|
||||
const riesgo: Resource = {
|
||||
resourceType: 'RiskAssessment', id: 'relacion-ados2-P-4A59E9D8B4', status: 'final',
|
||||
meta: { tag: resources(bundle)[0].meta?.tag },
|
||||
extension: [{ url: `${SD}/modelo-version`, valueString: '1.0.0' }, { url: `${SD}/modelo-validado`, valueBoolean: false },
|
||||
{ url: `${SD}/modelo-nivel`, valueString: 'item' }, { url: `${SD}/modelo-n-cohorte`, valueInteger: 40 }],
|
||||
prediction: [prediccion('occipital', -2.6), prediccion('parietal', null)],
|
||||
};
|
||||
bundle.entry = [...(bundle.entry ?? []), { resource: riesgo }];
|
||||
return bundle;
|
||||
}
|
||||
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
|
||||
|
||||
describe('Indicadores sobre FHIR', () => {
|
||||
@@ -173,14 +218,15 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
|
||||
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
|
||||
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
|
||||
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 });
|
||||
expect(response.resumen_eeg).toMatchObject({ validadas: true, con_eeg_valido: 3, normales: 2, anormales: 1, sin_eeg: 3 });
|
||||
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
|
||||
});
|
||||
|
||||
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
|
||||
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each
|
||||
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
|
||||
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
|
||||
// Pins down: the age group from the summary's episode, ADOS-2 domains whose totals add up (the page checks it),
|
||||
// the EEG analysis's checks as its report writes them (value or text, A/N, decisive), each metric's state, effects
|
||||
// and median from the code system and its observation, and one map per evaluable metric from its electrodes'
|
||||
// z-scores. Fails if the summary stops passing the page's checks or a map appears for a metric without electrodes.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
@@ -188,13 +234,70 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(detalle.grupo_edad).toBe('16-23 meses');
|
||||
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
|
||||
expect(detalle.eeg!.calidad).toBe('bueno');
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' });
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'line-noise')).toMatchObject({ valor: 3.5, unidad: 'dB', nivel: 'bueno', decisivo: false, electrodo: null });
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'clean-windows')).toMatchObject({ valor: 95, decisivo: true });
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'triage-level')?.valor).toBe('completo');
|
||||
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
|
||||
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 });
|
||||
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08, referencia: { min: 4.5, max: 7, mediana: 5.75 }, sin_evaluar: null });
|
||||
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
|
||||
});
|
||||
|
||||
it('el mapa de electrodos del reporte no da una segunda tarjeta a su métrica', async () => {
|
||||
// Pins down: the report's result lists each metric's observation and its electrode-map one, both coded under the
|
||||
// metric's code, and only the metric observation becomes a card. Fails if the alteraciones filter stops skipping
|
||||
// `electrodos-*` observations and the metric shows up twice.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
const codigos = detalle.eeg!.alteraciones.map(a => a.codigo);
|
||||
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
|
||||
});
|
||||
|
||||
it('el resumen lleva la edad al EEG y la norma por edad de la métrica cuando la WebApi las manda', async () => {
|
||||
// Pins down: the report's `edad-meses` extension as the EEG's age and a metric observation's `curva-referencia`
|
||||
// sub-extensions read back in order as the age norm (ages, five percentiles, source and state), so the page's
|
||||
// checks accept it. Fails if the adapter stops reading either extension or scrambles the series.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect(detalle.eeg!.edad_meses).toBe(23.6);
|
||||
expect(detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!.curva_referencia).toEqual({
|
||||
fuente: 'tea-ritmo_posterior/3', estado: 'validada', edad_meses: [12, 24, 36],
|
||||
p5: [4, 4.5, 5], p25: [5, 5.5, 6], mediana: [5.5, 6, 6.5], p75: [6, 6.5, 7], p95: [6.5, 7, 7.5] });
|
||||
});
|
||||
|
||||
it('el resumen arma la relación con el ADOS-2 del RiskAssessment y deja fuera la fila incompleta', async () => {
|
||||
// Pins down: the model's version, validation, level and cohort from the resource's extensions, and each
|
||||
// prediction as a row with the metric's and zone's labels, the outcome, OR, interval, q, z, both probabilities
|
||||
// and the observed score; a prediction without its z is dropped instead of failing the page's checks. Fails if
|
||||
// the adapter stops reading the RiskAssessment or lets an incomplete row through.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const relacion = (await answer).relacion_ados2!;
|
||||
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
|
||||
expect(relacion.filas).toEqual([{
|
||||
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
|
||||
resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
|
||||
});
|
||||
|
||||
it('sin edad, norma ni modelo el resumen no inventa esos campos', async () => {
|
||||
// Pins down: a summary without the new extensions or a RiskAssessment (the fixture as the WebApi served it before
|
||||
// the analysis wrote them) leaves `edad_meses`, `curva_referencia` and `relacion_ados2` out, so the page hides
|
||||
// the chart and the panel. Fails if the adapter fills them with defaults.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect('edad_meses' in detalle.eeg!).toBe(false);
|
||||
expect(detalle.eeg!.alteraciones.some(a => 'curva_referencia' in a)).toBe(false);
|
||||
expect('relacion_ados2' in detalle).toBe(false);
|
||||
});
|
||||
|
||||
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
|
||||
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
|
||||
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
|
||||
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
|
||||
} from './indicadores-cama-fhir';
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
|
||||
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
|
||||
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
|
||||
@@ -40,8 +41,8 @@ const POPULATION_GROUP: Record<string, string> = {
|
||||
};
|
||||
|
||||
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures
|
||||
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`).
|
||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
||||
// and CaCu's have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`, `CACU-EU7` -> `cacu_eu7`).
|
||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? CACU_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
||||
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
|
||||
// Age groups travel as `16_23`; the page names them `16-23`.
|
||||
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
|
||||
@@ -56,10 +57,21 @@ function decimal(score: Score | undefined, name: string): number | null {
|
||||
}
|
||||
const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
// keeps every category ungrouped.
|
||||
export function categorias(measure: Measure): Record<string, Categoria> {
|
||||
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
|
||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : [];
|
||||
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null,
|
||||
grupo: extension(e, 'grupo')?.valueCode ?? null }]] : [];
|
||||
}));
|
||||
}
|
||||
// The groups a composition's categories belong to (`categoria-grupo`: code and caption), in the Measure's order; empty
|
||||
// when the Measure declares none.
|
||||
export function gruposDeCategoria(measure: Measure): Record<string, string> {
|
||||
return Object.fromEntries(extensions(measure, 'categoria-grupo').flatMap(e => {
|
||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||
return codigo && etiqueta ? [[codigo, etiqueta]] : [];
|
||||
}));
|
||||
}
|
||||
function contrato(measure: Measure): string {
|
||||
@@ -193,6 +205,34 @@ function cruceDeHistopatologia(group: Group, estrato: string): Map<string, numbe
|
||||
return celdas;
|
||||
}
|
||||
|
||||
// A composition (C2) by one of its strata, from the report's stratifier that crosses the stratum with the category
|
||||
// (`[estrato, categoria]`, as the WebApi publishes it): each stratum value with its caption, and each cell's count.
|
||||
// FHIR lists only the cells that have units and the report is complete, so a cell it doesn't list is a zero; a stratum
|
||||
// value nobody falls in isn't listed at all. A report with no units has no cell to cross. A missing component, a
|
||||
// category the Measure doesn't declare, a repeated cell or cells that don't add up to the period's units are contract
|
||||
// errors, never a silent zero. FHIR publishes no suppression marker, so nothing here is read as suppressed.
|
||||
function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly string[]) {
|
||||
const unidades = count(group.population, 'initial-population');
|
||||
const valores = new Map<string, string>(), celdas = new Map<string, number>();
|
||||
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
|
||||
if (!stratifier && unidades === 0) return { valores, celdas };
|
||||
if (!stratifier) throw new Error('Dimensión no admitida');
|
||||
let suma = 0;
|
||||
for (const stratum of stratifier.stratum ?? []) {
|
||||
const del = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
|
||||
const valor = code(del?.value), categoria = code(cat?.value), n = stratum.population?.[0]?.count;
|
||||
if (!valor || !categoria || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) throw new Error('Celda del estrato incompleta');
|
||||
if (!declaradas.includes(categoria)) throw new Error('Categoría no declarada en el estrato');
|
||||
const e = estratoValor(valor), clave = `${e}|${categoria}`;
|
||||
if (celdas.has(clave)) throw new Error('Celda del estrato repetida');
|
||||
if (!valores.has(e)) valores.set(e, display(del!.value) ?? e);
|
||||
celdas.set(clave, n);
|
||||
suma += n;
|
||||
}
|
||||
if (unidades !== null && suma !== unidades) throw new Error('Los conteos por estrato no suman las unidades del periodo');
|
||||
return { valores, celdas };
|
||||
}
|
||||
|
||||
// The `/datos` answer for `measure`, from one report per period.
|
||||
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
|
||||
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
|
||||
@@ -200,6 +240,8 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
|
||||
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
|
||||
const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
|
||||
// Any other composition asked by a stratum is read from its crossed stratifier (`cruceDeComposicion`).
|
||||
const porEstrato = kind === 'C2' && estrato !== undefined && !cruzado;
|
||||
const cats: Record<string, Categoria> = cruzado
|
||||
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
|
||||
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
|
||||
@@ -241,6 +283,21 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (porEstrato) {
|
||||
const declaradasEnOrden = Object.keys(cats);
|
||||
const { valores: delPeriodo, celdas } = cruceDeComposicion(group, estrato!, declaradasEnOrden);
|
||||
for (const [e, etiqueta] of delPeriodo) {
|
||||
let total = 0;
|
||||
declaradasEnOrden.forEach((categoria, orden) => {
|
||||
const n = celdas.get(`${e}|${categoria}`) ?? 0;
|
||||
total += n;
|
||||
filas.push({ periodo, grupo, estrato: e, categoria, n, orden, suprimido: 0 });
|
||||
});
|
||||
totales.push({ periodo, grupo, estrato: e, n: total, suprimido: 0 });
|
||||
if (!valores.has(e)) valores.set(e, etiqueta);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (kind === 'C2') {
|
||||
const strata = group.stratifier?.[0]?.stratum ?? [];
|
||||
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
|
||||
@@ -280,10 +337,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
periodos,
|
||||
estrato: estrato ?? null,
|
||||
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
|
||||
...(cruzado ? { totales_estrato: totales } : {}),
|
||||
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
|
||||
grupos,
|
||||
categorias: cats,
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
|
||||
notas: [],
|
||||
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
|
||||
filas,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Covers CaMa's histopathology by BI-RADS (CAM-03): the adapter that turns the published C2 matrix into rows,
|
||||
// rates and figures, and the catalog wiring of the local view. The fixtures are what WebApi publishes for the synthetic
|
||||
// rates and figures, and the view that draws it. The fixtures are what WebApi publishes for the synthetic
|
||||
// demonstration data (fixtures/cama_histopatologia_birads_*.json: six strata, six categories, one patient per
|
||||
// period; BIRADS_4 is a row of its own and BENIGNO/RIESGO_B3/IN_SITU/INVASOR make the denominator).
|
||||
import { Component, input, output } from '@angular/core';
|
||||
@@ -235,32 +235,124 @@ describe('Histopatología por BI-RADS: componente', () => {
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
it('carga las dos figuras al hacerse visible y redibuja en tema oscuro sin consultar WebApi', () => {
|
||||
f.componentRef.setInput('visible', false);
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred');
|
||||
f.componentRef.setInput('visible', true);
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2);
|
||||
expect(f.componentInstance.selectionLabel).toBe('Riesgo a carcinoma');
|
||||
f.componentRef.setInput('tema', 'oscuro');
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839');
|
||||
const solicitud = () => http.expectOne(req => req.url === '/cama/indicadores/cama_histopatologia_birads/datos');
|
||||
function flush(body: unknown = estratoFixture) {
|
||||
const r = solicitud();
|
||||
expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO);
|
||||
r.flush(body as Record<string, unknown>); f.detectChanges();
|
||||
}
|
||||
const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.legend button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
|
||||
|
||||
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => {
|
||||
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');
|
||||
flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
|
||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
|
||||
expect([...f.nativeElement.querySelectorAll('.tabs button')].map((b: Element) => b.textContent!.trim()))
|
||||
.toEqual(['No maligno', 'Maligno']);
|
||||
expect(f.nativeElement.querySelector('.tabs button[aria-selected=true]')!.textContent!.trim()).toBe('Maligno');
|
||||
expect([...f.nativeElement.querySelectorAll('.tab-panel button')].map((b: Element) => b.textContent!.trim()))
|
||||
.toEqual(['Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']);
|
||||
const grafica = f.nativeElement.querySelector('.figures') as HTMLElement;
|
||||
const leyenda = f.nativeElement.querySelector('.legend') as HTMLElement;
|
||||
const contexto = f.nativeElement.querySelector('.view-context') as HTMLElement;
|
||||
expect(leyenda.compareDocumentPosition(grafica) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
|
||||
expect(f.nativeElement.textContent).not.toContain('Filtro general aplicado');
|
||||
expect(f.nativeElement.querySelector('.selection-status')).toBeNull();
|
||||
expect(f.nativeElement.querySelector('.rate-states')).toBeNull();
|
||||
expect(f.nativeElement.textContent).not.toContain('Sin pacientes con resultado de biopsia');
|
||||
expect(contexto.textContent).toContain('Intervalo semestral');
|
||||
expect(contexto.textContent).toContain('Periodo 2025-S1');
|
||||
expect(f.componentInstance.selectionLabel).toBe('Maligno');
|
||||
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
|
||||
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(
|
||||
['Categoría BI-RADS', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor', 'Con resultado', 'Sin biopsia reportada', 'Sin dato', 'Total de pacientes']);
|
||||
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent))).toEqual([
|
||||
['BI-RADS 4 sin subtipo', '2', '0', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4A', '1', '1', '1', '2', '5', '1', '1', '7'],
|
||||
['BI-RADS 4B', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4C', '1', '1', '1', '1', '4', '1', '1', '6'],
|
||||
['BI-RADS 5', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 6', '1', '1', '1', '1', '4', '1', '1', '6']]);
|
||||
expect(f.nativeElement.querySelector('.note').textContent).toContain('Convención provisional;');
|
||||
});
|
||||
it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => {
|
||||
f.detectChanges(); flush();
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
|
||||
expect(f.nativeElement.textContent).not.toContain('Volver');
|
||||
boton('No maligno').click(); f.detectChanges();
|
||||
const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
|
||||
expect(b3.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(f.componentInstance.reading).toContain('Proporción con resultado lesión de riesgo (B3)');
|
||||
b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' });
|
||||
boton('Maligno').click(); f.detectChanges();
|
||||
boton('Carcinoma invasor').click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' });
|
||||
boton('Maligno').click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
||||
charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
|
||||
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
||||
charts[1].plotClick.emit({ points: [] }); charts[1].plotClick.emit(null); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('aplica el periodo mensual y deja la vista vacía para un mes sin conteos', () => {
|
||||
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 2 });
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.contextPeriod).toBe('2025-02');
|
||||
it('una celda suprimida: la fila lo dice, la dona no suma un total parcial y el resto de las tasas se conserva', () => {
|
||||
const d = estrato(); Object.assign(fila(d, 'BIRADS_4C', 'BENIGNO'), { n: null, suprimido: 1 });
|
||||
f.detectChanges(); flush(d);
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2024-02'] }, revision: 3 });
|
||||
f.detectChanges();
|
||||
expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos');
|
||||
expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('Suprimido');
|
||||
const tabla = [...f.nativeElement.querySelectorAll('tbody tr')].map((tr: Element) => [...tr.children].map(td => td.textContent));
|
||||
expect(tabla[3][1]).toBe('Suprimido'); expect(tabla[3][5]).toBe('Suprimido'); expect(tabla[0][5]).toBe('4');
|
||||
});
|
||||
it('un estrato no publicado se lee «No disponible» en la tabla y en las tasas, y no como cero', () => {
|
||||
const d = estrato(); d.filas = d.filas.filter(r => r['estrato'] !== 'BIRADS_6'); d.valores_estrato = d.valores_estrato.filter(v => v !== 'BIRADS_6');
|
||||
d.totales_estrato = d.totales_estrato.filter(t => t['estrato'] !== 'BIRADS_6');
|
||||
f.detectChanges(); flush(d);
|
||||
const ultima = [...f.nativeElement.querySelectorAll('tbody tr')].pop() as HTMLElement;
|
||||
expect([...ultima.children].map(td => td.textContent)).toEqual(['BI-RADS 6', ...Array(8).fill('No disponible')]);
|
||||
expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('No disponible');
|
||||
});
|
||||
it('sin filas en el periodo lo dice y conserva la tabla vacía', () => {
|
||||
const d = estrato(); d.filas = []; d.totales_estrato = [];
|
||||
f.detectChanges(); flush(d);
|
||||
expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(f.nativeElement.textContent).toContain('No hay resultados de biopsia para el periodo seleccionado.');
|
||||
expect(f.nativeElement.textContent).toContain('No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('error se anuncia con reintento que recupera; una respuesta fuera de contrato es incompatible y no dibuja', () => {
|
||||
f.detectChanges();
|
||||
solicitud().flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
f.componentInstance.retry(); flush({ ...estrato(), estrato: 'otro' });
|
||||
expect(f.componentInstance.status()).toBe('incompatible');
|
||||
expect(f.nativeElement.querySelector('[role=alert]').textContent).toContain('Respuesta incompatible');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('un filtro general incompatible, otro dominio u otro indicador no piden datos', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('dominio', 'cacu'); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('el tema oscuro redibuja con la paleta oscura sin pedir otra vez', () => {
|
||||
f.detectChanges(); flush();
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
|
||||
});
|
||||
it('«Cómo leer» explica el denominador y añade lo que el servicio publique de las dos figuras, nada más', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const pedido = vi.fn(); f.componentInstance.metadataRequested.subscribe(pedido);
|
||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||
expect(pedido).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('no entran en el denominador');
|
||||
f.componentRef.setInput('metadata', { descripcion: 'No va', figuras_detalle: [
|
||||
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] }, { figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] });
|
||||
f.detectChanges();
|
||||
const ayuda = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
expect([...ayuda.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']);
|
||||
for (const ausente of ['No va', 'Otra', 'No.']) expect(ayuda.textContent).not.toContain(ausente);
|
||||
});
|
||||
|
||||
it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => {
|
||||
|
||||
@@ -15,7 +15,7 @@ export const ESTRATO_BIRADS = 'birads';
|
||||
// The six strata of the contract, in the order they are published. BIRADS_4 is a row of its own and is never
|
||||
// split among 4A/4B/4C nor added to them.
|
||||
export const ESTRATOS_BIRADS = ['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'] as const;
|
||||
export const ETIQUETA_ESTRATO: Readonly<Record<typeof ESTRATOS_BIRADS[number], string>> = {
|
||||
const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
|
||||
BIRADS_4: 'BI-RADS 4 sin subtipo', BIRADS_4A: 'BI-RADS 4A', BIRADS_4B: 'BI-RADS 4B', BIRADS_4C: 'BI-RADS 4C', BIRADS_5: 'BI-RADS 5', BIRADS_6: 'BI-RADS 6',
|
||||
};
|
||||
// The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two
|
||||
@@ -41,21 +41,19 @@ export interface Categoria { id: string; etiqueta: string; color: string; grupo:
|
||||
export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; }
|
||||
export interface FilaBirads {
|
||||
id: string; etiqueta: string;
|
||||
// Categories with a biopsy result.
|
||||
// The four categories with a result.
|
||||
celdas: Record<string, Celda>;
|
||||
// SIN_BIOPSIA and SIN_DATO, when the catalog publishes them.
|
||||
aparte: Record<string, Celda>;
|
||||
// Patients of the stratum, as the response publishes them.
|
||||
total: Celda;
|
||||
// Patients with a biopsy result: the denominator. Null while any result cell is unknown.
|
||||
// Patients with a biopsy result: the denominator. Null while any of the four cells is unknown.
|
||||
den: number | null; estado: Celda['estado'];
|
||||
}
|
||||
export interface ModeloHistopatologia {
|
||||
periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string;
|
||||
filas: FilaBirads[]; totales: Record<string, number | null>; conResultado: number | null;
|
||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
||||
// When set, the outer ring shows the subtype distribution within this group.
|
||||
grupoAnilloExterior?: string;
|
||||
}
|
||||
export interface SeleccionHistopatologia { grupo: string; categoria?: string; }
|
||||
export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||
@@ -68,7 +66,7 @@ const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').re
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
|
||||
// A label inside a sentence: «Lesión de riesgo (B3)» reads «lesión de riesgo (B3)», keeping the code's capitals.
|
||||
const enFrase = (v: string) => v === v.toUpperCase() ? v : v.charAt(0).toLowerCase() + v.slice(1);
|
||||
const enFrase = (v: string) => v.charAt(0).toLowerCase() + v.slice(1);
|
||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||
|
||||
// 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available.
|
||||
@@ -185,9 +183,6 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
|
||||
}
|
||||
|
||||
export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; }
|
||||
export function categoriasExteriores(m: ModeloHistopatologia): Categoria[] {
|
||||
return m.grupoAnilloExterior ? m.categorias.filter(c => c.grupo === m.grupoAnilloExterior) : m.categorias;
|
||||
}
|
||||
export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] {
|
||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? [];
|
||||
}
|
||||
@@ -199,15 +194,12 @@ export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
|
||||
if (traza === 'centro') return seleccionBase(m);
|
||||
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = categoriasExteriores(m)[indice];
|
||||
const c = m.categorias[indice];
|
||||
if (!c) return sel;
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
}
|
||||
/** The axis title says what the rate reads. */
|
||||
export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string {
|
||||
if (m.grupoAnilloExterior) {
|
||||
return 'Proporción con ' + enFrase(seleccionEtiqueta(m, sel)) + ' entre pacientes con resultado de biopsia';
|
||||
}
|
||||
if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia';
|
||||
if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia';
|
||||
return 'Proporción con resultado ' + enFrase(seleccionEtiqueta(m, sel));
|
||||
@@ -237,19 +229,16 @@ export function rangoTasas(valores: Tasa[]): [number, number] {
|
||||
// `estrecho`: a phone-width plot, where the labels wrap and the axis keeps only what fits.
|
||||
export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const barras = !!m.grupoAnilloExterior;
|
||||
const valores = tasas(m, sel);
|
||||
const color = sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color;
|
||||
const tono = tonoDe(sel.categoria ?? sel.grupo);
|
||||
const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color];
|
||||
const y = valores.map(t => t.fila.etiqueta);
|
||||
const colores = sel.categoria || barras ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
|
||||
const rango = rangoTasas(valores);
|
||||
const colores = sel.categoria ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
|
||||
return { data: [{
|
||||
...(barras ? { type: 'bar', orientation: 'h', width: .5 } : { type: 'scatter', mode: 'markers' }),
|
||||
uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: barras ? { color: colores } : { size: 12, color: colores }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color: barras ? p.text : colores, thickness: 2, width: 6,
|
||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: { size: 12, color: colores }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color: colores, thickness: 2, width: 6,
|
||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||
@@ -259,8 +248,8 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
|
||||
margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 },
|
||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true,
|
||||
...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '<br>sin subtipo')) } : {}) },
|
||||
xaxis: { range: barras ? [0, rango[1]] : rango, ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
|
||||
title: { text: estrecho ? 'Porcentaje' : (barras ? 'Porcentaje con ' : 'Porcentaje con resultado ') + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
|
||||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
|
||||
title: { text: estrecho ? 'Porcentaje' : 'Porcentaje con resultado ' + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
|
||||
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
||||
font: { size: estrecho ? 11 : 12, color: p.text },
|
||||
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||
@@ -273,27 +262,17 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
|
||||
const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado;
|
||||
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
|
||||
const interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0));
|
||||
const categorias = categoriasExteriores(m);
|
||||
const exterior = categorias.map(c => m.totales[c.id]!);
|
||||
const centro = m.grupoAnilloExterior
|
||||
? `<b>${miles(k)}</b><br>de ${miles(total)}<br>con resultado`
|
||||
: `<b>${miles(k)}</b><br>de ${miles(total)} con resultado`;
|
||||
const exterior = m.categorias.map(c => m.totales[c.id]!);
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes con resultado, %{customdata[1]}<extra></extra>' };
|
||||
const custom = (values: number[]) => {
|
||||
const subtotal = values.reduce((s, n) => s + n, 0);
|
||||
return values.map(n => [miles(n), subtotal === 0 ? '—' : shareText(n, subtotal)]);
|
||||
};
|
||||
const hoverExterior = m.grupoAnilloExterior
|
||||
? { hovertemplate: '%{label}<br>%{customdata[0]} pacientes (%{customdata[1]} del grupo Riesgo a carcinoma)<extra></extra>' }
|
||||
: hover;
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
const zoomGrupo = (id: string, hijos: readonly string[]) =>
|
||||
sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1;
|
||||
const zoomCategoria = (id: string) => sel.categoria === id ? ZOOM_ELEGIDO : !sel.categoria && activos.has(id) ? ZOOM_HIJO : 1;
|
||||
const zoomDe = (values: number[]) => Math.max(1, ...values);
|
||||
const tinta = (colores: string[], zoom: number[]) => colores.map((color, i) => zoom[i] > 1 ? color : 'rgba(0,0,0,0)');
|
||||
const gruposZoom = m.grupos.map(g => zoomGrupo(g.id, g.categorias));
|
||||
const categoriasZoom = categorias.map(c => zoomCategoria(c.id));
|
||||
const categoriasZoom = m.categorias.map(c => zoomCategoria(c.id));
|
||||
const anillo = (name: string, values: number[], labels: string[], hole: number, base: readonly [number, number, number, number], zoom: number[], colores: string[]) => ({
|
||||
...comun, ...hover, name, values, labels, hole, customdata: custom(values),
|
||||
domain: caja(base, zoomDe(zoom)),
|
||||
@@ -301,16 +280,16 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
|
||||
});
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside',
|
||||
text: [centro], textfont: { size: 16, color: p.text },
|
||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con resultado`], textfont: { size: 16, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: caja(CAJA_GRUPO, 1),
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => g.color), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hoverExterior, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
|
||||
labels: categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: m.grupoAnilloExterior ? 1 : 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
|
||||
labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: m.categorias.map(c => c.color), line: { color: p.background, width: 2 } } },
|
||||
anillo('grupos', interior, m.grupos.map(g => escapar(g.etiqueta)), .62, CAJA_GRUPO, gruposZoom, m.grupos.map(g => g.color)),
|
||||
{ ...anillo('categorias', exterior, categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, categorias.map(c => c.color)), ...hoverExterior },
|
||||
anillo('categorias', exterior, m.categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, m.categorias.map(c => c.color)),
|
||||
], layout: { autosize: true, height: 360, margin: { t: 16, l: 16, r: 16, b: 16 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ describe('Histórico: C2 (conteos por categoría)', () => {
|
||||
expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
|
||||
expect(r.comoLeer).toContain('mastografías');
|
||||
});
|
||||
it('Pacientes evaluadas con BI-RADS 4, 5 y 6 conserva la gráfica y omite la explicación de la barra', () => {
|
||||
it('Pacientes evaluadas con BI-RADS 4, 5 o 6 conserva la gráfica y omite la explicación de la barra', () => {
|
||||
const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' }));
|
||||
expect(pacientes.comoLeer).toBe('');
|
||||
expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
|
||||
|
||||
@@ -14,12 +14,9 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
|
||||
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
|
||||
// CaMa's day-count lines sit next to the histopathology bars, so they borrow that figure's blue, purple and rose.
|
||||
const DIAS: Readonly<Record<string, { claro: string; oscuro: string; relleno: string }>> = {
|
||||
cama_dias_toma_diagnostico: { claro: '#2F6DB3', oscuro: '#9DBFE3', relleno: '#9DBFE380' },
|
||||
cama_eu38a: { claro: '#9C42C2', oscuro: '#D2A4EA', relleno: '#9C42C240' },
|
||||
cama_dias_resultado_diagnostico: { claro: '#C24269', oscuro: '#E7A3B8', relleno: '#C2426940' },
|
||||
};
|
||||
// CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
|
||||
const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
|
||||
const FONDO_AZUL = '#9DBFE380';
|
||||
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
// sortedPeriods lists the newest first, for selectors; time here runs left to right.
|
||||
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
|
||||
@@ -92,17 +89,24 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<str
|
||||
return { validas, suprimidos, sinDato };
|
||||
}
|
||||
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
|
||||
// CaMa's line charts share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
function colorDeLinea(id: string, tema: Tema) {
|
||||
if (LINEAS[id]) return { linea: LINEAS[id], relleno: LINEAS[id] + '40' };
|
||||
if (id.startsWith('cama_')) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
const linea = c2Theme(tema).line;
|
||||
return { linea, relleno: linea + '40' };
|
||||
}
|
||||
|
||||
type Trazo = Omit<HistoricoFigura, 'contrato'>;
|
||||
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data);
|
||||
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = LINEAS[data.id] ?? c2Theme(tema).line;
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 },
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
|
||||
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
@@ -113,13 +117,11 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
|
||||
const periodos = validar(data), unidad = unidadDe(data);
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
|
||||
const propio = DIAS[data.id];
|
||||
const linea = propio ? (tema === 'oscuro' ? propio.oscuro : propio.claro) : c2Theme(tema).line;
|
||||
const relleno = propio && tema === 'claro' ? propio.relleno : linea + '40';
|
||||
const trazo = colorDeLinea(data.id, tema);
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea, relleno),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 }, marker: { color: linea },
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', trazo.linea, trazo.relleno),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
|
||||
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
], layout: (() => {
|
||||
|
||||
@@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => {
|
||||
|
||||
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
fixture.componentInstance.changeSection('analisis');
|
||||
fixture.detectChanges();
|
||||
@@ -42,13 +42,13 @@ describe('Pestaña Histórico', () => {
|
||||
// Fails if the history tab of TEA or CaMa leaks into CaCu.
|
||||
abrir('cama', []);
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).toBeNull();
|
||||
});
|
||||
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Resumen se oculta', () => {
|
||||
|
||||
@@ -63,15 +63,19 @@ describe('Figuras de histórico', () => {
|
||||
expect(traza(data, 0).y).toEqual([30, 10]);
|
||||
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
|
||||
});
|
||||
it('las líneas de días de CaMa usan el azul, el morado y el rosa de la histopatología', () => {
|
||||
const color = (id: string, tema: 'claro' | 'oscuro') => {
|
||||
it('las líneas de CaMa comparten el morado y, si hay banda, el fondo azul', () => {
|
||||
const dias = (id: string, tema: 'claro' | 'oscuro') => {
|
||||
const figure = historicoFigura({ ...base, id, contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }, tema).figure;
|
||||
return { linea: (figure.data[1]['line'] as { color: string }).color, banda: figure.data[0]['fillcolor'] };
|
||||
return { linea: (figure.data[1]['line'] as { color: string }).color, puntos: (figure.data[1]['marker'] as { color: string }).color, banda: figure.data[0]['fillcolor'] };
|
||||
};
|
||||
expect(color('cama_dias_toma_diagnostico', 'claro')).toEqual({ linea: '#2F6DB3', banda: '#9DBFE380' });
|
||||
expect(color('cama_eu38a', 'claro')).toEqual({ linea: '#9C42C2', banda: '#9C42C240' });
|
||||
expect(color('cama_dias_resultado_diagnostico', 'claro')).toEqual({ linea: '#C24269', banda: '#C2426940' });
|
||||
expect(color('cama_dias_toma_diagnostico', 'oscuro').linea).toBe('#9DBFE3');
|
||||
for (const id of ['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico']) {
|
||||
expect(dias(id, 'claro')).toEqual({ linea: '#9C42C2', puntos: '#9C42C2', banda: '#9DBFE380' });
|
||||
}
|
||||
expect(dias('cama_dias_toma_diagnostico', 'oscuro')).toEqual({ linea: '#D2A4EA', puntos: '#D2A4EA', banda: '#9DBFE380' });
|
||||
const tasa = historicoFigura({ ...base, id: 'cama_confirmacion_birads45', contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure;
|
||||
expect((tasa.data[1]['line'] as { color: string }).color).toBe('#9C42C2');
|
||||
expect((tasa.data[1]['marker'] as { color: string }).color).toBe('#9C42C2');
|
||||
expect(tasa.data[0]['fillcolor']).toBe('#9DBFE380');
|
||||
});
|
||||
it('las líneas usan el verde legible en cada tema', () => {
|
||||
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
|
||||
|
||||
@@ -28,7 +28,7 @@ const PERSONALIZADO = -1;
|
||||
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
|
||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
|
||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
|
||||
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
|
||||
@@ -62,7 +62,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
selector: 'app-indicadores-historico',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
template: `
|
||||
<div class="controles">
|
||||
<div class="controles compacto">
|
||||
<h2>Filtros</h2>
|
||||
<div class="controles-fila">
|
||||
<div class="interval">
|
||||
@@ -127,10 +127,22 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
</div>
|
||||
`,
|
||||
styles: `
|
||||
@use '@angular/material' as mat;
|
||||
|
||||
:host { display: block; min-width: 0; }
|
||||
.controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
||||
// Same field height as the summary filters. The theme also rewrites corners, which would turn the switch into a pill.
|
||||
.controles.compacto {
|
||||
@include mat.theme((density: -4));
|
||||
--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;
|
||||
}
|
||||
.controles-fila { 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; }
|
||||
.interval mat-button-toggle-group { --mat-button-toggle-height: 40px; --mat-button-toggle-shape: 6px; }
|
||||
@@ -151,7 +163,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||
h3 { margin: 0; font: var(--mat-sys-title-small); }
|
||||
mat-form-field { flex: 0 1 14rem; width: 14rem; min-width: 14rem; max-width: 24rem; }
|
||||
mat-form-field { flex: 0 1 14rem; min-width: 0; max-width: 24rem; }
|
||||
`,
|
||||
})
|
||||
export class IndicadoresHistorico {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { CACU_RESULTADO_KPI, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { pending } from './indicadores-memory';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@@ -64,11 +64,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
// CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards.
|
||||
function cards() {
|
||||
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
// The shared request queue runs four at a time: flushing a batch starts the next.
|
||||
function flushPanels(period: string, expected = definitions.length - 1) {
|
||||
|
||||
@@ -47,7 +47,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
|
||||
it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => {
|
||||
if (domain === 'cama') {
|
||||
expect(anchor.id).toBe('cama_birads_456_paciente');
|
||||
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
|
||||
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 o 6');
|
||||
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
|
||||
} else expect(anchor.id).toBe('cacu_eu7');
|
||||
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
|
||||
|
||||
@@ -14,7 +14,7 @@ export const CACU_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
|
||||
};
|
||||
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
||||
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía a interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
||||
};
|
||||
// Institutional definitions retained for consumers outside the opportunity strip.
|
||||
export const CAMA_CONFIRMACION_KPI: KpiDefinition = {
|
||||
@@ -25,7 +25,7 @@ export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
};
|
||||
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
|
||||
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
|
||||
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
|
||||
c1Info: (n, d) => `${n} de ${d} biopsias con riesgo a carcinoma.`,
|
||||
};
|
||||
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de interpretación radiológica a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
||||
@@ -58,7 +58,7 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
],
|
||||
cama: [
|
||||
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
|
||||
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6', contrato: 'C2', unit: 'pacientes' },
|
||||
CAMA_TAMIZAJE_RESULTADO_KPI,
|
||||
],
|
||||
};
|
||||
|
||||
@@ -15,7 +15,6 @@ import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@@ -37,9 +36,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
harness.detectChanges();
|
||||
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
|
||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
// CaMa leads with the histopathology card, which reads a local source; the figure request comes from the next one.
|
||||
const card = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||
.find(item => item.indicador.id !== ID_HISTOPATOLOGIA_CAMA)!;
|
||||
const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
if (!card.visible) { card.setVisible(true); harness.detectChanges(); }
|
||||
const req = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
req.flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
<h1 id="dashboard-title">Ficha del paciente</h1>
|
||||
<p>Consulta individual de seguimiento de {{ domainLabels[dominio] }}</p>
|
||||
} @else {
|
||||
@if (dominio !== 'cama') { <span class="domain">{{ domainTitles[dominio] }}, investigación</span> }
|
||||
<h1 id="dashboard-title">{{ dominio === 'cama' ? 'Cáncer de mama' : 'Indicadores' }}</h1>
|
||||
<h1 id="dashboard-title">{{ domainTitles[dominio] }}</h1>
|
||||
<p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
|
||||
}
|
||||
</header>
|
||||
@@ -23,10 +22,7 @@
|
||||
@if (!catalogLoading() && filters; as state) {
|
||||
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
|
||||
<h2 id="global-filters-title" class="section-title">Filtros</h2>
|
||||
@if (dominio !== 'cama') {
|
||||
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
|
||||
}
|
||||
<app-indicador-period-filters [state]="state" [compact]="dominio === 'cama'" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
|
||||
<app-indicador-period-filters [state]="state" [compact]="true" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
|
||||
(retryAvailability)="retryAvailability()"
|
||||
(edited)="editFilters()" (apply)="applyFilters()" />
|
||||
</section>
|
||||
@@ -50,7 +46,10 @@
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
@let resumen = teaResumenPeriodo;
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
|
||||
<div class="kpi-heading">
|
||||
<h2 id="kpi-section-title" class="section-title">Indicadores de oportunidad</h2>
|
||||
@if (periodoCompartido) { <p class="kpi-period">Periodo {{ periodoCompartido }}</p> }
|
||||
</div>
|
||||
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
|
||||
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)">
|
||||
@@ -76,7 +75,7 @@
|
||||
|
||||
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
||||
<div class="catalog-heading">
|
||||
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
|
||||
<h2 id="graphic-section-title" class="section-title">Indicadores clínicos</h2>
|
||||
</div>
|
||||
@if (catalogLoading()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
|
||||
@@ -117,6 +116,7 @@
|
||||
</div>
|
||||
}
|
||||
<div class="catalog-grid">
|
||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
|
||||
@@ -6,17 +6,16 @@
|
||||
.dashboard { max-width: 1680px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
|
||||
h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; }
|
||||
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
|
||||
.state { padding: 1.25rem; margin: 0; }
|
||||
// CaMa's filter block is one compact row, as in the reference.
|
||||
.global-filters[data-domain='cama'] { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); }
|
||||
.global-filters[data-domain='cama'] .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
|
||||
.global-filters .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
|
||||
.section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
|
||||
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
|
||||
.kpi-section, .graphic-section { box-sizing: border-box; min-width: 0; margin-inline: var(--space-2);
|
||||
padding: var(--issste-space-4) var(--issste-space-5) var(--issste-space-6); border: 1px solid var(--issste-border);
|
||||
border-radius: var(--issste-radius); background: var(--issste-surface); }
|
||||
.kpi-section > .section-title { margin-bottom: var(--issste-space-4); }
|
||||
.kpi-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: var(--issste-space-3); }
|
||||
.kpi-section > .kpi-heading { margin-bottom: var(--issste-space-4); }
|
||||
.kpi-period { margin: .15rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; white-space: nowrap; }
|
||||
.graphic-section { margin-top: var(--issste-space-6); }
|
||||
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
|
||||
@@ -37,16 +36,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
h1 { font-size: 1.5rem; }
|
||||
}
|
||||
|
||||
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
|
||||
.global-filters { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
|
||||
|
||||
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
|
||||
.kpi-section[data-domain='cama'] .kpi-grid { grid-auto-rows: 1fr; }
|
||||
@container dashboard (min-width: 1350px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(5, minmax(0, 1fr)); } }
|
||||
.kpi-section[data-domain='cacu'] .kpi-grid {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
||||
align-items: stretch;
|
||||
}
|
||||
.kpi-section .kpi-grid { grid-auto-rows: 1fr; }
|
||||
@container dashboard (min-width: 1350px) { .kpi-section .kpi-grid { grid-template-columns: repeat(min(5, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
|
||||
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
|
||||
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
|
||||
|
||||
@@ -15,7 +15,6 @@ import { MatSelect } from '@angular/material/select';
|
||||
import { NgModel } from '@angular/forms';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@@ -38,11 +37,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
function load(items: Indicador[] = [item, second], domain = 'tea') {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
}
|
||||
// CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards.
|
||||
function cards() {
|
||||
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); }
|
||||
function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); }
|
||||
function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); }
|
||||
@@ -59,15 +54,15 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
});
|
||||
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
|
||||
load();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Trastorno del espectro autista');
|
||||
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
|
||||
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente');
|
||||
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de TEA');
|
||||
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de trastorno del espectro autista');
|
||||
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
|
||||
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Trastorno del espectro autista');
|
||||
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
|
||||
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
|
||||
expect(page.activeSection()).toBe('resumen');
|
||||
@@ -112,7 +107,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(host.querySelector('mat-select')).toBeNull();
|
||||
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
|
||||
expect(host.textContent).not.toContain('Contrato C1');
|
||||
expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
|
||||
expect(host.querySelector('.catalog-metadata')).toBeNull();
|
||||
expect(host.querySelector('.pin-toggle')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
|
||||
@@ -127,7 +123,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
const header = host.querySelector('header'); toggle(); flushAll();
|
||||
const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges();
|
||||
expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel);
|
||||
expect(host.querySelector('.catalog-metadata')).toBeTruthy(); http.expectNone(() => true);
|
||||
expect(host.querySelector('.catalog-metadata')).toBeNull(); http.expectNone(() => true);
|
||||
});
|
||||
it('UX-06C: conserva título largo completo y el control separado de la identidad', () => {
|
||||
const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive';
|
||||
@@ -136,7 +132,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(header.querySelector('h2')?.textContent).toBe(title);
|
||||
expect(header.querySelector('.card-identity button')).toBeNull();
|
||||
expect(header.querySelector('button')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.pin-toggle').getAttribute('aria-label')).toContain(title);
|
||||
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('UX-06B la navegación entre dominios es la del encabezado: la página no la duplica', () => {
|
||||
@@ -329,7 +325,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
|
||||
expect(control().entry.draft.mode).toBe('empty'); expect(control().state.applied?.selection.mode).toBe('todos');
|
||||
const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'saveGlobal');
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
expect(fixture.debugElement.queryAll(By.directive(MatSelect)).some(e => e.componentInstance.multiple)).toBe(false);
|
||||
const select = fixture.debugElement.query(By.directive(MatSelect));
|
||||
const writes = vi.spyOn(select.injector.get(NgModel).control, 'setValue');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
|
||||
@@ -31,12 +31,13 @@ import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'resumen', label: 'Resumen' },
|
||||
{ id: 'seguimiento', label: 'Seguimiento' },
|
||||
{ id: 'seguimiento', label: 'Análisis de riesgos' },
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
|
||||
@@ -47,11 +48,11 @@ export const CAMA_ANALYSIS_ENABLED = false;
|
||||
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
|
||||
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
|
||||
{ id: 'seguimiento', label: 'Análisis de Riesgos' }, SECTIONS_WITH_HISTORY[3]];
|
||||
SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -101,6 +102,14 @@ export class IndicadoresPage {
|
||||
private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
|
||||
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
|
||||
readonly kpiPanels = viewChildren(IndicadorKpiPanel);
|
||||
// The opportunity cards share the period their own query already resolved.
|
||||
get periodoCompartido(): string {
|
||||
const deConsulta = this.kpiPanels().map(panel => panel.temporalReference.trim())
|
||||
.find(text => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(text));
|
||||
if (deConsulta) return deConsulta;
|
||||
const applied = this.filters?.applied;
|
||||
return applied?.selection.mode === 'explicit' && applied.selection.periodos.length === 1 ? applied.selection.periodos[0] : '';
|
||||
}
|
||||
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
|
||||
private renderedCards: readonly IndicadorCatalogCard[] = [];
|
||||
private visibilityObserver?: IntersectionObserver;
|
||||
@@ -292,9 +301,12 @@ export class IndicadoresPage {
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly route = inject(ActivatedRoute, { optional: true });
|
||||
dominio: Dominio = 'tea';
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
|
||||
// At the start of the header line.
|
||||
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
|
||||
readonly domainLabels: Record<Dominio, string> = {
|
||||
tea: 'trastorno del espectro autista', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama',
|
||||
};
|
||||
readonly domainTitles: Record<Dominio, string> = {
|
||||
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
|
||||
};
|
||||
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
|
||||
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
|
||||
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
|
||||
@@ -314,15 +326,14 @@ export class IndicadoresPage {
|
||||
private cardsDeCama(catalog: Indicador[]) {
|
||||
const ids = catalog.map(item => item.id);
|
||||
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
|
||||
if (!ids.includes(ID_HISTOPATOLOGIA_CAMA)) {
|
||||
cards.unshift({
|
||||
id: ID_HISTOPATOLOGIA_CAMA, titulo: 'Resultado histopatológico por categoría BI-RADS',
|
||||
contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: ['fig_c2_barras', 'fig_c2_donas'],
|
||||
});
|
||||
}
|
||||
// The histopathology card comes first, including when only the local source is available.
|
||||
// The histopathology card keeps its place, first, whether pending or published.
|
||||
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
|
||||
}
|
||||
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
|
||||
get histopatologiaPendiente() {
|
||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
|
||||
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
|
||||
@@ -347,9 +358,9 @@ export class IndicadoresPage {
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
// Ids of the indicators to render; null shows the whole catalog.
|
||||
readonly indicatorSelection = signal<string[] | null>(null);
|
||||
// CaMa follows the mockup: no search box and no pins; its cards are the ones the summary draws.
|
||||
readonly searchVisible = computed(() => { const total = this.catalogOrder().length; return this.dominio !== 'cama' && total >= 2; });
|
||||
// Stable presentation priority; pins still take precedence in the grid.
|
||||
// The summary follows CaMa's mockup: no search box and no pins in any domain.
|
||||
readonly searchVisible = computed(() => false);
|
||||
// Stable presentation order. Pins no longer reorder the summary.
|
||||
readonly catalogOrder = computed(() => {
|
||||
const catalog = this.catalog();
|
||||
return this.dominio === 'cacu'
|
||||
@@ -365,9 +376,8 @@ export class IndicadoresPage {
|
||||
return selected.length + ' indicadores';
|
||||
});
|
||||
readonly searchResults = computed(() => {
|
||||
const selected = this.indicatorSelection();
|
||||
const items = selected === null ? this.catalogOrder() : this.catalogOrder().filter(item => selected.includes(item.id));
|
||||
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
|
||||
});
|
||||
readonly catalogLoading = signal(true);
|
||||
readonly catalogError = signal('');
|
||||
|
||||
@@ -97,14 +97,17 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges();
|
||||
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
|
||||
expect(fixture.nativeElement.querySelector('.period-builder')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador');
|
||||
expect(fixture.nativeElement.querySelector('.fields.compact')).not.toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Existe reporte en al menos un indicador');
|
||||
expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
|
||||
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
|
||||
expect(control.selectedPeriods).toEqual(['2025-10']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-02']);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
const replaced = flushDatos('cacu');
|
||||
expect(replaced.every(r => r.request.params.get('periodos') === '2025-02')).toBe(true);
|
||||
expect(panels().every(p => p.result().state !== 'Selección no consolidable')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
await fixture.whenStable();
|
||||
|
||||
@@ -8,7 +8,6 @@ import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||
import { Indicador } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
@@ -36,46 +35,40 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
function card(id: string) { return cards().find(c => c.indicador.id === id)!; }
|
||||
function ids() { return cards().map(c => c.indicador.id); }
|
||||
function button(id: string): HTMLButtonElement { return card(id).host.nativeElement.querySelector('.pin-toggle')!; }
|
||||
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
|
||||
async function pin(id: string) { button(id).click(); fixture.detectChanges(); await settle(); }
|
||||
async function pin(id: string) { page.togglePinned(card(id).indicador); fixture.detectChanges(); await settle(); }
|
||||
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); }
|
||||
|
||||
it('fija y desfija con control nativo, texto, estado accesible y sin HTTP', async () => {
|
||||
const control = button('i3');
|
||||
expect(control.type).toBe('button'); expect(control.tabIndex).toBe(0);
|
||||
expect(control.textContent).toContain('Fijar indicador'); expect(control.getAttribute('aria-pressed')).toBe('false');
|
||||
expect(control.getAttribute('aria-label')).toContain('Fijar indicador');
|
||||
for (const key of ['Enter', ' ']) {
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
control.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
await pin('i3'); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
|
||||
expect(button('i3')).toBe(control); expect(control.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(control.textContent).toContain('Desfijar indicador'); expect(control.getAttribute('aria-label')).toContain('Desfijar indicador');
|
||||
await pin('i3'); expect(ids()).toEqual(items.map(i => i.id)); expect(control.getAttribute('aria-pressed')).toBe('false');
|
||||
it('no muestra el control de fijar y la memoria no reordena las tarjetas', async () => {
|
||||
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
|
||||
await pin('i3');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i3');
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(false);
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('varios fijados conservan orden del catálogo, independientemente del orden de clics', async () => {
|
||||
it('varios fijados no alteran el orden del catálogo', async () => {
|
||||
const original = page.catalog(), snapshot = JSON.stringify(original);
|
||||
await pin('i4'); await pin('i2'); await pin('i0');
|
||||
expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
|
||||
await pin('i2'); expect(ids()).toEqual(['i0', 'i4', 'i1', 'i2', 'i3']);
|
||||
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
|
||||
expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i2'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
|
||||
});
|
||||
it('la selección de indicadores conserva la prioridad de los fijados', async () => {
|
||||
it('la selección de indicadores conserva el orden del catálogo', async () => {
|
||||
await pin('i3'); await pin('i4');
|
||||
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i3', 'i4', 'i1']);
|
||||
expect(ids()).toEqual(['i1', 'i3', 'i4']);
|
||||
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
|
||||
expect(cards()).toHaveLength(3); http.expectNone(() => true);
|
||||
});
|
||||
it('Mostrar todos restaura el catálogo con los fijados primero', async () => {
|
||||
it('Mostrar todos restaura el catálogo en su orden', async () => {
|
||||
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i0']);
|
||||
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
|
||||
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true);
|
||||
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
|
||||
page.showAllIndicators(); fixture.detectChanges(); await settle();
|
||||
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
|
||||
});
|
||||
it('un fijado sin seleccionar no se muestra', async () => {
|
||||
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
|
||||
@@ -83,12 +76,16 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
});
|
||||
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
||||
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
// CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins.
|
||||
// Its summary also leads with the histopathology card, which is not part of the catalog and cannot be pinned.
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual([ID_HISTOPATOLOGIA_CAMA, ...items.map(i => i.id)]);
|
||||
page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
|
||||
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
|
||||
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
const memory = TestBed.inject(IndicadoresMemory);
|
||||
expect(memory.isPinned('cacu', 'i1')).toBe(true);
|
||||
expect(memory.isPinned('tea', 'i3')).toBe(true);
|
||||
expect(memory.isPinned('cama', 'i1')).toBe(false);
|
||||
page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
page.changeDominio('tea'); load(); expect(ids()).toEqual(items.map(i => i.id));
|
||||
fixture.destroy(); create(); load();
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
|
||||
expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
|
||||
});
|
||||
it('no usa Storage y una nueva memoria reinicia la fijación', async () => {
|
||||
const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem');
|
||||
@@ -96,10 +93,12 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false);
|
||||
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true);
|
||||
});
|
||||
it('mover la tarjeta conserva foco en su botón existente', async () => {
|
||||
const control = button('i4'); control.focus(); await pin('i4');
|
||||
expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control);
|
||||
await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true);
|
||||
it('fijar no mueve la tarjeta ni pide figuras', async () => {
|
||||
const before = cards();
|
||||
await pin('i4');
|
||||
expect(cards()).toEqual(before);
|
||||
await pin('i4');
|
||||
expect(cards()).toEqual(before); http.expectNone(() => true);
|
||||
});
|
||||
it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => {
|
||||
card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle();
|
||||
|
||||
@@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
|
||||
expect(e.page.seleccionSeguimiento()).toBeUndefined();
|
||||
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
|
||||
dominio === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
dominio === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
e.page.changeDominio('cama'); e.harness.detectChanges();
|
||||
|
||||
@@ -4,7 +4,6 @@ import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
@@ -40,24 +39,20 @@ describe('Selección de indicadores gráficos', () => {
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
function ids() { return cards().map(c => c.indicador.id); }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
|
||||
function select() { return fixture.debugElement.query(By.css('.catalog-search mat-select'))?.componentInstance as MatSelect | undefined; }
|
||||
function showAll(): HTMLButtonElement { return fixture.nativeElement.querySelector('.catalog-search button'); }
|
||||
function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
|
||||
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
|
||||
|
||||
it.each([0, 1, 2, 5])('muestra el selector desde dos indicadores: catálogo de %i', count => {
|
||||
it.each([0, 1, 2, 5])('no ofrece buscador y muestra el catálogo completo: %i indicadores', count => {
|
||||
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
|
||||
expect(!!select()).toBe(count >= 2); expect(cards()).toHaveLength(count);
|
||||
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
|
||||
expect(cards()).toHaveLength(count);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('lista todo el catálogo, con todos seleccionados al inicio', () => {
|
||||
load();
|
||||
expect(select()!.multiple).toBe(true);
|
||||
expect(select()!.options.map(o => o._getHostElement().querySelector('.option-title')!.textContent)).toEqual(items.map(i => i.titulo));
|
||||
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
|
||||
expect(page.selectedIndicators()).toEqual(items.map(i => i.id));
|
||||
expect(page.selectionSummary()).toBe('Todos los indicadores');
|
||||
expect(result()).toBe('Mostrando 5 de 5 indicadores.');
|
||||
expect(showAll().disabled).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Mostrando 5 de 5 indicadores.');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
|
||||
@@ -66,7 +61,6 @@ describe('Selección de indicadores gráficos', () => {
|
||||
expect(ids()).toEqual(['B02', 'E05']);
|
||||
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
|
||||
expect(page.selectionSummary()).toBe('2 indicadores');
|
||||
expect(result()).toBe('Mostrando 2 de 5 indicadores.');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
|
||||
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
|
||||
expect(page.catalog()).toBe(original);
|
||||
@@ -76,9 +70,8 @@ describe('Selección de indicadores gráficos', () => {
|
||||
load(); choose([]);
|
||||
expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados');
|
||||
expect(showAll().disabled).toBe(false);
|
||||
showAll().click(); fixture.detectChanges();
|
||||
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(showAll().disabled).toBe(true);
|
||||
page.showAllIndicators(); fixture.detectChanges();
|
||||
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('marcar todos equivale a no filtrar', () => {
|
||||
@@ -90,26 +83,18 @@ describe('Selección de indicadores gráficos', () => {
|
||||
choose(['A01']);
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
|
||||
});
|
||||
it('«Ir» lleva a la tarjeta sin alternar la opción y muestra el indicador si estaba oculto', async () => {
|
||||
it('ir a un indicador oculto lo vuelve a mostrar y desplaza hasta su tarjeta', async () => {
|
||||
const scroll = vi.fn();
|
||||
Element.prototype.scrollIntoView = scroll;
|
||||
load(); choose(['A01']);
|
||||
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
const go = (id: string) => Array.from(document.querySelectorAll<HTMLAnchorElement>('.indicator-select-panel .option-go'))
|
||||
.find(a => a.closest('mat-option')!.textContent!.includes(items.find(i => i.id === id)!.titulo))!;
|
||||
expect(go('D04').getAttribute('aria-label')).toBe('Ir a Seguimiento');
|
||||
// The scroll waits until the panel has finished closing.
|
||||
const settle = (calls: number) => vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(calls); });
|
||||
go('D04').click(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(document.querySelector('.indicator-select-panel')).toBeNull();
|
||||
page.goToIndicator('D04'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
|
||||
expect(select()!.panelOpen).toBe(false);
|
||||
await settle(1);
|
||||
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(1); });
|
||||
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
|
||||
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
go('A01').click(); fixture.detectChanges(); await fixture.whenStable();
|
||||
// Already visible: the selection is untouched.
|
||||
page.goToIndicator('A01'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
|
||||
await settle(2);
|
||||
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(2); });
|
||||
http.match(() => true).forEach(r => r.flush({ data: [], layout: {} }));
|
||||
});
|
||||
it('no muestra el botón flotante de navegación por indicadores', () => {
|
||||
|
||||
@@ -39,9 +39,9 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
|
||||
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
|
||||
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
|
||||
// TEA and CaMa also have Histórico; the follow-up tab is named Análisis de riesgos in every domain; CaCu keeps its three tabs.
|
||||
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']
|
||||
: domain === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
||||
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||
|
||||
@@ -48,7 +48,9 @@ describe('Barras estratificadas: activación y caché',()=>{
|
||||
toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.dimension).toBe('grupo_edad');
|
||||
expect(toggle[1].getAttribute('aria-checked')).toBe('true');
|
||||
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2);
|
||||
// The dimensions, apart from the counts or percentage toggle that follows them.
|
||||
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions:not(.distribution-medida) [role="radio"]')).toHaveLength(2);
|
||||
expect(fixture.nativeElement.querySelectorAll('.distribution-medida [role="radio"]')).toHaveLength(2);
|
||||
for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); }
|
||||
});
|
||||
it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{
|
||||
@@ -93,3 +95,46 @@ describe('Barras estratificadas: activación y caché',()=>{
|
||||
expect(TestBed.inject(IndicadoresSnapshots).reading('cacu',item,applied)?.data).toEqual(general());
|
||||
});
|
||||
});
|
||||
|
||||
describe('Barra lateral de estratificación', () => {
|
||||
// Fija: con más de dos estratificadores, la elección de dimensión, los valores visibles y la medida van en una
|
||||
// barra lateral; ocultar y volver a mostrar valores redibuja sin pedir datos. Falla si la barra no aparece, si un
|
||||
// valor oculto sigue en la figura, si se puede ocultar el último o si un cambio local vuelve a consultar.
|
||||
let fixture:ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>, http:HttpTestingController;
|
||||
const tres:Indicador={...item,filtros:[...item.filtros!,{estrato:'estadio',etiqueta:'Estadio clínico',valores:[{valor:'I',etiqueta:'I'}]}]};
|
||||
const general=()=>({...c2Fixture(),id:item.id,version:item.version});
|
||||
beforeEach(()=>{
|
||||
TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]});
|
||||
TestBed.overrideComponent(IndicadorFigureCard,{remove:{imports:[PlotlyChart]},add:{imports:[ChartStub]}});
|
||||
fixture=TestBed.createComponent(IndicadorFigurePanel); http=TestBed.inject(HttpTestingController);
|
||||
for(const [k,v] of Object.entries({dominio:'cama',indicador:tres,figuraId:'fig_c2_barras',tema:'claro',applied})) fixture.componentRef.setInput(k,v);
|
||||
});
|
||||
afterEach(()=>{fixture.destroy();http.verify();});
|
||||
const request=()=>http.expectOne(r=>r.url.endsWith('/datos'));
|
||||
const aside=()=>fixture.nativeElement.querySelector('.strata-sidebar') as HTMLElement;
|
||||
it('lista los estratificadores y oculta o muestra valores sin consultar',()=>{
|
||||
fixture.detectChanges(); request().flush(general()); fixture.detectChanges();
|
||||
expect(aside()).not.toBeNull(); expect(fixture.nativeElement.querySelector('.distribution-toggle')).toBeNull();
|
||||
const opciones=[...aside().querySelectorAll('[role="radiogroup"] [role="radio"]')] as HTMLButtonElement[];
|
||||
expect(opciones.map(b=>b.textContent!.trim())).toEqual(['Sin estratificar','Por grupo de edad','Por estatus de seguimiento','Por estadio clínico']);
|
||||
opciones[1].click(); request().flush(age); fixture.detectChanges();
|
||||
const valores=()=>[...aside().querySelectorAll('.stratum-toggle')] as HTMLButtonElement[];
|
||||
expect(valores()).toHaveLength(age.valores_estrato.length);
|
||||
valores()[0].click(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().figure?.data.map(t=>t['name'])).not.toContain('<25');
|
||||
expect(valores()[0].getAttribute('aria-pressed')).toBe('false');
|
||||
for(const b of valores().slice(1,-1)) b.click(); fixture.detectChanges();
|
||||
expect(valores().at(-1)!.disabled).toBe(true); expect(fixture.componentInstance.result().figure?.data).toHaveLength(1);
|
||||
(aside().querySelector('.sidebar-reset') as HTMLButtonElement).click(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().figure?.data).toHaveLength(age.valores_estrato.length);
|
||||
http.expectNone(()=>true);
|
||||
});
|
||||
it('cambiar de estratificador muestra de nuevo todos los valores',()=>{
|
||||
fixture.detectChanges(); request().flush(general());
|
||||
fixture.componentInstance.changeDimension('grupo_edad'); request().flush(age);
|
||||
fixture.componentInstance.toggleEstrato('<25'); expect(fixture.componentInstance.ocultos.size).toBe(1);
|
||||
fixture.componentInstance.changeDimension('estatus_seguimiento'); request().flush(status);
|
||||
expect(fixture.componentInstance.ocultos.size).toBe(0);
|
||||
expect(fixture.componentInstance.estratos.map(e=>e.valor)).toEqual(status.valores_estrato);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json';
|
||||
import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json';
|
||||
import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { etiquetaDimension, stratifiedBars, stratifiedCapabilities, stratumOptions } from './indicadores-stratified';
|
||||
import { DimensionEstrato, Indicador } from './indicadores.models';
|
||||
|
||||
const age = { ...ageJson, tipo_periodo: 'semestre' as const };
|
||||
@@ -61,3 +61,52 @@ describe('Contratos simulados de estratificación de los analistas', () => {
|
||||
expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// A CaMa quantity of interest broken down by a stratifier: two strata of different size, one with a suppressed total.
|
||||
const porEtapa = () => ({
|
||||
id: 'cama_birads_cancer_invasor', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], estrato: 'etapa',
|
||||
valores_estrato: ['TEMPRANA', 'AVANZADA', 'SIN'], etiquetas_estrato: { TEMPRANA: 'Temprana', AVANZADA: 'Avanzada', SIN: 'Sin dato' },
|
||||
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, categorias: { B4A: { etiqueta: 'BI-RADS 4A' }, B5: { etiqueta: 'BI-RADS 5' } },
|
||||
totales_estrato: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'TEMPRANA', n: 40, suprimido: 0 }, { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'AVANZADA', n: 10, suprimido: 0 },
|
||||
{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'SIN', n: null, suprimido: 1 }],
|
||||
filas: [['TEMPRANA', 'B4A', 10], ['TEMPRANA', 'B5', 30], ['AVANZADA', 'B4A', 1], ['AVANZADA', 'B5', 9], ['SIN', 'B4A', null], ['SIN', 'B5', null]]
|
||||
.map(([estrato, categoria, n], i) => ({ periodo: '2025-S1', grupo: 'TOTAL', estrato, categoria, n, orden: i % 2, suprimido: n === null ? 1 : 0 })),
|
||||
});
|
||||
describe('Porcentaje en cada estrato', () => {
|
||||
it('cada categoría es la parte de su estrato, y un estrato con total suprimido no tiene porcentaje', () => {
|
||||
// Fails if the share is taken over the whole period instead of the stratum, or drawn over an unknown total.
|
||||
const { figure, cells } = stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro', {}, 'porcentaje');
|
||||
expect(cells.filter(c => c.stratum !== 'Sin dato').map(c => c.percent)).toEqual([25, 75, 10, 90]);
|
||||
expect(cells.filter(c => c.stratum === 'Sin dato').map(c => c.percent)).toEqual([null, null]);
|
||||
expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje del estrato');
|
||||
expect(stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro').figure.data[0]['x']).toEqual([10, 30]);
|
||||
});
|
||||
it('las dimensiones de CaMa toman su etiqueta del catálogo, y CaCu conserva la suya', () => {
|
||||
// Fails if a new stratifier is offered without its published label, or CaCu's wording changes.
|
||||
const item = { id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] as ['semestre'],
|
||||
filtros: [{ estrato: 'etapa', etiqueta: 'Etapa (temprana o avanzada)', valores: [{ valor: 'TEMPRANA', etiqueta: 'Temprana' }] },
|
||||
{ estrato: 'grupo_edad', etiqueta: 'Grupo de edad', valores: [{ valor: '40-49', etiqueta: '40-49' }] }] };
|
||||
expect(stratifiedCapabilities(item)).toEqual(['grupo_edad', 'etapa']);
|
||||
expect(etiquetaDimension(item, 'etapa')).toBe('Por etapa (temprana o avanzada)');
|
||||
expect(etiquetaDimension(item, 'grupo_edad')).toBe('Por grupo de edad');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Estratos ocultos', () => {
|
||||
// Fija: ocultar valores de un estrato quita sus series y sus celdas, cada estrato conserva su trama y nunca se
|
||||
// quedan todas fuera. Falla si el filtro deja de aplicarse, si las tramas se recorren o si se puede vaciar la figura.
|
||||
it('quita las series ocultas, conserva la trama de cada estrato y no deja la figura vacía', () => {
|
||||
const todos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro');
|
||||
const patron = (f: typeof todos.figure, nombre: string) => (f.data.find(t => t['name'] === nombre)!['marker'] as Record<string, Record<string, unknown>>)['pattern']['shape'];
|
||||
const algunos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(['<25', '35-44']));
|
||||
expect(algunos.figure.data.map(t => t['name'])).toEqual(['25-34', '45-54', '55-64', '65+', 'Sin dato']);
|
||||
expect(new Set(algunos.cells.map(c => c.stratum))).toEqual(new Set(['25-34', '45-54', '55-64', '65+', 'Sin dato']));
|
||||
for (const nombre of ['25-34', '65+', 'Sin dato']) expect(patron(algunos.figure, nombre)).toEqual(patron(todos.figure, nombre));
|
||||
const ninguno = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(age.valores_estrato));
|
||||
expect(ninguno.figure.data).toHaveLength(todos.figure.data.length);
|
||||
});
|
||||
it('lista los valores del estrato con su etiqueta, en el orden publicado', () => {
|
||||
expect(stratumOptions(age).map(e => e.etiqueta)).toEqual(['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'Sin dato']);
|
||||
expect(stratumOptions(age).at(-1)).toEqual({ valor: 'sin_dato', etiqueta: 'Sin dato' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,30 +4,60 @@ import { c2Theme, seriesColors } from './indicadores-c2-palette';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The dimensions a C2's bars can be broken down by, in this order; `citologia_alto_grado` belongs to CaCu's C1 donut.
|
||||
const ESTRATIFICABLES: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'birads', 'brca', 'estadio', 'tamano', 'etapa'];
|
||||
/** The button of a dimension: CaCu's two keep their wording; the rest take the label the catalog publishes. */
|
||||
export function etiquetaDimension(item: Indicador, d: DimensionEstrato): string {
|
||||
if (d === 'grupo_edad') return 'Por grupo de edad';
|
||||
if (d === 'estatus_seguimiento') return 'Por estatus de seguimiento';
|
||||
const etiqueta = item.filtros?.find(f => f.estrato === d)?.etiqueta;
|
||||
return 'Por ' + (etiqueta ? etiqueta.charAt(0).toLowerCase() + etiqueta.slice(1) : d);
|
||||
}
|
||||
export type MedidaEstrato = 'conteo' | 'porcentaje';
|
||||
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
|
||||
return item.contrato === 'C2' && Array.isArray(item.filtros)
|
||||
? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
|
||||
? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d
|
||||
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
|
||||
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
|
||||
}
|
||||
export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
// Whether a composition declares `estrato` among its strata: the catalog from FHIR carries the Measure's declared strata
|
||||
// (`estratos`) and no local filters. Only views that read one fixed stratum use it (CaCu's EU7 by follow-up status);
|
||||
// it doesn't turn on stratified figures or filters for other C2 measures.
|
||||
export function declaraEstrato(item: Indicador, estrato: DimensionEstrato): boolean {
|
||||
const declarados = (item as Indicador & { estratos?: unknown }).estratos;
|
||||
return item.contrato === 'C2' && Array.isArray(declarados) && declarados.includes(estrato);
|
||||
}
|
||||
/** A stratum a reader can show or hide: its published value and label, in the published order. */
|
||||
export interface StratumOption { valor: string; etiqueta: string; }
|
||||
export function stratumOptions(data: IndicadorDatos): StratumOption[] {
|
||||
const valores = Array.isArray(data['valores_estrato']) ? data['valores_estrato'] as unknown[] : [];
|
||||
const etiquetas = record(data['etiquetas_estrato']) ? data['etiquetas_estrato'] : {};
|
||||
return valores.filter((v): v is string => typeof v === 'string')
|
||||
.map(valor => ({ valor, etiqueta: typeof etiquetas[valor] === 'string' ? etiquetas[valor] as string : valor }));
|
||||
}
|
||||
// `percent`: the cell's share of its stratum, when the stratum's total is known.
|
||||
export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
/** The bars of one period broken down by `dimension`; the strata in `hidden` are left out of the figure and the cells,
|
||||
* unless that would leave none. */
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet<string> = new Set()): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
|
||||
|| !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos'])
|
||||
|| Object.keys(data['grupos']).length !== 1
|
||||
|| !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length
|
||||
|| !data['valores_estrato'].every(v => typeof v === 'string')
|
||||
|| new Set(data['valores_estrato']).size !== data['valores_estrato'].length || !record(data['etiquetas_estrato'])) throw new Error('Distribución estratificada inválida');
|
||||
const strata = data['valores_estrato'] as string[], labels = data['etiquetas_estrato'];
|
||||
const published = data['valores_estrato'] as string[], labels = data['etiquetas_estrato'];
|
||||
const shown = published.filter(s => !hidden.has(s));
|
||||
const strata = shown.length ? shown : published;
|
||||
const statisticalGroup = Object.keys(data['grupos'])[0];
|
||||
if (strata.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas');
|
||||
if (published.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas');
|
||||
const catalog = data['categorias'], groups = data['grupos_de_categoria'];
|
||||
const entries = new Map<string, { order: number; label: string; color?: string; parent?: string }>();
|
||||
const rows = new Map<string, Record<string, unknown>>();
|
||||
for (const row of data.filas) {
|
||||
const id = row['categoria'], stratum = row['estrato'], n = row['n'];
|
||||
if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id
|
||||
|| typeof stratum !== 'string' || !strata.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden'])
|
||||
|| typeof stratum !== 'string' || !published.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden'])
|
||||
|| ![0, 1].includes(row['suprimido'] as number) || (row['suprimido'] === 1 ? n !== null : n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) throw new Error('Fila estratificada inválida');
|
||||
const key = JSON.stringify([id, stratum]);
|
||||
if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas');
|
||||
@@ -44,21 +74,39 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
||||
const cells: StratifiedCell[] = [];
|
||||
const theme = c2Theme(tema);
|
||||
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
|
||||
const figure: PlotlyFigure = { data: strata.map((s, series) => {
|
||||
// The stratum's total: the one published, or else the sum of its cells when every one is published. A share is
|
||||
// only drawn over a known total; a suppressed or missing total leaves the stratum without percentages.
|
||||
const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record<string, unknown>[] : [];
|
||||
const totalDe = (s: string): number | null => {
|
||||
const publicado = totales.find(t => t['periodo'] === period && t['estrato'] === s && t['grupo'] === statisticalGroup);
|
||||
if (publicado) return publicado['suprimido'] === 0 && typeof publicado['n'] === 'number' && publicado['n'] > 0 ? publicado['n'] : null;
|
||||
const propias = [...entries.keys()].map(id => rows.get(JSON.stringify([id, s])));
|
||||
if (propias.some(r => !r || r['suprimido'] !== 0 || typeof r['n'] !== 'number')) return null;
|
||||
const suma = propias.reduce((a, r) => a + (r!['n'] as number), 0);
|
||||
return suma > 0 ? suma : null;
|
||||
};
|
||||
const porcentaje = medida === 'porcentaje';
|
||||
const figure: PlotlyFigure = { data: strata.map(s => {
|
||||
const series = published.indexOf(s); // a stratum keeps its pattern when others are hidden
|
||||
const selected = categories.map(([id, c]) => {
|
||||
const row = rows.get(JSON.stringify([id, s]));
|
||||
const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible';
|
||||
const value = status === 'Publicado' ? row!['n'] as number : null;
|
||||
cells.push({ category: c.label, stratum: labels[s] as string, value, status });
|
||||
return value;
|
||||
const total = totalDe(s);
|
||||
const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null;
|
||||
cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status });
|
||||
return { value, percent, total };
|
||||
});
|
||||
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
|
||||
const x = selected.map(v => porcentaje ? v.percent : v.value);
|
||||
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)),
|
||||
customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']),
|
||||
marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
|
||||
hovertemplate: '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
|
||||
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true,
|
||||
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
|
||||
font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 },
|
||||
xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
|
||||
xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid }
|
||||
: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
|
||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true },
|
||||
legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } };
|
||||
return { figure, cells };
|
||||
|
||||
@@ -61,15 +61,23 @@
|
||||
@if (teaData; as response) {
|
||||
<section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo">
|
||||
<h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3>
|
||||
<dl>
|
||||
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
|
||||
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
|
||||
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
|
||||
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
|
||||
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
|
||||
}
|
||||
</dl>
|
||||
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
|
||||
@if (response.resumen_eeg.validadas) {
|
||||
<dl>
|
||||
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
|
||||
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
|
||||
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
|
||||
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
|
||||
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
|
||||
}
|
||||
</dl>
|
||||
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
|
||||
} @else {
|
||||
<dl>
|
||||
<div><dt>Con EEG válido</dt><dd>{{ response.resumen_eeg.con_eeg_valido }}</dd></div>
|
||||
<div><dt>Sin EEG válido</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
|
||||
</dl>
|
||||
<p>Las alteraciones del EEG se muestran cuando se validen sus curvas de referencia.</p>
|
||||
}
|
||||
</section>
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
|
||||
@@ -12,7 +12,7 @@ import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { ALTERACIONES_EEG, EEG_VALIDO, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
|
||||
@Component({
|
||||
@@ -98,6 +98,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.tiposAlteracion = data.tipos_alteracion;
|
||||
// Until the alterations are validated, the EEG filter can only tell a valid EEG from none.
|
||||
this.statuses = data.resumen_eeg.validadas ? ALTERACIONES_EEG : EEG_VALIDO;
|
||||
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.draft = { ...this.applied };
|
||||
}
|
||||
|
||||
@@ -186,11 +186,11 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render();
|
||||
page.changeIndicatorSelection([items[3].id, items[4].id]); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
|
||||
observer().emit(target); await idle(); http.expectNone(() => true);
|
||||
// The pinned indicator leads; the other selected one keeps its component.
|
||||
expect(cards()).toEqual([before[4], before[3]]);
|
||||
positions(cards().map((_, i) => [i === 1 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
|
||||
// Pins no longer reorder; the selected indicators keep catalog order and their components.
|
||||
expect(cards()).toEqual([before[3], before[4]]);
|
||||
positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
|
||||
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
|
||||
expect(cards()[1].selectedFigure).toBe('f');
|
||||
expect(cards()[0].selectedFigure).toBe('f');
|
||||
});
|
||||
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
|
||||
await load([items[0]]); positions([[200, 0]]); notify(); await confirm();
|
||||
|
||||
@@ -18,8 +18,16 @@ export interface Indicador {
|
||||
filtros?: IndicadorFiltro[];
|
||||
// Tabs that show it; without this field, all of them.
|
||||
vistas?: string[];
|
||||
// Interactive donut and bars by one stratum, like CaCu's EU7.
|
||||
escenario?: VistaEscenario;
|
||||
// How the breakdown by stratum opens: counts, or each category's share of its stratum.
|
||||
medida_estrato?: 'conteo' | 'porcentaje';
|
||||
}
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads';
|
||||
// CaMa's stratifiers (brca, estadio, tamano, etapa) break down its quantities of interest.
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads' | 'brca' | 'estadio' | 'tamano' | 'etapa';
|
||||
export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads', 'brca', 'estadio', 'tamano', 'etapa'];
|
||||
// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico».
|
||||
export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; }
|
||||
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
|
||||
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
|
||||
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
|
||||
|
||||
@@ -142,6 +142,23 @@ describe('UX-04 validación defensiva HTTP', () => {
|
||||
|
||||
describe('contrato datos exclusivo de KPI', () => {
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
|
||||
it('conserva los conteos, totales y celdas suprimidas que publica WebApi para mastografías de CaMa', () => {
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
const payload = {
|
||||
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'],
|
||||
filas: [
|
||||
{ periodo: '2025-S1', categoria: 'BIRADS_4', n: 15, suprimido: 0 },
|
||||
{ periodo: '2025-S1', categoria: 'BIRADS_5', n: 0, suprimido: 0 },
|
||||
{ periodo: '2025-S2', categoria: 'BIRADS_4', n: null, suprimido: 1 },
|
||||
],
|
||||
totales_estrato: [{ periodo: '2025-S1', estrato: 'BIRADS_4', n: 15, suprimido: 0 }],
|
||||
};
|
||||
let result: unknown;
|
||||
TestBed.inject(IndicadoresService).datos('cama', payload.id, 'semestre', payload.periodos).subscribe(value => result = value);
|
||||
http.expectOne(req => req.url === `/cama/indicadores/${payload.id}/datos`).flush(payload);
|
||||
expect(result).toEqual(payload);
|
||||
http.verify();
|
||||
});
|
||||
it('envía sólo periodos explícitos sin intervalo de tiempo ni tema y conserva filas y notas', () => {
|
||||
const http = TestBed.inject(HttpTestingController); let result: unknown;
|
||||
TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// Covers the histologic-type classification and its column in the follow-up table. It uses the CaMa follow-up
|
||||
// fixture (fixtures/cama_seguimiento.json), to which each test adds a synthetic `tipo_histologico` per row.
|
||||
import fixtureData from './fixtures/cama_seguimiento.json';
|
||||
import { clasificacionHistologica, MAPEO_HISTOLOGICO, SIN_CLASIFICAR } from './mapeo-histologico';
|
||||
import { seguimientoTablaResponse } from './seguimiento-tabla.service';
|
||||
|
||||
const respuesta = () => structuredClone(fixtureData) as unknown as { columnas: { clave: string; etiqueta: string }[]; items: Record<string, string | number | null>[] };
|
||||
|
||||
describe('Clasificación histológica', () => {
|
||||
it.each([
|
||||
['Ductal (NST)', 'Carcinoma invasor'], ['Lobulillar', 'Carcinoma invasor'], ['Ductal-lobulillar mixto', 'Carcinoma invasor'],
|
||||
['Mucinoso', 'Carcinoma invasor'], ['Paget', 'Carcinoma in situ'], ['Papilar', 'Revisar (Benigno / In situ / Invasor)'],
|
||||
['Tubular', 'Carcinoma invasor'], ['cribiforme', 'Revisar (In situ / Invasor)'], ['Micropapilar', 'Revisar (In situ / Invasor)'],
|
||||
['Inflamatorio', 'Carcinoma invasor'], ['Medular', 'Carcinoma invasor'], ['Otros', 'Revisar (Benigno / In situ / Invasor)'],
|
||||
['SIN MAPEAR', 'Sin clasificar'],
|
||||
])('asigna a «%s» la clasificación «%s»', (tipo, clasificacion) => {
|
||||
// Fails if a type is moved to another group or dropped from the mapping.
|
||||
expect(clasificacionHistologica(tipo)).toBe(clasificacion);
|
||||
});
|
||||
it('la categoría combinada «Tubular / cribiforme» del gráfico es carcinoma invasor', () => {
|
||||
// Fails if the chart's merged category stops being classified, which would leave its patients unclassified.
|
||||
expect(clasificacionHistologica('Tubular / cribiforme')).toBe('Carcinoma invasor');
|
||||
});
|
||||
it('un tipo fuera del mapeo, incluido uno heredado del prototipo de objeto, es «Sin clasificar»', () => {
|
||||
// Fails if the lookup returns inherited properties such as «constructor» instead of the fallback.
|
||||
for (const tipo of ['Desconocido', '', 'constructor', 'toString']) expect(clasificacionHistologica(tipo)).toBe(SIN_CLASIFICAR);
|
||||
});
|
||||
it('el mapeo conserva sus trece tipos y sus cuatro clasificaciones directas', () => {
|
||||
// Fails if a type is added or removed without reviewing its classification.
|
||||
expect(Object.keys(MAPEO_HISTOLOGICO)).toHaveLength(14);
|
||||
expect(new Set(Object.values(MAPEO_HISTOLOGICO))).toEqual(new Set([
|
||||
'Carcinoma invasor', 'Carcinoma in situ', 'Revisar (Benigno / In situ / Invasor)', 'Revisar (In situ / Invasor)', 'Sin clasificar']));
|
||||
});
|
||||
});
|
||||
|
||||
describe('Seguimiento: columna de clasificación histológica', () => {
|
||||
const tipos = ['Ductal (NST)', 'Paget', 'Otros', 'SIN MAPEAR', 'Zzz'];
|
||||
it('cada paciente recibe la clasificación de su propio tipo, en una columna tras el tipo o tras el resultado de la biopsia', () => {
|
||||
// Fails if the classification is computed from another row or placed away from the biopsy columns.
|
||||
const datos = respuesta();
|
||||
const conBiopsia = datos.items.filter(item => item['biopsia'] !== null);
|
||||
conBiopsia.forEach((item, i) => { item['tipo_histologico'] = tipos[i % tipos.length]; });
|
||||
const r = seguimientoTablaResponse(datos);
|
||||
const claves = r.columnas.map(c => c.clave);
|
||||
expect(claves[claves.indexOf('biopsia') + 1]).toBe('clasificacion_histologica');
|
||||
expect(r.columnas.find(c => c.clave === 'clasificacion_histologica')!.etiqueta).toBe('Clasificación histológica');
|
||||
for (const item of r.items.filter(item => typeof item['tipo_histologico'] === 'string')) {
|
||||
expect(item['clasificacion_histologica']).toBe(clasificacionHistologica(item['tipo_histologico'] as string));
|
||||
}
|
||||
});
|
||||
it('con una columna de tipo, la clasificación va justo después de ella', () => {
|
||||
// Fails if the derived column ignores the type's own column and lands elsewhere.
|
||||
const datos = respuesta();
|
||||
datos.columnas.splice(datos.columnas.findIndex(c => c.clave === 'biopsia') + 1, 0, { clave: 'tipo_histologico', etiqueta: 'Tipo histológico' });
|
||||
datos.items.forEach(item => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Lobulillar'; });
|
||||
const claves = seguimientoTablaResponse(datos).columnas.map(c => c.clave);
|
||||
expect(claves.slice(claves.indexOf('tipo_histologico'), claves.indexOf('tipo_histologico') + 2)).toEqual(['tipo_histologico', 'clasificacion_histologica']);
|
||||
});
|
||||
it('un paciente sin tipo no recibe clasificación y los demás campos quedan como llegaron', () => {
|
||||
// Fails if a patient without biopsy is shown as «Sin clasificar», or if other row values are altered.
|
||||
const datos = respuesta();
|
||||
datos.items.forEach((item, i) => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Medular'; });
|
||||
const original = structuredClone(datos.items);
|
||||
const r = seguimientoTablaResponse(datos);
|
||||
r.items.forEach((item, i) => {
|
||||
if (original[i]['tipo_histologico'] === null) expect('clasificacion_histologica' in item).toBe(false);
|
||||
expect({ ...item, clasificacion_histologica: undefined }).toEqual({ ...original[i], clasificacion_histologica: undefined });
|
||||
});
|
||||
});
|
||||
it('una lista sin tipo histológico no cambia', () => {
|
||||
// Fails if the column appears while the API does not send the field.
|
||||
const r = seguimientoTablaResponse(respuesta());
|
||||
expect(r.columnas.map(c => c.clave)).not.toContain('clasificacion_histologica');
|
||||
expect(r.items.some(item => 'clasificacion_histologica' in item)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
// Groups the histologic type of a biopsy into the classification shown beside it.
|
||||
export const SIN_CLASIFICAR = 'Sin clasificar';
|
||||
|
||||
export const MAPEO_HISTOLOGICO: Readonly<Record<string, string>> = {
|
||||
'Ductal (NST)': 'Carcinoma invasor',
|
||||
'Lobulillar': 'Carcinoma invasor',
|
||||
'Ductal-lobulillar mixto': 'Carcinoma invasor',
|
||||
'Mucinoso': 'Carcinoma invasor',
|
||||
'Paget': 'Carcinoma in situ',
|
||||
'Papilar': 'Revisar (Benigno / In situ / Invasor)',
|
||||
'Tubular': 'Carcinoma invasor',
|
||||
'Tubular / cribiforme': 'Carcinoma invasor',
|
||||
'cribiforme': 'Revisar (In situ / Invasor)',
|
||||
'Micropapilar': 'Revisar (In situ / Invasor)',
|
||||
'Inflamatorio': 'Carcinoma invasor',
|
||||
'Medular': 'Carcinoma invasor',
|
||||
'Otros': 'Revisar (Benigno / In situ / Invasor)',
|
||||
'SIN MAPEAR': SIN_CLASIFICAR,
|
||||
};
|
||||
|
||||
/** The classification of a histologic type; a type outside the mapping is «Sin clasificar». */
|
||||
export const clasificacionHistologica = (tipo: string) =>
|
||||
Object.hasOwn(MAPEO_HISTOLOGICO, tipo) ? MAPEO_HISTOLOGICO[tipo] : SIN_CLASIFICAR;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
@let r = respuesta();
|
||||
<section aria-labelledby="analisis-recurrencia-titulo">
|
||||
<h5 id="analisis-recurrencia-titulo">Análisis de recurrencia</h5>
|
||||
@if (r === undefined) { <p role="status">Buscando el análisis de recurrencia…</p> }
|
||||
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
|
||||
@if (r) {
|
||||
@if (r.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos de recurrencia para mostrar.</p> }
|
||||
@else {
|
||||
<label class="selector">Cohorte
|
||||
<select [value]="cohorte()" (change)="elegirCohorte($any($event.target).value)">
|
||||
@for (c of cohortes; track c.id) { <option [value]="c.id" [selected]="c.id === cohorte()">{{ c.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()?.escenario" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track f.escenario) { <option [value]="f.escenario" [selected]="f.escenario === escenario()?.escenario">{{ f.escenario }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + escenario()?.escenario + ', ' + escenario()?.cohorte_nombre" /> }
|
||||
}
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="factores-recurrencia-titulo">
|
||||
<h5 id="factores-recurrencia-titulo">Factores de riesgo</h5>
|
||||
@if (r && r.escenarios.length) {
|
||||
<label class="selector horizons">Horizonte
|
||||
<select [value]="horizonte()" (change)="elegirHorizonte(+$any($event.target).value)">
|
||||
@for (h of horizontes(); track h) { <option [value]="h" [selected]="h === horizonte()">{{ h }} meses</option> }
|
||||
</select>
|
||||
</label>
|
||||
<app-cama-factores-riesgo [fila]="factores()" />
|
||||
} @else { <p class="pending">Se muestran al elegir un escenario clínico.</p> }
|
||||
</section>
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { Component, computed, inject, input, signal } from '@angular/core';
|
||||
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
|
||||
export const COHORTES: { id: string; nombre: string }[] = [{ id: 'metabric', nombre: 'METABRIC' }, { id: 'scanb', nombre: 'SCAN-B' }];
|
||||
export const HORIZONTE_PREDETERMINADO = 60;
|
||||
|
||||
/**
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo»: two chained menus, the cohort (METABRIC or SCAN-B) and then its clinical
|
||||
* scenarios; the scenario chosen decides the curve and the label at once, one at a time, and the cohorts are never mixed. The label has
|
||||
* a horizon (12, 36 or 60 months, 60 by default). The menu opens on the scenario the patient's covariates place her in, when one does.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-recurrencia',
|
||||
imports: [PlotlyChart, CamaFactoresRiesgo],
|
||||
templateUrl: './cama-analisis-recurrencia.component.html',
|
||||
styleUrl: './cama-analisis.component.scss',
|
||||
})
|
||||
export class CamaAnalisisRecurrencia {
|
||||
readonly pacId = input.required<string>();
|
||||
private readonly service = inject(CamaRecurrenciaService);
|
||||
readonly cohortes = COHORTES;
|
||||
/** The analysis; `undefined` while it loads, `null` when there is no recurrence model in production. */
|
||||
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
|
||||
private readonly cohorteElegida = signal<string | null>(null);
|
||||
private readonly escenarioElegido = signal<string | null>(null);
|
||||
readonly horizonte = signal<number>(HORIZONTE_PREDETERMINADO);
|
||||
readonly cohorte = computed(() => this.cohorteElegida() ?? this.respuesta()?.predeterminado?.cohorte
|
||||
?? COHORTES.find(c => this.respuesta()?.escenarios.some(f => f.cohorte === c.id))?.id ?? null);
|
||||
/** The scenarios of the cohort chosen, from the list of that cohort only. */
|
||||
readonly escenarios = computed(() => this.respuesta()?.escenarios.filter(f => f.cohorte === this.cohorte()) ?? []);
|
||||
readonly escenario = computed(() => {
|
||||
const lista = this.escenarios();
|
||||
const pedido = this.escenarioElegido() ?? (this.respuesta()?.predeterminado?.cohorte === this.cohorte() ? this.respuesta()?.predeterminado?.escenario : null);
|
||||
return lista.find(f => f.escenario === pedido) ?? lista[0] ?? null;
|
||||
});
|
||||
readonly figura = computed(() => { const f = this.escenario(); return f ? figuraRecurrencia(f) : null; });
|
||||
readonly horizontes = computed(() => this.respuesta()?.horizontes ?? []);
|
||||
readonly factores = computed(() => {
|
||||
const f = this.escenario();
|
||||
return f ? this.respuesta()?.resumen.find(r => r.cohorte === f.cohorte && r.escenario === f.escenario && r.horizonte_meses === this.horizonte()) ?? null : null;
|
||||
});
|
||||
|
||||
elegirCohorte(id: string): void { this.cohorteElegida.set(id); this.escenarioElegido.set(null); }
|
||||
elegirEscenario(nombre: string): void { this.escenarioElegido.set(nombre); }
|
||||
elegirHorizonte(meses: number): void { this.horizonte.set(meses); }
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
<section aria-labelledby="analisis-supervivencia-titulo">
|
||||
<h5 id="analisis-supervivencia-titulo">Análisis de supervivencia</h5>
|
||||
@let m = menu();
|
||||
@if (m === undefined) { <p role="status">Buscando los escenarios clínicos…</p> }
|
||||
@if (m === null) { <p role="status">Todavía no hay un modelo de supervivencia en producción.</p> }
|
||||
@if (m) {
|
||||
@if (m.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@else {
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of m.escenarios; track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@let l = lectura();
|
||||
@if (l?.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
|
||||
@if (l?.tipo === 'rechazada') { <p role="status">{{ $any(l).motivo }}</p> }
|
||||
@if (l?.tipo === 'error') { <p role="alert">No se pudo calcular la supervivencia de este escenario.</p> }
|
||||
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Supervivencia: ' + escenario()" /> }
|
||||
}
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="factores-supervivencia-titulo">
|
||||
<h5 id="factores-supervivencia-titulo">Factores de riesgo</h5>
|
||||
@if (lectura()?.tipo === 'lista') { <app-cama-factores-riesgo [fila]="factores()" /> }
|
||||
@else { <p class="pending">Se muestran al elegir un escenario clínico.</p> }
|
||||
</section>
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { Component, computed, inject, input, signal } from '@angular/core';
|
||||
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { catchError, map, of, startWith, switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { CamaCurvasService, EscenarioConFactores, SeleccionRechazada } from './cama-curvas.service';
|
||||
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
|
||||
import { figuraSupervivencia } from './cama-supervivencia-figura';
|
||||
|
||||
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: EscenarioConFactores };
|
||||
|
||||
/**
|
||||
* «Análisis de supervivencia» and its «Factores de riesgo»: a menu of clinical scenarios; the one chosen decides the curve and the label
|
||||
* at once, one scenario at a time. The curve is computed from the data ingested so far with the model in production; the menu opens on
|
||||
* the scenario the patient belongs to.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-supervivencia',
|
||||
imports: [PlotlyChart, CamaFactoresRiesgo],
|
||||
templateUrl: './cama-analisis-supervivencia.component.html',
|
||||
styleUrl: './cama-analisis.component.scss',
|
||||
})
|
||||
export class CamaAnalisisSupervivencia {
|
||||
readonly pacId = input.required<string>();
|
||||
private readonly service = inject(CamaCurvasService);
|
||||
/** The menu; `undefined` while it loads, `null` when there is no model in production. */
|
||||
readonly menu = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id))));
|
||||
private readonly elegido = signal<string | null>(null);
|
||||
readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null);
|
||||
readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of<Lectura | null>(null) : this.service.consulta(nombre).pipe(
|
||||
map((datos): Lectura => ({ tipo: 'lista', datos })),
|
||||
catchError(error => of<Lectura>(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })),
|
||||
startWith<Lectura>({ tipo: 'cargando' })))), { initialValue: null as Lectura | null });
|
||||
readonly figura = computed(() => { const l = this.lectura(); return l?.tipo === 'lista' ? figuraSupervivencia(l.datos.respuesta.curvas) : null; });
|
||||
readonly factores = computed(() => { const l = this.lectura(); return l?.tipo === 'lista' ? l.datos.factores : null; });
|
||||
|
||||
elegir(nombre: string): void { this.elegido.set(nombre); }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
:host { display: block; }
|
||||
.selector { display: inline-flex; flex-direction: column; gap: .25rem; margin: 0 1.5rem .75rem 0; font-size: .85rem; }
|
||||
.selector select { font: inherit; padding: .35rem .5rem; min-width: 16rem; max-width: 100%; }
|
||||
.horizons { margin: 0 0 .5rem; }
|
||||
.pending { color: var(--mat-sys-outline, #777); margin: 0; }
|
||||
@@ -0,0 +1,177 @@
|
||||
// Covers Luis's specification of CaMa's record: the risk-factor label built from a summary row (the factors present in at least 95 % and in
|
||||
// 50-95 % of the scenario, robust solid and suggestive outlined, grey "none" message), the survival analysis (one menu of scenarios; the
|
||||
// one chosen decides the curve and the label at once; it opens on the patient's) and the recurrence analysis (two chained menus, the
|
||||
// cohorts never mixed, a horizon for the label with 60 months by default). Fixtures: stubs of `CamaCurvasService` and
|
||||
// `CamaRecurrenciaService` with a record like the API answers.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
|
||||
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
|
||||
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
|
||||
import { CamaCurvasService, respuestaCurvas } from './cama-curvas.service';
|
||||
import { CamaFactoresRiesgo, entradasDe } from './cama-factores-riesgo.component';
|
||||
import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
|
||||
const meses = Array.from({ length: 25 }, (_, i) => i);
|
||||
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24));
|
||||
const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) });
|
||||
const curvas = (escenario: string, n = 245) => ({ modelo: { nombre: 'cama-survival', version: '3' }, curvas: {
|
||||
version: 1, escenario, n, events: 67, median_follow_up_months: 9, horizons_months: [6, 12, 18], months_max: 24, bootstrap_replicas: 200,
|
||||
km: { months: meses, S: decreciente(0.7), low: decreciente(0.6), high: decreciente(0.8) }, km_adjusted: { months: meses, S: decreciente(0.72) },
|
||||
weibull: { t: [0, 12, 24], S: [1, 0.85, 0.72] }, weibull_fractional: { t: [0, 12, 24], S: [1, 0.84, 0.71] },
|
||||
points: { LR: serie([0.93, 0.85, 0.78]), HBN: serie([0.92, 0.84, 0.77]), COMB: serie([0.925, 0.845, 0.775]) }, etiquetas: {} } });
|
||||
const fila = (escenario: string, extra: object = {}) => ({ escenario, riesgo_definitorios: 'Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)', riesgo_mayoritarios: 'HER2=H3 (sugerente, 60%)',
|
||||
n_factores_riesgo_incluidos: 3, incluye_factor_riesgo: true, ...extra });
|
||||
|
||||
const texto = (f: { nativeElement: unknown }) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
|
||||
function plotly() {
|
||||
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||
const runtime = { react: vi.fn(() => Promise.resolve()), purge: vi.fn(), Plots: { resize: vi.fn(() => Promise.resolve()) },
|
||||
addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) };
|
||||
return { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) };
|
||||
}
|
||||
function elegir(f: { nativeElement: unknown; detectChanges(): void }, etiqueta: string, valor: string) {
|
||||
const select = [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!.querySelector('select')!;
|
||||
select.value = valor;
|
||||
select.dispatchEvent(new Event('change'));
|
||||
f.detectChanges();
|
||||
}
|
||||
|
||||
describe('Factores de riesgo: la etiqueta', () => {
|
||||
const montar = (f: object | null) => {
|
||||
const fx = TestBed.createComponent(CamaFactoresRiesgo);
|
||||
fx.componentRef.setInput('fila', f);
|
||||
fx.detectChanges();
|
||||
return fx;
|
||||
};
|
||||
|
||||
// Fails if an entry is cut at the wrong place or its strength is read from anything but its own parentheses.
|
||||
it('reads the entries of a cell and whether each is robust', () => {
|
||||
expect(entradasDe('Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)')).toEqual([
|
||||
{ texto: 'Grado=G3 (robusto, 97%)', robusto: true }, { texto: 'Ki67=alto (sugerente, 96%)', robusto: false }]);
|
||||
expect(entradasDe('')).toEqual([]);
|
||||
});
|
||||
|
||||
// Fails if the two groups lose their order or a robust factor is not told from a suggestive one.
|
||||
it('lists the defining factors, then the majority ones, a robust one solid and a suggestive one outlined', () => {
|
||||
const fx = montar(fila('< 45 años'));
|
||||
const items = [...(fx.nativeElement as HTMLElement).querySelectorAll('li')];
|
||||
|
||||
expect(texto(fx)).toContain('Factores de riesgo de este escenario');
|
||||
expect(items.map(i => i.textContent!.trim())).toEqual(['Grado=G3 (robusto, 97%)', 'Ki67=alto (sugerente, 96%)', 'HER2=H3 (sugerente, 60%)']);
|
||||
expect(items.map(i => i.classList.contains('robust'))).toEqual([true, false, false]);
|
||||
});
|
||||
|
||||
// Fails if a scenario with no factors is shown empty, or with a different message.
|
||||
it.each([[null], [fila('X', { incluye_factor_riesgo: false })], [fila('X', { n_factores_riesgo_incluidos: 0 })]])('says there are none (%#)', f => {
|
||||
const fx = montar(f);
|
||||
|
||||
expect(texto(fx)).toContain('Sin factores de riesgo identificados en este escenario.');
|
||||
expect((fx.nativeElement as HTMLElement).querySelector('li')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de supervivencia', () => {
|
||||
let consulta: ReturnType<typeof vi.fn>;
|
||||
beforeEach(() => {
|
||||
consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: nombre === 'Estadio I' ? null : fila(nombre) }));
|
||||
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], predeterminado: 'Estadio I' }), consulta } }] });
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
|
||||
f.componentRef.setInput('pacId', '7');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
return f;
|
||||
};
|
||||
|
||||
// Fails if the menu does not open on the patient's scenario, or offers anything but the scenarios the API listed.
|
||||
it('opens on the patient\'s scenario with the menu the API gave', () => {
|
||||
const f = montar();
|
||||
const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim());
|
||||
|
||||
expect(opciones).toEqual(['< 45 años', 'Estadio I']);
|
||||
expect(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I');
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
|
||||
});
|
||||
|
||||
// Fails if choosing a scenario changes only the curve or only the label: the selector decides both at once, one scenario at a time.
|
||||
it('changes the curve and the label together when another scenario is chosen, and never draws two', () => {
|
||||
const f = montar();
|
||||
expect(texto(f)).toContain('Sin factores de riesgo identificados'); // Estadio I has no row
|
||||
|
||||
elegir(f, 'Escenario clínico', '< 45 años');
|
||||
|
||||
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
|
||||
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
|
||||
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de recurrencia', () => {
|
||||
// Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2.
|
||||
it('scales the y axis to the months it draws', () => {
|
||||
const largo = { ...figura('metabric', 'Largo'), observado_hasta: 300, months_max: 72,
|
||||
km: { months: Array.from({ length: 301 }, (_, i) => i), S: Array.from({ length: 301 }, (_, i) => 1 - i / 400), low: Array.from({ length: 301 }, (_, i) => (i <= 72 ? 0.85 : 0.2)), high: Array.from({ length: 301 }, () => 1) } };
|
||||
|
||||
expect((figuraRecurrencia(respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios: [largo], resumen: [], predeterminado: null }).escenarios[0]).layout as any).yaxis.range[0]).toBeGreaterThan(0.5);
|
||||
});
|
||||
|
||||
const figura = (cohorte: string, escenario: string) => ({ cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, n: 300, recaidas: 180,
|
||||
horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72,
|
||||
km: { months: Array.from({ length: 61 }, (_, i) => i), S: Array.from({ length: 61 }, (_, i) => 1 - i / 200), low: Array.from({ length: 61 }, (_, i) => 1 - i / 190), high: Array.from({ length: 61 }, () => 1) },
|
||||
weibull: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, weibull_fractional: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, points: { COMB: { S: [0.9, 0.8, 0.7], low: [0.85, 0.75, 0.65], high: [0.95, 0.85, 0.75] } } });
|
||||
const resumen = (cohorte: string, escenario: string, h: number) => ({ cohorte, escenario, horizonte_meses: h, riesgo_definitorios: `Marca=${cohorte}-${h} (robusto, 99%)`, riesgo_mayoritarios: '',
|
||||
n_factores_riesgo_incluidos: 1, incluye_factor_riesgo: true });
|
||||
const respuesta = () => respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60],
|
||||
escenarios: [figura('metabric', '< 45 años'), figura('metabric', 'Tumor >50 mm'), figura('scanb', '< 45 años'), figura('scanb', 'Grado 3')],
|
||||
resumen: ['metabric', 'scanb'].flatMap(c => [12, 36, 60].flatMap(h => [resumen(c, '< 45 años', h), resumen(c, 'Tumor >50 mm', h), resumen(c, 'Grado 3', h)])),
|
||||
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' } });
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(respuesta()) } }] }));
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
const f = TestBed.createComponent(CamaAnalisisRecurrencia);
|
||||
f.componentRef.setInput('pacId', '7');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
return f;
|
||||
};
|
||||
const opciones = (f: { nativeElement: unknown }, etiqueta: string) => [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!
|
||||
.querySelectorAll('option');
|
||||
|
||||
// Fails if the menus do not open on the patient's cohort and scenario, or the scenario list is not that of the cohort chosen.
|
||||
it('opens on the patient\'s cohort and scenario, with only that cohort\'s scenarios', () => {
|
||||
const f = montar();
|
||||
|
||||
expect([...opciones(f, 'Cohorte')].map(o => o.textContent!.trim())).toEqual(['METABRIC', 'SCAN-B']);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Grado 3']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her scenario, the label at 60 months
|
||||
});
|
||||
|
||||
// Fails if a change of cohort leaves the other cohort's scenarios, curve or label on screen: the cohorts are never mixed.
|
||||
it('reloads the scenarios, the curve and the label when the cohort changes, and keeps one curve', () => {
|
||||
const f = montar();
|
||||
|
||||
elegir(f, 'Cohorte', 'metabric');
|
||||
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Tumor >50 mm']);
|
||||
expect(texto(f)).toContain('Marca=metabric-60');
|
||||
expect(texto(f)).not.toContain('scanb');
|
||||
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
||||
});
|
||||
|
||||
// Fails if the label ignores the horizon, or does not open on 60 months.
|
||||
it('shows the label at the horizon chosen, 60 months by default', () => {
|
||||
const f = montar();
|
||||
expect((f.nativeElement as HTMLElement).querySelector<HTMLSelectElement>('.horizons select')!.value).toBe('60');
|
||||
|
||||
elegir(f, 'Horizonte', '12');
|
||||
|
||||
expect(texto(f)).toContain('Marca=scanb-12');
|
||||
expect(texto(f)).not.toContain('Marca=scanb-60');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { catchError, map, Observable, of, throwError } from 'rxjs';
|
||||
|
||||
// The cohort's survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the
|
||||
// model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the
|
||||
// version they come from and says when the data are simulated. A 404 is "no model in production yet".
|
||||
export interface SerieDeSupervivencia { S: number[]; low: number[]; high: number[]; }
|
||||
export interface CurvasSupervivencia {
|
||||
escenario?: string;
|
||||
n: number; events: number; median_follow_up_months: number;
|
||||
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
km_adjusted: { months: number[]; S: number[] };
|
||||
weibull: { t: number[]; S: number[] };
|
||||
weibull_fractional: { t: number[]; S: number[] };
|
||||
points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia };
|
||||
etiquetas: Record<string, string>;
|
||||
}
|
||||
export interface RespuestaCurvas {
|
||||
modelo: { nombre: string; version: string };
|
||||
curvas: CurvasSupervivencia;
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length);
|
||||
const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1);
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||
|
||||
function invalid(): never {
|
||||
throw new Error('Respuesta de curvas de supervivencia inválida');
|
||||
}
|
||||
|
||||
function serie(v: unknown, horizons: number): SerieDeSupervivencia {
|
||||
if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid();
|
||||
const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[];
|
||||
if (low.some((l, i) => l > high[i])) invalid();
|
||||
return { S: s, low, high };
|
||||
}
|
||||
|
||||
/** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */
|
||||
export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid();
|
||||
const m = v['modelo'] as Record<string, unknown>, c = v['curvas'] as Record<string, unknown>;
|
||||
if (!text(m['nombre']) || !text(m['version'])) invalid();
|
||||
const horizons = c['horizons_months'];
|
||||
if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events'])
|
||||
|| !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid();
|
||||
const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points'];
|
||||
if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length)
|
||||
|| !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid();
|
||||
if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid();
|
||||
for (const curve of [weibull, fractional]) {
|
||||
if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid();
|
||||
}
|
||||
if (!record(points)) invalid();
|
||||
const p = points as Record<string, unknown>, h = (horizons as number[]).length;
|
||||
const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record<string, string> : {};
|
||||
return {
|
||||
modelo: { nombre: m['nombre'] as string, version: m['version'] as string },
|
||||
curvas: {
|
||||
escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined,
|
||||
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
|
||||
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
|
||||
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
|
||||
weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'],
|
||||
points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The scenario summary's row of a scenario: its risk factors. `riesgo_*` are entries `Variable=Categoría (robusto|sugerente, porcentaje)`
|
||||
* separated by `;`; `horizonte_meses` and `cohorte` only in the recurrence analysis. */
|
||||
export interface FilaFactores {
|
||||
escenario: string; riesgo_definitorios: string; riesgo_mayoritarios: string;
|
||||
n_factores_riesgo_incluidos: number; incluye_factor_riesgo: boolean; horizonte_meses?: number; cohorte?: string;
|
||||
}
|
||||
export function filaFactores(v: unknown): FilaFactores {
|
||||
if (!record(v) || typeof v['escenario'] !== 'string') invalid();
|
||||
const f = v as Record<string, any>;
|
||||
return { escenario: f['escenario'], riesgo_definitorios: typeof f['riesgo_definitorios'] === 'string' ? f['riesgo_definitorios'] : '',
|
||||
riesgo_mayoritarios: typeof f['riesgo_mayoritarios'] === 'string' ? f['riesgo_mayoritarios'] : '',
|
||||
n_factores_riesgo_incluidos: Number.isFinite(f['n_factores_riesgo_incluidos']) ? f['n_factores_riesgo_incluidos'] : 0,
|
||||
incluye_factor_riesgo: f['incluye_factor_riesgo'] === true || f['incluye_factor_riesgo'] === 'True',
|
||||
...(Number.isFinite(f['horizonte_meses']) ? { horizonte_meses: f['horizonte_meses'] } : {}), ...(typeof f['cohorte'] === 'string' ? { cohorte: f['cohorte'] } : {}) };
|
||||
}
|
||||
|
||||
/** The scenarios the menu offers, and the one the patient belongs to first. */
|
||||
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; predeterminado: string | null; }
|
||||
/** A scenario's figure with its risk factors (`null`: it has no summary row). */
|
||||
export interface EscenarioConFactores { respuesta: RespuestaCurvas; factores: FilaFactores | null; }
|
||||
/** The selection was refused with a reason (a 422): a scenario with too few patients, or one that does not exist. */
|
||||
export class SeleccionRechazada extends Error {}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaCurvasService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */
|
||||
escenarios(pacId: string): Observable<MenuEscenarios | null> {
|
||||
return this.http.get<unknown>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe(
|
||||
map(r => {
|
||||
if (!record(r) || !Array.isArray(r['escenarios'])) invalid();
|
||||
const lista = (r['escenarios'] as unknown[]).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
|
||||
return { escenarios: lista, predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
|
||||
}),
|
||||
catchError(() => of(null)),
|
||||
);
|
||||
}
|
||||
|
||||
/** The figure of one scenario scored with the production version over the data ingested so far, and its risk factors. A refused
|
||||
* scenario fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */
|
||||
consulta(escenario: string): Observable<EscenarioConFactores> {
|
||||
return this.http.post<unknown>('/cama/modelo/curvas/consulta', { escenario }).pipe(
|
||||
map(r => ({ respuesta: respuestaCurvas(r), factores: record(r) && r['factores'] ? filaFactores(r['factores']) : null })),
|
||||
catchError(error => error instanceof HttpErrorResponse && error.status === 422
|
||||
? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'El escenario no se puede calcular.')))
|
||||
: throwError(() => error)),
|
||||
);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@if (hay()) {
|
||||
<p class="title">Factores de riesgo de este escenario</p>
|
||||
@if (definitorios().length) {
|
||||
<div class="group"><span class="marker" aria-hidden="true">▲</span>
|
||||
<ul aria-label="Presentes en al menos 95 % del escenario">
|
||||
@for (e of definitorios(); track e.texto) { <li [class.robust]="e.robusto" [class.suggestive]="!e.robusto">{{ e.texto }}</li> }
|
||||
</ul></div>
|
||||
}
|
||||
@if (mayoritarios().length) {
|
||||
<div class="group"><span class="marker" aria-hidden="true">▲</span>
|
||||
<ul aria-label="Presentes en 50 a 95 % del escenario">
|
||||
@for (e of mayoritarios(); track e.texto) { <li [class.robust]="e.robusto" [class.suggestive]="!e.robusto">{{ e.texto }}</li> }
|
||||
</ul></div>
|
||||
}
|
||||
} @else {
|
||||
<p class="none">Sin factores de riesgo identificados en este escenario.</p>
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
:host { display: block; }
|
||||
.title { font-weight: 600; margin: 0 0 .5rem; }
|
||||
.group { display: flex; gap: .5rem; align-items: flex-start; margin: .25rem 0; }
|
||||
.marker { color: var(--mat-sys-error, #b3261e); line-height: 1.9; }
|
||||
ul { display: flex; flex-wrap: wrap; gap: .4rem; list-style: none; margin: 0; padding: 0; }
|
||||
li { border: 1px solid var(--mat-sys-error, #b3261e); border-radius: 1rem; padding: .15rem .7rem; font-size: .9rem; }
|
||||
li.robust { background: var(--mat-sys-error, #b3261e); color: var(--mat-sys-on-error, #fff); }
|
||||
li.suggestive { background: transparent; color: var(--mat-sys-error, #b3261e); }
|
||||
.none { color: var(--mat-sys-outline, #777); margin: 0; }
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import { FilaFactores } from './cama-curvas.service';
|
||||
|
||||
export interface EntradaFactor { texto: string; robusto: boolean; }
|
||||
|
||||
/** The entries of a summary cell, `Variable=Categoría (robusto|sugerente, porcentaje)` separated by `;`. */
|
||||
export function entradasDe(celda: string): EntradaFactor[] {
|
||||
return celda.split(';').map(e => e.trim()).filter(Boolean).map(texto => ({ texto, robusto: /\(\s*robusto\b/i.test(texto) }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The risk factors of one clinical scenario, from its row of the scenario summary: the factors present in at least 95 % of the scenario
|
||||
* and those in 50 to 95 %, a robust one solid and a suggestive one outlined. A scenario with none says so, in grey.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-factores-riesgo',
|
||||
templateUrl: './cama-factores-riesgo.component.html',
|
||||
styleUrl: './cama-factores-riesgo.component.scss',
|
||||
})
|
||||
export class CamaFactoresRiesgo {
|
||||
readonly fila = input<FilaFactores | null>(null);
|
||||
readonly definitorios = computed(() => entradasDe(this.fila()?.riesgo_definitorios ?? ''));
|
||||
readonly mayoritarios = computed(() => entradasDe(this.fila()?.riesgo_mayoritarios ?? ''));
|
||||
readonly hay = computed(() => (this.fila()?.incluye_factor_riesgo ?? false) && (this.fila()?.n_factores_riesgo_incluidos ?? 0) > 0
|
||||
&& this.definitorios().length + this.mayoritarios().length > 0);
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
<dl class="summary">
|
||||
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
|
||||
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
|
||||
<div><dt>Escenario clínico</dt><dd>{{ p.clinicalScenario ?? notAvailable }}</dd></div>
|
||||
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
|
||||
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
|
||||
<div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div>
|
||||
@@ -36,12 +37,21 @@
|
||||
<mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title">
|
||||
<mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
<ul>
|
||||
@for (item of placeholders; track item.key) {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
|
||||
}
|
||||
</ul>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
@if (p.idField === 'pac_id' && p.clinicalScenario === postTreatment) { <app-cama-analisis-recurrencia [pacId]="p.patientId" /> }
|
||||
<section aria-labelledby="recomendaciones-pronostico-title">
|
||||
<h5 id="recomendaciones-pronostico-title">Recomendaciones</h5>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
</section>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card class="risk-card" appearance="outlined" aria-labelledby="riesgo-individual-title">
|
||||
<mat-card-header><h3 id="riesgo-individual-title">Riesgo de muerte</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
@if (p.idField === 'pac_id') { <app-cama-analisis-supervivencia [pacId]="p.patientId" /> }
|
||||
<section aria-labelledby="recomendaciones-riesgo-title">
|
||||
<h5 id="recomendaciones-riesgo-title">Recomendaciones</h5>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
</section>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
|
||||
@@ -1,22 +1,27 @@
|
||||
// Covers CaMa's individual record: how a follow-up row becomes its summary, what the card shows (only fields the list
|
||||
// carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus
|
||||
// carries, "No disponible" for the rest, the two analyses with their risk factors in the order Luis's specification gives), and its focus
|
||||
// and back behaviour. Fixture: fixtures/cama_seguimiento.json.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { EMPTY, of } from 'rxjs';
|
||||
import { CamaCurvasService } from './cama-curvas.service';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from '../paciente-riesgo.provider';
|
||||
import fixtureData from '../../fixtures/cama_seguimiento.json';
|
||||
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
|
||||
import { CamaPatientCard } from './cama-patient-card';
|
||||
import { CamaPatientSummary, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
|
||||
import { CamaPatientSummary, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
|
||||
|
||||
const rows = () => seguimientoTablaResponse(structuredClone(fixtureData)).items;
|
||||
const complete = () => rows().find(r => r['biopsia'] !== null && r['dias_mastografia_diagnostico'] !== null)!;
|
||||
const incomplete = () => rows().find(r => r['biopsia'] === null)!;
|
||||
const withPacId = (escenario: string | null = null) => ({ ...complete(), pac_id: '7', id_seudonimo: null, escenario_clinico: escenario });
|
||||
|
||||
describe('Ficha CaMa: resumen', () => {
|
||||
// Fails if a field of the row is mapped to another one or lost on the way to the card.
|
||||
it('reads every field the follow-up row carries', () => {
|
||||
const row = complete();
|
||||
expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({
|
||||
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
|
||||
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], clinicalScenario: null, status: row['estatus'], priority: row['prioridad'],
|
||||
birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'],
|
||||
daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'],
|
||||
});
|
||||
@@ -39,6 +44,11 @@ describe('Ficha CaMa: resumen', () => {
|
||||
describe('Ficha CaMa: componente', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<CamaPatientCard>>;
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
// The record asks for the analyses; here there is no model in production, so the card shows what the list carries.
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [
|
||||
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } },
|
||||
{ provide: CamaCurvasService, useValue: { escenarios: () => of(null), consulta: () => EMPTY } },
|
||||
{ provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(null) } }] }));
|
||||
function montar(summary: CamaPatientSummary) {
|
||||
fixture = TestBed.createComponent(CamaPatientCard);
|
||||
fixture.componentRef.setInput('summary', summary);
|
||||
@@ -71,17 +81,28 @@ describe('Ficha CaMa: componente', () => {
|
||||
expect(text).toContain('Días de mastografía a diagnóstico');
|
||||
});
|
||||
|
||||
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
|
||||
it('has placeholders, with no figures, for recurrence, survival and prognostic factors', () => {
|
||||
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
|
||||
const items = [...root().querySelectorAll('[data-pronostico]')];
|
||||
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'survival', 'factors']);
|
||||
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico']);
|
||||
for (const item of items) {
|
||||
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
|
||||
expect(item.textContent).not.toMatch(/\d/);
|
||||
}
|
||||
expect(root().textContent).toContain(RECOMMENDATIONS_UNAVAILABLE);
|
||||
// Fails if the cards or their subsections leave the order and the names of the specification: recurrence first, then death, each with
|
||||
// its risk factors, and the recommendations unchanged (not available) in both.
|
||||
it('has "Pronóstico y recomendaciones" (recurrence, risk factors, recommendations) before "Riesgo de muerte" (survival, risk factors, recommendations)', () => {
|
||||
montar(toCamaPatientSummary(withPacId('Post-tratamiento'), '2026-10-20')!);
|
||||
const card = (selector: string) => root().querySelector(selector) as HTMLElement;
|
||||
const subsections = (selector: string) => [...card(selector).querySelectorAll('h5')].map(h => h.textContent!.trim());
|
||||
|
||||
expect([...root().querySelectorAll('mat-card h3')].map(h => h.textContent!.trim()).slice(-2)).toEqual(['Pronóstico y recomendaciones', 'Riesgo de muerte']);
|
||||
expect(subsections('.prognosis-card')).toEqual(['Análisis de recurrencia', 'Factores de riesgo', 'Recomendaciones']);
|
||||
expect(subsections('.risk-card')).toEqual(['Análisis de supervivencia', 'Factores de riesgo', 'Recomendaciones']);
|
||||
expect(root().textContent!.split(RECOMMENDATIONS_UNAVAILABLE).length - 1).toBe(2);
|
||||
expect(root().textContent).not.toMatch(/Información simulada|Entorno DEV|Riesgo individual CaMa|Probabilidad de recurrencia|Factores pronóstico/);
|
||||
});
|
||||
|
||||
// Fails if a patient who has not been treated is shown the recurrence analysis (and its factors), which only makes sense after treatment.
|
||||
it('shows the recurrence analysis only to a patient after treatment', () => {
|
||||
montar(toCamaPatientSummary(withPacId('En observación'), '2026-10-20')!);
|
||||
const subsections = (selector: string) => [...(root().querySelector(selector) as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim());
|
||||
|
||||
expect(subsections('.prognosis-card')).toEqual(['Recomendaciones']);
|
||||
expect(subsections('.risk-card')).toEqual(['Análisis de supervivencia', 'Factores de riesgo', 'Recomendaciones']);
|
||||
expect(root().textContent).not.toContain('Análisis de recurrencia');
|
||||
});
|
||||
|
||||
// Fails if the record opens without moving focus to its title, which strands keyboard and screen-reader users.
|
||||
|
||||
@@ -3,17 +3,20 @@ import { downloadBlob, exportFilename } from '../../export/download-file';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
|
||||
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
|
||||
import {
|
||||
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
|
||||
CamaPatientSummary, NOT_AVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
|
||||
} from './cama-patient.models';
|
||||
|
||||
/**
|
||||
* Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
|
||||
* survival and prognostic factors are placeholders until a validated model supplies them.
|
||||
* Individual record of a CaMa follow-up patient. It shows what the follow-up list carries, the recurrence analysis with its risk
|
||||
* factors ("Pronóstico y recomendaciones") and the survival analysis with its risk factors ("Riesgo de muerte"), one clinical
|
||||
* scenario at a time (the recurrence analysis only for patients after treatment); the recommendations are not available yet.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-patient-card',
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule],
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia],
|
||||
templateUrl: './cama-patient-card.html',
|
||||
styleUrl: './cama-patient-card.scss',
|
||||
})
|
||||
@@ -21,8 +24,8 @@ export class CamaPatientCard implements AfterViewInit {
|
||||
readonly summary = input.required<CamaPatientSummary>();
|
||||
readonly back = output<void>();
|
||||
readonly notAvailable = NOT_AVAILABLE;
|
||||
readonly placeholders = PROGNOSIS_PLACEHOLDERS;
|
||||
readonly prognosisUnavailable = PROGNOSIS_UNAVAILABLE;
|
||||
/** The recurrence analysis is for patients who have been treated: it is shown only in this clinical scenario. */
|
||||
readonly postTreatment = 'Post-tratamiento';
|
||||
readonly recommendationsUnavailable = RECOMMENDATIONS_UNAVAILABLE;
|
||||
private readonly title = viewChild<ElementRef<HTMLElement>>('title');
|
||||
readonly generating = signal(false);
|
||||
|
||||
@@ -21,6 +21,7 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo
|
||||
...section('Resumen', [
|
||||
[patient.idLabel, patient.patientId],
|
||||
['Grupo de edad', patient.ageGroup],
|
||||
['Escenario clínico', patient.clinicalScenario],
|
||||
['Estatus de seguimiento', patient.status],
|
||||
['Prioridad', patient.priority],
|
||||
['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis],
|
||||
|
||||
@@ -14,6 +14,8 @@ export interface CamaPatientSummary {
|
||||
idLabel: string;
|
||||
cutoff: string;
|
||||
ageGroup: string | null;
|
||||
/** «Post-tratamiento» or «En observación» at the cut-off. */
|
||||
clinicalScenario: string | null;
|
||||
status: string | null;
|
||||
priority: string | null;
|
||||
birads: string | null;
|
||||
@@ -25,7 +27,8 @@ export interface CamaPatientSummary {
|
||||
daysMammographyToDiagnosis: number | null;
|
||||
}
|
||||
|
||||
/** Placeholders for results that exist only once a validated model and its clinical definition do. */
|
||||
/** Placeholders for results that exist only once a validated model and its clinical definition do: what the exported PDF of the
|
||||
* record says about them (on screen, the analyses and their risk factors are drawn from the models). */
|
||||
export const PROGNOSIS_PLACEHOLDERS = [
|
||||
{ key: 'recurrence', label: 'Probabilidad de recurrencia' },
|
||||
{ key: 'survival', label: 'Supervivencia' },
|
||||
@@ -51,6 +54,7 @@ export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas:
|
||||
idLabel: ETIQUETA_IDENTIDAD[identity.campo],
|
||||
cutoff,
|
||||
ageGroup: text(row['grupo_edad']),
|
||||
clinicalScenario: text(row['escenario_clinico']),
|
||||
status: text(row['estatus']),
|
||||
priority: text(row['prioridad']),
|
||||
birads: text(row['birads']),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user