Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ab10cc9025 | |||
| 1fef7812b4 | |||
| 6465165e34 | |||
| a26df55214 | |||
| 72e5f9bf93 | |||
| 08f1d812ac | |||
| ce207a72a5 | |||
| 5094880622 | |||
| 093ceffa36 | |||
| 6a7c1d0cbd | |||
| fb5a4ed5cc | |||
| e8ce7a487b | |||
| a3a552ad0e | |||
| fb54cfb188 | |||
| 7adceb86bf | |||
| 4e9b25bd8f | |||
| a7b5f4c50b | |||
| 4d159ae0d0 | |||
| 4fba4fa861 | |||
| db4d743413 | |||
| d6c52c8536 | |||
| 1969ffdb5f | |||
| 699d4b13e1 | |||
| c5cbaaab13 | |||
| cc802cbb57 | |||
| e7a6398168 | |||
| 62027f2216 | |||
| 88dc7537c2 | |||
| 0cb9395cd6 | |||
| e74e3d8fd4 | |||
| 0fc80bd29a | |||
| dae8bc517e | |||
| 68e2930e65 | |||
| bb957ec6a4 | |||
| 02e28e624b | |||
| 08161db1c4 | |||
| fa029d69b8 | |||
| 67ae7f482f | |||
| 304c563845 | |||
| efe4404c4e | |||
| 7d180417d8 | |||
| 00f773dd75 | |||
| 3bb1c8dd84 | |||
| ef4f606648 | |||
| 54b3e50ca5 | |||
| 680cc0adc6 | |||
| b53322ed72 | |||
| c32d2b6012 | |||
| 7aa3d2c6e6 | |||
| c2c6d9ef47 | |||
| d4d3ea3837 | |||
| 04795a09cc |
@@ -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,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,11 +41,15 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"titulo": "Tasa de confirmación histopatológica",
|
||||
"version": "0.1.2",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"unidades_periodo": {
|
||||
"2021-S1": 0,
|
||||
"2025-S2": 1
|
||||
},
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
@@ -80,51 +84,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 +106,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 +138,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 +206,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 +223,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 +255,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 +323,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 +343,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 +375,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -421,7 +388,7 @@
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"grupos": {
|
||||
"principal": "principal"
|
||||
"total": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
@@ -447,7 +414,7 @@
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": null,
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -460,7 +427,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": null,
|
||||
"suprimido": 0,
|
||||
"numerador": 1,
|
||||
@@ -474,7 +441,7 @@
|
||||
]
|
||||
},
|
||||
"grupo_edad": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -500,7 +467,7 @@
|
||||
"<25": "<25"
|
||||
},
|
||||
"grupos": {
|
||||
"principal": "principal"
|
||||
"total": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
@@ -526,7 +493,7 @@
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": "25-34",
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -539,7 +506,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": "35-44",
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -552,7 +519,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": "45-54",
|
||||
"suprimido": 0,
|
||||
"numerador": 1,
|
||||
@@ -565,7 +532,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": "55-64",
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -578,7 +545,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": "<25",
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -592,7 +559,7 @@
|
||||
]
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"id": "CACU_EU13",
|
||||
"id": "cacu_eu13",
|
||||
"titulo": "Tasa de detección histopatológica",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -610,7 +577,7 @@
|
||||
"PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA"
|
||||
},
|
||||
"grupos": {
|
||||
"principal": "principal"
|
||||
"total": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
@@ -636,7 +603,7 @@
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": "PRE_COLPOSCOPIA",
|
||||
"suprimido": 0,
|
||||
"numerador": 1,
|
||||
@@ -652,9 +619,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 +639,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,11 +661,15 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "CACU_EU7",
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"unidades_periodo": {
|
||||
"2021-S1": 0,
|
||||
"2025-S2": 89
|
||||
},
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
@@ -733,91 +704,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 +728,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,11 +750,15 @@
|
||||
},
|
||||
"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",
|
||||
"unidad": "paciente",
|
||||
"unidades_periodo": {
|
||||
"2021-S1": 0,
|
||||
"2025-S2": 0
|
||||
},
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
@@ -894,9 +795,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 +812,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 +844,7 @@
|
||||
},
|
||||
"datos": {
|
||||
"total": {
|
||||
"id": "IND1",
|
||||
"id": "ind1",
|
||||
"titulo": "Pacientes con citología anómala",
|
||||
"version": "0.3.2",
|
||||
"contrato": "C1",
|
||||
@@ -956,7 +857,7 @@
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"grupos": {
|
||||
"principal": "principal"
|
||||
"total": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
@@ -982,7 +883,7 @@
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": null,
|
||||
"suprimido": 0,
|
||||
"numerador": 0,
|
||||
@@ -995,7 +896,7 @@
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "principal",
|
||||
"grupo": "total",
|
||||
"estrato": null,
|
||||
"suprimido": 0,
|
||||
"numerador": 19,
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -37,10 +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[data-domain='cama']) .value { font-size: 1.65rem; }
|
||||
: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 {
|
||||
@@ -48,7 +47,7 @@ export class IndicadorKpiCard {
|
||||
@Input() value?: string | number | null;
|
||||
@Input() unit?: string;
|
||||
@Input() temporalReference?: string;
|
||||
// CaMa's opportunity strip shares one period, shown by the parent instead of on every card.
|
||||
// The opportunity strip shares one period, shown by the parent instead of on every card.
|
||||
@Input() showPeriod = true;
|
||||
@Input() loading = false;
|
||||
@Input() notes: string[] = [];
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -192,12 +192,9 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||
]));
|
||||
if (domain === 'cama') {
|
||||
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
|
||||
} else {
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([expect.stringContaining('2025-S1')]));
|
||||
}
|
||||
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
|
||||
expect(cards.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,15 +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'"
|
||||
[showPeriod]="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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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';
|
||||
@@ -113,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 } };
|
||||
|
||||
@@ -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,9 @@ 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';
|
||||
|
||||
const esMedidaCacu = (measureId: string | undefined): boolean => measureId !== undefined && Object.hasOwn(CACU_MEASURE_IDS, measureId);
|
||||
|
||||
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
|
||||
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
|
||||
@@ -40,8 +43,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 +59,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,13 +207,45 @@ 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);
|
||||
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id), cacu = esMedidaCacu(measure.id);
|
||||
// What each period's report says its units are (CaCu's compositions): the history checks its categories against them.
|
||||
const unidadesPeriodo: Record<string, number> = {};
|
||||
const declaradas = categorias(measure);
|
||||
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
|
||||
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
|
||||
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];
|
||||
@@ -209,10 +255,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
: { ...declaradas,
|
||||
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
|
||||
const totales: Record<string, unknown>[] = [];
|
||||
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
|
||||
// The page names the primary group of a proportion `total`; the WebApi names it `principal`.
|
||||
const nombre = (codigo: string | undefined) => {
|
||||
const grupo = codigo ?? 'TOTAL';
|
||||
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
|
||||
return kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
|
||||
};
|
||||
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
|
||||
const id = nombre(code(g.code));
|
||||
@@ -241,6 +287,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]));
|
||||
@@ -249,6 +310,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) {
|
||||
throw new Error('Los conteos por categoría no suman las unidades del periodo');
|
||||
}
|
||||
if (cacu && units !== null) unidadesPeriodo[periodo] = units;
|
||||
Object.keys(cats).forEach((categoria, orden) =>
|
||||
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
|
||||
continue;
|
||||
@@ -280,10 +342,11 @@ 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 } : {}),
|
||||
...(cacu && kind === 'C2' ? { unidades_periodo: unidadesPeriodo } : {}),
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// What this module covers: how CaCu's FHIR measures, as the WebApi publishes them, reach the history figures: the
|
||||
// primary group of a proportion (`principal`), the page ids, the unit labels, the reconciliation of a composition and
|
||||
// the periods without units. The Measures are the catalog fixture (`fixtures/cacu_fhir_measures.json`); the reports
|
||||
// are synthetic and carry what the WebApi serialises, `group.code` included: the older bundle fixtures name the group
|
||||
// with `group.id` only, which hides the `principal` / `TOTAL` mismatch this spec pins down.
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { Measure, Report, datosDeReportes, indicadorDeMeasure } from './indicadores-fhir';
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
import { disponibilidadDe, HISTORICO_CACU, historicoDeDominio } from './indicadores-historico-config';
|
||||
import { historicoFigura, HistoricoOpciones } from './indicadores-historico-figures';
|
||||
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||
import camaMeasuresData from './fixtures/cama_fhir_measures.json';
|
||||
|
||||
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const medida = (id: string) => publicadas.find(m => m.id === id)!;
|
||||
const cod = (c: string) => ({ coding: [{ code: c }] });
|
||||
const pob = (c: string, count: number) => ({ code: cod(c), count });
|
||||
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
|
||||
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
|
||||
const SEMESTRE = { start: '2025-01-01', end: '2025-06-30' };
|
||||
const SEMESTRE_2 = { start: '2025-07-01', end: '2025-12-31' };
|
||||
|
||||
// A proportion as the WebApi serialises it: group `principal`, a score only when the denominator is positive.
|
||||
const c1 = (period: { start: string; end: string }, numerador: number, denominador: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('principal'), population: [pob('initial-population', denominador), pob('denominator', denominador), pob('numerator', numerador)],
|
||||
...(denominador > 0 ? { measureScore: { value: numerador / denominador } } : {}) }],
|
||||
} as unknown as Report);
|
||||
// A composition: the categories as the first stratifier, the units as the initial population.
|
||||
const c2 = (m: Measure, period: { start: string; end: string }, conteos: Record<string, number>, unidades?: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('TOTAL'), population: [pob('initial-population', unidades ?? Object.values(conteos).reduce((a, b) => a + b, 0))],
|
||||
stratifier: [{ code: [cod('categoria')], stratum: Object.entries(conteos).map(([c, n]) => ({ value: cod(c), population: [pob('initial-population', n)] })) }] }],
|
||||
} as unknown as Report);
|
||||
// A duration: the median and the quartiles as extensions of the score.
|
||||
const c3r = (period: { start: string; end: string }, n: number, mediana?: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('TOTAL'), population: [pob('initial-population', n + 1), pob('measure-observation', n), pob('measure-population-exclusion', 1)],
|
||||
...(mediana === undefined ? {} : { measureScore: { value: mediana, unit: 'd', extension: [
|
||||
{ url: `${STRUCTURE}/q1`, valueDecimal: mediana - 2 }, { url: `${STRUCTURE}/q3`, valueDecimal: mediana + 3 }] } }) }],
|
||||
} as unknown as Report);
|
||||
const traza = (datos: ReturnType<typeof datosDeReportes>, i: number, opciones?: HistoricoOpciones) =>
|
||||
historicoFigura(datos, 'claro', opciones).figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
|
||||
const CACU: HistoricoOpciones = { unidades: historicoDeDominio('cacu')!.unidades, conciliarC2: true, c2SinPoblacionSinDato: true };
|
||||
|
||||
describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
|
||||
it('EU13 con el grupo `principal` que publica el WebApi: el cero es un valor y el panel no queda vacío', () => {
|
||||
// Pins down: the proportion's group reaches the history as the total. Fails if `principal` stays as it is and the
|
||||
// selector of the total drops every row, which left EU13's panel empty.
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 4, valor: 0 });
|
||||
expect(Object.keys(datos['grupos'] as object)).toEqual(['total']);
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect(traza(datos, 1).y).toEqual([0]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
});
|
||||
it('IND1 se publica como `ind1` y conserva su valor', () => {
|
||||
const datos = datosDeReportes(medida('IND1'), [c1(SEMESTRE, 1, 4), c1(SEMESTRE_2, 1, 4)], 'semestre');
|
||||
expect(datos.id).toBe('ind1');
|
||||
expect(traza(datos, 1).y).toEqual([25, 25]);
|
||||
});
|
||||
it('un denominador cero es «sin dato», no un cero', () => {
|
||||
// The WebApi omits the score when there is no denominator: the period is listed as missing, not drawn at zero.
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 0), c1(SEMESTRE_2, 1, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ valor: null, denominador: 0 });
|
||||
expect(traza(datos, 1).y).toEqual([null, 25]);
|
||||
expect(historicoFigura(datos, 'claro').sinDato).toEqual(['2025 S1']);
|
||||
});
|
||||
it('sin intervalo publicado la banda queda vacía: el cliente no lo calcula ni lo inventa', () => {
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 1, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ ic_bajo: null, ic_alto: null });
|
||||
expect(traza(datos, 0)).toMatchObject({ name: 'Intervalo de confianza', x: [], y: [] });
|
||||
});
|
||||
it('en CaMa el grupo principal sigue siendo `total`', () => {
|
||||
// Regression: the normalisation CaCu shares with CaMa keeps CaMa's own result.
|
||||
const cama = (resources(camaMeasuresData as unknown as Bundle, 'Measure') as Measure[]).find(m => m.id === 'CAMA-CONFIRMACION-BIRADS45')!;
|
||||
const datos = datosDeReportes(cama, [c1(SEMESTRE, 2, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ grupo: 'total', valor: 50 });
|
||||
});
|
||||
it('los paneles activos usan ids de página y contratos que el catálogo publica', () => {
|
||||
// Pins down the compatibility of the identifiers: every active panel is a measure `dev` publishes, under the id
|
||||
// the page gives it, and with the contract the panel expects.
|
||||
const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)]));
|
||||
const activos = HISTORICO_CACU.filter(p => disponibilidadDe(p) === 'activo');
|
||||
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']);
|
||||
for (const panel of activos) {
|
||||
expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id);
|
||||
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
|
||||
}
|
||||
});
|
||||
it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => {
|
||||
const reservados = HISTORICO_CACU.filter(p => disponibilidadDe(p) !== 'activo');
|
||||
expect(reservados.map(p => [p.id, p.fhir, disponibilidadDe(p)])).toEqual([
|
||||
['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'integracion_pendiente'],
|
||||
['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'integracion_pendiente'],
|
||||
['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'pendiente_validacion'],
|
||||
]);
|
||||
// The risk bands are in the catalog and stay reserved.
|
||||
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Histórico de CaCu: composiciones (C2)', () => {
|
||||
const eu7 = () => medida('CACU-EU7');
|
||||
const conteos = (extra: Record<string, number> = {}) => ({ ...Object.fromEntries(declaradas(eu7()).map((c, i) => [c, [8, 3, 2, 1, 1, 0, 1][i]])), ...extra });
|
||||
|
||||
it('el reporte de EU7 conserva las unidades de cada periodo y la conciliación pasa', () => {
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos())], 'semestre');
|
||||
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 16 });
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(figura.figure.data.map(t => (t['y'] as number[])[0])).toEqual([8, 3, 2, 1, 1, 0, 1]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
});
|
||||
it('una categoría que el Measure no declara rompe la conciliación del Histórico y no cambia el Resumen', () => {
|
||||
// Pins down: a category the report counts but the Measure does not declare (the glandular results are still an open
|
||||
// decision) is no longer a shorter bar. The adapter itself reads the report as before.
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos({ AGC: 2 }))], 'semestre');
|
||||
expect(datos.filas.map(f => f['categoria'])).not.toContain('AGC');
|
||||
expect(() => historicoFigura(datos, 'claro', CACU)).toThrow('Los conteos por categoría no suman las unidades del periodo');
|
||||
expect(() => historicoFigura(datos, 'claro')).not.toThrow();
|
||||
});
|
||||
it('un periodo sin pacientes es «sin dato» en CaCu y no barras en cero', () => {
|
||||
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0), c2(eu7(), SEMESTRE_2, conteos())], 'semestre');
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(figura.sinDato).toEqual(['2025 S1']);
|
||||
expect(figura.figure.data.every(t => (t['y'] as (number | null)[])[0] === null)).toBe(true);
|
||||
expect((figura.figure.data[0]['y'] as number[])[1]).toBe(8);
|
||||
});
|
||||
it('sin la opción de CaCu un periodo sin unidades se dibuja como antes (CaMa no cambia)', () => {
|
||||
// Regression: the rule is the domain's, not the figure module's.
|
||||
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0)], 'semestre');
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
expect(figura.figure.data.every(t => (t['y'] as number[])[0] === 0)).toBe(true);
|
||||
});
|
||||
it('la confirmación por citología declara sus categorías y se concilia igual', () => {
|
||||
const m = medida('CACU-CONFIRMACION-CITOLOGIA');
|
||||
const datos = datosDeReportes(m, [c2(m, SEMESTRE, Object.fromEntries(declaradas(m).map((c, i) => [c, i])))], 'semestre');
|
||||
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 21 });
|
||||
expect(() => historicoFigura(datos, 'claro', CACU)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Histórico de CaCu: tiempos (C3r) y etiquetas de unidad', () => {
|
||||
const m = () => medida('CACU-EU-TIEMPO-REPORTE');
|
||||
it('la mediana y los cuartiles hablan de citologías en CaCu', () => {
|
||||
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12), c3r(SEMESTRE_2, 0)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ mediana: 12, q1: 10, q3: 15, n: 6, unidad: 'dias' });
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(traza(datos, 1, CACU)['text'][0]).toBe('Mediana: 12 días<br>Q1 a Q3: 10 a 15 días<br>6 citologías');
|
||||
expect(figura.comoLeer).toContain('las citologías');
|
||||
expect(figura.comoLeer).not.toContain('mastograf');
|
||||
// A period without observations is missing, not zero.
|
||||
expect(traza(datos, 1, CACU)['y']).toEqual([12, null]);
|
||||
expect(figura.sinDato).toEqual(['2025 S2']);
|
||||
});
|
||||
it('sin la configuración de CaCu el texto de los exámenes sigue siendo el de CaMa', () => {
|
||||
// Regression: `examen` keeps reading «mastografías» wherever the domain does not name it otherwise.
|
||||
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12)], 'semestre');
|
||||
expect(traza(datos, 1)['text'][0]).toContain('6 mastografías');
|
||||
expect(historicoFigura(datos, 'claro').comoLeer).toContain('las mastografías');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,204 @@
|
||||
// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing
|
||||
// until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and
|
||||
// the notice. Responses are synthetic, shaped like /cacu/indicadores/<id>/periodos and /datos.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { AVISO_CACU, HISTORICO_CACU } from './indicadores-historico-config';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: { data: { name?: string; y?: (number | null)[]; text?: string[] }[] }; label?: string; }
|
||||
|
||||
const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStart(2, '0')}`);
|
||||
const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1'];
|
||||
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
|
||||
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico'];
|
||||
const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
||||
// Every measure the catalog could publish, reserved ones included: publishing them must not activate them.
|
||||
const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item);
|
||||
|
||||
function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) {
|
||||
const contrato = opciones.contrato ?? CONTRATOS[id];
|
||||
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
|
||||
const vacio = (p: string) => p === opciones.sinPoblacion;
|
||||
const filas = contrato === 'C2'
|
||||
? periodos.flatMap(p => [fila(p, { categoria: 'NORMAL', n: vacio(p) ? 0 : 7, orden: 0 }), fila(p, { categoria: 'ASC-US', n: vacio(p) ? 0 : 5, orden: 1 })])
|
||||
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 0, numerador: 0, denominador: 10, ic_bajo: null, ic_alto: null }))
|
||||
: periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' }));
|
||||
return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' ? 'paciente' : 'examen', filas,
|
||||
categorias: { NORMAL: { etiqueta: 'Normal', color: '#9DBFE3' }, 'ASC-US': { etiqueta: 'ASC-US', color: '#2F6DB3' } },
|
||||
...(contrato === 'C2' ? { unidades_periodo: Object.fromEntries(periodos.map(p => [p, vacio(p) ? 0 : 12])) } : {}) };
|
||||
}
|
||||
|
||||
describe('Histórico de CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
|
||||
const abrirDialogo = vi.fn();
|
||||
function montar(catalog: Indicador[] = CATALOGO, active = false) {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }] });
|
||||
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog);
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
|
||||
// Answers in waves, because the shared request queue runs four at a time. `pedidos` keeps what each data request asked for.
|
||||
const pedidos: { id: string; periodos: string[] }[] = [];
|
||||
function responder(opciones: { fallo?: (r: TestRequest) => boolean; datos?: (id: string) => { contrato?: string; sinPoblacion?: string } } = {}) {
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
const url = r.request.url, id = url.split('/').at(-2)!;
|
||||
if (opciones.fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; }
|
||||
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||
else {
|
||||
const periodos = r.request.params.get('periodos')!.split(',');
|
||||
pedidos.push({ id, periodos });
|
||||
r.flush(datos(id, periodos[0].includes('S') ? 'semestre' : 'mes', periodos, opciones.datos?.(id)));
|
||||
}
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
}
|
||||
beforeEach(() => { pedidos.length = 0; });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
|
||||
const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!;
|
||||
const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo;
|
||||
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!;
|
||||
|
||||
it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => {
|
||||
// Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it.
|
||||
montar();
|
||||
http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
const vistos = new Set<string>();
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
vistos.add(r.request.url.split('/').at(-2)!);
|
||||
const id = r.request.url.split('/').at(-2)!;
|
||||
if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: MESES.map(periodo => ({ periodo, tipo: 'mes' })) });
|
||||
else r.flush(datos(id, 'mes', r.request.params.get('periodos')!.split(',')));
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
|
||||
for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false);
|
||||
});
|
||||
it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(graficas()).toHaveLength(6);
|
||||
const reservados = paneles().slice(6);
|
||||
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
|
||||
expect(reservados.map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']);
|
||||
expect(reservados[0].textContent).toContain('Integración pendiente');
|
||||
expect(reservados[2].textContent).toContain('Pendiente de validación');
|
||||
// Title and description, no figures, no invented numbers.
|
||||
expect(reservados[2].textContent).toContain('banda de riesgo de CIN2+');
|
||||
expect(reservados.every(p => !/\d+ de \d+|0 %|rango/i.test(p.querySelector('p.rango')?.textContent ?? ''))).toBe(true);
|
||||
});
|
||||
it('un panel reservado sigue reservado aunque el catálogo no lo publique ni lo publique', () => {
|
||||
// Pins down: the state of a reserved panel comes from the config alone.
|
||||
for (const catalogo of [ACTIVOS.map(item), CATALOGO]) {
|
||||
montar(catalogo, true); responder();
|
||||
expect(paneles().slice(6).map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']);
|
||||
fixture.destroy(); TestBed.resetTestingModule();
|
||||
}
|
||||
});
|
||||
it('el aviso de validación clínica y supresión se ve siempre', () => {
|
||||
montar();
|
||||
const aviso = root().querySelector('[data-aviso="historico"]')!;
|
||||
expect(aviso.textContent).toBe(AVISO_CACU);
|
||||
expect(aviso.textContent).toContain('validación clínica');
|
||||
expect(aviso.textContent).toContain('supresión');
|
||||
});
|
||||
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
|
||||
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||
});
|
||||
it('elegir «Todos» pide solo los periodos que faltan y los suma', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
// Going back to five is local: nothing is asked again.
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toEqual([]);
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||
});
|
||||
it('cambiar a Semestral pide los últimos cinco semestres una vez y volver a Mensual no repite', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toEqual([]);
|
||||
});
|
||||
it('una medida activa que el catálogo no publica es «Integración pendiente» y no se consulta', () => {
|
||||
montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder();
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.textContent).toContain('Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.');
|
||||
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
});
|
||||
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
|
||||
montar(CATALOGO, true);
|
||||
responder({ fallo: r => r.request.url.includes('/cacu_eu13/') && r.request.url.endsWith('/datos') });
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(panel.textContent).not.toContain('private');
|
||||
expect(graficas()).toHaveLength(5);
|
||||
const reintentar = panel.querySelector('button') as HTMLButtonElement;
|
||||
reintentar.click(); fixture.detectChanges(); responder();
|
||||
expect(graficas()).toHaveLength(6);
|
||||
});
|
||||
it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => {
|
||||
// Pins down the expected contract: the panel does not draw a C1 where it declared a composition.
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} });
|
||||
const panel = panelDe(tituloDe('cacu_eu7'));
|
||||
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1');
|
||||
expect(graficas()).toHaveLength(5);
|
||||
});
|
||||
it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => {
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} });
|
||||
expect(graficaDe(tituloDe('cacu_eu13')).figure!.data[1].y).toEqual([0, 0, 0, 0, 0]);
|
||||
expect(panelDe(tituloDe('cacu_eu13')).querySelector('[data-plegable="sin-dato"]')).toBeNull();
|
||||
const eu7 = panelDe(tituloDe('cacu_eu7'));
|
||||
expect(eu7.querySelector('[data-plegable="sin-dato"]')?.textContent).toContain('Periodos sin dato (1)');
|
||||
expect(eu7.textContent).toContain('oct 2025');
|
||||
expect(graficaDe(tituloDe('cacu_eu7')).figure!.data[0].y).toEqual([7, 7, null, 7, 7]);
|
||||
});
|
||||
it('los tiempos hablan de citologías', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
for (const id of ['cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']) {
|
||||
expect(graficaDe(tituloDe(id)).figure!.data[1].text![0]).toContain('20 citologías');
|
||||
expect(panelDe(tituloDe(id)).textContent).toContain('las citologías');
|
||||
expect(panelDe(tituloDe(id)).textContent).not.toContain('mastograf');
|
||||
}
|
||||
});
|
||||
it('sin ninguna medida activa en el catálogo no hay paneles ni consultas', () => {
|
||||
montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true);
|
||||
expect(paneles()).toEqual([]);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
|
||||
// What each domain's history tab draws, declared as data: the panels and their order, the contract each one is
|
||||
// expected to carry, the labels of its unit and what the tab may ask for. A domain without an entry here (TEA) draws
|
||||
// its whole catalog.
|
||||
|
||||
export type ContratoHistorico = 'C1' | 'C2' | 'C3r';
|
||||
// The mark each contract gets in `historicoFigura`: counts add up to a total, percentages and medians do not.
|
||||
export type GraficaHistorico = 'barras_apiladas' | 'linea_porcentaje' | 'linea_mediana';
|
||||
// `activo`: the tab asks for its data when the catalog publishes it. The other two are reserved: the panel shows its
|
||||
// title, its description and the reason, and never asks for a report, whatever the catalog publishes. Activating a
|
||||
// reserved panel is an explicit edit of this table, once its contract, its tests and its approval are in place.
|
||||
export type DisponibilidadPanel = 'activo' | 'integracion_pendiente' | 'pendiente_validacion';
|
||||
|
||||
export interface PanelHistorico {
|
||||
// The page's id of the measure (what `indicadorId` gives).
|
||||
id: string;
|
||||
titulo: string;
|
||||
contrato?: ContratoHistorico;
|
||||
grafica?: GraficaHistorico;
|
||||
estado?: DisponibilidadPanel;
|
||||
descripcion?: string;
|
||||
// The FHIR ids the measure is expected to have, for the reserved panels whose measure is not in the catalog yet.
|
||||
fhir?: readonly string[];
|
||||
}
|
||||
export interface UnidadHistorico { plural: string; eje: string }
|
||||
export interface HistoricoDominio {
|
||||
paneles: readonly PanelHistorico[];
|
||||
// The unit a measure publishes (`examen`) named as the domain calls it; overrides the figure module's default.
|
||||
unidades?: Readonly<Record<string, UnidadHistorico>>;
|
||||
// How many of the latest periods are requested when the tab opens. Without it, every period is requested.
|
||||
periodosIniciales?: number;
|
||||
// A composition (C2) whose categories do not add up to the report's units is an error, not a shorter bar.
|
||||
conciliarC2?: boolean;
|
||||
// A composition period with no units is «sin dato», not a bar of zeros.
|
||||
c2SinPoblacionSinDato?: boolean;
|
||||
// Shown above the panels.
|
||||
aviso?: string;
|
||||
}
|
||||
|
||||
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
|
||||
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
|
||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
|
||||
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
|
||||
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||
];
|
||||
|
||||
// Whether CaCu offers the history tab. The panels carry no clinical validation and no suppression policy yet (see
|
||||
// `AVISO_CACU`): while they wait, this is the switch that takes the tab out.
|
||||
export const HISTORICO_CACU_HABILITADO = true;
|
||||
|
||||
export const AVISO_CACU = 'Los resultados de CaCu están sujetos a validación clínica y a la política institucional de supresión estadística. '
|
||||
+ 'Los conjuntos clínicos, los horizontes y los umbrales son provisionales. No los use para decidir.';
|
||||
|
||||
// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved.
|
||||
export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', estado: 'integracion_pendiente',
|
||||
fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'],
|
||||
descripcion: 'Días de la toma de la citología al primer tratamiento. La medida no está en el catálogo de dev.' },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', estado: 'integracion_pendiente',
|
||||
fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'],
|
||||
descripcion: 'Días del diagnóstico que resuelve la citología al primer tratamiento. La medida no está en el catálogo de dev.' },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', estado: 'pendiente_validacion',
|
||||
fhir: ['CACU-RIESGO-BANDA'],
|
||||
descripcion: 'Pacientes de la cohorte de vigilancia por banda de riesgo de CIN2+. El horizonte, el modelo y los cortes no están aprobados.' },
|
||||
];
|
||||
|
||||
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||
cama: { paneles: HISTORICO_CAMA },
|
||||
cacu: {
|
||||
paneles: HISTORICO_CACU,
|
||||
// `examen` is the citology here.
|
||||
unidades: { examen: { plural: 'citologías', eje: 'Citologías' } },
|
||||
periodosIniciales: 5,
|
||||
conciliarC2: true,
|
||||
c2SinPoblacionSinDato: true,
|
||||
aviso: AVISO_CACU,
|
||||
},
|
||||
};
|
||||
|
||||
// The domain's declared history, if it has one and the tab is on.
|
||||
export function historicoDeDominio(dominio: Dominio): HistoricoDominio | undefined {
|
||||
return dominio === 'cacu' && !HISTORICO_CACU_HABILITADO ? undefined : HISTORICOS[dominio];
|
||||
}
|
||||
export const disponibilidadDe = (panel: PanelHistorico): DisponibilidadPanel => panel.estado ?? 'activo';
|
||||
@@ -31,12 +31,19 @@ export interface HistoricoOpciones {
|
||||
// Same vertical scale across small charts, so their heights compare.
|
||||
yMax?: number;
|
||||
pequena?: boolean;
|
||||
// The unit a measure publishes, named as the domain calls it; falls back to the defaults below (CaMa's).
|
||||
unidades?: Readonly<Record<string, { plural: string; eje: string }>>;
|
||||
// A composition whose categories do not add up to the report's units (`unidades_periodo`) is an error.
|
||||
conciliarC2?: boolean;
|
||||
// A composition period with no units is «sin dato», not a bar of zeros.
|
||||
c2SinPoblacionSinDato?: boolean;
|
||||
}
|
||||
// What the unit a measure publishes is called in the charts' texts.
|
||||
const UNIDADES: Readonly<Record<string, { plural: string; eje: string }>> = {
|
||||
paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' },
|
||||
};
|
||||
const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' };
|
||||
const unidadDe = (data: IndicadorDatos, propias?: HistoricoOpciones['unidades']) =>
|
||||
propias?.[String(data['unidad'])] ?? UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' };
|
||||
function validar(data: IndicadorDatos) {
|
||||
for (const row of data.filas) {
|
||||
if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida');
|
||||
@@ -115,7 +122,7 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
};
|
||||
}
|
||||
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
|
||||
const periodos = validar(data), unidad = unidadDe(data);
|
||||
const periodos = validar(data), unidad = unidadDe(data, opciones.unidades);
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
|
||||
const trazo = colorDeLinea(data.id, tema);
|
||||
return {
|
||||
@@ -137,8 +144,8 @@ const CONTEOS: Readonly<Record<string, { eje: string; comoLeer: string }>> = {
|
||||
M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' },
|
||||
M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' },
|
||||
};
|
||||
function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data);
|
||||
function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): Trazo {
|
||||
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data, opciones.unidades);
|
||||
const celdas = new Map<string, Record<string, unknown>>(), categorias = new Map<string, number>();
|
||||
for (const row of data.filas) {
|
||||
const id = row['categoria'], key = JSON.stringify([id, row['periodo']]);
|
||||
@@ -151,7 +158,22 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const orden = [...[...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id), ...Object.keys(catalogo).filter(id => !categorias.has(id))];
|
||||
const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo])));
|
||||
const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1));
|
||||
const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])));
|
||||
// The units each report says it has, when the adapter kept them: what the categories of a period must add up to.
|
||||
const unidades = record(data['unidades_periodo']) ? data['unidades_periodo'] : undefined;
|
||||
const suma = (p: string) => {
|
||||
const valores = estadoDe(p).map(row => row?.['n']);
|
||||
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
|
||||
};
|
||||
if (opciones.conciliarC2 && unidades) {
|
||||
for (const p of periodos) {
|
||||
const total = unidades[p], contado = suma(p);
|
||||
if (numero(total) && contado !== null && contado !== total) throw new Error('Los conteos por categoría no suman las unidades del periodo');
|
||||
}
|
||||
}
|
||||
// A period with no units is not a period of zeros: it is drawn as a gap and listed.
|
||||
const sinPoblacion = new Set(opciones.c2SinPoblacionSinDato
|
||||
? periodos.filter(p => !suprimidos.includes(p) && (numero(unidades?.[p]) ? unidades![p] === 0 : suma(p) === 0)) : []);
|
||||
const sinDato = periodos.filter(p => sinPoblacion.has(p) || (!suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))));
|
||||
const curso = { frio: 0, calido: 0, neutro: 0 };
|
||||
return {
|
||||
figure: { data: orden.map((id, i) => {
|
||||
@@ -159,7 +181,7 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined;
|
||||
const tono = tonoDe(typeof meta['grupo'] === 'string' ? meta['grupo'] : id);
|
||||
const slot = tono === 'neutro' ? i : curso[tono]++;
|
||||
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
|
||||
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) && !sinPoblacion.has(p) ? n : null; });
|
||||
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
|
||||
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
|
||||
@@ -176,7 +198,7 @@ function etiquetaCategoria(meta: Record<string, unknown>, id: string) {
|
||||
// The plot follows from what the contract's numbers mean: counts add up to a total, percentages
|
||||
// and medians do not, so those two are never stacked.
|
||||
export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura {
|
||||
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
|
||||
const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? porcentaje(data, tema)
|
||||
: data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined;
|
||||
if (!figura) throw new Error('Representación no soportada');
|
||||
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
|
||||
|
||||
@@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => {
|
||||
|
||||
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
fixture.componentInstance.changeSection('analisis');
|
||||
fixture.detectChanges();
|
||||
@@ -38,17 +38,18 @@ describe('Pestaña Histórico', () => {
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
http.expectNone(request => request.url.startsWith('/cama/analisis'));
|
||||
});
|
||||
it('cacu no tiene la pestaña Histórico', () => {
|
||||
// Fails if the history tab of TEA or CaMa leaks into CaCu.
|
||||
it('cacu tiene Histórico y no Análisis epidemiológico', () => {
|
||||
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
|
||||
abrir('cama', []);
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).toBeNull();
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Resumen se oculta', () => {
|
||||
|
||||
@@ -14,27 +14,25 @@ import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadore
|
||||
import { IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
import { disponibilidadDe, DisponibilidadPanel, HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
|
||||
|
||||
export { HISTORICO_CAMA };
|
||||
|
||||
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
|
||||
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
||||
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato'] }; rango?: string } & (
|
||||
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
|
||||
// `disponibles` is every period the indicator publishes for the interval, kept when only the latest were requested.
|
||||
type Carga = { estado: 'listo'; datos: IndicadorDatos; disponibles?: string[] } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
||||
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato']; descripcion?: string }; rango?: string } & (
|
||||
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'reservado'; disponibilidad: Exclude<DisponibilidadPanel, 'activo'> } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
|
||||
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
const CASOS = 'M28_casos_por_estado';
|
||||
const PERSONALIZADO = -1;
|
||||
|
||||
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
|
||||
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
|
||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
|
||||
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
|
||||
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||
];
|
||||
// What two answers for the same indicator give together: the periods, rows and reports of both.
|
||||
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'] : [])];
|
||||
const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) };
|
||||
return { ...a, periodos: [...a.periodos, ...b.periodos.filter(p => !a.periodos.includes(p))], filas: [...a.filas, ...b.filas],
|
||||
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
|
||||
}
|
||||
|
||||
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
||||
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
|
||||
@@ -62,7 +60,8 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
selector: 'app-indicadores-historico',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
template: `
|
||||
<div class="controles" [class.compacto]="dominio() === 'cama'">
|
||||
@if (aviso(); as texto) { <p class="aviso" role="note" data-aviso="historico">{{ texto }}</p> }
|
||||
<div class="controles compacto">
|
||||
<h2>Filtros</h2>
|
||||
<div class="controles-fila">
|
||||
<div class="interval">
|
||||
@@ -88,6 +87,14 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
||||
@switch (panel.estado) {
|
||||
@case ('pendiente') { <p role="status">Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.</p> }
|
||||
@case ('reservado') {
|
||||
@if (panel.item.descripcion) { <p>{{ panel.item.descripcion }}</p> }
|
||||
@if (panel.disponibilidad === 'pendiente_validacion') {
|
||||
<p role="status" data-reservado="validacion">Pendiente de validación. Este indicador no se consulta hasta que su contrato, sus pruebas y su autorización estén aprobados.</p>
|
||||
} @else {
|
||||
<p role="status" data-reservado="integracion">Integración pendiente. Este indicador no se consulta hasta que su integración se active de forma explícita.</p>
|
||||
}
|
||||
}
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
|
||||
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
|
||||
@case ('error') {
|
||||
@@ -130,6 +137,8 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
@use '@angular/material' as mat;
|
||||
|
||||
:host { display: block; min-width: 0; }
|
||||
.aviso { margin: 0 0 var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-left-width: 4px; border-radius: var(--issste-radius); font: var(--mat-sys-body-medium); }
|
||||
.controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
||||
@@ -171,9 +180,17 @@ export class IndicadoresHistorico {
|
||||
readonly catalog = input.required<readonly Indicador[]>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
// The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere.
|
||||
private readonly publicados = computed(() => this.dominio() === 'cama'
|
||||
? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog());
|
||||
// What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog.
|
||||
private readonly config = computed(() => historicoDeDominio(this.dominio()));
|
||||
readonly aviso = computed(() => this.config()?.aviso);
|
||||
// The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active;
|
||||
// the whole catalog elsewhere. A reserved panel is never one of them, whatever the catalog publishes.
|
||||
private readonly publicados = computed(() => {
|
||||
const config = this.config();
|
||||
return config
|
||||
? config.paneles.filter(entrada => disponibilidadDe(entrada) === 'activo').flatMap(entrada => this.catalog().filter(item => item.id === entrada.id))
|
||||
: this.catalog();
|
||||
});
|
||||
// Only the granularities some indicator publishes; monthly first when there is one.
|
||||
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
|
||||
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
|
||||
@@ -183,15 +200,23 @@ export class IndicadoresHistorico {
|
||||
});
|
||||
// How many of the latest periods to show, per granularity; 0 shows them all.
|
||||
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
|
||||
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
|
||||
// Until the user picks one, the domain's initial window (when it declares one and there are more periods) or all.
|
||||
readonly ventana = computed(() => {
|
||||
const elegida = this.ventanas()[this.tipo()];
|
||||
if (elegida !== undefined) return elegida;
|
||||
const inicial = this.config()?.periodosIniciales ?? 0, total = this.totalDisponibles();
|
||||
return inicial && (!total || total > inicial) ? inicial : 0;
|
||||
});
|
||||
readonly PERSONALIZADO = PERSONALIZADO;
|
||||
// The periods the user picked in the dialog, per granularity.
|
||||
private readonly personalizados = signal<Partial<Record<TipoPeriodo, readonly string[]>>>({});
|
||||
private readonly dialogo = inject(MatDialog);
|
||||
private readonly selector = viewChild<MatSelect>('selector');
|
||||
// Every period published for the granularity by any indicator.
|
||||
private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {})
|
||||
.flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : [])));
|
||||
private readonly disponibles = computed(() => cronologico([...new Set(Object.values(this.cargas()[this.tipo()] ?? {})
|
||||
.flatMap(carga => carga.estado === 'listo' ? carga.disponibles ?? carga.datos.periodos : []))]));
|
||||
private readonly totalDisponibles = computed(() => Math.max(0, ...Object.values(this.cargas()[this.tipo()] ?? {})
|
||||
.map(carga => carga.estado === 'listo' ? (carga.disponibles ?? carga.datos.periodos).length : 0)));
|
||||
// The periods on screen, out of those an indicator publishes.
|
||||
private recortar(periodos: readonly string[]) {
|
||||
const orden = cronologico(periodos), ventana = this.ventana();
|
||||
@@ -209,7 +234,7 @@ export class IndicadoresHistorico {
|
||||
// Steps of five, up to what the indicator with the most periods has published.
|
||||
readonly opciones = computed(() => {
|
||||
const tipo = this.tipo();
|
||||
const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0));
|
||||
const total = this.totalDisponibles();
|
||||
const opciones = [];
|
||||
for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` });
|
||||
const elegidos = this.personalizados()[tipo]?.length;
|
||||
@@ -236,16 +261,26 @@ export class IndicadoresHistorico {
|
||||
const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`;
|
||||
const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`;
|
||||
try {
|
||||
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos };
|
||||
const esperado = this.config()?.paneles.find(entrada => entrada.id === item.id)?.contrato;
|
||||
if (esperado && datos.contrato !== esperado) throw new Error(`Contrato inesperado: se esperaba ${esperado} y llegó ${datos.contrato}`);
|
||||
const propias = this.config();
|
||||
const opciones = { ...(TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}),
|
||||
...(propias ? { unidades: propias.unidades, conciliarC2: propias.conciliarC2, c2SinPoblacionSinDato: propias.c2SinPoblacionSinDato } : {}) };
|
||||
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, opciones), datos };
|
||||
} catch (error) {
|
||||
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
||||
}
|
||||
};
|
||||
if (this.dominio() === 'cama') {
|
||||
const config = this.config();
|
||||
if (config) {
|
||||
if (!this.publicados().length) return [];
|
||||
return HISTORICO_CAMA.map((entrada): Panel => {
|
||||
return config.paneles.map((entrada: PanelHistorico): Panel => {
|
||||
const disponibilidad = disponibilidadDe(entrada);
|
||||
// Reserved: title, description and reason, whatever the catalog says. Nothing is requested for it.
|
||||
if (disponibilidad !== 'activo') return { item: { id: entrada.id, titulo: entrada.titulo, descripcion: entrada.descripcion }, estado: 'reservado', disponibilidad };
|
||||
const item = this.catalog().find(i => i.id === entrada.id);
|
||||
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
|
||||
const visible = { id: entrada.id, titulo: entrada.titulo };
|
||||
return item ? { ...panelDe(item), item: { ...visible, contrato: item.contrato } } : { item: visible, estado: 'pendiente' };
|
||||
});
|
||||
}
|
||||
return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
|
||||
@@ -268,17 +303,49 @@ export class IndicadoresHistorico {
|
||||
});
|
||||
});
|
||||
}
|
||||
// The periods the window on screen needs out of those published: all of them, unless the domain declares an
|
||||
// initial window, in which case only those. Choosing a wider window later requests the rest (`ampliar`).
|
||||
private necesarios(disponibles: readonly string[]): string[] {
|
||||
if (!this.config()?.periodosIniciales) return [...disponibles];
|
||||
const orden = cronologico(disponibles), ventana = this.ventana();
|
||||
if (ventana === PERSONALIZADO) return orden.filter(p => (this.personalizados()[this.tipo()] ?? []).includes(p));
|
||||
return ventana ? orden.slice(-ventana) : orden;
|
||||
}
|
||||
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
|
||||
const limitada = !!this.config()?.periodosIniciales;
|
||||
return this.periodos.periodos(this.dominio(), item.id).pipe(
|
||||
map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)),
|
||||
switchMap((periodos): Observable<Carga> => periodos.length
|
||||
? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos })))
|
||||
? this.service.datos(this.dominio(), item.id, tipo, this.necesarios(periodos)).pipe(
|
||||
map(datos => ({ estado: 'listo', datos, ...(limitada ? { disponibles: periodos } : {}) })))
|
||||
: of({ estado: 'vacio' })),
|
||||
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
|
||||
}
|
||||
// The window got wider than what was requested: asks only for the periods that are missing, and adds them.
|
||||
private ampliar() {
|
||||
const tipo = this.tipo(), cargas = this.cargas()[tipo];
|
||||
if (!cargas || !this.config()?.periodosIniciales) return;
|
||||
for (const item of this.publicados()) {
|
||||
const carga = cargas[item.id];
|
||||
if (carga?.estado !== 'listo' || !carga.disponibles) continue;
|
||||
const faltan = this.necesarios(carga.disponibles).filter(p => !carga.datos.periodos.includes(p));
|
||||
if (!faltan.length) continue;
|
||||
this.service.datos(this.dominio(), item.id, tipo, faltan).pipe(takeUntilDestroyed(this.destruccion)).subscribe({
|
||||
next: datos => this.cargas.update(actual => {
|
||||
const vigente = actual[tipo]?.[item.id];
|
||||
return vigente?.estado === 'listo' && vigente === carga
|
||||
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { ...vigente, datos: unir(vigente.datos, datos) } } } : actual;
|
||||
}),
|
||||
error: error => this.cargas.update(actual => actual[tipo]?.[item.id] === carga
|
||||
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { estado: 'error', mensaje: httpMessage(error) } } } : actual),
|
||||
});
|
||||
}
|
||||
}
|
||||
private readonly destruccion = inject(DestroyRef);
|
||||
elegirVentana(valor: number) {
|
||||
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
|
||||
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
|
||||
this.ampliar();
|
||||
}
|
||||
abrirPersonalizado() {
|
||||
const tipo = this.tipo(), periodos = this.disponibles();
|
||||
@@ -290,6 +357,7 @@ export class IndicadoresHistorico {
|
||||
if (resultado?.length) {
|
||||
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
|
||||
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
|
||||
this.ampliar();
|
||||
}
|
||||
// Cancelled, the selector goes back to what's on screen.
|
||||
this.selector()?.writeValue(this.ventana());
|
||||
|
||||
@@ -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>
|
||||
@@ -51,7 +47,7 @@
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
@let resumen = teaResumenPeriodo;
|
||||
<div class="kpi-heading">
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
|
||||
<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()" /> }
|
||||
@@ -79,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" />
|
||||
|
||||
@@ -6,11 +6,8 @@
|
||||
.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);
|
||||
@@ -39,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);
|
||||
|
||||
@@ -54,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');
|
||||
@@ -107,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', () => {
|
||||
@@ -122,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';
|
||||
@@ -131,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', () => {
|
||||
@@ -324,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,16 +31,17 @@ import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { historicoDeDominio } from './indicadores-historico-config';
|
||||
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'resumen', label: 'Resumen' },
|
||||
{ id: 'seguimiento', label: 'Seguimiento' },
|
||||
{ id: 'seguimiento', label: 'Análisis de riesgos' },
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
|
||||
// TEA, CaMa and CaCu (while its tab is on, see `HISTORICO_CACU_HABILITADO`) have a history; the epidemiological analysis is CaMa's,
|
||||
// between its history and its follow-up list.
|
||||
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
|
||||
@@ -48,7 +49,7 @@ 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',
|
||||
@@ -58,7 +59,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
|
||||
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
|
||||
get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; }
|
||||
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
readonly fichaPacienteAbierta = signal(false);
|
||||
@@ -104,7 +105,6 @@ export class IndicadoresPage {
|
||||
readonly kpiPanels = viewChildren(IndicadorKpiPanel);
|
||||
// The opportunity cards share the period their own query already resolved.
|
||||
get periodoCompartido(): string {
|
||||
if (this.dominio !== 'cama') return '';
|
||||
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;
|
||||
@@ -302,9 +302,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); }
|
||||
@@ -356,9 +359,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'
|
||||
@@ -375,8 +378,7 @@ export class IndicadoresPage {
|
||||
});
|
||||
readonly searchResults = computed(() => {
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
const items = this.catalogOrder().filter(item => selected.has(item.id));
|
||||
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
|
||||
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();
|
||||
|
||||
@@ -35,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();
|
||||
@@ -82,11 +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.
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(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);
|
||||
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');
|
||||
@@ -94,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']);
|
||||
['Resumen', 'Histórico', '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,8 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
|
||||
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
|
||||
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
|
||||
// TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain.
|
||||
const esperadas = ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
||||
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||
|
||||
@@ -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; }
|
||||
|
||||
+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']),
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { PlotlyFigure, Tema } from '../../indicadores.models';
|
||||
import { FiguraRecurrencia } from './cama-recurrencia.service';
|
||||
|
||||
export const ETIQUETAS_RECURRENCIA = {
|
||||
eje_x: 'Meses desde el diagnóstico', eje_y: 'Libre de recaída S(t)', km: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull',
|
||||
weibull_fraccional: 'Weibull fraccional', puntos: 'LR + HBN combinado (IC 95 % bootstrap)',
|
||||
} as const;
|
||||
export const COLORES_RECURRENCIA = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a' } as const;
|
||||
|
||||
/** A curve in two parts: solid up to the follow-up the cohort has, dotted after it (the extrapolation). */
|
||||
function curva(t: number[], S: number[], hasta: number, color: string, nombre: string, dash?: string): Record<string, unknown>[] {
|
||||
const dentro = t.map((x, i) => i).filter(i => t[i] <= hasta), fuera = t.map((x, i) => i).filter(i => t[i] >= hasta);
|
||||
return [
|
||||
{ type: 'scatter', mode: 'lines', x: dentro.map(i => t[i]), y: dentro.map(i => S[i]), line: { color, width: 3, ...(dash ? { dash } : {}) }, name: nombre, legendgroup: nombre,
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + nombre + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: fuera.map(i => t[i]), y: fuera.map(i => S[i]), line: { color, width: 1.8, dash: 'dot' }, showlegend: false, legendgroup: nombre, hoverinfo: 'skip' },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The recurrence analysis' figure of one scenario of one cohort, as the pipeline draws it: the Kaplan-Meier curve of the scenario's
|
||||
* patients with its Greenwood band, the classic and the fractional Weibull (dotted past the follow-up), and the recurrence-free
|
||||
* probability at each horizon by the combination of the LR and the HBN, as diamonds with their bootstrap interval.
|
||||
*/
|
||||
export function figuraRecurrencia(f: FiguraRecurrencia, tema: Tema = 'claro'): PlotlyFigure {
|
||||
const L = ETIQUETAS_RECURRENCIA, d = f.points.COMB, km = f.km;
|
||||
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
|
||||
const visibles = (t: number[], S: number[]) => S.filter((_, i) => t[i] <= f.months_max);
|
||||
const minimo = Math.max(0, Math.floor((Math.min(...visibles(km.months, km.low), ...visibles(f.weibull.t, f.weibull.S), ...visibles(f.weibull_fractional.t, f.weibull_fractional.S), ...d.low) - 0.02) * 20) / 20);
|
||||
const data: Record<string, unknown>[] = [
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES_RECURRENCIA.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES_RECURRENCIA.km, width: 2, shape: 'hv' }, name: L.km, legendgroup: 'km',
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + L.km + '</extra>' },
|
||||
...curva(f.weibull.t, f.weibull.S, f.observado_hasta, COLORES_RECURRENCIA.weibull, L.weibull),
|
||||
...curva(f.weibull_fractional.t, f.weibull_fractional.S, f.observado_hasta, COLORES_RECURRENCIA.fraccional, L.weibull_fraccional, 'dash'),
|
||||
{ type: 'scatter', mode: 'markers', name: L.puntos, x: f.horizons_months, y: d.S,
|
||||
marker: { symbol: 'diamond', size: 15, color: COLORES_RECURRENCIA.modelo, line: { color: 'white', width: 1.5 } },
|
||||
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES_RECURRENCIA.modelo, thickness: 2, width: 6,
|
||||
array: d.high.map((hi, i) => Math.max(0, hi - d.S[i])), arrayminus: d.S.map((s, i) => Math.max(0, s - d.low[i])) },
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + L.puntos + '</extra>' },
|
||||
];
|
||||
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
|
||||
const layout: Record<string, unknown> = {
|
||||
title: { text: `${f.escenario}<br>${f.cohorte_nombre} · n=${f.n.toLocaleString('es-MX')}, recaídas=${f.recaidas.toLocaleString('es-MX')}`, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
|
||||
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
|
||||
xaxis: { ...eje, title: { text: L.eje_x }, range: [0, f.months_max + 0.8], dtick: 12 },
|
||||
yaxis: { ...eje, title: { text: L.eje_y }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
|
||||
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
|
||||
};
|
||||
return { data, layout, config: { responsive: true, displaylogo: false } };
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { catchError, map, Observable, of } from 'rxjs';
|
||||
import { FilaFactores, filaFactores } from './cama-curvas.service';
|
||||
|
||||
// CaMa's recurrence figures of a patient, `GET /cama/modelo/recurrencia?paciente=`: the clinical scenarios her covariates meet,
|
||||
// each as the recurrence analysis of an external cohort (METABRIC or SCAN-B) drew it. They describe the scenario's patients in
|
||||
// that cohort, not her; the answer names the version that published them. A 404 or a failure is "none to show".
|
||||
export interface FiguraRecurrencia {
|
||||
cohorte: string; cohorte_nombre: string; escenario: string; n: number; recaidas: number;
|
||||
horizons_months: number[]; observado_hasta: number; months_max: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
weibull: { t: number[]; S: number[] };
|
||||
weibull_fractional: { t: number[]; S: number[] };
|
||||
points: { COMB: { S: number[]; low: number[]; high: number[] } };
|
||||
}
|
||||
export interface RespuestaRecurrencia {
|
||||
modelo: { nombre: string; version: string }; horizontes: number[]; escenarios: FiguraRecurrencia[];
|
||||
/** The summary's rows, one per cohort, scenario and horizon: the risk-factor label. */
|
||||
resumen: FilaFactores[];
|
||||
/** The cohort and scenario the patient's own covariates place her in first, if any. */
|
||||
predeterminado: { cohorte: string; escenario: string } | null;
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number' && Number.isFinite(x)) && (length === undefined || v.length === length);
|
||||
const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1);
|
||||
|
||||
function invalid(): never { throw new Error('Respuesta de recurrencia inválida'); }
|
||||
|
||||
function figura(v: unknown, horizons: number): FiguraRecurrencia {
|
||||
if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte_nombre'] !== 'string' || typeof v['cohorte'] !== 'string') invalid();
|
||||
const f = v as Record<string, any>;
|
||||
if (!numbers(f['horizons_months'], horizons) || !Number.isFinite(f['n']) || !Number.isFinite(f['recaidas']) || !Number.isFinite(f['observado_hasta']) || !Number.isFinite(f['months_max'])) invalid();
|
||||
const km = f['km'], w = f['weibull'], k = f['weibull_fractional'], p = f['points']?.['COMB'];
|
||||
const n = Array.isArray(km?.months) ? km.months.length : -1;
|
||||
if (!numbers(km?.months) || !probabilities(km?.S, n) || !probabilities(km?.low, n) || !probabilities(km?.high, n)) invalid();
|
||||
for (const c of [w, k]) if (!numbers(c?.t) || !probabilities(c?.S, c.t.length)) invalid();
|
||||
if (!probabilities(p?.S, horizons) || !probabilities(p?.low, horizons) || !probabilities(p?.high, horizons)) invalid();
|
||||
if ((p.low as number[]).some((l, i) => l > p.high[i])) invalid();
|
||||
return f as FiguraRecurrencia;
|
||||
}
|
||||
|
||||
/** Validate at the boundary: the shapes and ranges, so the chart never draws a partial or impossible curve. */
|
||||
export function respuestaRecurrencia(v: unknown): RespuestaRecurrencia {
|
||||
if (!record(v) || !record(v['modelo']) || !Array.isArray(v['escenarios']) || !numbers(v['horizontes'])) invalid();
|
||||
const m = v['modelo'] as Record<string, unknown>, h = (v['horizontes'] as number[]).length;
|
||||
if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid();
|
||||
if (!Array.isArray(v['resumen'])) invalid();
|
||||
const d = v['predeterminado'];
|
||||
return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, horizontes: v['horizontes'] as number[],
|
||||
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)), resumen: (v['resumen'] as unknown[]).map(filaFactores),
|
||||
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null };
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaRecurrenciaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The recurrence analysis of both cohorts and the patient's default, or `null` when there is no recurrence model in production or it fails. */
|
||||
recurrencia(pacId: string): Observable<RespuestaRecurrencia | null> {
|
||||
return this.http.get<unknown>('/cama/modelo/recurrencia', { params: { paciente: pacId } }).pipe(
|
||||
map(respuestaRecurrencia), catchError(() => of(null)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { PlotlyFigure, Tema } from '../../indicadores.models';
|
||||
import { CurvasSupervivencia } from './cama-curvas.service';
|
||||
|
||||
/** The wording of the chart, as the SEER pipeline's own figure has it. The model's run can publish another wording for any
|
||||
* of these (`[config.etiquetas]`), so the clinicians define it, not the code. */
|
||||
export const ETIQUETAS_PREDETERMINADAS: Readonly<Record<string, string>> = {
|
||||
eje_x: 'Meses desde el diagnóstico', eje_y: 'Supervivencia S(t)',
|
||||
km_crudo: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull', weibull_fraccional: 'Weibull fraccional',
|
||||
puntos: 'LR + HBN combinado (IC 95 % bootstrap)',
|
||||
};
|
||||
export const COLORES = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a' } as const;
|
||||
|
||||
const etiqueta = (c: CurvasSupervivencia, clave: string) => c.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave;
|
||||
|
||||
/**
|
||||
* The SEER pipeline's survival figure of one clinical scenario: the Kaplan-Meier curve of its patients with its Greenwood band,
|
||||
* the classic and the fractional Weibull, and the model's survival at each horizon as diamonds with their bootstrap interval.
|
||||
* Titled with the scenario, its patients and its deaths.
|
||||
*/
|
||||
export function figuraSupervivencia(c: CurvasSupervivencia, tema: Tema = 'claro'): PlotlyFigure {
|
||||
const km = c.km, diamantes = c.points.COMB, t = (clave: string) => etiqueta(c, clave);
|
||||
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
|
||||
const minimo = Math.max(0, Math.floor((Math.min(...km.low, ...c.weibull_fractional.S, ...diamantes.low) - 0.02) * 20) / 20);
|
||||
const data: Record<string, unknown>[] = [
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km, width: 2, shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km',
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('km_crudo') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: c.weibull.t, y: c.weibull.S, line: { color: COLORES.weibull, width: 3 }, name: t('weibull'),
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: c.weibull_fractional.t, y: c.weibull_fractional.S, line: { color: COLORES.fraccional, width: 3, dash: 'dash' }, name: t('weibull_fraccional'),
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull_fraccional') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'markers', name: t('puntos'), x: c.horizons_months, y: diamantes.S,
|
||||
marker: { symbol: 'diamond', size: 15, color: COLORES.modelo, line: { color: 'white', width: 1.5 } },
|
||||
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.modelo, thickness: 2, width: 6,
|
||||
array: diamantes.high.map((hi, i) => hi - diamantes.S[i]), arrayminus: diamantes.S.map((s, i) => s - diamantes.low[i]) },
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('puntos') + '</extra>' },
|
||||
];
|
||||
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
|
||||
const layout: Record<string, unknown> = {
|
||||
title: { text: `${c.escenario ?? 'Toda la cohorte'}<br>n=${c.n.toLocaleString('es-MX')}, fallecidos=${c.events.toLocaleString('es-MX')}`, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
|
||||
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
|
||||
xaxis: { ...eje, title: { text: t('eje_x') }, range: [0, c.months_max + 0.8], dtick: 5 },
|
||||
yaxis: { ...eje, title: { text: t('eje_y') }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
|
||||
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
|
||||
};
|
||||
return { data, layout, config: { responsive: true, displaylogo: false } };
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
</header>
|
||||
@if (estado.tipo === 'cargando') { <p role="status">Cargando información…</p> }
|
||||
@if (estado.tipo === 'no-disponible') { <p class="availability" role="status">Información no disponible.</p> }
|
||||
@if (estado.tipo === 'error') { <p class="availability" role="alert">No se pudo cargar la información de este paciente. Regresa a Seguimiento para intentar de nuevo.</p> }
|
||||
@if (estado.tipo === 'error') { <p class="availability" role="alert">No se pudo cargar la información de este paciente. Regresa a Análisis de riesgos para intentar de nuevo.</p> }
|
||||
@if (registrosTemporales.length) { <p class="pending-changes" role="status">Cambios sin guardar</p> }
|
||||
<div class="detail-grid">
|
||||
<mat-card class="history-card" appearance="outlined" aria-labelledby="historial-title">
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
// Covers the patient's risk in CaMa's record: the table asks the CaMa endpoint (and CaCu's calls stay as they were), says
|
||||
// whose model scored her, shows the mortality at the horizons the model gives (6, 12 and 18 months) and the model's
|
||||
// index date; the CaMa record does not show it (its two analyses replace it). Fixtures: a Bundle like `GET /cama/fhir/RiskAssessment?subject=
|
||||
// Patient/7` answers it (`riesgoCamaEjemplo`), and a provider that returns it.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { CamaPatientCard } from './cama/cama-patient-card';
|
||||
import { CamaPatientSummary } from './cama/cama-patient.models';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
import { EMPTY } from 'rxjs';
|
||||
import { CamaCurvasService } from './cama/cama-curvas.service';
|
||||
import { CamaRecurrenciaService } from './cama/cama-recurrencia.service';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { INTERVALO, prediccion } from './paciente-riesgo.testing';
|
||||
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
|
||||
/** TEST ONLY. Patient 7's current CaMa `RiskAssessment`: mortality at 6, 12 and 18 months from the model's index date. */
|
||||
function riesgoCamaEjemplo(): any {
|
||||
const muerte = (p: number, fin: string) => {
|
||||
const item = prediccion(p, '2025-06-19', fin);
|
||||
item.outcome = { coding: [{ system: `${CS}/desenlace`, code: 'muerte', display: 'Muerte por cualquier causa' }] };
|
||||
return item;
|
||||
};
|
||||
return {
|
||||
resourceType: 'Bundle', type: 'searchset', total: 1,
|
||||
entry: [{
|
||||
fullUrl: 'http://localhost/cama/fhir/RiskAssessment/3-7',
|
||||
resource: {
|
||||
resourceType: 'RiskAssessment', id: '3-7', status: 'final',
|
||||
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
|
||||
subject: { reference: 'Patient/7' }, occurrenceDateTime: '2026-01-02T10:00:00Z',
|
||||
method: { coding: [{ system: `${CS}/modelo`, code: 'cama-survival', version: '1' }] },
|
||||
prediction: [muerte(0.07, '2025-12-19'), muerte(0.178, '2026-06-19'), muerte(0.251, '2026-12-19')],
|
||||
},
|
||||
search: { mode: 'match' },
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
const resumen = (idField: 'pac_id' | 'id_seudonimo'): CamaPatientSummary => ({
|
||||
patientId: '7', idField, idLabel: 'pac_id', cutoff: '2026-01-01', ageGroup: '50-59', status: null, priority: null,
|
||||
birads: 'B5', mammographyDate: '2025-06-01', histopathology: 'CARCINOMA_INVASOR', biopsyDate: '2025-06-19',
|
||||
daysMammographyToDiagnosis: null, clinicalScenario: null,
|
||||
});
|
||||
|
||||
describe('Riesgo individual de la paciente CaMa', () => {
|
||||
const obtener = vi.fn();
|
||||
beforeEach(() => {
|
||||
obtener.mockReset().mockImplementation(() => of(riesgoCamaEjemplo()));
|
||||
TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener } },
|
||||
{ provide: CamaCurvasService, useValue: { escenarios: () => of(null), consulta: () => EMPTY } },
|
||||
{ provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(null) } }] });
|
||||
});
|
||||
|
||||
// Fails if the table stops asking the domain it was given, or if CaCu's call changes shape (`obtener(pacId)` only).
|
||||
it('asks its domain for the patient, and CaCu with the id alone', () => {
|
||||
const cama = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
cama.componentRef.setInput('pacId', '7');
|
||||
cama.componentRef.setInput('dominio', 'cama');
|
||||
cama.detectChanges();
|
||||
const cacu = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
cacu.componentRef.setInput('pacId', '7');
|
||||
cacu.detectChanges();
|
||||
|
||||
expect(obtener).toHaveBeenNthCalledWith(1, '7', 'cama');
|
||||
expect(obtener).toHaveBeenNthCalledWith(2, '7');
|
||||
expect(cama.nativeElement.textContent).toContain('Riesgo individual CaMa');
|
||||
expect(cacu.nativeElement.textContent).toContain('Riesgo individual CaCu');
|
||||
});
|
||||
|
||||
// Fails if the mortality, its outcome, the model or the index date of the Bundle are not what the card shows.
|
||||
it('shows the model, the index date, the outcome and the mortality at each horizon', () => {
|
||||
const f = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
f.componentRef.setInput('pacId', '7');
|
||||
f.componentRef.setInput('dominio', 'cama');
|
||||
f.detectChanges();
|
||||
|
||||
const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
|
||||
expect(text).toContain('cama-survival');
|
||||
expect(text).toContain('2025-06-19');
|
||||
expect(text).toContain('Muerte por cualquier causa');
|
||||
expect(text).toContain('7 %');
|
||||
expect(text).toContain('17.8 %');
|
||||
expect(text).toContain('25.1 %');
|
||||
expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/);
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
|
||||
});
|
||||
|
||||
// Fails if the CaMa record goes back to showing the individual risk table, which its two analyses replace.
|
||||
it('is not in the CaMa record: its analyses and their risk factors are', () => {
|
||||
const f = TestBed.createComponent(CamaPatientCard);
|
||||
f.componentRef.setInput('summary', resumen('pac_id'));
|
||||
f.detectChanges();
|
||||
|
||||
expect(obtener).not.toHaveBeenCalled();
|
||||
expect(f.nativeElement.querySelector('app-paciente-riesgo-tabla')).toBeNull();
|
||||
expect(INTERVALO).toContain('intervalo-confianza');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
<h4>Riesgo individual CaCu</h4>
|
||||
<h4>Riesgo individual {{ rotulo() }}</h4>
|
||||
@let lectura = estado();
|
||||
@switch (lectura.tipo) {
|
||||
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
|
||||
@@ -7,46 +7,24 @@
|
||||
}
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
<p class="simulated-label" id="riesgo-simulado">Información simulada · Entorno DEV · Sin evaluación clínica</p>
|
||||
@if (lectura.datos.cohorte; as cohorte) {
|
||||
<h5>Cohorte</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Definición de cohorte</dt><dd>{{ cohorte.url }}</dd></div>
|
||||
<div><dt>Versión de cohorte</dt><dd>{{ cohorte.version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ cohorte.fecha_indice }}</dd></div>
|
||||
</dl>
|
||||
<details>
|
||||
<summary>Variables del modelo PIMM</summary>
|
||||
<p class="availability">Códigos técnicos del modelo; no constituyen un diagnóstico.</p>
|
||||
<dl class="metadata">
|
||||
<div><dt>tipo_censura</dt><dd>{{ cohorte.tipo_censura ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>c (estado basal)</dt><dd>{{ cohorte.c ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>l (años desde índice)</dt><dd>{{ cohorte.l ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>r (años desde índice)</dt><dd>{{ cohorte.r ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>pap_0 (citología índice)</dt><dd>{{ cohorte.pap_0 ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>hpv_0 (VPH índice)</dt><dd>{{ cohorte.hpv_0 ?? 'No disponible' }}</dd></div>
|
||||
</dl>
|
||||
</details>
|
||||
} @else {
|
||||
<p role="status">Sin membresía en la cohorte vigente.</p>
|
||||
}
|
||||
@if (lectura.datos.riesgo; as riesgo) {
|
||||
@let riesgo = lectura.datos.riesgo;
|
||||
<h5>Modelo y evaluación</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
@if (riesgo.horizontes.length) {
|
||||
<div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0">
|
||||
<table aria-describedby="riesgo-simulado">
|
||||
<caption>Probabilidades simuladas por horizonte desde la fecha índice</caption>
|
||||
<table>
|
||||
<caption>Probabilidades por horizonte desde la fecha índice</caption>
|
||||
<thead><tr>
|
||||
<th scope="col">Horizonte (años)</th>
|
||||
<th scope="col">Probabilidad (%)</th>
|
||||
<th scope="col">Intervalo de confianza (%)</th>
|
||||
<th scope="col">Estado de evaluación</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (h of riesgo.horizontes; track h.horizonte_anios) {
|
||||
@@ -54,14 +32,12 @@
|
||||
<th scope="row">{{ h.horizonte_anios }}</th>
|
||||
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
|
||||
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
|
||||
<td>{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
} @else { <p role="status">Sin riesgo disponible: no hay lote vigente.</p> }
|
||||
}
|
||||
}
|
||||
<p class="recommendations">Recomendaciones no disponibles.</p>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Component, effect, inject, input } from '@angular/core';
|
||||
import { Component, computed, effect, inject, input } from '@angular/core';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { DominioRiesgo } from './paciente-riesgo.models';
|
||||
import { PacienteRiesgoState } from './paciente-riesgo.state';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
@@ -13,11 +14,13 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
export class PacienteRiesgoTabla {
|
||||
/** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */
|
||||
readonly pacId = input.required<string | null>();
|
||||
/** The domain whose model scored her: CaCu unless said otherwise. */
|
||||
readonly dominio = input<DominioRiesgo>('cacu');
|
||||
readonly rotulo = computed(() => this.dominio() === 'cama' ? 'CaMa' : 'CaCu');
|
||||
private readonly state = inject(PacienteRiesgoState);
|
||||
readonly estado = this.state.estado;
|
||||
readonly tieneIntervalo = tieneIntervalo;
|
||||
|
||||
constructor() {
|
||||
effect(() => this.state.pacId.set(this.pacId()));
|
||||
effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +1,44 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
export type EstadoEvaluacionCacu = 'preliminary' | 'final';
|
||||
export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo';
|
||||
|
||||
export interface CohorteRiesgoCacu {
|
||||
url: string;
|
||||
version: string;
|
||||
fecha_indice: string;
|
||||
tipo_censura: TipoCensuraCacu | null;
|
||||
c: number | null;
|
||||
l: number | null;
|
||||
r: number | null;
|
||||
pap_0: string | null;
|
||||
hpv_0: string | null;
|
||||
}
|
||||
/** The domain whose patient's risk is read: its FHIR endpoint is `/<dominio>/fhir`. CaCu unless said otherwise. */
|
||||
export type DominioRiesgo = 'cacu' | 'cama';
|
||||
|
||||
export interface HorizonteRiesgoCacu {
|
||||
/** Years from the risk's index date: the length of the prediction's `whenPeriod`; 0 is the immediate risk. */
|
||||
horizonte_anios: number;
|
||||
/** Transport values remain probabilities in [0, 1], never percentages. */
|
||||
probabilidad: number;
|
||||
ic_bajo?: number | null;
|
||||
ic_alto?: number | null;
|
||||
estado: EstadoEvaluacionCacu;
|
||||
}
|
||||
|
||||
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
|
||||
export interface LoteRiesgoCacu {
|
||||
lote_id: number;
|
||||
/** The resource's id, `<lote_id>-<pac_id>`. */
|
||||
id: string;
|
||||
modelo_nombre: string;
|
||||
modelo_version: string;
|
||||
/** The model's index date for this patient (the predictions' `whenPeriod.start`): the horizons count from it. */
|
||||
fecha_indice: string;
|
||||
evaluado_en: string;
|
||||
estado_lote: EstadoEvaluacionCacu;
|
||||
/** The prediction's outcome code (e.g. `cin2_mas`) and its display. */
|
||||
desenlace: string;
|
||||
desenlace_texto: string | null;
|
||||
horizontes: HorizonteRiesgoCacu[];
|
||||
}
|
||||
|
||||
/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
|
||||
/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */
|
||||
export interface RiesgoPacienteCacu {
|
||||
simulado: true;
|
||||
cohorte: CohorteRiesgoCacu | null;
|
||||
riesgo: LoteRiesgoCacu | null;
|
||||
riesgo: LoteRiesgoCacu;
|
||||
}
|
||||
|
||||
/** `null` when the patient has no risk data. */
|
||||
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
|
||||
export interface PacienteRiesgoProvider {
|
||||
obtener(pacId: string): Observable<unknown>;
|
||||
obtener(pacId: string, dominio?: DominioRiesgo): Observable<unknown>;
|
||||
}
|
||||
|
||||
export type PacienteRiesgoEstado =
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
|
||||
import { inject, InjectionToken } from '@angular/core';
|
||||
import { catchError, of, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
|
||||
// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
|
||||
// The patient's risk is a FHIR `RiskAssessment` searched by `subject=Patient/<pac_id>`, the identifier a follow-up row
|
||||
// carries as `pac_id`, in the domain's endpoint (`/cacu/fhir`, or `/cama/fhir`); an empty Bundle (or a 404) is a patient
|
||||
// without risk data.
|
||||
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
|
||||
providedIn: 'root', factory: () => {
|
||||
const http = inject(HttpClient);
|
||||
return {
|
||||
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
|
||||
obtener: (pacId: string, dominio = 'cacu') => http.get<unknown>(`/${dominio}/fhir/RiskAssessment`, {
|
||||
params: new HttpParams().set('subject', `Patient/${pacId}`),
|
||||
}).pipe(
|
||||
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import { of, Subject, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
@@ -22,10 +22,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
TestBed.inject(HttpTestingController).verify();
|
||||
});
|
||||
|
||||
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
|
||||
it('pide el RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => {
|
||||
const f = setup(), root: HTMLElement = f.nativeElement;
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
|
||||
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42')
|
||||
.flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' });
|
||||
f.detectChanges();
|
||||
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
@@ -33,27 +33,33 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
|
||||
it('un Bundle vacío es una paciente sin riesgo confirmado', () => {
|
||||
const f = setup({ obtener: () => of({ resourceType: 'Bundle', type: 'searchset', total: 0 }) });
|
||||
expect(f.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(f.nativeElement.querySelector('table')).toBeNull();
|
||||
});
|
||||
|
||||
it('renderiza el ejemplo contractual, metadatos y porcentajes sin alterar los datos', () => {
|
||||
const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data));
|
||||
data.riesgo!.horizontes[1].estado = 'preliminary';
|
||||
const baseline = structuredClone(data);
|
||||
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(4);
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) {
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado');
|
||||
expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV');
|
||||
// The record no longer shows the cohort's internals (its definition, version or model variables).
|
||||
expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/);
|
||||
// The record never says its data are test data: with real information it makes real predictions.
|
||||
expect(root.textContent).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica|simuladas/);
|
||||
expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/);
|
||||
// Internal batch key stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toContain('lote_id');
|
||||
// The resource id (batch and patient) stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toMatch(/lote_id|12-42/);
|
||||
expect(data).toEqual(baseline);
|
||||
});
|
||||
|
||||
@@ -67,17 +73,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
|
||||
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
|
||||
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
|
||||
expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM');
|
||||
expect(root.textContent).toContain('no constituyen un diagnóstico');
|
||||
});
|
||||
|
||||
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
data.riesgo!.estado_lote = 'preliminary';
|
||||
data.riesgo!.horizontes = [
|
||||
{ horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' },
|
||||
{ horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' },
|
||||
{ horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' },
|
||||
data.entry[0].resource.status = 'preliminary';
|
||||
data.entry[0].resource.prediction = [
|
||||
prediccion(0, '2026-06-01', '2026-12-01', [0, 0]),
|
||||
prediccion(1, '2026-06-01', '2034-06-01'),
|
||||
prediccion(0.00123, '2026-06-01', '2038-09-01'),
|
||||
];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
@@ -86,31 +90,9 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
|
||||
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null };
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent);
|
||||
expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']);
|
||||
expect(f.nativeElement.textContent).not.toMatch(/undefined|null/);
|
||||
});
|
||||
|
||||
it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null;
|
||||
if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null;
|
||||
if (caso === 'horizontes') data.riesgo!.horizontes = [];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente');
|
||||
if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente');
|
||||
if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados');
|
||||
if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull();
|
||||
expect(root.textContent).toContain('Información simulada');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
});
|
||||
|
||||
it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => {
|
||||
const data = { ...riesgoCacuEjemplo(), simulado };
|
||||
if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag;
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
|
||||
@@ -118,7 +100,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
});
|
||||
|
||||
it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
|
||||
const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
|
||||
const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12;
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
|
||||
@@ -134,14 +116,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
it('aísla estado y fixture entre instancias sin reutilizar información', () => {
|
||||
const source = new Subject<unknown>(), f = setup({ obtener: () => source });
|
||||
const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges();
|
||||
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
|
||||
data.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges();
|
||||
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
|
||||
f.destroy();
|
||||
const otra = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
|
||||
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
|
||||
expect(otra.nativeElement.querySelector('table')).toBeNull();
|
||||
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
|
||||
expect(riesgoCacuEjemplo().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08);
|
||||
otra.destroy(); expect(source.observed).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable, inject, signal } from '@angular/core';
|
||||
import { Injectable, computed, inject, signal } from '@angular/core';
|
||||
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
|
||||
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
|
||||
import { DominioRiesgo, PacienteRiesgoEstado } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
|
||||
|
||||
@@ -12,10 +12,15 @@ export class PacienteRiesgoState {
|
||||
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
|
||||
// `undefined` until the input is set; `null` is a patient without `pac_id`.
|
||||
readonly pacId = signal<string | null | undefined>(undefined);
|
||||
readonly estado = toSignal(toObservable(this.pacId).pipe(
|
||||
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
|
||||
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
|
||||
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
|
||||
readonly dominio = signal<DominioRiesgo>('cacu');
|
||||
// The patient and her domain are one query, so changing both never asks for the patient in the wrong domain.
|
||||
private readonly consulta = computed(() => ({ id: this.pacId(), dominio: this.dominio() }));
|
||||
readonly estado = toSignal(toObservable(this.consulta).pipe(
|
||||
switchMap(({ id, dominio }) => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => dominio === 'cacu' ? this.provider.obtener(id) : this.provider.obtener(id, dominio)).pipe(
|
||||
map((respuesta): PacienteRiesgoEstado => {
|
||||
const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id);
|
||||
return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos };
|
||||
}),
|
||||
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
|
||||
startWith(CARGANDO),
|
||||
)),
|
||||
|
||||
@@ -1,20 +1,51 @@
|
||||
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
|
||||
export function riesgoCacuEjemplo(): RiesgoPacienteCacu {
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
|
||||
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
|
||||
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
|
||||
return {
|
||||
outcome: { coding: [{ system: `${CS}/desenlace`, code: 'cin2_mas', display: 'CIN2+ por biopsia' }] },
|
||||
probabilityDecimal: p, whenPeriod: { start: inicio, end: fin },
|
||||
...(ic ? { extension: [{ url: INTERVALO, valueRange: { low: { value: ic[0] }, high: { value: ic[1] } } }] } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** TEST ONLY. The external contract example: a `searchset` Bundle with patient 42's current `RiskAssessment`, as
|
||||
* `GET /cacu/fhir/RiskAssessment?subject=Patient/42` answers it; never belongs to the selected patient. */
|
||||
export function riesgoCacuEjemplo(): any {
|
||||
return {
|
||||
resourceType: 'Bundle', type: 'searchset', total: 1,
|
||||
entry: [{
|
||||
fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/12-42',
|
||||
resource: {
|
||||
resourceType: 'RiskAssessment', id: '12-42', status: 'final',
|
||||
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
|
||||
subject: { reference: 'Patient/42' }, occurrenceDateTime: '2026-10-01T00:00:00Z',
|
||||
method: { coding: [{ system: `${CS}/modelo`, code: 'modelo-cacu', version: '2.1.0' }] },
|
||||
prediction: [
|
||||
prediccion(0.08, '2026-06-01', '2027-06-01', [0.05, 0.12]),
|
||||
prediccion(0.21, '2026-06-01', '2029-06-01', [0.15, 0.28]),
|
||||
prediccion(0.34, '2026-06-01', '2031-06-01', [0.26, 0.44]),
|
||||
],
|
||||
},
|
||||
search: { mode: 'match' },
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */
|
||||
export function riesgoCacuVista(): RiesgoPacienteCacu {
|
||||
return {
|
||||
simulado: true,
|
||||
cohorte: {
|
||||
url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15',
|
||||
tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO',
|
||||
},
|
||||
riesgo: {
|
||||
lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final',
|
||||
id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia',
|
||||
horizontes: [
|
||||
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' },
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' },
|
||||
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,121 +1,89 @@
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { prediccion, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
|
||||
import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation';
|
||||
import { TipoCensuraCacu } from './paciente-riesgo.models';
|
||||
|
||||
describe('RIESGO-CACU-02: frontera del contrato DEV', () => {
|
||||
it('conserva todos los campos del ejemplo externo y copia los objetos', () => {
|
||||
const recurso = (v: any) => v.entry[0].resource;
|
||||
|
||||
describe('RIESGO-CACU-02: frontera del contrato FHIR RiskAssessment (DEV)', () => {
|
||||
it('lee el Bundle searchset en la vista de la ficha y no comparte objetos con la entrada', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
salida.riesgo!.horizontes[0].probabilidad = 0;
|
||||
salida.cohorte!.c = -999;
|
||||
const salida = riesgoPacienteResponse(entrada, '42')!;
|
||||
expect(salida).toEqual(riesgoCacuVista());
|
||||
salida.riesgo.horizontes[0].probabilidad = 0;
|
||||
expect(entrada).toEqual(riesgoCacuEjemplo());
|
||||
});
|
||||
|
||||
it('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
|
||||
const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
it('un Bundle vacío es una paciente sin riesgo confirmado, con o sin `entry`', () => {
|
||||
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0 })).toBeNull();
|
||||
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0, entry: [] })).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])(
|
||||
'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null;
|
||||
expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserva los nulos independientes y el sentinel basal del contrato', () => {
|
||||
it('el horizonte sale del whenPeriod; el inmediato es un periodo de un día', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
entrada.riesgo = null;
|
||||
entrada.cohorte.c = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null });
|
||||
recurso(entrada).prediction = [prediccion(0.02, '2026-06-01', '2026-06-01'), prediccion(0.4, '2026-06-01', '2034-06-01')];
|
||||
expect(riesgoPacienteResponse(entrada)!.riesgo.horizontes.map(h => h.horizonte_anios)).toEqual([0, 8]);
|
||||
});
|
||||
|
||||
it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
|
||||
it('ordena las predicciones por horizonte y admite campos aditivos de FHIR', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
recurso(entrada).prediction.reverse();
|
||||
recurso(entrada).note = [{ text: 'simulado' }];
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(riesgoCacuVista());
|
||||
});
|
||||
|
||||
it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
|
||||
it.each([[undefined], [[]], [[{ url: 'otra', valueString: 'x' }]]])('sin extensión de intervalo no fabrica límites (%j)', ext => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({
|
||||
horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final',
|
||||
}));
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null },
|
||||
{ ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 },
|
||||
])('conserva IC incompletos sin generar límites: %j', limites => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }];
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false);
|
||||
const p = recurso(entrada).prediction[0];
|
||||
if (ext === undefined) delete p.extension; else p.extension = ext;
|
||||
const h = riesgoPacienteResponse(entrada)!.riesgo.horizontes[0];
|
||||
expect([h.ic_bajo, h.ic_alto]).toEqual([null, null]);
|
||||
expect(tieneIntervalo(h)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.estado_lote = 'preliminary';
|
||||
entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }];
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true);
|
||||
recurso(entrada).status = 'preliminary';
|
||||
recurso(entrada).prediction = [prediccion(p, '2026-06-01', '2030-06-01', [p, p])];
|
||||
const salida = riesgoPacienteResponse(entrada)!;
|
||||
expect(salida.riesgo.estado_lote).toBe('preliminary');
|
||||
expect(salida.riesgo.horizontes[0]).toEqual({ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p });
|
||||
expect(tieneIntervalo(salida.riesgo.horizontes[0])).toBe(true);
|
||||
});
|
||||
|
||||
const invalidos: [string, (v: any) => void][] = [
|
||||
['no simulado', v => v.simulado = false],
|
||||
['simulado string', v => v.simulado = 'true'],
|
||||
['sin simulado', v => delete v.simulado],
|
||||
['sin cohorte', v => delete v.cohorte],
|
||||
['sin riesgo', v => delete v.riesgo],
|
||||
['cohorte lista', v => v.cohorte = []],
|
||||
['URL ajena', v => v.cohorte.url = 'otra'],
|
||||
['versión ausente', v => delete v.cohorte.version],
|
||||
['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'],
|
||||
['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'],
|
||||
['basal string', v => v.cohorte.c = '0'],
|
||||
['variable no finita', v => v.cohorte.l = Infinity],
|
||||
['variable omitida', v => delete v.cohorte.r],
|
||||
['pap no textual', v => v.cohorte.pap_0 = 5],
|
||||
['hpv no textual', v => v.cohorte.hpv_0 = false],
|
||||
['lote fraccionario', v => v.riesgo.lote_id = 1.5],
|
||||
['lote string', v => v.riesgo.lote_id = '12'],
|
||||
['modelo omitido', v => delete v.riesgo.modelo_nombre],
|
||||
['versión no textual', v => v.riesgo.modelo_version = 2],
|
||||
['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'],
|
||||
['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'],
|
||||
['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'],
|
||||
['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'],
|
||||
['sin horizontes', v => delete v.riesgo.horizontes],
|
||||
['horizontes nulos', v => v.riesgo.horizontes = null],
|
||||
['horizonte nulo', v => v.riesgo.horizontes[0] = null],
|
||||
['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'],
|
||||
['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN],
|
||||
['horizontes desordenados', v => v.riesgo.horizontes.reverse()],
|
||||
['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1],
|
||||
['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01],
|
||||
['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01],
|
||||
['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'],
|
||||
['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null],
|
||||
['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN],
|
||||
['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'],
|
||||
['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01],
|
||||
['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01],
|
||||
['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'],
|
||||
['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })],
|
||||
['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07],
|
||||
['no es Bundle', v => v.resourceType = 'RiskAssessment'],
|
||||
['Bundle no searchset', v => v.type = 'collection'],
|
||||
['sin total', v => delete v.total],
|
||||
['entry no lista', v => v.entry = {}],
|
||||
['recurso ajeno', v => recurso(v).resourceType = 'Observation'],
|
||||
['no simulado', v => delete recurso(v).meta],
|
||||
['etiqueta ajena', v => recurso(v).meta.tag[0].code = 'real'],
|
||||
['sin id', v => delete recurso(v).id],
|
||||
['estado desconocido', v => recurso(v).status = 'amended'],
|
||||
['estado anulado', v => recurso(v).status = 'entered-in-error'],
|
||||
['otra paciente', v => recurso(v).subject.reference = 'Patient/43'],
|
||||
['sujeto no paciente', v => recurso(v).subject.reference = 'Group/42'],
|
||||
['evaluación sin UTC', v => recurso(v).occurrenceDateTime = '2026-10-01T00:00:00-06:00'],
|
||||
['evaluación fecha imposible', v => recurso(v).occurrenceDateTime = '2026-02-30T00:00:00Z'],
|
||||
['sin modelo', v => delete recurso(v).method],
|
||||
['modelo sin versión', v => delete recurso(v).method.coding[0].version],
|
||||
['sin predicciones', v => recurso(v).prediction = []],
|
||||
['predicción nula', v => recurso(v).prediction[0] = null],
|
||||
['sin desenlace', v => delete recurso(v).prediction[0].outcome],
|
||||
['probabilidad string', v => recurso(v).prediction[0].probabilityDecimal = '0.08'],
|
||||
['probabilidad mayor a uno', v => recurso(v).prediction[0].probabilityDecimal = 1.01],
|
||||
['probabilidad negativa', v => recurso(v).prediction[0].probabilityDecimal = -0.01],
|
||||
['sin periodo', v => delete recurso(v).prediction[0].whenPeriod],
|
||||
['periodo con fecha imposible', v => recurso(v).prediction[0].whenPeriod.end = '2027-02-30'],
|
||||
['periodo invertido', v => recurso(v).prediction[0].whenPeriod.end = '2025-06-01'],
|
||||
['dos fechas índice', v => recurso(v).prediction[1].whenPeriod.start = '2026-07-01'],
|
||||
['horizontes repetidos', v => recurso(v).prediction[1].whenPeriod.end = '2027-06-01'],
|
||||
['IC invertido', v => recurso(v).prediction[0].extension[0].valueRange = { low: { value: 0.12 }, high: { value: 0.05 } }],
|
||||
['IC fuera de probabilidad', v => recurso(v).prediction[0].extension[0].valueRange.high.value = 0.07],
|
||||
['IC string', v => recurso(v).prediction[0].extension[0].valueRange.high.value = '0.12'],
|
||||
];
|
||||
it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => {
|
||||
const entrada = riesgoCacuEjemplo(); mutar(entrada);
|
||||
expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida');
|
||||
expect(() => riesgoPacienteResponse(entrada, '42')).toThrow('Respuesta de riesgo individual DEV inválida');
|
||||
});
|
||||
it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => {
|
||||
expect(() => riesgoPacienteResponse(entrada)).toThrow();
|
||||
|
||||
@@ -1,54 +1,104 @@
|
||||
import { isoDate } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const nullableNumber = (v: unknown) => v === null || finite(v);
|
||||
const nullableText = (v: unknown) => v === null || typeof v === 'string';
|
||||
const text = (v: unknown) => typeof v === 'string';
|
||||
const estado = (v: unknown) => v === 'preliminary' || v === 'final';
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||
const estado = (v: unknown): v is 'preliminary' | 'final' => v === 'preliminary' || v === 'final';
|
||||
const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
|
||||
const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
|
||||
const DAYS_PER_YEAR = 365.25;
|
||||
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
const SIMULATED = 'simulado';
|
||||
|
||||
function utcTimestamp(v: unknown) {
|
||||
function utcTimestamp(v: unknown): v is string {
|
||||
return typeof v === 'string'
|
||||
&& /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v)
|
||||
&& isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v));
|
||||
}
|
||||
|
||||
function cohorteValida(v: unknown) {
|
||||
return v === null || record(v)
|
||||
&& v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice'])
|
||||
&& (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string))
|
||||
&& nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r'])
|
||||
&& nullableText(v['pap_0']) && nullableText(v['hpv_0']);
|
||||
function invalid(): never {
|
||||
throw new Error('Respuesta de riesgo individual DEV inválida');
|
||||
}
|
||||
|
||||
function horizonteValido(v: unknown) {
|
||||
if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false;
|
||||
for (const key of ['ic_bajo', 'ic_alto']) {
|
||||
if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false;
|
||||
/** Years between two ISO dates, to two decimals: a prediction's horizon from its `whenPeriod`. */
|
||||
function years(start: string, end: string): number {
|
||||
const days = (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000;
|
||||
return Math.round(days / DAYS_PER_YEAR * 100) / 100;
|
||||
}
|
||||
|
||||
function interval(prediction: Record<string, unknown>): { ic_bajo: number | null; ic_alto: number | null } {
|
||||
const extensions = prediction['extension'];
|
||||
if (extensions === undefined) return { ic_bajo: null, ic_alto: null };
|
||||
if (!Array.isArray(extensions)) invalid();
|
||||
const found = extensions.find(e => record(e) && e['url'] === INTERVAL);
|
||||
if (found === undefined) return { ic_bajo: null, ic_alto: null };
|
||||
const range = found['valueRange'];
|
||||
const low = record(range) && record(range['low']) ? range['low']['value'] : undefined;
|
||||
const high = record(range) && record(range['high']) ? range['high']['value'] : undefined;
|
||||
if (!probability(low) || !probability(high) || low > high) invalid();
|
||||
return { ic_bajo: low, ic_alto: high };
|
||||
}
|
||||
|
||||
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
|
||||
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
|
||||
const period = prediction['whenPeriod'];
|
||||
if (!record(period) || !isoDate(period['start']) || !isoDate(period['end'])) invalid();
|
||||
const from = period['start'] as string, to = period['end'] as string;
|
||||
if (start !== undefined && from !== start) invalid(); // one index date per patient
|
||||
const h = years(from, to);
|
||||
if (h < 0) invalid();
|
||||
const ic = interval(prediction);
|
||||
const p = prediction['probabilityDecimal'];
|
||||
if (ic.ic_bajo !== null && ic.ic_alto !== null && !(ic.ic_bajo <= p && p <= ic.ic_alto)) invalid();
|
||||
return { horizonte: { horizonte_anios: h, probabilidad: p, ...ic }, start: from };
|
||||
}
|
||||
|
||||
function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
|
||||
if (!record(v) || v['resourceType'] !== 'RiskAssessment' || !text(v['id']) || !estado(v['status'])
|
||||
|| !utcTimestamp(v['occurrenceDateTime'])) invalid();
|
||||
const subject = v['subject'];
|
||||
if (!record(subject) || !text(subject['reference']) || !subject['reference'].startsWith('Patient/')
|
||||
|| (pacId !== null && subject['reference'] !== `Patient/${pacId}`)) invalid();
|
||||
const method = v['method'];
|
||||
const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined;
|
||||
if (!record(model) || !text(model['code']) || !text(model['version'])) invalid();
|
||||
const predictions = v['prediction'];
|
||||
if (!Array.isArray(predictions) || predictions.length === 0) invalid();
|
||||
let start: string | undefined;
|
||||
const horizontes: HorizonteRiesgoCacu[] = [];
|
||||
for (const prediction of predictions) {
|
||||
const found = horizon(prediction, start);
|
||||
start = found.start;
|
||||
horizontes.push(found.horizonte);
|
||||
}
|
||||
// Missing/null endpoints are preserved. A complete interval must contain the probability.
|
||||
return !(probability(v['ic_bajo']) && probability(v['ic_alto']))
|
||||
|| v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto'];
|
||||
horizontes.sort((a, b) => a.horizonte_anios - b.horizonte_anios);
|
||||
if (horizontes.some((h, i) => i > 0 && horizontes[i - 1].horizonte_anios === h.horizonte_anios)) invalid();
|
||||
const outcome = record(predictions[0]) && record(predictions[0]['outcome']) && Array.isArray(predictions[0]['outcome']['coding'])
|
||||
? predictions[0]['outcome']['coding'][0] : undefined;
|
||||
if (!record(outcome) || !text(outcome['code'])) invalid();
|
||||
return {
|
||||
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
|
||||
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
|
||||
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
|
||||
horizontes,
|
||||
};
|
||||
}
|
||||
|
||||
function riesgoValido(v: unknown) {
|
||||
if (v === null) return true;
|
||||
if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version'])
|
||||
|| !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false;
|
||||
const horizontes = v['horizontes'];
|
||||
return horizontes.every(horizonteValido)
|
||||
&& horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']);
|
||||
function simulated(resource: Record<string, unknown>): boolean {
|
||||
const meta = resource['meta'];
|
||||
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED);
|
||||
}
|
||||
|
||||
/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */
|
||||
export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu {
|
||||
if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) {
|
||||
throw new Error('Respuesta de riesgo individual DEV inválida');
|
||||
}
|
||||
return structuredClone(v) as unknown as RiesgoPacienteCacu;
|
||||
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only).
|
||||
* `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */
|
||||
export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null {
|
||||
if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid();
|
||||
const entries = v['entry'] ?? [];
|
||||
if (!Array.isArray(entries)) invalid();
|
||||
if (entries.length === 0) return null;
|
||||
const resource = record(entries[0]) ? entries[0]['resource'] : undefined;
|
||||
if (!record(resource) || !simulated(resource)) invalid();
|
||||
return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) };
|
||||
}
|
||||
|
||||
/** Presentation helper: an incomplete interval must never become a fabricated range. */
|
||||
|
||||
@@ -72,7 +72,13 @@ describe('Tabla de seguimiento con pac_id', () => {
|
||||
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
// Opening a CaMa record asks for the patient's risk; in these tests nobody has one.
|
||||
afterEach(() => {
|
||||
http.match(r => r.url === '/cama/fhir/RiskAssessment').forEach(r => { if (!r.cancelled) r.flush({ resourceType: 'Bundle', type: 'searchset', total: 0 }); });
|
||||
// The record asks for the two analyses of the patient (survival's menu and recurrence's); there is no model for them here.
|
||||
http.match(r => r.url.startsWith('/cama/modelo/')).forEach(r => { if (!r.cancelled) r.flush({ error: 'sin modelo' }, { status: 404, statusText: 'Not Found' }); });
|
||||
fixture.destroy(); http.verify();
|
||||
});
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const cargar = (respuesta: Record<string, any>) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); };
|
||||
const enlaces = () => [...root().querySelectorAll<HTMLButtonElement>('tbody button.patient-link')];
|
||||
|
||||
@@ -147,7 +147,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR
|
||||
}),
|
||||
};
|
||||
}
|
||||
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true };
|
||||
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true, escenario_clinico: true };
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class SeguimientoTablaService {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
|
||||
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacion[a.clasificacion] }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
|
||||
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacionDe(a) }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
|
||||
</div>
|
||||
@for (dom of a.dominios; track dom.codigo) {
|
||||
<div class="dominio">
|
||||
@@ -37,39 +37,45 @@
|
||||
</section>
|
||||
|
||||
<section class="panel calidad" aria-label="Calidad del EEG">
|
||||
<h3>Calidad del EEG @if (d.eeg) { <span class="mock">Datos de ejemplo</span> }</h3>
|
||||
<h3>Calidad del EEG</h3>
|
||||
@if (d.eeg; as e) {
|
||||
<p class="meta">{{ e.fecha }} · {{ e.duracion_min }} min · {{ e.canales }} canales</p>
|
||||
<p class="meta">{{ e.fecha }}@if (e.duracion_min !== null) { · {{ e.duracion_min }} min }@if (e.canales !== null) { · {{ e.canales }} canales }</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
|
||||
<small>La calificación general es la peor de sus criterios.</small>
|
||||
<small>{{ e.calidad === 'sin_analizar' ? 'El análisis del EEG aún no lo revisa.' : 'Veredicto del análisis del EEG, según las reglas siguientes.' }}</small>
|
||||
</div>
|
||||
<dl>
|
||||
@for (c of e.criterios_calidad; track c.codigo) {
|
||||
<dt>{{ c.etiqueta }}</dt><dd [attr.data-calidad]="c.nivel">{{ c.valor }} {{ c.unidad === 'canales' ? 'de ' + e.canales : c.unidad }}</dd>
|
||||
@for (c of delEstudio(e); track c.codigo) {
|
||||
<dt>{{ c.etiqueta }}@if (c.decisivo) {<small> (decisiva)</small>}</dt><dd [attr.data-calidad]="c.nivel">{{ valorDe(c) }}</dd>
|
||||
}
|
||||
</dl>
|
||||
@if (canalesMalos(e).length) {
|
||||
<p class="efectos-titulo">Canales descartados</p>
|
||||
<ul class="canales-malos">
|
||||
@for (c of canalesMalos(e); track $index) { <li><strong>{{ c.electrodo }}</strong> · {{ c.etiqueta }}</li> }
|
||||
</ul>
|
||||
}
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
|
||||
@if (d.eeg; as e) {
|
||||
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
|
||||
<div class="alteraciones-zona" [class.abierta]="abierto(e)">
|
||||
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
|
||||
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
|
||||
<p class="meta">Referencia neurotípica para {{ d.grupo_edad }} y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p>
|
||||
<p class="meta">Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<ul class="metricas">
|
||||
@for (m of e.alteraciones; track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado">
|
||||
<div class="metrica">
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === m.codigo"
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : abierto(e) && mapaElegido === m.codigo"
|
||||
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
|
||||
<span class="estado">{{ estado[m.estado] }}</span>
|
||||
</div>
|
||||
@if (m.valor !== null) {
|
||||
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p>
|
||||
@if (m.referencia; as r) {
|
||||
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ r.min }}–{{ r.max }}@if (r.mediana !== null) { (mediana {{ r.mediana }}) } · z = {{ m.valor_z }}</p>
|
||||
} @else {
|
||||
<p class="valor">Sin registro de sueño en el estudio.</p>
|
||||
<p class="valor">@if (m.valor !== null) { {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</p>
|
||||
}
|
||||
@if (m.efectos.length) {
|
||||
<p class="efectos-titulo">Posibles efectos asociados</p>
|
||||
@@ -82,8 +88,24 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@if (mapaActual(e); as mapa) {
|
||||
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas">
|
||||
@if (abierto(e)) {
|
||||
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
|
||||
@if (mapaActual(e) && normaActual(e)) {
|
||||
<div class="vistas" role="group" aria-label="Qué mostrar">
|
||||
<button type="button" [attr.aria-pressed]="vista === 'zonas'" (click)="verVista('zonas')">Zonas de la cabeza</button>
|
||||
<button type="button" [attr.aria-pressed]="vista === 'norma'" (click)="verVista('norma')">Norma por edad</button>
|
||||
</div>
|
||||
}
|
||||
@if (vista === 'norma' && normaActual(e); as m) {
|
||||
<h3>Norma por edad</h3>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
|
||||
@if (figuraNorma) {
|
||||
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
|
||||
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<p class="leyenda-norma">La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura).
|
||||
El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).</p>
|
||||
} @else if (mapaActual(e); as mapa) {
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
|
||||
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
|
||||
@@ -96,9 +118,54 @@
|
||||
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
|
||||
}
|
||||
</ol>
|
||||
}
|
||||
</section></div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
<section class="panel relacion" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
|
||||
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
|
||||
<p class="meta">Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se
|
||||
asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2.
|
||||
No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}</p>
|
||||
@if (!filasRelacion(rel).length) {
|
||||
<p class="sin-alteraciones">Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara con el ADOS-2 en la cohorte.</p>
|
||||
} @else {
|
||||
<div class="tabla-relacion" role="region" aria-label="Asociaciones por zona" tabindex="0">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Zona del EEG</th><th scope="col">Aspecto del ADOS-2</th><th scope="col">Asociación en la cohorte</th>
|
||||
<th scope="col">Probabilidad para este paciente</th><th scope="col">Lo que muestra su ADOS-2</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
|
||||
<tr [class.alterada]="zonaAlterada(f)">
|
||||
<td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
|
||||
<td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
|
||||
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
|
||||
<td>
|
||||
<span class="prob">{{ porcentaje(f.probabilidad) }} %</span>
|
||||
<span class="barra" aria-hidden="true">
|
||||
<span class="paciente" [style.width.%]="porcentaje(f.probabilidad)"></span>
|
||||
<span class="referencia" [style.left.%]="porcentaje(f.probabilidad_referencia)"></span>
|
||||
</span>
|
||||
<small>{{ f.evento }} · con z = 0: {{ porcentaje(f.probabilidad_referencia) }} %</small>
|
||||
</td>
|
||||
<td>{{ observado(f) }}@if (coincide(f) !== null) { <small>{{ coincide(f) ? 'Coincide con lo que el modelo esperaba' : 'No coincide con lo que el modelo esperaba' }}</small> }</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="nota">OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La
|
||||
probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0.
|
||||
Solo se muestran las zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
:host { display: block; container-type: inline-size; }
|
||||
:host { display: block; container: host / inline-size; }
|
||||
.resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; }
|
||||
.panel { min-width: 0; padding: .75rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); }
|
||||
h3 { margin: 0 0 .15rem; font-size: 1rem; }
|
||||
@@ -9,7 +9,7 @@ h3 { margin: 0 0 .15rem; font-size: 1rem; }
|
||||
border: 2px solid var(--issste-border); border-radius: var(--issste-radius); font-size: 1.1rem; font-weight: 700; }
|
||||
.css small { margin: 0; font-size: .7rem; font-weight: 400; }
|
||||
.css[data-nivel=alto], .css[data-calidad=malo] { border-color: #B3261E; color: #B3261E; }
|
||||
.css[data-nivel=moderado], .css[data-calidad=aceptable] { border-color: #B26A00; color: #B26A00; }
|
||||
.css[data-nivel=moderado], .css[data-calidad=sin_analizar] { border-color: #B26A00; color: #B26A00; }
|
||||
.css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=bueno] { border-color: var(--issste-accent); }
|
||||
.css[data-calidad] { flex: none; white-space: nowrap; }
|
||||
dd[data-calidad=malo] { color: #B3261E; }
|
||||
@@ -23,7 +23,6 @@ button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outl
|
||||
.leyenda-mapa span { width: .8rem; height: .8rem; border-radius: 2px; }
|
||||
.leyenda-mapa .azul { background: #2166AC; }
|
||||
.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; }
|
||||
dd[data-calidad=aceptable] { color: #B26A00; }
|
||||
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; }
|
||||
.bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; }
|
||||
.bar span { display: block; height: 100%; background: var(--issste-text); }
|
||||
@@ -56,7 +55,7 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re
|
||||
.mapa h3 { margin-top: 0; }
|
||||
@keyframes aparecer { from { opacity: 0; } }
|
||||
@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } }
|
||||
@container zona (max-width: 42rem) { .mapa { width: 100cqw; } }
|
||||
@container host (max-width: 42rem) { .mapa { width: 100cqw; } }
|
||||
@container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } }
|
||||
@media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } }
|
||||
.metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; }
|
||||
@@ -72,3 +71,26 @@ li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font
|
||||
.efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; }
|
||||
.efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .8rem; }
|
||||
button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; }
|
||||
|
||||
.canales-malos { margin: .25rem 0 0; padding-inline-start: 1.1rem; font-size: .85rem; }
|
||||
|
||||
// Relation with the ADOS-2 (association model): full width, a scrollable table on narrow screens.
|
||||
.relacion { grid-column: 1 / -1; }
|
||||
.tabla-relacion { overflow-x: auto; }
|
||||
.tabla-relacion table { width: 100%; min-width: 44rem; border-collapse: collapse; font-size: .85rem; }
|
||||
.tabla-relacion th, .tabla-relacion td { padding: .45rem .5rem; border-top: 1px solid var(--issste-border); text-align: start; vertical-align: top; }
|
||||
.tabla-relacion thead th { font-size: .8rem; color: var(--issste-text-secondary); font-weight: 600; }
|
||||
.tabla-relacion small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); font-size: .75rem; }
|
||||
.tabla-relacion tr.alterada td:first-child { box-shadow: inset 4px 0 0 #B3261E; }
|
||||
.tabla-relacion .marca { color: #B3261E; font-weight: 600; }
|
||||
.or, .prob { font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.barra { position: relative; display: block; height: .45rem; margin-top: .25rem; border-radius: 999px; background: var(--issste-border); }
|
||||
.barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); }
|
||||
.barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); }
|
||||
.nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); }
|
||||
// The switch between the head map and the age norm, when the metric has both.
|
||||
.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; }
|
||||
.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; }
|
||||
.vistas button + button { border-inline-start: 1px solid var(--issste-border); }
|
||||
.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; }
|
||||
.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); }
|
||||
|
||||
@@ -2,12 +2,17 @@ import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaEegMapa, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import {
|
||||
CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle,
|
||||
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
|
||||
} from './tea-seguimiento.service';
|
||||
|
||||
// A zone counts as altered from |z| ≥ 2, as the alteration cards do.
|
||||
const Z_ALTERADO = 2;
|
||||
|
||||
const CLASIFICACION: Record<TeaAdos2['clasificacion'], string> = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' };
|
||||
// ADOS-2 calibrated severity score ranges.
|
||||
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
|
||||
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Bueno', aceptable: 'Aceptable', malo: 'Malo' };
|
||||
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Válido', malo: 'No válido', sin_analizar: 'Sin analizar' };
|
||||
const ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' };
|
||||
const INK = '#081839';
|
||||
|
||||
@@ -43,6 +48,36 @@ export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): Pl
|
||||
};
|
||||
}
|
||||
|
||||
// The age norm around the patient: the 5–95 and 25–75 percentile bands, the median line and the patient as a point.
|
||||
const BANDA_EXTERIOR = 'rgba(49,130,189,.16)', BANDA_INTERIOR = 'rgba(49,130,189,.32)', MEDIANA = '#2C6FA6', ALTERADO = '#B3261E';
|
||||
export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure {
|
||||
const c = m.curva_referencia!, x = c.edad_meses, atras = [...x].reverse();
|
||||
const banda = (bajo: number[], alto: number[], color: string, nombre: string) => ({
|
||||
type: 'scatter', mode: 'lines', x: [...x, ...atras], y: [...alto, ...[...bajo].reverse()], fill: 'toself', fillcolor: color,
|
||||
line: { width: 0 }, name: nombre, hoverinfo: 'skip',
|
||||
});
|
||||
const unidad = m.unidad ? ` ${m.unidad}` : '';
|
||||
const alterado = m.estado === 'aumentado' || m.estado === 'disminuido';
|
||||
return {
|
||||
data: [
|
||||
banda(c.p5, c.p95, BANDA_EXTERIOR, 'Del 5 al 95 %'),
|
||||
banda(c.p25, c.p75, BANDA_INTERIOR, 'Del 25 al 75 %'),
|
||||
{ type: 'scatter', mode: 'lines', x, y: c.mediana, name: 'Mediana', line: { color: MEDIANA, width: 2 },
|
||||
hovertemplate: `%{x} meses: mediana %{y:.2f}${unidad}<extra></extra>` },
|
||||
{ type: 'scatter', mode: 'markers', x: [edad], y: [m.valor], name: 'Este paciente',
|
||||
marker: { size: 11, color: alterado ? ALTERADO : INK, line: { color: '#FFFFFF', width: 2 } },
|
||||
hovertemplate: `Este paciente: %{y:.2f}${unidad} a los %{x:.1f} meses (z = ${m.valor_z})<extra></extra>` },
|
||||
],
|
||||
layout: {
|
||||
margin: { l: 52, r: 12, t: 8, b: 44 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
|
||||
showlegend: true, legend: { orientation: 'h', y: -0.28, font: { size: 11 } }, font: { color: INK },
|
||||
xaxis: { title: { text: 'Edad (meses)' }, range: [x[0], x[x.length - 1]], dtick: 6, gridcolor: 'rgba(8,24,57,.08)', fixedrange: true },
|
||||
yaxis: { title: { text: m.unidad || m.etiqueta }, gridcolor: 'rgba(8,24,57,.08)', zeroline: false, fixedrange: true },
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-tea-paciente-resumen',
|
||||
imports: [PlotlyChart],
|
||||
@@ -56,7 +91,7 @@ export class TeaPacienteResumen implements OnInit {
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
|
||||
figura?: PlotlyFigure;
|
||||
private mapaElegido?: string;
|
||||
mapaElegido?: string;
|
||||
private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
// The first solid background around this component: the map has no box of its own.
|
||||
private fondo() {
|
||||
@@ -66,14 +101,30 @@ export class TeaPacienteResumen implements OnInit {
|
||||
}
|
||||
return '#FFFFFF';
|
||||
}
|
||||
// The side panel shows the chosen metric's head map, its age norm, or both with a switch between them.
|
||||
vista: 'zonas' | 'norma' = 'zonas';
|
||||
figuraNorma?: PlotlyFigure;
|
||||
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
|
||||
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||||
// The chosen card closes the map again, and the cards take the whole space back.
|
||||
const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo);
|
||||
this.mapaElegido = mapa?.codigo;
|
||||
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||
// The age norm can only be drawn with the curve, the patient's value and their age.
|
||||
private conNorma(eeg: TeaEeg, codigo?: string) {
|
||||
const m = eeg.alteraciones.find(a => a.codigo === codigo);
|
||||
return m && m.curva_referencia && m.valor !== null && typeof eeg.edad_meses === 'number' ? m : undefined;
|
||||
}
|
||||
readonly clasificacion = CLASIFICACION;
|
||||
normaActual(eeg: TeaEeg) { return this.conNorma(eeg, this.mapaElegido); }
|
||||
abierto(eeg: TeaEeg) { return !!this.mapaActual(eeg) || !!this.normaActual(eeg); }
|
||||
private mostrar(eeg: TeaEeg, codigo: string | undefined) {
|
||||
const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo);
|
||||
this.mapaElegido = mapa || norma ? codigo : undefined;
|
||||
this.vista = mapa ? 'zonas' : 'norma';
|
||||
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||
this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number);
|
||||
}
|
||||
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||||
// The chosen card closes the panel again, and the cards take the whole space back.
|
||||
this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo);
|
||||
}
|
||||
verVista(vista: 'zonas' | 'norma') { this.vista = vista; }
|
||||
readonly clasificacion = CLASIFICACIONES_ADOS2;
|
||||
readonly nivelCss = NIVEL_CSS;
|
||||
readonly calidad = CALIDAD;
|
||||
readonly estado = ESTADO;
|
||||
@@ -82,15 +133,48 @@ export class TeaPacienteResumen implements OnInit {
|
||||
this.status.set('loading');
|
||||
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: d => {
|
||||
// Opens on the first altered metric, or on the first one if none is altered.
|
||||
const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0];
|
||||
this.mapaElegido = inicial?.codigo;
|
||||
this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined;
|
||||
// Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered.
|
||||
const e = d.eeg;
|
||||
if (e) {
|
||||
const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo));
|
||||
this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo);
|
||||
} else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; }
|
||||
this.detalle.set(d); this.status.set('ready');
|
||||
},
|
||||
error: () => this.status.set('error'),
|
||||
});
|
||||
}
|
||||
// The study-wide checks, then each bad channel.
|
||||
delEstudio(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo === null); }
|
||||
canalesMalos(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo !== null); }
|
||||
valorDe(c: TeaCriterioCalidad) {
|
||||
return c.valor === null ? '' : typeof c.valor === 'number' ? `${Math.round(c.valor * 100) / 100}${c.unidad ? ' ' + c.unidad : ''}` : c.valor;
|
||||
}
|
||||
// Why a metric couldn't be evaluated, in the reader's terms.
|
||||
sinEvaluar(m: TeaEegAlteracion) {
|
||||
return m.sin_evaluar === 'sin_valor' ? 'No se pudo medir en el estudio.' : 'Sin referencia para la edad del niño.';
|
||||
}
|
||||
clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; }
|
||||
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); }
|
||||
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
|
||||
|
||||
// Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first.
|
||||
zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; }
|
||||
filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); }
|
||||
direccion(f: TeaRelacionAdos2) {
|
||||
return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad';
|
||||
}
|
||||
porcentaje(p: number) { return Math.round(100 * p); }
|
||||
qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; }
|
||||
observado(f: TeaRelacionAdos2) {
|
||||
if (f.observado === null) return 'Sin dato';
|
||||
if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)';
|
||||
return `CSS ${f.observado}`;
|
||||
}
|
||||
// Whether what the patient shows matches what the model leans to (above or below one half).
|
||||
coincide(f: TeaRelacionAdos2) {
|
||||
if (f.observado === null) return null;
|
||||
const presente = f.tipo === 'item' ? f.observado >= 1 : f.observado >= 8;
|
||||
return presente === (f.probabilidad >= .5);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { forkJoin, map, Observable, of, shareReplay } from 'rxjs';
|
||||
import { Bundle, code, codeIn, Concept, display, extension, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
|
||||
import { Bundle, code, codeIn, Concept, display, extension, extensions, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
|
||||
import { estratoValor } from './indicadores-fhir';
|
||||
import { SeguimientoQuery } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import {
|
||||
RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad,
|
||||
teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
|
||||
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad,
|
||||
TeaCurvaReferencia, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaRelacionAdos2,
|
||||
TeaRelacionModelo, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
|
||||
} from './tea-seguimiento.service';
|
||||
|
||||
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
|
||||
@@ -19,15 +20,19 @@ interface Observation extends Resource {
|
||||
valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept;
|
||||
interpretation?: Concept[]; dataAbsentReason?: Concept;
|
||||
referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[];
|
||||
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
|
||||
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueBoolean?: boolean; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
|
||||
}
|
||||
interface Report extends Resource {
|
||||
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
|
||||
}
|
||||
interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] }
|
||||
interface Prediction { outcome?: Concept; probabilityDecimal?: number; extension?: Resource['extension'] }
|
||||
|
||||
const MAX_COUNT = 200;
|
||||
const METRICAS = 'tea-eeg-metrica';
|
||||
// The EEG analysis's quality checks, under the code system of its own validation report.
|
||||
const CRITERIOS = 'urn:tea:validation';
|
||||
const FILTRO_EEG: Record<string, string> = { sin_eeg_valido: 'sin-eeg-valido' };
|
||||
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { H: 'aumentado', L: 'disminuido', N: 'normal' };
|
||||
|
||||
// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average.
|
||||
@@ -77,10 +82,16 @@ export function mapaDeElectrodos(codigo: string, etiqueta: string, valores: Reco
|
||||
return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones };
|
||||
}
|
||||
|
||||
// The module as the page writes it: `MODULO_1` is 1, the toddler module is T.
|
||||
function moduloAdos2(codigo: string | undefined): string | undefined {
|
||||
const modulo = codigo?.replace(/^ados2\.modulo\./, '');
|
||||
return modulo === 'TODDLER' ? 'T' : modulo?.replace(/^MODULO_/, '');
|
||||
}
|
||||
|
||||
export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null {
|
||||
const css = component(o, 'ados2.css')?.valueInteger;
|
||||
if (!o?.effectiveDateTime || typeof css !== 'number') return null;
|
||||
const modulo = code(component(o, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '') ?? '';
|
||||
const modulo = moduloAdos2(code(component(o, 'ados2.modulo')?.valueCodeableConcept)) ?? '';
|
||||
const clasificacion = code(component(o, 'ados2.clasificacion')?.valueCodeableConcept)?.replace('ados2.clasificacion.', '').toLowerCase();
|
||||
const items = (o.component ?? []).filter(c => extension(c, 'dominio'));
|
||||
const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => {
|
||||
@@ -96,25 +107,56 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
|
||||
return {
|
||||
fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '',
|
||||
dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0),
|
||||
clasificacion: (clasificacion ?? 'no_espectro') as TeaAdos2['clasificacion'], css,
|
||||
clasificacion: clasificacion && Object.hasOwn(CLASIFICACIONES_ADOS2, clasificacion) ? clasificacion as TeaAdos2['clasificacion'] : null, css,
|
||||
nivel_css: (RANGOS_CSS.find(r => css >= r.min && css <= r.max)?.codigo ?? 'minimo') as TeaAdos2['nivel_css'],
|
||||
};
|
||||
}
|
||||
|
||||
// The age norm a metric observation carries: one sub-extension per point, read back in order, because a FHIR
|
||||
// extension holds scalars, not arrays.
|
||||
function curvaDe(o: Observation): TeaCurvaReferencia | null {
|
||||
const curva = extension(o, 'curva-referencia');
|
||||
if (!curva) return null;
|
||||
const serie = (nombre: string) => extensions(curva, nombre).map(e => e.valueDecimal).filter((v): v is number => typeof v === 'number');
|
||||
return {
|
||||
fuente: extension(curva, 'fuente')?.valueString ?? '', estado: extension(curva, 'estado')?.valueString ?? '',
|
||||
edad_meses: serie('edad-meses'), p5: serie('p5'), p25: serie('p25'), mediana: serie('mediana'), p75: serie('p75'), p95: serie('p95'),
|
||||
};
|
||||
}
|
||||
|
||||
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
|
||||
// cover the child's age (or none is in production yet).
|
||||
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
const codigo = code(o.code) ?? '';
|
||||
const metrica = metricas.find(m => m.code === codigo);
|
||||
const evaluable = !o.dataAbsentReason && typeof o.valueQuantity?.value === 'number';
|
||||
const valor = o.valueQuantity?.value ?? null;
|
||||
const z = component(o, 'z')?.valueQuantity?.value;
|
||||
const evaluable = valor !== null && typeof z === 'number';
|
||||
const estado = evaluable ? INTERPRETACION[code(o.interpretation?.[0]) ?? ''] ?? 'normal' : 'no_evaluable';
|
||||
const range = o.referenceRange?.[0];
|
||||
const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value;
|
||||
const referencia = typeof low === 'number' && typeof high === 'number'
|
||||
? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null;
|
||||
const curva = evaluable ? curvaDe(o) : null;
|
||||
return {
|
||||
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
|
||||
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
|
||||
referencia: { min: range?.low?.value ?? 0, max: range?.high?.value ?? 0 },
|
||||
valor: evaluable ? o.valueQuantity!.value! : null,
|
||||
valor_z: evaluable ? component(o, 'z')?.valueQuantity?.value ?? null : null,
|
||||
estado,
|
||||
referencia: evaluable ? referencia : null,
|
||||
valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
|
||||
sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
|
||||
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
|
||||
...(curva ? { curva_referencia: curva } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// One quality check as the EEG analysis reports it: its value or reason, A/N, the bad channel's electrode, whether it
|
||||
// alone invalidates the EEG.
|
||||
function criterio(o: Observation): TeaCriterioCalidad {
|
||||
const parte = (nombre: string) => o.component?.find(c => c.code?.text === nombre);
|
||||
return {
|
||||
codigo: codeIn(o.code, CRITERIOS)!, etiqueta: display(o.code) ?? codeIn(o.code, CRITERIOS)!,
|
||||
valor: o.valueQuantity?.value ?? o.valueString ?? null, unidad: o.valueQuantity?.unit ?? '',
|
||||
nivel: code(o.interpretation?.[0]) === 'A' ? 'malo' : 'bueno',
|
||||
electrodo: parte('electrode')?.valueString ?? null, decisivo: parte('decisive')?.valueBoolean === true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -123,8 +165,11 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
if (!report?.effectiveDateTime) return null;
|
||||
const ids = new Set((report.result ?? []).map(r => referenceId(r)));
|
||||
const listed = observations.filter(o => ids.has(o.id));
|
||||
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'MALO').toLowerCase() as TeaNivelCalidad;
|
||||
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS)).map(o => alteracion(o, metricas));
|
||||
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
|
||||
const duracion = extension(report, 'duracion-min')?.valueDecimal;
|
||||
const edad = extension(report, 'edad-meses')?.valueDecimal;
|
||||
// The report lists each metric's electrode map under the same code too; it feeds the maps, not the cards.
|
||||
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS) && !o.id?.startsWith('electrodos-')).map(o => alteracion(o, metricas));
|
||||
// A metric's electrode values are `electrodos-<the metric observation's id>`.
|
||||
const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length)))
|
||||
.map(o => {
|
||||
@@ -135,19 +180,44 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
.filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable'));
|
||||
return {
|
||||
fecha: report.effectiveDateTime.slice(0, 10),
|
||||
duracion_min: Math.round(extension(report, 'duracion-min')?.valueDecimal ?? 0),
|
||||
canales: extension(report, 'canales')?.valueInteger ?? 0,
|
||||
duracion_min: duracion === undefined ? null : Math.round(duracion),
|
||||
canales: extension(report, 'canales')?.valueInteger ?? null,
|
||||
...(typeof edad === 'number' ? { edad_meses: edad } : {}),
|
||||
calidad: calidad(report.conclusionCode?.[0]),
|
||||
criterios_calidad: listed.filter(o => code(o.code)?.startsWith('eeg.calidad_')).map(o => ({
|
||||
codigo: code(o.code)!.replace('eeg.calidad_', ''), etiqueta: display(o.code) ?? '',
|
||||
valor: o.valueInteger ?? o.valueQuantity?.value ?? 0, unidad: typeof o.valueInteger === 'number' ? 'canales' : o.valueQuantity?.unit ?? '',
|
||||
nivel: calidad(o.interpretation?.[0]),
|
||||
})),
|
||||
criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
|
||||
alteraciones, mapas,
|
||||
ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) },
|
||||
};
|
||||
}
|
||||
|
||||
// The ADOS-2 association model: one `RiskAssessment`, a prediction per association row with the patient's z and
|
||||
// probabilities. A row missing a number the panel needs is left out; without rows there is no panel.
|
||||
export function relacionDeRiesgo(riesgo: Resource | undefined): TeaRelacionModelo | null {
|
||||
if (!riesgo) return null;
|
||||
const nivel = extension(riesgo, 'modelo-nivel')?.valueString;
|
||||
const filas = ((riesgo['prediction'] ?? []) as Prediction[]).map((p): TeaRelacionAdos2 | null => {
|
||||
const numero = (nombre: string) => extension(p, nombre)?.valueDecimal;
|
||||
const biomarcador = extension(p, 'biomarcador')?.valueCoding, zona = extension(p, 'zona')?.valueCoding;
|
||||
const tipo = extension(p, 'tipo')?.valueString, evento = extension(p, 'evento')?.valueString;
|
||||
const valores = [numero('valor-z'), numero('odds-ratio'), numero('ic-inf'), numero('ic-sup'), numero('q'), p.probabilityDecimal,
|
||||
numero('probabilidad-referencia')];
|
||||
if (!biomarcador?.code || !zona?.code || (tipo !== 'item' && tipo !== 'dominio') || !evento || !code(p.outcome)
|
||||
|| !valores.every(v => typeof v === 'number')) return null;
|
||||
const [valor_z, or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia] = valores as number[];
|
||||
return {
|
||||
biomarcador: biomarcador.display ?? biomarcador.code, zona: zona.code, zona_etiqueta: zona.display ?? zona.code, valor_z,
|
||||
tipo, resultado: code(p.outcome)!, resultado_etiqueta: display(p.outcome) ?? code(p.outcome)!, evento,
|
||||
or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia, observado: extension(p, 'observado')?.valueInteger ?? null,
|
||||
};
|
||||
}).filter((f): f is TeaRelacionAdos2 => f !== null);
|
||||
if ((nivel !== 'item' && nivel !== 'dominio') || !filas.length) return null;
|
||||
return {
|
||||
validado: extension(riesgo, 'modelo-validado')?.valueBoolean === true, nivel,
|
||||
n_cohorte: extension(riesgo, 'modelo-n-cohorte')?.valueInteger ?? 0,
|
||||
version: extension(riesgo, 'modelo-version')?.valueString ?? '', filas,
|
||||
};
|
||||
}
|
||||
|
||||
function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null {
|
||||
if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null;
|
||||
return alteracionesDe(report, observations).length ? 'anormal' : 'normal';
|
||||
@@ -166,7 +236,7 @@ export function pacienteDeEpisodio(episode: Resource, included: Resource[], vali
|
||||
const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined;
|
||||
const ados2 = byCode(observations, 'ados2');
|
||||
const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined;
|
||||
const modulo = code(component(ados2, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '');
|
||||
const modulo = moduloAdos2(code(component(ados2, 'ados2.modulo')?.valueCodeableConcept));
|
||||
return {
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
@@ -221,7 +291,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
const corte = query.corte ?? isoDay(this.today());
|
||||
const { desde, hasta } = ventana(corte, query.meses);
|
||||
let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta);
|
||||
if (query.estatus) params = params.set('resultado-eeg', query.estatus);
|
||||
if (query.estatus) params = params.set('resultado-eeg', FILTRO_EEG[query.estatus] ?? query.estatus);
|
||||
if (query.grupo_edad) params = params.set('grupo-edad', grupoCodigo(query.grupo_edad));
|
||||
const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css);
|
||||
if (mchat) params = params.append('mchat', 'ge' + mchat.min).append('mchat', 'le' + mchat.max);
|
||||
@@ -248,6 +318,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)),
|
||||
tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [],
|
||||
resumen_eeg: {
|
||||
validadas, con_eeg_valido: validadas ? parameter(resumen, 'normales') + parameter(resumen, 'anormales') : parameter(resumen, 'con_eeg_valido'),
|
||||
normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'),
|
||||
por_alteracion: porAlteracion(resumen, metricas),
|
||||
},
|
||||
@@ -261,14 +332,15 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
}).pipe(map(({ bundle, metricas }) => {
|
||||
const all = resources(bundle);
|
||||
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
|
||||
const metric = observations.find(o => codeIn(o.code, METRICAS) && o.referenceRange?.[0]?.text);
|
||||
const edad = metric?.referenceRange?.[0]?.text?.split(': ').pop();
|
||||
const episode = resources(bundle, 'EpisodeOfCare')[0];
|
||||
const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]);
|
||||
return teaPacienteDetalle({
|
||||
simulado: all.length > 0 && all.every(isSimulated),
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(edad),
|
||||
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
|
||||
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
|
||||
...(relacion ? { relacion_ados2: relacion } : {}),
|
||||
}, id);
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@ import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
|
||||
export type AlteracionesEeg = 'normal' | 'anormal';
|
||||
// The EEG filter: by alteration once the domain expert has validated them, otherwise only by a valid EEG or none.
|
||||
export type AlteracionesEeg = 'normal' | 'anormal' | 'valido' | 'sin_eeg_valido';
|
||||
export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo';
|
||||
export interface TeaSeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
@@ -12,7 +13,7 @@ export interface TeaSeguimientoPaciente {
|
||||
ultimo_eeg: string | null;
|
||||
mchat: number | null;
|
||||
css_ados2: number | null;
|
||||
alteraciones_eeg: AlteracionesEeg | null;
|
||||
alteraciones_eeg: 'normal' | 'anormal' | null;
|
||||
modulo_ados2: string | null;
|
||||
estado_caso: EstadoCaso;
|
||||
// What a case in process still lacks.
|
||||
@@ -21,6 +22,9 @@ export interface TeaSeguimientoPaciente {
|
||||
alteraciones: string[];
|
||||
}
|
||||
export interface TeaResumenEeg {
|
||||
// Without validated alterations only the split by a valid EEG is known: `normales`, `anormales` and `por_alteracion`
|
||||
// stay empty.
|
||||
validadas: boolean; con_eeg_valido: number;
|
||||
normales: number; anormales: number; sin_eeg: number;
|
||||
por_alteracion: { codigo: string; etiqueta: string; n: number }[];
|
||||
}
|
||||
@@ -35,28 +39,60 @@ export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: nu
|
||||
export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] }
|
||||
export interface TeaAdos2 {
|
||||
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
|
||||
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||||
clasificacion: ClasificacionAdos2 | null; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||||
}
|
||||
export type ClasificacionAdos2 = 'autismo' | 'espectro_autista' | 'no_espectro' | 'preocupacion_leve_moderada' | 'preocupacion_severa';
|
||||
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
|
||||
// Mock: EEG metrics with placeholder reference ranges and associated effects, pending medical review.
|
||||
export type TeaNivelCalidad = 'bueno' | 'aceptable' | 'malo';
|
||||
// EEG metrics against age baselines and their associated effects, both pending medical validation.
|
||||
export type TeaNivelCalidad = 'bueno' | 'malo' | 'sin_analizar';
|
||||
// One quality check of the EEG analysis: a study-wide rule, or a bad channel with its electrode and reason.
|
||||
export interface TeaCriterioCalidad {
|
||||
codigo: string; etiqueta: string; valor: number | string | null; unidad: string; nivel: 'bueno' | 'malo';
|
||||
electrodo: string | null; decisivo: boolean;
|
||||
}
|
||||
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
|
||||
export interface TeaEegAlteracion {
|
||||
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number };
|
||||
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number; mediana: number | null } | null;
|
||||
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
|
||||
// Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age.
|
||||
sin_evaluar: 'sin_valor' | 'sin_referencia' | null;
|
||||
// The age norm the reference comes from (percentiles by month), when the analysis sends it.
|
||||
curva_referencia?: TeaCurvaReferencia | null;
|
||||
}
|
||||
export interface TeaCurvaReferencia {
|
||||
fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[];
|
||||
}
|
||||
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
|
||||
export interface TeaEeg {
|
||||
fecha: string; duracion_min: number; canales: number;
|
||||
// The overall rating is in words, like Automagic, and is the worst of its criteria, which report numbers.
|
||||
calidad: TeaNivelCalidad; criterios_calidad: { codigo: string; etiqueta: string; valor: number; unidad: string; nivel: TeaNivelCalidad }[];
|
||||
fecha: string; duracion_min: number | null; canales: number | null;
|
||||
// Age at the EEG, to place the patient on the age norms.
|
||||
edad_meses?: number | null;
|
||||
// The overall rating is the EEG analysis's verdict; its checks say why.
|
||||
calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[];
|
||||
alteraciones: TeaEegAlteracion[];
|
||||
// One map per alteration that could be evaluated, on shared axes.
|
||||
mapas: TeaEegMapa[];
|
||||
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
|
||||
}
|
||||
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null }
|
||||
// The association model (OR) of each EEG alteration by zone with an ADOS-2 item or domain, fitted on the cohort; for
|
||||
// this patient, their z, the probability the model gives them and what their ADOS-2 shows. Pending medical validation.
|
||||
export interface TeaRelacionAdos2 {
|
||||
biomarcador: string; zona: string; zona_etiqueta: string; valor_z: number;
|
||||
tipo: 'item' | 'dominio'; resultado: string; resultado_etiqueta: string; evento: string;
|
||||
or: number; ic_inf: number; ic_sup: number; q: number;
|
||||
probabilidad: number; probabilidad_referencia: number; observado: number | null;
|
||||
}
|
||||
export interface TeaRelacionModelo { validado: boolean; nivel: 'item' | 'dominio'; n_cohorte: number; version: string; filas: TeaRelacionAdos2[] }
|
||||
export interface TeaPacienteDetalle {
|
||||
simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null;
|
||||
// Absent until the WebApi serves the model.
|
||||
relacion_ados2?: TeaRelacionModelo | null;
|
||||
}
|
||||
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
|
||||
export const CLASIFICACIONES_ADOS2: Record<ClasificacionAdos2, string> = {
|
||||
autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro',
|
||||
preocupacion_leve_moderada: 'Preocupación leve a moderada', preocupacion_severa: 'Preocupación de moderada a severa',
|
||||
};
|
||||
export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' };
|
||||
export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses'];
|
||||
// M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary.
|
||||
@@ -71,15 +107,22 @@ export const RANGOS_CSS = [
|
||||
{ codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 },
|
||||
{ codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 },
|
||||
];
|
||||
export const ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }];
|
||||
export const ALTERACIONES_EEG: SeguimientoStatus[] = [
|
||||
{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' },
|
||||
];
|
||||
export const EEG_VALIDO: SeguimientoStatus[] = [{ codigo: 'valido', etiqueta: 'Con EEG válido' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' }];
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
|
||||
const filtroEeg = (v: unknown) => v === null || ['normal', 'anormal', 'valido', 'sin_eeg_valido'].includes(v as string);
|
||||
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
|
||||
// ADOS-2 item codes: 0 to 3, and 7 to 9 for an item that doesn't apply or wasn't scored.
|
||||
const CODIGOS_REACTIVO = [0, 1, 2, 3, 7, 8, 9];
|
||||
const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string');
|
||||
function validResumenEeg(r: unknown): boolean {
|
||||
return record(r) && integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
|
||||
return record(r) && typeof r['validadas'] === 'boolean' && integer(r['con_eeg_valido'])
|
||||
&& integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
|
||||
&& r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n']));
|
||||
}
|
||||
export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
|
||||
@@ -88,7 +131,7 @@ export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || !eeg(filters['alteraciones_eeg'])
|
||||
|| !record(filters) || !filtroEeg(filters['alteraciones_eeg'])
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
|
||||
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
|
||||
@@ -106,33 +149,52 @@ const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
|
||||
const text = (v: unknown) => typeof v === 'string' && v.length > 0;
|
||||
function validAdos(a: unknown): boolean {
|
||||
if (a === null) return true;
|
||||
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || !text(a['algoritmo']) || !score(a['css'], 1, 10)
|
||||
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string)
|
||||
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || typeof a['algoritmo'] !== 'string' || !score(a['css'], 1, 10)
|
||||
|| !(a['clasificacion'] === null || Object.hasOwn(CLASIFICACIONES_ADOS2, a['clasificacion'] as string))
|
||||
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
|
||||
// Items score 0–3 (algorithm 0–2); each domain and the total must be the sum of their parts.
|
||||
// Items carry an ADOS-2 code (algorithm 0–2); each domain and the total must be the sum of their parts.
|
||||
const dominios = a['dominios'] as unknown[];
|
||||
const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos'])
|
||||
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && score(r['puntaje'], 0, 3) && score(r['puntaje_algoritmo'], 0, 2))
|
||||
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && CODIGOS_REACTIVO.includes(r['puntaje'] as number) && score(r['puntaje_algoritmo'], 0, 2))
|
||||
&& d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0)
|
||||
&& d['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
|
||||
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
|
||||
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
|
||||
}
|
||||
// A metric without a value cannot be evaluated; one with a value is out of range exactly when it is altered.
|
||||
// An age norm: ages in increasing order and, at each one, percentiles that never cross.
|
||||
const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const;
|
||||
function validCurva(c: unknown): boolean {
|
||||
if (c === undefined || c === null) return true;
|
||||
if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false;
|
||||
const edades = c['edad_meses'] as unknown[], n = edades.length;
|
||||
if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false;
|
||||
const series = PERCENTILES.map(k => c[k]);
|
||||
return series.every(s => Array.isArray(s) && s.length === n && s.every(finite))
|
||||
&& edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i]));
|
||||
}
|
||||
// A metric that can't be evaluated says why and has no z; one that can has its value, z and reference.
|
||||
function validAlteracion(a: unknown): boolean {
|
||||
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !record(a['referencia'])
|
||||
|| !finite(a['referencia']['min']) || !finite(a['referencia']['max']) || (a['referencia']['min'] as number) > (a['referencia']['max'] as number)
|
||||
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false;
|
||||
const ref = a !== null && record(a) ? a['referencia'] : undefined;
|
||||
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string'
|
||||
|| !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number)
|
||||
&& (ref['mediana'] === null || finite(ref['mediana'])))
|
||||
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false;
|
||||
const estado = a['estado'];
|
||||
if (estado === 'no_evaluable') return a['valor'] === null && a['valor_z'] === null;
|
||||
return finite(a['valor']) && finite(a['valor_z']) && ['normal', 'aumentado', 'disminuido'].includes(estado as string);
|
||||
if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string)
|
||||
&& (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null);
|
||||
return finite(a['valor']) && finite(a['valor_z']) && ref !== null && a['sin_evaluar'] === null
|
||||
&& ['normal', 'aumentado', 'disminuido'].includes(estado as string);
|
||||
}
|
||||
function validEeg(e: unknown): boolean {
|
||||
if (e === null) return true;
|
||||
const nivel = (v: unknown) => ['bueno', 'aceptable', 'malo'].includes(v as string);
|
||||
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad'])
|
||||
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad'])
|
||||
&& (c['unidad'] === 'canales' ? integer(c['valor']) && (c['valor'] as number) <= (e['canales'] as number) : finite(c['valor']) && (c['valor'] as number) >= 0))) return false;
|
||||
const optional = (v: unknown) => v === null || integer(v);
|
||||
const edad = record(e) ? e['edad_meses'] : undefined;
|
||||
if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales'])
|
||||
|| !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0)
|
||||
|| !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string)
|
||||
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta'])
|
||||
&& ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean'
|
||||
&& (c['electrodo'] === null || text(c['electrodo'])) && (c['valor'] === null || finite(c['valor']) || text(c['valor'])))) return false;
|
||||
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
|
||||
const ejes = e['ejes_mapa'];
|
||||
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
|
||||
@@ -143,9 +205,21 @@ function validEeg(e: unknown): boolean {
|
||||
&& m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
|
||||
&& Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z'])));
|
||||
}
|
||||
const probability = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 1;
|
||||
function validRelacion(r: unknown): boolean {
|
||||
if (r === undefined || r === null) return true;
|
||||
return record(r) && typeof r['validado'] === 'boolean' && ['item', 'dominio'].includes(r['nivel'] as string)
|
||||
&& integer(r['n_cohorte'], 1) && text(r['version']) && Array.isArray(r['filas'])
|
||||
&& r['filas'].every(f => record(f) && text(f['biomarcador']) && text(f['zona_etiqueta']) && finite(f['valor_z'])
|
||||
&& ['item', 'dominio'].includes(f['tipo'] as string) && text(f['resultado_etiqueta']) && text(f['evento'])
|
||||
&& finite(f['or']) && finite(f['ic_inf']) && finite(f['ic_sup']) && (f['ic_inf'] as number) <= (f['ic_sup'] as number)
|
||||
&& probability(f['q']) && probability(f['probabilidad']) && probability(f['probabilidad_referencia'])
|
||||
&& (f['observado'] === null || finite(f['observado'])));
|
||||
}
|
||||
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']))
|
||||
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])
|
||||
|| !validRelacion(v['relacion_ados2']))
|
||||
throw new Error('Resumen del paciente inválido');
|
||||
return v as unknown as TeaPacienteDetalle;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user