Compare commits
107 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 29d021b347 | |||
| 98e9b60e83 | |||
| 5061350dd8 | |||
| eb887be447 | |||
| 0b22b3c309 | |||
| 6ade415f63 | |||
| 5791928976 | |||
| f4d1829cd3 | |||
| 069cc459a4 | |||
| 881c613744 | |||
| be46429627 | |||
| 25f584c864 | |||
| 561a5dde36 | |||
| bf89099ce8 | |||
| ff1f6758ba | |||
| f38a2c6bb4 | |||
| 40c19a6a1f | |||
| 329c0891ae | |||
| 34c6f2af3a | |||
| 7ab2567dc9 | |||
| 14d6875d9b | |||
| f82ce8cc38 | |||
| 61867ff973 | |||
| 8bca0fbcdf | |||
| ec8542de9f | |||
| 29c9e6853b | |||
| b1ff6cadb2 | |||
| 26285a87fa | |||
| f058f1f476 | |||
| 7f1e43bdc5 | |||
| 5bf6af8ecf | |||
| 253290ed6a | |||
| ec5b8fde6b | |||
| 2a36397fac | |||
| eada50d2ff | |||
| 396902541d | |||
| 68b5e927e7 | |||
| 990cab0e37 | |||
| 39e1e3e094 | |||
| 4e08bb8c4b | |||
| 686580af81 | |||
| 60c71bfc3d | |||
| ad4edbe2a1 | |||
| 1af0c21291 | |||
| dd356efb6b | |||
| 01271621b7 | |||
| b8bf57e235 | |||
| 17cef51d90 | |||
| 7692952ec9 | |||
| feaed5ff0e | |||
| 999bc4ecf5 | |||
| 6ed87ff3d8 | |||
| ff4ad2c964 | |||
| b5f8e5bfc2 | |||
| f04478e600 | |||
| 6a0c3c9e92 | |||
| e3c9849e29 | |||
| 10773edcc1 | |||
| 8b80e1d26c | |||
| 2a48c28245 | |||
| e1a8127c22 | |||
| 6de193f44e | |||
| 0059427179 | |||
| 8192f92be9 | |||
| 1fef7812b4 | |||
| 6465165e34 | |||
| a26df55214 | |||
| 72e5f9bf93 | |||
| 08f1d812ac | |||
| ce207a72a5 | |||
| 5094880622 | |||
| 093ceffa36 | |||
| 6a7c1d0cbd | |||
| fb5a4ed5cc | |||
| e8ce7a487b | |||
| a3a552ad0e | |||
| fb54cfb188 | |||
| 7adceb86bf | |||
| 4e9b25bd8f | |||
| a7b5f4c50b | |||
| 4d159ae0d0 | |||
| 4fba4fa861 | |||
| db4d743413 | |||
| d6c52c8536 | |||
| 1969ffdb5f | |||
| 699d4b13e1 | |||
| c5cbaaab13 | |||
| cc802cbb57 | |||
| e7a6398168 | |||
| 62027f2216 | |||
| 88dc7537c2 | |||
| 0cb9395cd6 | |||
| e74e3d8fd4 | |||
| 0fc80bd29a | |||
| dae8bc517e | |||
| 68e2930e65 | |||
| bb957ec6a4 | |||
| 02e28e624b | |||
| 08161db1c4 | |||
| fa029d69b8 | |||
| 67ae7f482f | |||
| 304c563845 | |||
| efe4404c4e | |||
| 54b3e50ca5 | |||
| 680cc0adc6 | |||
| b53322ed72 | |||
| 7aa3d2c6e6 |
@@ -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()
|
||||
@@ -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>
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia';
|
||||
export type OrdenSeguimiento = 'reciente' | ProbabilidadClave;
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||
export interface SeguimientoPaciente {
|
||||
@@ -9,13 +11,20 @@ export interface SeguimientoPaciente {
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
||||
dias_toma_diagnostico: number | null;
|
||||
/** CaCu: her latest biopsy reported by the cut-off, with its grade. */
|
||||
ultima_biopsia?: { fecha: string; grado: string | null } | null;
|
||||
/** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */
|
||||
probabilidades?: Partial<Record<ProbabilidadClave, ProbabilidadHorizonte[]>> | null;
|
||||
prioridad: SeguimientoStatus | null;
|
||||
}
|
||||
export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; }
|
||||
export interface SeguimientoResponse {
|
||||
simulado: boolean;
|
||||
corte: string;
|
||||
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
||||
filtros: { estatus: string | null };
|
||||
filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number };
|
||||
/** The horizons the models give, in years, for ordering and showing the probabilities. */
|
||||
horizontes_disponibles?: number[];
|
||||
estatus_disponibles: SeguimientoStatus[];
|
||||
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
|
||||
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
||||
@@ -29,3 +38,15 @@ export function isoDate(value: unknown): value is string {
|
||||
export function latestStudy(item: SeguimientoPaciente): string | null {
|
||||
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
|
||||
}
|
||||
/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */
|
||||
export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined {
|
||||
return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte);
|
||||
}
|
||||
/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival).
|
||||
* Every patient or an unknown status shows none: each scenario has its own models. */
|
||||
export const COLUMNAS_DE_PROBABILIDAD: Readonly<Record<string, readonly ProbabilidadClave[]>> = {
|
||||
CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'],
|
||||
};
|
||||
export const ETIQUETA_PROBABILIDAD: Readonly<Record<ProbabilidadClave, string>> = {
|
||||
lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia',
|
||||
};
|
||||
|
||||
@@ -3,11 +3,20 @@ import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||
import { identidadDe, identidadesDe } from './paciente-identidad';
|
||||
import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia'];
|
||||
const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
|
||||
const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
|
||||
// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates.
|
||||
const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string');
|
||||
const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) =>
|
||||
['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad'])
|
||||
&& (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto']))));
|
||||
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= 200;
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX;
|
||||
}
|
||||
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
// The current authorization covers demonstration records only. Validate this
|
||||
@@ -16,15 +25,18 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||
|| (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string))
|
||||
|| (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios)))
|
||||
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']))
|
||||
&& biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']);
|
||||
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as SeguimientoResponse;
|
||||
}
|
||||
@@ -36,6 +48,8 @@ export class CacuSeguimientoService {
|
||||
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
||||
if (query.corte) params = params.set('corte', query.corte);
|
||||
if (query.estatus) params = params.set('estatus', query.estatus);
|
||||
if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden);
|
||||
if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte);
|
||||
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,12 +36,13 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
const root:HTMLElement=fixture.nativeElement;
|
||||
expect(root.textContent).not.toContain('Datos simulados — uso de demostración');
|
||||
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
|
||||
expect(root.querySelector('h2')?.textContent).toBe('Modelos de riesgo asociados a cáncer cervicouterino');
|
||||
expect(root.textContent).toContain('Ventana consultada:');
|
||||
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
|
||||
expect(root.textContent).toContain('Insatisfactoria');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9);
|
||||
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||
@@ -96,4 +97,50 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||
http.expectNone(()=>true);
|
||||
});
|
||||
// Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the
|
||||
// horizon stop reaching the API (the list is paginated, so ordering happens there).
|
||||
it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => {
|
||||
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||
...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' },
|
||||
probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }],
|
||||
cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] },
|
||||
} : item);
|
||||
const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } };
|
||||
open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const fila = root.querySelector('tbody tr')!;
|
||||
expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %');
|
||||
expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)');
|
||||
expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']);
|
||||
|
||||
fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1;
|
||||
fixture.componentInstance.apply();
|
||||
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1');
|
||||
req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges();
|
||||
expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)');
|
||||
});
|
||||
|
||||
// Fails if the columns stop following the status filtered: each scenario has its own models.
|
||||
it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => {
|
||||
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||
...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' },
|
||||
probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item);
|
||||
const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } };
|
||||
open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim());
|
||||
expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)');
|
||||
expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false);
|
||||
expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)');
|
||||
expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']);
|
||||
|
||||
fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia';
|
||||
fixture.componentInstance.apply();
|
||||
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.has('orden')).toBe(false);
|
||||
req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges();
|
||||
expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false);
|
||||
expect(root.querySelector('select[name="orden"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,14 +7,19 @@ const HISTOLOGIA: Readonly<Record<string, string>> = {
|
||||
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
|
||||
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[];
|
||||
}
|
||||
@@ -19,6 +19,7 @@ export interface Resource {
|
||||
}
|
||||
export interface Bundle extends Resource {
|
||||
total?: number;
|
||||
link?: { relation: string; url: string }[];
|
||||
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
|
||||
}
|
||||
|
||||
|
||||
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,
|
||||
@@ -2367,7 +2268,7 @@
|
||||
"grupo": null
|
||||
},
|
||||
"MALO": {
|
||||
"etiqueta": "Malo",
|
||||
"etiqueta": "No aceptable",
|
||||
"color": "#B8433A",
|
||||
"grupo": null
|
||||
},
|
||||
@@ -2402,7 +2303,7 @@
|
||||
"grupo": null
|
||||
},
|
||||
"MALO": {
|
||||
"etiqueta": "Malo",
|
||||
"etiqueta": "No aceptable",
|
||||
"color": "#B8433A",
|
||||
"grupo": null
|
||||
},
|
||||
|
||||
@@ -0,0 +1,835 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "collection",
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "ados2-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2",
|
||||
"display": "ADOS-2"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.modulo",
|
||||
"display": "Módulo"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.modulo.MODULO_2"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.css",
|
||||
"display": "Puntaje de severidad (CSS)"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 8
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.clasificacion",
|
||||
"display": "Clasificación"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.clasificacion.AUTISMO"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||
"code": "SA",
|
||||
"display": "Afecto social"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 10
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||
"code": "RRB",
|
||||
"display": "Comportamiento restringido y repetitivo"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_a4",
|
||||
"display": "Uso estereotipado o idiosincrásico de palabras o frases"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_d2",
|
||||
"display": "Manierismos de manos y dedos y otros manierismos complejos"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_d4",
|
||||
"display": "Intereses inusualmente repetitivos o comportamientos estereotipados"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_a6",
|
||||
"display": "Señalar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_a7",
|
||||
"display": "Señalar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 0,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b1",
|
||||
"display": "Contacto visual inusual"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b12",
|
||||
"display": "Características de las iniciaciones sociales"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b2",
|
||||
"display": "Expresiones faciales dirigidas a otros"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b3",
|
||||
"display": "Expresiones faciales dirigidas a otros"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 0,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b5",
|
||||
"display": "Disfrute compartido durante la interacción"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b6",
|
||||
"display": "Iniciación espontánea de la atención conjunta"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b8",
|
||||
"display": "Características de las iniciaciones sociales"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Procedure",
|
||||
"id": "eeg-vista-previa",
|
||||
"status": "completed",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "eeg",
|
||||
"display": "Electroencefalograma"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"performedDateTime": "1985-01-01",
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "DiagnosticReport",
|
||||
"id": "eeg-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "eeg",
|
||||
"display": "Electroencefalograma"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"result": [
|
||||
{
|
||||
"reference": "Observation/calidad-bad-scalp-triage-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-clean-windows-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-internal-coverage-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-line-noise-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-triage-level-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-usable-scalp-vista-previa"
|
||||
}
|
||||
],
|
||||
"conclusionCode": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/calidad",
|
||||
"code": "MALO"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "not-valid"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/duracion-min",
|
||||
"valueDecimal": 2.0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/edad-meses",
|
||||
"valueDecimal": 30.0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/canales",
|
||||
"valueInteger": 24
|
||||
}
|
||||
],
|
||||
"conclusion": "EEG de mala calidad: no es válido para el estudio (nivel de triaje: no_analizable).",
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-bad-scalp-triage-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "bad-scalp-triage",
|
||||
"display": "bad-scalp-triage"
|
||||
}
|
||||
],
|
||||
"text": "bad-scalp-triage"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 0.0,
|
||||
"unit": "electrodes"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"high": {
|
||||
"value": 2.0,
|
||||
"unit": "electrodes"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-clean-windows-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "clean-windows",
|
||||
"display": "clean-windows"
|
||||
}
|
||||
],
|
||||
"text": "clean-windows"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 100.0,
|
||||
"unit": "%"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 60.0,
|
||||
"unit": "%"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-internal-coverage-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "internal-coverage",
|
||||
"display": "internal-coverage"
|
||||
}
|
||||
],
|
||||
"text": "internal-coverage"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 1.0,
|
||||
"unit": "fraction"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 0.9,
|
||||
"unit": "fraction"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-line-noise-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "line-noise",
|
||||
"display": "line-noise"
|
||||
}
|
||||
],
|
||||
"text": "line-noise"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 9.231034526452635,
|
||||
"unit": "dB"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"high": {
|
||||
"value": 45.0,
|
||||
"unit": "dB"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": false
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-triage-level-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "triage-level",
|
||||
"display": "triage-level"
|
||||
}
|
||||
],
|
||||
"text": "triage-level"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "A"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueString": "no_analizable",
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-usable-scalp-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "usable-scalp",
|
||||
"display": "usable-scalp"
|
||||
}
|
||||
],
|
||||
"text": "usable-scalp"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 19.0,
|
||||
"unit": "electrodes"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 12.0,
|
||||
"unit": "electrodes"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Covers the round "?" help of TEA's cards: hover or focus shows the text, a click keeps it until the next click.
|
||||
// Fixture: a host component that projects one line of text into the button.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
|
||||
@Component({ imports: [IndicadorAyuda], template: `<app-indicador-ayuda etiqueta="Cómo leer: prueba" (opened)="aperturas = aperturas + 1">Texto de ayuda</app-indicador-ayuda>` })
|
||||
class Host { aperturas = 0; }
|
||||
|
||||
describe('Ayuda redonda', () => {
|
||||
function crear() {
|
||||
const fixture = TestBed.createComponent(Host);
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const boton = () => root.querySelector<HTMLButtonElement>('.ayuda-boton')!;
|
||||
const texto = () => root.querySelector('.ayuda-texto')?.textContent?.trim();
|
||||
const ayuda = root.querySelector('.ayuda')!;
|
||||
return { fixture, boton, texto, ayuda };
|
||||
}
|
||||
|
||||
it('muestra el texto al pasar el cursor y lo oculta al salir', () => {
|
||||
// Fails if hovering stops showing the guide or leaving leaves it open when it was not pinned.
|
||||
const { fixture, texto, ayuda } = crear();
|
||||
expect(texto()).toBeUndefined();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseenter')); fixture.detectChanges();
|
||||
expect(texto()).toBe('Texto de ayuda');
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||
expect(texto()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('un clic fija el texto hasta el siguiente clic', () => {
|
||||
// Fails if the click stops pinning the text, if leaving closes a pinned text, or if a second click does not close it.
|
||||
const { fixture, boton, texto, ayuda } = crear();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseenter')); boton().click(); fixture.detectChanges();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||
expect(texto()).toBe('Texto de ayuda');
|
||||
expect(boton().getAttribute('aria-expanded')).toBe('true');
|
||||
boton().click(); fixture.detectChanges();
|
||||
expect(texto()).toBeUndefined();
|
||||
expect(boton().getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
|
||||
it('avisa solo al abrirse con un clic y nombra el botón', () => {
|
||||
// Fails if closing also reports an opening (the metadata would be requested again) or the accessible name is lost.
|
||||
const { fixture, boton } = crear();
|
||||
boton().click(); boton().click(); boton().click(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.aperturas).toBe(2);
|
||||
expect(boton().getAttribute('aria-label')).toBe('Cómo leer: prueba');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Component, input, output, signal } from '@angular/core';
|
||||
|
||||
// Round "?" button at the top right of a card. Hover or focus shows its text; a click keeps it open until the next click.
|
||||
@Component({
|
||||
selector: 'app-indicador-ayuda',
|
||||
template: `
|
||||
<div class="ayuda" (mouseenter)="sobre.set(true)" (mouseleave)="sobre.set(false)" (focusin)="sobre.set(true)" (focusout)="sobre.set(false)">
|
||||
<button type="button" class="ayuda-boton" [attr.aria-label]="etiqueta()" [attr.aria-expanded]="visible()"
|
||||
[attr.aria-controls]="visible() ? idPanel : null" (click)="alternar()"><span aria-hidden="true">?</span></button>
|
||||
@if (visible()) {
|
||||
<div class="ayuda-texto" role="tooltip" [id]="idPanel"><ng-content /></div>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
styles: `
|
||||
:host { position: absolute; top: .5rem; right: .5rem; z-index: 2; }
|
||||
.ayuda { position: relative; }
|
||||
.ayuda-boton { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; padding: 0; border: 0;
|
||||
border-radius: 50%; background: transparent; box-shadow: inset 0 0 0 1.5px var(--issste-text-secondary); color: var(--issste-text); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
|
||||
.ayuda-boton:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.ayuda-texto { position: absolute; top: calc(100% + .375rem); right: 0; width: min(22rem, 80vw); box-sizing: border-box; padding: var(--issste-space-3) var(--issste-space-4);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-inline-start: 3px solid var(--issste-accent);
|
||||
border-radius: var(--issste-radius); box-shadow: 0 4px 16px rgb(0 0 0 / .18); font: var(--mat-sys-body-small); line-height: 1.5; text-align: start; overflow-wrap: anywhere; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorAyuda {
|
||||
readonly etiqueta = input('Cómo leer');
|
||||
readonly opened = output<void>();
|
||||
readonly sobre = signal(false);
|
||||
readonly fijo = signal(false);
|
||||
private static contador = 0;
|
||||
readonly idPanel = 'ayuda-' + ++IndicadorAyuda.contador;
|
||||
visible() { return this.sobre() || this.fijo(); }
|
||||
alternar() {
|
||||
const abre = !this.fijo();
|
||||
this.fijo.set(abre);
|
||||
if (abre) this.opened.emit();
|
||||
}
|
||||
}
|
||||
@@ -24,16 +24,18 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
import { parConteos } from './indicadores-conteos-pareados';
|
||||
|
||||
const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacientes_evaluados'];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos', '[class.doble]': 'ocupaDos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
@if (!conteos) {
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
<h2 [id]="titleId" tabindex="-1" [class.con-ayuda]="dominio === 'tea'">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
}
|
||||
@@ -81,12 +83,13 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
mat-card { position: relative; flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
|
||||
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
||||
.graphic-region { flex: 1; min-width: 0; }
|
||||
:host(.dual-card) { grid-column: 1 / -1; }
|
||||
:host(.doble) { grid-column: span 2; }
|
||||
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
|
||||
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
|
||||
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
|
||||
@@ -108,6 +111,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
.card-identity { min-width: 0; }
|
||||
h2, p { overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
||||
h2.con-ayuda { padding-right: 2.5rem; }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
@@ -137,13 +141,15 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
}
|
||||
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
|
||||
get sobrio() { return true; }
|
||||
// TEA's stacked case charts span two columns of its three-column grid.
|
||||
get ocupaDos() { return this.dominio === 'tea' && DOBLE_ANCHO_TEA.includes(this.indicador.id); }
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
||||
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
get tiempos() { return this.individual ? undefined : parTiempos(this.dominio, this.indicador.id); }
|
||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
@@ -170,6 +176,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@Input() pinned = false;
|
||||
// Draws the indicator alone even when it belongs to a connected pair.
|
||||
@Input() individual = false;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
readonly pinChanged = output<void>();
|
||||
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' && model; as m) {
|
||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en ' + m.periodo;
|
||||
@let tituloPacientes = 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en ' + m.periodo;
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
|
||||
/** A figure the catalog does not publish yet: it keeps its place and title, with no figure and no number. */
|
||||
@Component({
|
||||
selector: 'app-indicador-figura-pendiente',
|
||||
imports: [MatCardModule],
|
||||
template: `
|
||||
<mat-card>
|
||||
<h2>{{ titulo }}</h2>
|
||||
<p class="estado" role="status"><strong>Integración pendiente.</strong> {{ detalle }}</p>
|
||||
<div class="vacio">Sin datos publicados</div>
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.estado { color: var(--issste-text-secondary); }
|
||||
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
|
||||
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
||||
`,
|
||||
})
|
||||
export class IndicadorFiguraPendiente {
|
||||
@Input({ required: true }) titulo!: string;
|
||||
@Input() detalle = 'Este indicador aún no está publicado por el catálogo institucional.';
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected) {
|
||||
<mat-card class="figure-card" [class.sin-marco]="ayudaRedonda" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected && ayudaRedonda) {
|
||||
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + selected.titulo" (opened)="!metadata && metadataRequested.emit()">
|
||||
<ul class="ayuda-lista">@for (line of interpretation; track $index) { <li>{{ line }}</li> }</ul>
|
||||
@if (state.status === 'ready' && state.footnotes?.length) {
|
||||
@for (note of state.footnotes; track $index) { <p class="ayuda-nota">{{ note }}</p> }
|
||||
}
|
||||
</app-indicador-ayuda>
|
||||
} @else if (selected) {
|
||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
|
||||
@@ -37,8 +44,10 @@
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
@if (!ayudaRedonda) {
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
}
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
@@ -84,7 +93,7 @@
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<div class="highlight-legend" [class.sin-estado]="ayudaRedonda" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
|
||||
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
||||
.figure-card.sin-marco { position: static; border: 0; box-shadow: none; background: transparent; --mat-card-outlined-outline-width: 0; --mat-card-elevated-container-elevation: none; }
|
||||
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
|
||||
.interpretation { grid-row: 1; }
|
||||
.figure-legend { grid-row: 3; min-width: 0; }
|
||||
@@ -117,6 +118,7 @@
|
||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||
.dark .highlight-legend { color: #eef1f7; }
|
||||
.highlight-status { margin: 0; font-weight: 600; }
|
||||
.sin-estado .highlight-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.highlight-back { justify-self: start; }
|
||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||
@@ -126,3 +128,6 @@
|
||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||
.highlight-legend .highlight-group { font-weight: 600; }
|
||||
|
||||
.ayuda-lista { margin: 0; padding-left: 1.1rem; }
|
||||
.ayuda-nota { margin: .5rem 0 0; }
|
||||
|
||||
@@ -515,4 +515,14 @@ describe('IndicadorFigureCard', () => {
|
||||
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
|
||||
});
|
||||
|
||||
it('con la ayuda redonda no repite el título ni el nombre de la figura', () => {
|
||||
// Fails if TEA's cards bring back the heading box with the title and «Figura: …» under the card's own title.
|
||||
fixture.componentRef.setInput('ayudaRedonda', true);
|
||||
ready({ data: [{ y: [1] }], layout: {} });
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('.figure-title')).toBeNull();
|
||||
expect(root.querySelector('.figure-id')).toBeNull();
|
||||
expect(root.querySelector('.ayuda-boton')).not.toBeNull();
|
||||
expect(root.querySelector('.interpretation')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { CategoryLabel } from './indicadores-axis-labels';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||
@@ -41,7 +42,7 @@ export interface FigureState {
|
||||
selector: 'app-indicador-figure-card',
|
||||
standalone: true,
|
||||
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, IndicadorAyuda],
|
||||
templateUrl: './indicador-figure-card.html',
|
||||
styleUrl: './indicador-figure-card.scss',
|
||||
})
|
||||
@@ -142,6 +143,8 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
// A round "?" button with the reading guide instead of the «Cómo leer» box.
|
||||
@Input() ayudaRedonda = false;
|
||||
@Input() selected?: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
|
||||
@@ -33,6 +33,8 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1');
|
||||
// These tests cover the «Cómo leer» box shared by the domains; TEA's round help has its own spec.
|
||||
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
@@ -373,6 +375,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
|
||||
@@ -16,17 +16,58 @@ import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||
import { 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';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
host: { '[class.ayuda-externa]': 'conAyudaRedonda' },
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section class="figure-panel" [attr.aria-labelledby]="titleId">
|
||||
<section class="figure-panel" [class.sin-linea]="conAyudaRedonda" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
@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 +77,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 +90,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> }
|
||||
}
|
||||
@@ -64,15 +111,15 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
</nav>
|
||||
}
|
||||
</header>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
<app-indicador-figure-card [ayudaRedonda]="conAyudaRedonda" [state]="result()" [selected]="indicador"
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
<div class="stratified-detail">
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (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> }
|
||||
@@ -84,6 +131,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
:host { display: grid; min-width: 0; }
|
||||
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
|
||||
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
|
||||
.sin-linea .panel-controls { border-top: 0; padding-block: 0; }
|
||||
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
|
||||
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
|
||||
@@ -117,6 +165,32 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
|
||||
.donut-periods button: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; }
|
||||
// A container is a containing block for absolute children; the round help must reach the outer card.
|
||||
:host(.ayuda-externa) { container-type: normal; }
|
||||
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
|
||||
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
|
||||
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
|
||||
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
|
||||
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
|
||||
.sidebar-list { display: grid; gap: .25rem; }
|
||||
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
|
||||
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
|
||||
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.sidebar-reset { margin-top: .5rem; }
|
||||
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
@container (max-width: 559px) {
|
||||
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
|
||||
.strata-sidebar { position: static; }
|
||||
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
|
||||
}
|
||||
.visually-hidden {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
@@ -128,6 +202,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
// Round "?" help instead of the «Cómo leer» box; TEA draws it unless told otherwise.
|
||||
@Input() ayudaRedonda?: boolean;
|
||||
get conAyudaRedonda() { return this.ayudaRedonda ?? this.dominio === 'tea'; }
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@@ -165,7 +242,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 +286,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 +462,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';
|
||||
|
||||
@@ -182,12 +182,12 @@ describe('KPI integración con autoridad global', () => {
|
||||
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
|
||||
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
|
||||
fixture.detectChanges();
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(5);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
|
||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
|
||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Integración pendiente', 'Integración pendiente']
|
||||
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
||||
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.'),
|
||||
|
||||
@@ -19,8 +19,8 @@ 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]="true"
|
||||
[showPeriod]="false" />
|
||||
[loading]="result().loading ?? false" [notes]="notes" [quietWhenAvailable]="true"
|
||||
[showPeriod]="showPeriod" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
@@ -37,6 +37,7 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input() applied?: GlobalApplied;
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() initialPresentation = false;
|
||||
@Input() showPeriod = false;
|
||||
private readonly queries = inject(IndicadoresKpiQueries);
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
@@ -44,6 +45,10 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
private key = '';
|
||||
readonly usedPeriod = signal<string | undefined>(undefined);
|
||||
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
||||
get notes(): string[] {
|
||||
const notes = this.dominio === 'tea' ? this.result().notes ?? [] : [];
|
||||
return this.definition.note ? [this.definition.note, ...notes] : notes;
|
||||
}
|
||||
get temporalReference() {
|
||||
if (this.result().earlier) return 'Último dato visible, ' + this.usedPeriod();
|
||||
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<section class="route" aria-label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje">
|
||||
<h3 class="figure-title">Tiempos de la ruta del tamizaje</h3>
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando los tiempos de la ruta del tamizaje" /><p role="status">Cargando los tiempos de la ruta…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>{{ message() }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (model(); as m) {
|
||||
<div class="controls">
|
||||
@if (m.period) { <p class="period">Periodo: {{ periodLabel(m.period) }}</p> }
|
||||
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
|
||||
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
|
||||
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
|
||||
</mat-button-toggle-group>
|
||||
</div>
|
||||
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
|
||||
@else if (figure(); as figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
|
||||
<details class="how-to-read"><summary>Cómo leer</summary>
|
||||
<p class="note">
|
||||
@if (view() === 'cumulative') {
|
||||
Barra: mediana de días desde la toma hasta el evento; bigote: Q1 a Q3. Cada evento cuenta solo a quienes llegaron a él.
|
||||
El diagnóstico también se da tras el tamizaje o la colposcopía, por eso puede quedar antes que la biopsia.
|
||||
} @else {
|
||||
Cada barra es el tramo desde el evento anterior; en color, el más lento. Cuenta a quienes llegaron a sus dos eventos,
|
||||
y las medianas de los tramos no suman el acumulado.
|
||||
}
|
||||
</p>
|
||||
</details>
|
||||
}
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
|
||||
<table><caption>Días por evento en {{ m.period ? periodLabel(m.period) : 'el periodo' }}</caption>
|
||||
<thead><tr><th scope="col">Evento</th><th scope="col">Desde la toma</th><th scope="col">Desde el paso anterior</th></tr></thead>
|
||||
<tbody>@for (row of m.rows; track row.step.id) {
|
||||
<tr><th scope="row">{{ row.step.label }}</th><td>{{ cellText(row.fromSample) }}</td><td>{{ cellText(row.fromPrevious) }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,14 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.route { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
|
||||
.how-to-read summary { cursor: pointer; color: var(--issste-text-secondary); }
|
||||
.note { color: var(--issste-text-secondary); max-width: 70ch; }
|
||||
app-plotly-chart { --plot-height: 360px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -0,0 +1,125 @@
|
||||
// What this module covers: the screening route component: when it loads, the seven requests it makes, what it draws for
|
||||
// each view and period, and its empty, error and incompatible states. The model and the figure have their own spec
|
||||
// (`screening-route.spec.ts`).
|
||||
// Fixtures: `payload`, synthetic C3r /datos shaped like /cacu/indicadores/<id>/datos; `ChartStub` stands for the chart.
|
||||
import { Component, input } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { ROUTE_IDS } from './screening-route';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
||||
|
||||
const row = (periodo: string, n: number, q1: number, mediana: number, q3: number, suprimido = 0) =>
|
||||
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
|
||||
const MEDIANAS: Record<string, number> = {
|
||||
cacu_eu_tiempo_reporte: 7.9, cacu_dias_toma_colposcopia: 35.7, cacu_dias_resultado_colposcopia: 27.8, cacu_dias_toma_biopsia: 52.1,
|
||||
cacu_dias_colposcopia_biopsia: 16.4, cacu_dias_toma_diagnostico: 18.4, cacu_dias_biopsia_diagnostico: 12.8,
|
||||
};
|
||||
const payload = (id: string, suprimido = 0): IndicadorDatos => ({
|
||||
id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], version: '1',
|
||||
filas: [row('2025-S1', 100, 3, MEDIANAS[id] + 1, MEDIANAS[id] + 9, suprimido), row('2025-S2', 120, 4, MEDIANAS[id], MEDIANAS[id] + 8, suprimido)],
|
||||
});
|
||||
|
||||
describe('Ruta del tamizaje: componente', () => {
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorScreeningRoute>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorScreeningRoute], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorScreeningRoute, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorScreeningRoute);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('tema', 'claro');
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.match(() => true); http.verify(); });
|
||||
// The shared request queue runs a few at a time: answer in waves until nothing is left.
|
||||
function responder(entrega: (id: string) => IndicadorDatos = id => payload(id)) {
|
||||
const vistos: string[] = [];
|
||||
for (;;) {
|
||||
const pendientes = http.match(r => r.url.endsWith('/datos'));
|
||||
if (!pendientes.length) return vistos;
|
||||
for (const r of pendientes) { const id = r.request.url.split('/').at(-2)!; vistos.push(id); r.flush(entrega(id)); }
|
||||
f.detectChanges();
|
||||
}
|
||||
}
|
||||
const charts = () => f.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
|
||||
it('carga diferida; pide las siete medidas; dibuja una gráfica y cambia de vista y de periodo sin otra petición', () => {
|
||||
// Pins down: nothing is requested while hidden, each of the seven measures is requested once, the view and the period
|
||||
// are chosen without new requests, and the theme redraws the same data. Fails if the region loads before it is
|
||||
// visible, a measure is missing or repeated, or a control triggers a request.
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading');
|
||||
expect(responder().sort()).toEqual([...ROUTE_IDS].sort());
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(charts()).toHaveLength(1);
|
||||
expect(charts()[0].figure()).toBe(f.componentInstance.figure());
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
|
||||
f.componentInstance.selectView('steps'); f.detectChanges();
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
|
||||
// the period follows the page's filter, with no request of its own
|
||||
f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges();
|
||||
expect(f.componentInstance.model()!.period).toBe('2025-S1');
|
||||
expect(f.nativeElement.querySelector('mat-select')).toBeNull();
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('la tabla de valores publicados dice la mediana de cada evento y el estado si no hay caja', () => {
|
||||
// Fails if the table drops an event or shows a suppressed box as a number.
|
||||
f.detectChanges();
|
||||
responder(id => (id === 'cacu_dias_toma_biopsia' ? payload(id, 1) : payload(id)));
|
||||
const text = f.nativeElement.querySelector('table').textContent as string;
|
||||
expect(text).toContain('Resultado de citología');
|
||||
expect(text).toContain('mediana 35.7');
|
||||
expect(text).toContain('Suprimido');
|
||||
});
|
||||
it('la lectura de la gráfica es breve y va plegada en «Cómo leer»', () => {
|
||||
// Fails if the reading note goes back to an open paragraph under the chart.
|
||||
f.detectChanges();
|
||||
responder(id => payload(id));
|
||||
const guia = f.nativeElement.querySelector('details.how-to-read') as HTMLDetailsElement;
|
||||
expect(guia.querySelector('summary')!.textContent).toBe('Cómo leer');
|
||||
expect(guia.open).toBe(false);
|
||||
expect(guia.textContent).toContain('bigote: Q1 a Q3');
|
||||
expect(f.nativeElement.querySelector('section > p.note')).toBeNull();
|
||||
});
|
||||
|
||||
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||
// Fails if an empty route draws a chart or hides the reason.
|
||||
f.detectChanges();
|
||||
responder(id => payload(id, 1));
|
||||
expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(charts()).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay tiempos publicados');
|
||||
});
|
||||
it('un fallo del servicio se anuncia como error y reintentar vuelve a pedir', () => {
|
||||
// Fails if an error leaves a stale chart, hides the alert, or retry does not request again.
|
||||
f.detectChanges();
|
||||
http.match(r => r.url.endsWith('/datos'))[0].flush({}, { status: 500, statusText: 'Server Error' });
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error');
|
||||
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
expect(charts()).toHaveLength(0);
|
||||
http.match(() => true); // the other requests of the first try were cancelled with it
|
||||
f.componentInstance.retry(); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading');
|
||||
expect(responder().length).toBe(ROUTE_IDS.length);
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('datos de otro contrato quedan incompatibles y no se dibujan', () => {
|
||||
// Fails if a payload that is not a duration is drawn as one.
|
||||
f.detectChanges();
|
||||
responder(id => (id === 'cacu_dias_toma_biopsia' ? { ...payload(id), contrato: 'C1' } : payload(id)));
|
||||
expect(f.componentInstance.status()).toBe('incompatible');
|
||||
expect(charts()).toHaveLength(0);
|
||||
expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { etiquetaPeriodo } from './indicadores-historico-figures';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, routeHasData, routeModel } from './screening-route';
|
||||
|
||||
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
|
||||
@Component({
|
||||
selector: 'app-indicador-screening-route',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-screening-route.html',
|
||||
styleUrl: './indicador-screening-route.scss',
|
||||
})
|
||||
export class IndicadorScreeningRoute {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly tipo = input<TipoPeriodo>('semestre');
|
||||
/** The periods of the page's filter: the chart shows the newest of them with data, and has no period filter of its own. */
|
||||
readonly periodos = input<readonly string[] | undefined>(undefined);
|
||||
/** The measures load once the region is visible. */
|
||||
readonly visible = input(true);
|
||||
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly message = signal('');
|
||||
readonly view = signal<RouteView>('cumulative');
|
||||
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
|
||||
readonly model = computed(() => {
|
||||
const data = this.payloads();
|
||||
return data ? routeModel(data, this.tipo(), this.periodos()) : undefined;
|
||||
});
|
||||
readonly figure = computed(() => {
|
||||
const model = this.model();
|
||||
return model && routeHasData(model) ? routeFigure(model, this.view(), this.tema()) : undefined;
|
||||
});
|
||||
readonly periodLabel = etiquetaPeriodo;
|
||||
readonly cellText = routeCellText;
|
||||
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private subscription?: Subscription;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const dominio = this.dominio(), tipo = this.tipo();
|
||||
if (!this.visible()) { this.status.set('deferred'); return; }
|
||||
untracked(() => this.load(dominio, tipo));
|
||||
});
|
||||
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
||||
}
|
||||
|
||||
retry() { this.load(this.dominio(), this.tipo()); }
|
||||
selectView(view: RouteView) { this.view.set(view); }
|
||||
|
||||
private load(dominio: Dominio, tipo: TipoPeriodo) {
|
||||
this.subscription?.unsubscribe();
|
||||
this.payloads.set(undefined);
|
||||
this.status.set('loading');
|
||||
const requests = Object.fromEntries(ROUTE_IDS.map(id => [id, this.snapshots.datos(dominio, id, tipo)]));
|
||||
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: data => {
|
||||
try {
|
||||
const model = routeModel(data, tipo, this.periodos());
|
||||
this.payloads.set(data);
|
||||
this.status.set(routeHasData(model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => this.failure(error),
|
||||
});
|
||||
}
|
||||
|
||||
private failure(error: unknown) {
|
||||
this.payloads.set(undefined);
|
||||
this.message.set(error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof RouteIncompatible ? error.message : httpMessage(error));
|
||||
this.status.set(error instanceof RouteIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError))
|
||||
? 'incompatible' : 'error');
|
||||
}
|
||||
}
|
||||
@@ -97,13 +97,13 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
|
||||
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
|
||||
<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>
|
||||
|
||||
@@ -59,8 +59,8 @@ describe('Dona de dos anillos para C1', () => {
|
||||
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
||||
});
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
|
||||
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, tomado de la paleta compartida', () => {
|
||||
const colores = ['#A8C243', '#42C29C', '#9C42C2'];
|
||||
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||
if (dona.status !== 'supported') throw new Error('sin figura');
|
||||
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
||||
|
||||
@@ -13,8 +13,8 @@ export const C2_PALETTE = Object.freeze({
|
||||
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
|
||||
]),
|
||||
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
||||
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
|
||||
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
|
||||
// Age groups of the EEG indicators (M21, M22): the same lime, teal and purple the other domains' series use.
|
||||
edades: Object.freeze(['#A8C243', '#42C29C', '#9C42C2']),
|
||||
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
|
||||
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
|
||||
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(),provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied })) fixture.componentRef.setInput(name,value);
|
||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied, ayudaRedonda: false })) fixture.componentRef.setInput(name,value);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos'));
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
// What this module covers: CaCu's compositions as the page reads them from FHIR once the Measure publishes category
|
||||
// groups and the reports their crossed strata: the groups, the rows by stratum (codes, captions, explicit zeros, totals),
|
||||
// the contract errors that must never become zeros, the EU7 view by follow-up status and the histopathological
|
||||
// confirmation, a period without units, and that measures without groups (CaMa's) read unchanged.
|
||||
// Fixtures: `fixtures/cacu_fhir_measures.json` (the Measure bundle `GET /cacu/fhir/Measure` returns with the groups
|
||||
// declared) and `fixtures/cacu_fhir_reportes_estratos.json` (real `GET /cacu/fhir/MeasureReport` answers of EU7 and the
|
||||
// confirmation for 2025-S2, with units, and 2021-S1, without; synthetic data of the isolated installation, N_CACU=300).
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { categorias, datosDeReportes, gruposDeCategoria, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
|
||||
import { barras, dona, modelo } from './indicadores-eu7-escenario';
|
||||
import { donaConfirmacion, modeloConfirmacion } from './indicadores-confirmacion-citologia';
|
||||
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||
import reportsData from './fixtures/cacu_fhir_reportes_estratos.json';
|
||||
import camaData from './fixtures/cama_fhir_measures.json';
|
||||
|
||||
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const measure = (id: string) => measures.find(m => m.id === id)!;
|
||||
const answers = reportsData as unknown as Record<string, Bundle>;
|
||||
const reports = (key: string) => resources(answers[key], 'MeasureReport') as Report[];
|
||||
const EU7 = 'CACU-EU7', CONF = 'CACU-CONFIRMACION-CITOLOGIA';
|
||||
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
||||
type Fila = Record<string, unknown>;
|
||||
const n = (filas: Fila[], estrato: string | null, categoria: string) =>
|
||||
filas.filter(f => f['estrato'] === estrato && f['categoria'] === categoria).reduce((s, f) => s + (f['n'] as number), 0);
|
||||
|
||||
describe('Grupos de categoría publicados por la Measure', () => {
|
||||
it('EU7 y la confirmación leen el grupo de cada categoría y los nombres de los grupos, en su orden', () => {
|
||||
// Pins down: the optional `grupo` inside each `categoria` and the `categoria-grupo` captions reach the page as the
|
||||
// EU7 and confirmation views read them; «Sin biopsia aún» keeps no group. Fails if either is dropped or reordered.
|
||||
expect(Object.fromEntries(Object.entries(categorias(measure(EU7))).map(([c, v]) => [c, v.grupo]))).toEqual({
|
||||
NORMAL: 'NO_ANORMAL', 'ASC-US': 'ANORMAL', LIEBG: 'ANORMAL', 'ASC-H': 'ANORMAL', LIEAG: 'ANORMAL', CIS: 'ANORMAL', SIN_DATO: 'SIN_DATO' });
|
||||
expect(Object.entries(gruposDeCategoria(measure(EU7)))).toEqual([
|
||||
['NO_ANORMAL', 'Sin anomalía'], ['ANORMAL', 'Anormal'], ['SIN_DATO', 'Sin dato']]);
|
||||
expect(categorias(measure(CONF))['SIN_BIOPSIA'].grupo).toBeNull();
|
||||
expect(gruposDeCategoria(measure(CONF))).toEqual({ NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Biopsia sin grado' });
|
||||
});
|
||||
|
||||
it('una Measure sin grupos se lee como antes: sin grupo por categoría y sin grupos de categoría', () => {
|
||||
// Pins down: groups are opt-in. CaMa's Measures declare none, so every category keeps `grupo: null` and the data
|
||||
// carry no `grupos_de_categoria`. Fails if reading the new extensions changes what CaMa's views receive.
|
||||
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
|
||||
for (const m of cama) {
|
||||
expect(Object.values(categorias(m)).every(c => c.grupo === null), m.id).toBe(true);
|
||||
expect(gruposDeCategoria(m), m.id).toEqual({});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Composiciones por estrato desde el estratificador cruzado', () => {
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre');
|
||||
const porEstatus = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' });
|
||||
|
||||
it('cada estrato tiene una fila por categoría declarada, con su código y su etiqueta, y ceros explícitos', () => {
|
||||
// Pins down: one row per (status, category), the status code as the value and its caption from the report, and a
|
||||
// zero for every cell FHIR doesn't list (the report is complete). Fails if a cell goes missing or a code is replaced.
|
||||
const valores = porEstatus['valores_estrato'] as string[];
|
||||
expect(valores.length).toBeGreaterThan(0);
|
||||
expect(porEstatus.filas.length).toBe(valores.length * Object.keys(porEstatus['categorias'] as object).length);
|
||||
expect((porEstatus['etiquetas_estrato'] as Record<string, string>)['PRE_COLPOSCOPIA']).toBe('Pre colposcopia');
|
||||
const listadas = (reports('eu7_2025S2')[0].group![0].stratifier as { code: unknown[]; stratum: unknown[] }[])
|
||||
.find(s => s.code.length === 2 && JSON.stringify(s.code[0]).includes('estatus_seguimiento'))!.stratum.length;
|
||||
expect(porEstatus.filas.filter(f => f['n'] === 0).length).toBe(porEstatus.filas.length - listadas);
|
||||
expect(porEstatus.filas.every(f => f['suprimido'] === 0 && f['grupo'] === 'TOTAL')).toBe(true);
|
||||
});
|
||||
|
||||
it('los conteos por estrato suman los de la distribución general, categoría por categoría y en total', () => {
|
||||
// Pins down: the strata partition the period's units (112 patients in 2025-S2) and each category adds up across
|
||||
// them; the per-stratum totals are published. Fails if the crossed stratifier is read with a shift or a loss.
|
||||
const totales = porEstatus['totales_estrato'] as { n: number }[];
|
||||
expect(totales.reduce((s, t) => s + t.n, 0)).toBe(112);
|
||||
for (const categoria of Object.keys(general['categorias'] as object)) {
|
||||
const porEstratos = (porEstatus['valores_estrato'] as string[]).reduce((s, e) => s + n(porEstatus.filas, e, categoria), 0);
|
||||
expect(porEstratos, categoria).toBe(n(general.filas, null, categoria));
|
||||
}
|
||||
const porEdad = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'grupo_edad' });
|
||||
expect((porEdad['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(112);
|
||||
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['25-34']).toBe('25-34');
|
||||
});
|
||||
|
||||
it('una celda que falta, una categoría no declarada o un estratificador ausente son errores de contrato, no ceros', () => {
|
||||
// Pins down: what can't be read as a complete partition fails loudly: cells that no longer add up to the units, a
|
||||
// category the Measure doesn't declare, and a period with units but without the crossed stratifier. Fails if any
|
||||
// of them is silently turned into a zero.
|
||||
const sinCelda = clone(reports('eu7_2025S2'));
|
||||
const cruzado = sinCelda[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as { stratum: unknown[] };
|
||||
cruzado.stratum.shift();
|
||||
expect(() => datosDeReportes(measure(EU7), sinCelda, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Los conteos por estrato no suman las unidades del periodo');
|
||||
const ajena = clone(reports('eu7_2025S2'));
|
||||
const celda = (ajena[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as
|
||||
{ stratum: { component: { value: { coding: { code: string }[] } }[] }[] }).stratum[0];
|
||||
celda.component[1].value.coding[0].code = 'GLANDULAR';
|
||||
expect(() => datosDeReportes(measure(EU7), ajena, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Categoría no declarada en el estrato');
|
||||
const sinCruce = clone(reports('eu7_2025S2'));
|
||||
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
|
||||
expect(() => datosDeReportes(measure(EU7), sinCruce, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Dimensión no admitida');
|
||||
});
|
||||
|
||||
it('un periodo sin unidades no tiene filas por estrato y no es un error', () => {
|
||||
// Pins down: 2021-S1 has no patients; its report has nothing to cross, so the stratified data carry the period but
|
||||
// no rows, and the general distribution is all zeros. Fails if an empty period is read as an error or as data.
|
||||
const vacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' });
|
||||
expect(vacio.periodos).toEqual(['2021-S1']);
|
||||
expect(vacio.filas).toEqual([]);
|
||||
const generalVacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre');
|
||||
expect(generalVacio.filas.every(f => f['n'] === 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vistas propias de CaCu con los datos de FHIR', () => {
|
||||
it('EU7: el modelo por escenario se construye y la dona y las barras tienen datos', () => {
|
||||
// Pins down: with the groups and the rows by follow-up status, EU7's coordinated view builds its model (112
|
||||
// patients in groups Anormal / Sin anomalía, «Sin dato» apart) and both figures have traces. Fails if the view
|
||||
// falls back to «incompatible» with the data FHIR publishes.
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
const m = modelo(general, escenarios, '2025-S2');
|
||||
expect(m.vacio).toBe(false);
|
||||
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Sin anomalía', 'Anormal']);
|
||||
expect(m.escenarios.map(e => e.etiqueta)).toContain('Pre colposcopia');
|
||||
expect(dona(m, {}, 'claro').data.length).toBeGreaterThan(0);
|
||||
expect(barras(m, {}, 'claro').data.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('EU7: el texto emergente de cada sector de la dona nombra la categoría, los pacientes y el porcentaje', () => {
|
||||
// Pins down: both rings carry one pre-formatted hover text per sector («2 pacientes, 2.1 % del total con
|
||||
// resultado» for LIEAG, 2 of the 95 patients with a result) and their template reads it by name. A pie wraps
|
||||
// `customdata` in an extra array, so a template that indexes it printed «2,2.1 pacientes, - %». Fails if the
|
||||
// template goes back to indexing `customdata` or a sector loses its text.
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
const m = modelo(general, escenarios, '2025-S2');
|
||||
const anillos = dona(m, {}, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
|
||||
expect(anillos.length).toBe(2);
|
||||
for (const anillo of anillos) {
|
||||
expect(anillo['hovertemplate']).not.toContain('customdata');
|
||||
expect(anillo['hovertemplate']).toContain('%{hovertext}');
|
||||
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
|
||||
}
|
||||
const exterior = anillos.find(t => t['name'] === 'categorias')!;
|
||||
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
|
||||
expect(m.total).toBe(95);
|
||||
expect(textos[etiquetas.indexOf('LIEAG')]).toBe('2 pacientes, 2.1 % del total con resultado');
|
||||
expect(textos.every(t => /^\d+ pacientes, \d+(\.\d)? % del total con resultado$/.test(t))).toBe(true);
|
||||
});
|
||||
|
||||
it('EU7: un periodo sin pacientes es un periodo vacío, no una respuesta incompatible', () => {
|
||||
// Pins down: for 2021-S1 FHIR publishes the general distribution as explicit zeros and no scenario; the view reads
|
||||
// it as empty. A positive count without scenarios is still rejected. Fails if an empty period shows
|
||||
// «incompatible», or if a real mismatch is hidden as empty.
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
const m = modelo(general, escenarios, '2021-S1');
|
||||
expect(m.vacio).toBe(true);
|
||||
expect(m.escenarios).toEqual([]);
|
||||
const conPacientes = clone(general);
|
||||
conPacientes.filas[0]['n'] = 3;
|
||||
expect(() => modelo(conPacientes, escenarios, '2021-S1')).toThrow(/No hay escenarios que correspondan/);
|
||||
});
|
||||
|
||||
it('EU7: el mismo reporte servido en dos respuestas es una sola procedencia aunque cambie la hora de la respuesta', () => {
|
||||
// Pins down: the view asks for the general and the stratified data in two requests; the WebApi serves the same
|
||||
// stored report (same id and cut-off) with each response's own `date`. That is one provenance; without report ids,
|
||||
// a different generation time still means different reports. Fails if the view rejects FHIR's two responses of one
|
||||
// report, or accepts two anonymous answers generated apart.
|
||||
const segunda = clone(reports('eu7_2025S2'));
|
||||
segunda[0].date = '2099-01-01T00:00:00Z';
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), segunda, 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
expect(modelo(general, escenarios, '2025-S2').vacio).toBe(false);
|
||||
const anonimo = (d: IndicadorDatos) => ({ ...d, reportes: (d['reportes'] as Fila[]).map(r => ({ ...r, report_id: null })) }) as IndicadorDatos;
|
||||
expect(() => modelo(anonimo(general), anonimo(escenarios), '2025-S2')).toThrow(/reportes distintos/);
|
||||
});
|
||||
|
||||
it('confirmación: la tabla por citología y los dos grupos de grados se construyen', () => {
|
||||
// Pins down: the confirmation by cytology result builds its table from the crossed stratifier (6 patients in
|
||||
// 2025-S2), with its two groups and LIEAG's as the base view, and «Sin biopsia aún» / «Biopsia sin grado»
|
||||
// apart. Fails if the view can't read FHIR's groups or strata.
|
||||
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
|
||||
const m = modeloConfirmacion(datos, '2025-S2');
|
||||
expect(m.vacio).toBe(false);
|
||||
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Menor que LIEAG', 'LIEAG o más']);
|
||||
expect(m.base).toBe('ANORMAL');
|
||||
expect(m.aparte.map(a => a.id).sort()).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
|
||||
expect((datos['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(6);
|
||||
});
|
||||
|
||||
it('confirmación: el texto emergente de cada sector de la dona nombra el grado, las mujeres con biopsia y el porcentaje', () => {
|
||||
// Pins down: both rings carry one pre-formatted hover text per sector («3 mujeres con biopsia, 75.0 %» for the
|
||||
// grades LIEAG o más… of the 4 women with a biopsy in 2025-S2) and their template reads it by name, because a pie
|
||||
// wraps `customdata` in an extra array and indexing it printed «3,75.0 % mujeres con biopsia, -». Fails if the
|
||||
// template goes back to indexing `customdata` or a sector loses its text.
|
||||
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
|
||||
const m = modeloConfirmacion(datos, '2025-S2');
|
||||
const anillos = donaConfirmacion(m, { grupo: m.base }, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
|
||||
expect(anillos.length).toBe(2);
|
||||
for (const anillo of anillos) {
|
||||
expect(anillo['hovertemplate']).not.toContain('customdata');
|
||||
expect(anillo['hovertemplate']).toContain('%{hovertext}');
|
||||
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
|
||||
}
|
||||
const exterior = anillos.find(t => t['name'] === 'categorias')!;
|
||||
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
|
||||
expect(textos[etiquetas.indexOf('LIEAG (CIN 2 y 3)')]).toBe('3 mujeres con biopsia, 75.0 %');
|
||||
expect(textos.every(t => /^\d+ mujeres con biopsia, \d+(\.\d)? %$/.test(t))).toBe(true);
|
||||
});
|
||||
|
||||
it('la compuerta de EU7 usa los estratos que declara la Measure y no activa filtros para otras composiciones', () => {
|
||||
// Pins down: EU7 declares `estatus_seguimiento`, so its view opens without local filters; the stratified
|
||||
// capabilities of the generic figure panel stay empty for every CaCu and CaMa measure. Fails if the gate is lost
|
||||
// or if filters appear for compositions that never had them.
|
||||
const eu7 = indicadorDeMeasure(measure(EU7));
|
||||
expect(declaraEstrato(eu7, 'estatus_seguimiento')).toBe(true);
|
||||
expect(declaraEstrato(indicadorDeMeasure(measure(CONF)), 'estatus_seguimiento')).toBe(false);
|
||||
expect(declaraEstrato(indicadorDeMeasure(measure('CACU-EU13')), 'estatus_seguimiento')).toBe(false);
|
||||
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
|
||||
for (const item of [...measures, ...cama].map(indicadorDeMeasure)) expect(stratifiedCapabilities(item), item.id).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
// What this module covers: how CaCu's FHIR measures reach the indicator page: the page's id of each measure, and what the
|
||||
// initial-period anchor (`cacu_eu7`) makes of a C2 Measure that publishes, or does not publish, its category labels.
|
||||
// The Measure and the report are synthetic and minimal: the shape of `GET /cacu/fhir/Measure` and `/MeasureReport`.
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { Measure, Report, datosDeReportes, indicadorDeMeasure, indicadorId } from './indicadores-fhir';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
|
||||
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const ENDPOINT = ['CACU-CONFIRMACION-CITOLOGIA', 'CACU-DIAS-TOMA-DIAGNOSTICO', 'CACU-EU-TIEMPO-REPORTE', 'CACU-EU13', 'CACU-EU7',
|
||||
'CACU-RIESGO-BANDA', 'IND1'];
|
||||
const etiqueta = (codigo: string, texto: string, color: string) => ({ url: `${STRUCTURE}/categoria`, extension: [
|
||||
{ url: 'codigo', valueCode: codigo }, { url: 'etiqueta', valueString: texto }, { url: 'color', valueString: color }] });
|
||||
const eu7 = (extra: object[]): Measure => ({
|
||||
resourceType: 'Measure', id: 'CACU-EU7', version: '0.3.3', title: 'Distribución de resultados citológicos',
|
||||
subjectCodeableConcept: { coding: [{ code: 'paciente' }] },
|
||||
extension: [{ url: `${STRUCTURE}/contrato`, valueCode: 'C2' }, { url: `${STRUCTURE}/tipos-periodo`, valueCode: 'semestre' }, ...extra],
|
||||
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [], stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [] }] }],
|
||||
} as unknown as Measure);
|
||||
const reporte = (): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'CACU-EU7-1', period: { start: '2025-07-01', end: '2025-12-31' },
|
||||
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 12 }],
|
||||
stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [
|
||||
{ value: { coding: [{ code: 'NORMAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 8 }] },
|
||||
{ value: { coding: [{ code: 'ASC-US' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 3 }] },
|
||||
{ value: { coding: [{ code: 'SIN_DATO' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 1 }] },
|
||||
] }] }],
|
||||
} as unknown as Report);
|
||||
const aplicado: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 0 };
|
||||
const ancla = KPI_BY_DOMAIN.cacu[0];
|
||||
|
||||
describe('Identificadores de CaCu entre FHIR y la página', () => {
|
||||
it('cada medida que publica el WebApi tiene el id de minúsculas que usa la página y ninguno se repite', () => {
|
||||
// Pins down: the table covers the seven measures `GET /cacu/fhir/Measure` lists and the ids are unique. Fails if a
|
||||
// measure is published without a correspondence (it would come back as `CACU_X`, which no card matches) or two
|
||||
// measures collapse into one page id.
|
||||
const ids = ENDPOINT.map(indicadorId);
|
||||
expect(ids.sort()).toEqual(['cacu_confirmacion_citologia', 'cacu_dias_toma_diagnostico', 'cacu_eu13', 'cacu_eu7',
|
||||
'cacu_eu_tiempo_reporte', 'cacu_riesgo_banda', 'ind1']);
|
||||
expect(ENDPOINT.every(id => Object.hasOwn(CACU_MEASURE_IDS, id))).toBe(true);
|
||||
});
|
||||
|
||||
it('los ids que la página busca (ancla, tiempos, confirmación) existen entre los publicados', () => {
|
||||
// Pins down: the page's own constants (the KPI definitions of CaCu, the confirmation card's id and the result-time KPI)
|
||||
// are values of the table. Fails if the page renames one of them without the table: the catalog would keep `CACU_EU7`
|
||||
// while the page looks for `cacu_eu7`, and no initial period would be searched.
|
||||
const publicados = Object.values(CACU_MEASURE_IDS);
|
||||
for (const id of [...KPI_BY_DOMAIN.cacu.map(k => k.id), CACU_RESULTADO_KPI.id, ID_CONFIRMACION, 'cacu_eu7']) {
|
||||
expect(publicados).toContain(id);
|
||||
}
|
||||
});
|
||||
|
||||
it('el catálogo de una medida de CaCu lleva el id de la página y sus figuras', () => {
|
||||
// Pins down: the catalog entry takes the page id and the `figuras` the Measure publishes. Fails if the mapper stops
|
||||
// using the CaCu table or drops the figures.
|
||||
const item = indicadorDeMeasure(eu7([{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_donas' },
|
||||
{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_barras' }]));
|
||||
expect(item.id).toBe('cacu_eu7');
|
||||
expect(item.figuras).toEqual(['fig_c2_donas', 'fig_c2_barras']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('El ancla de CaCu con y sin etiquetas de categoría publicadas', () => {
|
||||
it('con etiquetas, los conteos del periodo son filas y el ancla muestra el total', () => {
|
||||
// Pins down: a C2 Measure that publishes its categories gives one row per category and the anchor KPI the sum
|
||||
// (12 patients), so the initial-period search can stop on the period. Fails if the rows stop following the Measure's
|
||||
// categories or the anchor no longer accepts a CaCu partition.
|
||||
const measure = eu7([etiqueta('NORMAL', 'Normal', '#9DBFE3'), etiqueta('ASC-US', 'ASC-US', '#2F6DB3'),
|
||||
etiqueta('SIN_DATO', 'Sin dato', '#C9CDD2')]);
|
||||
const datos = datosDeReportes(measure, [reporte()], 'semestre');
|
||||
expect(datos.filas.map(f => [f['categoria'], f['n']])).toEqual([['NORMAL', 8], ['ASC-US', 3], ['SIN_DATO', 1]]);
|
||||
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
|
||||
expect(resultado.state).toBe('Disponible');
|
||||
expect(resultado.value).toBe(12);
|
||||
});
|
||||
|
||||
it('sin etiquetas, el mismo reporte no deja filas y el ancla no encuentra periodo', () => {
|
||||
// Pins down the failure the Measure without `categoria` causes: the report counts 12 patients, but with no declared
|
||||
// category there is no row, so the anchor reads «Sin filas utilizables» and the initial period stays empty. Fails
|
||||
// if the page starts inventing categories from the report (it must keep asking the Measure).
|
||||
const datos = datosDeReportes(eu7([]), [reporte()], 'semestre');
|
||||
expect(datos.filas).toEqual([]);
|
||||
expect(kpiResult(datos, ancla, 'cacu', aplicado).state).toBe('Sin filas utilizables');
|
||||
});
|
||||
});
|
||||
|
||||
// `fixtures/cacu_fhir_measures.json` is the Measure bundle `GET /cacu/fhir/Measure` returns from the dbt definitions once
|
||||
// CaCu declares its figures and category labels (WebApi with the figures and labels declared in Transformation); the reports are built
|
||||
// from the categories each Measure declares, as the WebApi would count them.
|
||||
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const medida = (id: string) => publicadas.find(m => m.id === id)!;
|
||||
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
|
||||
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
|
||||
const codigo = (c: string) => ({ coding: [{ code: c }] });
|
||||
const reporteDe = (m: Measure, conteos: number[]): Report => ({
|
||||
resourceType: 'MeasureReport', id: `${m.id}-1`, period: { start: '2025-07-01', end: '2025-12-31' },
|
||||
group: [{ code: codigo('TOTAL'), population: [{ code: codigo('initial-population'), count: conteos.reduce((a, b) => a + b, 0) }],
|
||||
stratifier: [{ code: [codigo('categoria')], stratum: declaradas(m).map((c, i) => ({
|
||||
value: codigo(c), population: [{ code: codigo('initial-population'), count: conteos[i] }] })) }] }],
|
||||
} as unknown as Report);
|
||||
|
||||
describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => {
|
||||
it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => {
|
||||
// Pins down: C2 measures offer the donut and the bars, the C3r the box plot, and the C1 and the risk bands none
|
||||
// yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not
|
||||
// checked against the renderer.
|
||||
const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras]));
|
||||
expect(figuras).toEqual({
|
||||
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_diagnostico_tratamiento: ['fig_c3r_caja'],
|
||||
cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||
cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||
cacu_riesgo_banda: [], ind1: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('con las etiquetas publicadas, el ancla muestra el total y el donut y las barras se dibujan', () => {
|
||||
// Pins down the whole chain for the anchor: published categories -> rows -> «Pacientes evaluadas» total (16) ->
|
||||
// supported C2 donut and bars. Fails if the page cannot read what the WebApi publishes for CaCu's distribution.
|
||||
const eu7 = medida('CACU-EU7');
|
||||
const datos = datosDeReportes(eu7, [reporteDe(eu7, [8, 3, 2, 1, 1, 0, 1])], 'semestre');
|
||||
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
|
||||
expect(resultado).toMatchObject({ state: 'Disponible', value: 16 });
|
||||
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
|
||||
const dibujo = c2Figure(datos, { dominio: 'cacu', indicador: 'cacu_eu7', figura, tipoPeriodo: 'semestre', tema: 'claro',
|
||||
periodos: ['2025-S2'] } as unknown as FigureSelection);
|
||||
expect(dibujo.status).toBe('supported');
|
||||
}
|
||||
});
|
||||
|
||||
it('un C1 publicado con su intervalo de Wilson llena la banda del histórico, en porcentaje', () => {
|
||||
// Pins down: the `ic-bajo` and `ic-alto` of a proportion's score (proportions) reach the rows as percentages and
|
||||
// the history trend draws them as its band. Fails if the bounds are read unconverted or dropped.
|
||||
const eu13 = medida('CACU-EU13');
|
||||
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||
const reporte13 = { resourceType: 'MeasureReport', id: 'CACU-EU13-1', period: { start: '2025-01-01', end: '2025-06-30' },
|
||||
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
|
||||
measureScore: { value: 0.25, extension: [{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 }, { url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 }] } }] } as unknown as Report;
|
||||
const datos = datosDeReportes(eu13, [reporte13], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
|
||||
const banda = (historicoFigura(datos, 'claro').figure as unknown as { data: { name: string; y: number[] }[] }).data[0];
|
||||
expect(banda.name).toBe('Intervalo de confianza');
|
||||
expect(banda.y).toEqual([69.9, 4.6]);
|
||||
});
|
||||
|
||||
it('un C1 de CaCu cuyo grupo se llama principal dibuja su tendencia en el histórico', () => {
|
||||
// Pins down: the WebApi names the group of a proportion `principal`; the page reads it as `total`, the group the
|
||||
// history trend draws, for CaCu as for CaMa. Fails if the rows keep the group `principal` and the trend comes out
|
||||
// empty, with its period listed as having no data.
|
||||
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
|
||||
for (const id of ['CACU-EU13', 'IND1']) {
|
||||
const medida13 = medida(id);
|
||||
const reporte = { resourceType: 'MeasureReport', id: id + '-1', period: { start: '2025-01-01', end: '2025-06-30' },
|
||||
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
|
||||
measureScore: { value: 0.25 } }] } as unknown as Report;
|
||||
const datos = datosDeReportes(medida13, [reporte], 'semestre');
|
||||
expect(datos.filas[0]['grupo']).toBe('total');
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect((figura.figure as unknown as { data: { y: number[] }[] }).data[1].y).toEqual([25]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
// How CaCu's FHIR measures map onto what the indicator page reads: the page's id of each measure.
|
||||
//
|
||||
// The WebApi names a measure `CACU-EU7`, `CACU-CONFIRMACION-CITOLOGIA` or `IND1`; the page, its KPI definitions, the
|
||||
// initial-period anchor and the cards that have a view of their own (`cacu_eu7`, `cacu_confirmacion_citologia`, the
|
||||
// time pair) all use the lower-case ids below. The generic rule would give `CACU_EU7`, which none of them matches, so
|
||||
// the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule.
|
||||
export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
|
||||
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
|
||||
'CACU-DIAS-BIOPSIA-DIAGNOSTICO': 'cacu_dias_biopsia_diagnostico',
|
||||
'CACU-DIAS-COLPOSCOPIA-BIOPSIA': 'cacu_dias_colposcopia_biopsia',
|
||||
'CACU-DIAS-DIAGNOSTICO-TRATAMIENTO': 'cacu_dias_diagnostico_tratamiento',
|
||||
'CACU-DIAS-RESULTADO-COLPOSCOPIA': 'cacu_dias_resultado_colposcopia',
|
||||
'CACU-DIAS-TOMA-BIOPSIA': 'cacu_dias_toma_biopsia',
|
||||
'CACU-DIAS-TOMA-COLPOSCOPIA': 'cacu_dias_toma_colposcopia',
|
||||
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
|
||||
'CACU-DIAS-TOMA-TRATAMIENTO': 'cacu_dias_toma_tratamiento',
|
||||
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
|
||||
'CACU-EU13': 'cacu_eu13',
|
||||
'CACU-EU7': 'cacu_eu7',
|
||||
'CACU-RIESGO-BANDA': 'cacu_riesgo_banda',
|
||||
'IND1': 'ind1',
|
||||
};
|
||||
@@ -19,7 +19,7 @@ import { figureApplied } from './indicadores-figure-selection';
|
||||
class ChartStub {}
|
||||
const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({
|
||||
id, titulo, contrato, tipos_periodo: ['semestre', 'mes'],
|
||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
|
||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : contrato === 'C2' ? ['fig_c2_barras'] : [], version: '1',
|
||||
});
|
||||
const catalog = [
|
||||
item('cacu_eu13', 'Tasa de detección histopatológica'),
|
||||
@@ -67,7 +67,8 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
const cards = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
|
||||
// The clinical section only: CaCu's time figures sit in the opportunity section.
|
||||
const cards = () => fixture.debugElement.query(By.css('.graphic-section')).queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
|
||||
const card = (id: string) => cards().find(c => c.indicador.id === id)!;
|
||||
const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel))
|
||||
.map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!;
|
||||
@@ -84,11 +85,12 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
|
||||
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
|
||||
'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
'Pacientes evaluadas', 'Tiempo desde la toma de muestra al resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
for (const kpi of kpis.slice(3)) {
|
||||
expect(kpi.querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
expect(kpi.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
|
||||
expect(kpi.textContent).toContain('aún no está publicado');
|
||||
expect(kpi.querySelector('.value, .period')).toBeNull();
|
||||
}
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// Covers how the Indicadores tab arranges CaCu's figures: the five times of «Tiempo de tamizaje a diagnóstico» under
|
||||
// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures. Fixtures: a CaCu catalog shaped like /cacu/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
|
||||
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||
const CACU = [
|
||||
item('cacu_eu13', 'Tasa de detección histopatológica', 'C1', []),
|
||||
item('cacu_eu7', 'Distribución de resultados citológicos', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
||||
item('cacu_eu_tiempo_reporte', 'Días de la toma de la citología a su resultado', 'C3r', ['fig_c3r_caja']),
|
||||
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
item('cacu_confirmacion_citologia', 'Tasa de confirmación histopatológica', 'C2', ['fig_c2_donas']),
|
||||
item('ind1', 'Pacientes con citología anómala', 'C1', []),
|
||||
];
|
||||
|
||||
// The route measures besides the cytology and diagnosis ones in CACU; with all of them the screening route chart appears.
|
||||
const RUTA = ['cacu_dias_resultado_colposcopia', 'cacu_dias_toma_colposcopia', 'cacu_dias_colposcopia_biopsia', 'cacu_dias_toma_biopsia', 'cacu_dias_biopsia_diagnostico']
|
||||
.map(id => item(id, id, 'C3r', ['fig_c3r_caja']));
|
||||
|
||||
describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
const abrir = (catalogo: ReturnType<typeof item>[]) => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(catalogo); fixture.detectChanges();
|
||||
http.match(() => true); fixture.detectChanges();
|
||||
};
|
||||
// The KPI and period requests are not what these tests are about.
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')]
|
||||
.map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim());
|
||||
|
||||
it('las figuras disponibles conservan su orden sin reservas vacías', () => {
|
||||
// Fails if a time figure changes place, if a missing indicator is drawn as a figure or if the published ones lose
|
||||
// the names of the request.
|
||||
abrir(CACU);
|
||||
expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico');
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
});
|
||||
|
||||
it('con la ruta del tamizaje no hay subsección «Tiempo de tamizaje a diagnóstico»: la gráfica dibuja los tiempos', () => {
|
||||
// Fails if the times the route chart draws also get a figure or a «pendiente» slot of their own next to it.
|
||||
abrir([...CACU, ...RUTA]);
|
||||
expect(root().querySelector('.subsection-title')).toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([]);
|
||||
expect(root().querySelector('app-indicador-screening-route')).not.toBeNull();
|
||||
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||
});
|
||||
|
||||
it('sin la gráfica de la ruta, colposcopía y biopsia publicadas son figuras con su nombre', () => {
|
||||
// Fails if a published measure of the route stays a pending slot while the chart that would draw it is not there.
|
||||
abrir([...CACU, ...RUTA.filter(medida => medida.id === 'cacu_dias_toma_colposcopia' || medida.id === 'cacu_dias_toma_biopsia')]);
|
||||
expect(root().querySelector('app-indicador-screening-route')).toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de colposcopía',
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de biopsia',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
});
|
||||
|
||||
it('el resultado de laboratorio se llama «Tiempo desde la toma de muestra al resultado»', () => {
|
||||
// Fails if the opportunity card goes back to «Días de toma a resultado».
|
||||
abrir(CACU);
|
||||
const titulosKpi = [...root().querySelectorAll('.kpi-section app-indicador-kpi-card h3')].map(h => h.textContent?.trim());
|
||||
expect(titulosKpi).toContain('Tiempo desde la toma de muestra al resultado');
|
||||
expect(titulosKpi).not.toContain('Días de toma a resultado');
|
||||
});
|
||||
|
||||
it('los indicadores clínicos son los dos pedidos, sin tarjetas vacías ni figuras pendientes', () => {
|
||||
// Fails if the time figures stay in the clinical section, if indicators with no figure get a card, or if a pending
|
||||
// figure («Progresión por grupo de riesgo», withdrawn) comes back.
|
||||
abrir(CACU);
|
||||
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||
expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull();
|
||||
});
|
||||
|
||||
it('Datos y definiciones conserva todo el catálogo', () => {
|
||||
// Fails if moving the time figures or hiding figure-less indicators removes them from the definitions tab.
|
||||
abrir(CACU);
|
||||
const definiciones = root().querySelector('#panel-datos')!.textContent!;
|
||||
for (const titulo of ['Tasa de detección histopatológica', 'Pacientes con citología anómala', 'Tiempo de toma de muestra a diagnóstico']) expect(definiciones).toContain(titulo);
|
||||
});
|
||||
});
|
||||
@@ -32,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () =>
|
||||
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
|
||||
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
|
||||
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
|
||||
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.' });
|
||||
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.', numerador: 0, denominador: 1 });
|
||||
});
|
||||
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
|
||||
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
@@ -143,8 +143,8 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
||||
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
||||
expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
|
||||
expect(titulos.filter(([, estado]) => estado === 'dibujado'))
|
||||
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado']]);
|
||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2]);
|
||||
.toEqual([['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Resultado histopatológico', 'dibujado']]);
|
||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([2, 6]);
|
||||
});
|
||||
it('el panel C3r avisa el periodo suprimido y la matriz CAM-03 sigue visible', () => {
|
||||
montar(false);
|
||||
@@ -199,15 +199,15 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
return pedidos;
|
||||
}
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const kpis = () => [...root().querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const tarjetas = () => [...root().querySelectorAll('.catalog-grid > *')] as HTMLElement[];
|
||||
const kpis = () => [...root().querySelectorAll('.kpi-section .kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const tarjetas = () => [...root().querySelectorAll('.graphic-section .catalog-grid > *')] as HTMLElement[];
|
||||
const completo = () => [...KPI_BY_DOMAIN.cama.map(propios), ...REALES];
|
||||
|
||||
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
|
||||
// Fails if the unavailable slot displays a value or displaces the published measures.
|
||||
const pedidos = cargar(completo());
|
||||
expect(kpis()).toHaveLength(5);
|
||||
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
||||
expect(root().querySelector('.kpi-section .kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
||||
expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
|
||||
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
|
||||
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con riesgo a carcinoma.');
|
||||
@@ -215,10 +215,11 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
|
||||
expect(kpis()[4].querySelector('.value')).toBeNull();
|
||||
});
|
||||
it('CAM-03 ocupa el lugar de la tarjeta pendiente, primero y con su vista especializada; no se consulta mientras no es visible', () => {
|
||||
it('CAM-03 ocupa el lugar de la tarjeta pendiente, después de los conteos y con su vista especializada; no se consulta mientras no es visible', () => {
|
||||
const pedidos = cargar(completo());
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
const primera = tarjetas()[0];
|
||||
// The exams' and patients' counts go first; the histopathology card is the last of the grid (the confirmation rate follows it).
|
||||
const primera = tarjetas().at(-1)!;
|
||||
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
expect(primera.querySelector('h2')!.textContent).toBe('Histopatología por BI-RADS');
|
||||
|
||||
@@ -50,10 +50,10 @@ describe('Identificadores de CaMa entre FHIR y la página', () => {
|
||||
});
|
||||
|
||||
it('el id de una medida de otro dominio sigue la regla general', () => {
|
||||
// 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', () => {
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => {
|
||||
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
|
||||
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
|
||||
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
|
||||
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.', numerador: 3, denominador: 20 });
|
||||
});
|
||||
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
|
||||
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
@@ -205,13 +205,15 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-section .kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const text = (card: HTMLElement, selector: string) => card.querySelector(selector)?.textContent?.trim();
|
||||
|
||||
it('con el catálogo actual: dos tarjetas con datos, dos pendientes y diagnóstico a tratamiento sin dato ni consulta', () => {
|
||||
// Fails if any card without a published measure makes a request or displays a value.
|
||||
const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
||||
// Fails if any card without a published measure makes a request or displays a value. The confirmation rate of the
|
||||
// clinical section is a published measure with its own panel, so it is requested too.
|
||||
const publicados = [...KPI_BY_DOMAIN.cama, CAMA_CONFIRMACION_KPI];
|
||||
const urls = load(publicados, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
expect([...new Set(urls)].sort()).toEqual(publicados.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
|
||||
@@ -260,7 +262,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
});
|
||||
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
|
||||
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
|
||||
load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
load([...KPI_BY_DOMAIN.cama, CAMA_CONFIRMACION_KPI], { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
const ids = fixture.componentInstance.searchResults().items.map(item => item.id);
|
||||
expect(ids).not.toContain('cama_biopsias');
|
||||
expect(ids).toContain('cama_birads_456_mastografia');
|
||||
|
||||
@@ -44,7 +44,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
}
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const section = () => root().querySelector('.graphic-section') as HTMLElement;
|
||||
const titles = () => [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
const titles = () => [...root().querySelectorAll('.graphic-section .catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
|
||||
it('CaMa: «Indicadores clínicos» muestra las tarjetas de la sección, sin el conteo de publicados', () => {
|
||||
// Fails if the heading goes back to the whole catalog while a card is not drawn.
|
||||
@@ -62,7 +62,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
|
||||
// Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones.
|
||||
open('cama', CAMA);
|
||||
for (const titulo of ['Tasa de confirmación histopatológica', 'Tiempo de tamizaje a diagnóstico', 'Días de la toma de la mastografía a su resultado']) {
|
||||
for (const titulo of ['Tiempo de tamizaje a diagnóstico', 'Días de la toma de la mastografía a su resultado']) {
|
||||
expect(section().textContent).not.toContain(titulo);
|
||||
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
|
||||
}
|
||||
@@ -70,7 +70,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
|
||||
open('cama', CAMA);
|
||||
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6');
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6');
|
||||
expect(nombres).not.toContain(CAMA[1].titulo);
|
||||
});
|
||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
||||
@@ -82,8 +82,23 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
|
||||
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
|
||||
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
|
||||
// It comes first, as in the reference, and is not counted as a published indicator.
|
||||
expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta);
|
||||
// It follows the exams' and patients' counts, as the request orders them, and is not counted as a published indicator.
|
||||
expect(root().querySelector('.graphic-section .catalog-grid')!.lastElementChild).toBe(tarjeta);
|
||||
});
|
||||
it('CaMa: el orden clínico es mastografías, pacientes, histopatología y tasa de confirmación', () => {
|
||||
// Fails if the clinical figures change order, if the confirmation rate leaves the clinical section or if the two
|
||||
// counts lose the titles of the request (BI-RADS 4, 5 ó 6, with the period).
|
||||
open('cama', CAMA);
|
||||
const orden = [...section().querySelectorAll('.catalog-grid > *, .kpi-grid > *')].map(e => e.tagName.toLowerCase());
|
||||
expect(orden).toEqual(['app-indicador-catalog-card', 'app-indicador-histopatologia-pendiente', 'app-indicador-kpi-panel']);
|
||||
expect(section().querySelector('.kpi-grid h3')?.textContent?.trim()).toBe('Tasa de confirmación histopatológica');
|
||||
});
|
||||
it('CaMa: sin la tasa de confirmación en el catálogo queda como pendiente al final', () => {
|
||||
// Fails if a missing indicator is dropped silently or drawn with numbers.
|
||||
open('cama', CAMA.filter(medida => medida.id !== 'cama_confirmacion_birads45'));
|
||||
const ultima = section().querySelector('.kpi-grid app-indicador-kpi-card') as HTMLElement;
|
||||
expect(ultima.textContent).toContain('Tasa de confirmación histopatológica');
|
||||
expect(ultima.textContent).toContain('Integración pendiente');
|
||||
});
|
||||
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
|
||||
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// Covers CaMa's «Tiempo de tamizaje a diagnóstico» in Indicadores de oportunidad: the five figures in the order of the
|
||||
// request, each pending while the catalog does not publish its indicator. Fixtures: a CaMa catalog shaped like /cama/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
|
||||
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||
const CAMA = [
|
||||
item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas']),
|
||||
item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja']),
|
||||
item('cama_dias_resultado_diagnostico', 'Tiempo de resultado a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
item('cama_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
];
|
||||
|
||||
describe('Indicadores de CaMa: tiempos de oportunidad', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
function abrir(catalogo: ReturnType<typeof item>[]) {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
http.expectOne('/cama/indicadores').flush(catalogo); fixture.detectChanges();
|
||||
http.match(() => true); fixture.detectChanges();
|
||||
}
|
||||
// The KPI and period requests are not what these tests are about.
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')]
|
||||
.map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim());
|
||||
|
||||
it('las cinco figuras van en su orden con los nombres pedidos; las no publicadas quedan pendientes', () => {
|
||||
// Fails if a time figure changes place, keeps the catalog's own title, or a missing indicator is drawn as a figure.
|
||||
abrir(CAMA);
|
||||
expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico');
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de mastografía a interpretación radiológica',
|
||||
'catalog-card: Tiempo de interpretación radiológica a diagnóstico',
|
||||
'figura-pendiente: Tiempo de interpretación radiológica a resultado de biopsia',
|
||||
'figura-pendiente: Tiempo de diagnóstico a tratamiento',
|
||||
'catalog-card: Tiempo de tamizaje a diagnóstico']);
|
||||
});
|
||||
|
||||
it('un indicador de tiempo que el catálogo no publica queda pendiente sin dejar de ocupar su lugar', () => {
|
||||
// Fails if a missing measure shifts the order or disappears instead of showing as pending.
|
||||
abrir(CAMA.filter(medida => medida.id !== 'cama_dias_resultado_diagnostico'));
|
||||
expect(titulos('.kpi-section .catalog-grid').slice(0, 2)).toEqual([
|
||||
'catalog-card: Tiempo de toma de mastografía a interpretación radiológica',
|
||||
'figura-pendiente: Tiempo de interpretación radiológica a diagnóstico']);
|
||||
});
|
||||
|
||||
it('las figuras de tiempo no se repiten en Indicadores clínicos ni salen del catálogo de Datos y definiciones', () => {
|
||||
// Fails if a time figure gets a second card in the clinical section or loses its definition entry.
|
||||
abrir(CAMA);
|
||||
expect(root().querySelector('.graphic-section')!.textContent).not.toContain('Tiempo de tamizaje a diagnóstico');
|
||||
expect(root().querySelector('#panel-datos')!.textContent).toContain('Días de la toma de la mastografía a su resultado');
|
||||
});
|
||||
});
|
||||
@@ -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 } };
|
||||
|
||||
@@ -213,11 +213,11 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
|
||||
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
|
||||
expect(h3).toEqual([
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, 2025-S2',
|
||||
'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 2025-S2',
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en 2025-S2',
|
||||
'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en 2025-S2',
|
||||
]);
|
||||
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, por paciente y por mastografía');
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6, por paciente y por mastografía');
|
||||
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
expect(graficas).toHaveLength(2);
|
||||
expect(graficas.map(g => g.label)).toEqual(h3);
|
||||
|
||||
@@ -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 } };
|
||||
|
||||
@@ -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,
|
||||
@@ -15,11 +17,56 @@ import {
|
||||
import * as fx from './indicadores-fhir.fixtures';
|
||||
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import vistaPreviaBundle from './fixtures/tea_vista_previa_bundle.json';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
|
||||
const SD = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
const CURVA = `${SD}/curva-referencia`;
|
||||
const curva = {
|
||||
url: CURVA, extension: [
|
||||
{ url: `${CURVA}/fuente`, valueString: 'tea-ritmo_posterior/3' }, { url: `${CURVA}/estado`, valueString: 'validada' },
|
||||
...[12, 24, 36].map(v => ({ url: `${CURVA}/edad-meses`, valueDecimal: v })),
|
||||
...([['p5', [4, 4.5, 5]], ['p25', [5, 5.5, 6]], ['mediana', [5.5, 6, 6.5]], ['p75', [6, 6.5, 7]], ['p95', [6.5, 7, 7.5]]] as [string, number[]][])
|
||||
.flatMap(([p, vs]) => vs.map(v => ({ url: `${CURVA}/${p}`, valueDecimal: v }))),
|
||||
],
|
||||
};
|
||||
const prediccion = (zona: string, z: number | null) => ({
|
||||
outcome: { coding: [{ system: `${CS}/tea-ados2-resultado`, code: 'ados2_item_11', display: 'Mostrar' }] },
|
||||
probabilityDecimal: 0.41,
|
||||
extension: [
|
||||
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
|
||||
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=1' },
|
||||
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
|
||||
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
|
||||
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
|
||||
],
|
||||
});
|
||||
// The fixture's patient summary with what the WebApi adds when the analysis and the association model have data.
|
||||
function conModelo(): Bundle {
|
||||
const bundle = structuredClone(fx.resumenPaciente) as Bundle;
|
||||
for (const r of resources(bundle)) {
|
||||
if (r.resourceType === 'DiagnosticReport') r.extension = [...(r.extension ?? []), { url: `${SD}/edad-meses`, valueDecimal: 23.6 }];
|
||||
const codigo = (r['code'] as { coding?: { code?: string }[] } | undefined)?.coding?.[0]?.code;
|
||||
if (r.resourceType === 'Observation' && codigo === 'ritmo_posterior' && !r.id?.startsWith('electrodos-'))
|
||||
r.extension = [...(r.extension ?? []), curva];
|
||||
}
|
||||
const riesgo: Resource = {
|
||||
resourceType: 'RiskAssessment', id: 'relacion-ados2-P-4A59E9D8B4', status: 'final',
|
||||
meta: { tag: resources(bundle)[0].meta?.tag },
|
||||
extension: [{ url: `${SD}/modelo-version`, valueString: '1.0.0' }, { url: `${SD}/modelo-validado`, valueBoolean: false },
|
||||
{ url: `${SD}/modelo-nivel`, valueString: 'item' }, { url: `${SD}/modelo-n-cohorte`, valueInteger: 40 }],
|
||||
prediction: [prediccion('occipital', -2.6), prediccion('parietal', null)],
|
||||
};
|
||||
bundle.entry = [...(bundle.entry ?? []), { resource: riesgo }];
|
||||
return bundle;
|
||||
}
|
||||
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
|
||||
|
||||
describe('Indicadores sobre FHIR', () => {
|
||||
@@ -85,6 +132,42 @@ describe('Indicadores sobre FHIR', () => {
|
||||
expect(figure.status).toBe('supported');
|
||||
});
|
||||
|
||||
it('la calidad del EEG muestra «No aceptable» en lugar de «Malo» sin cambiar los códigos de la categoría', () => {
|
||||
// Pins down: the caption is a presentation choice; the rows, the category catalog and the Measure keep MALO, and no
|
||||
// category is invented for «aceptable». Fails if the caption leaks into the codes, if «Malo» is drawn again or if a
|
||||
// fourth category appears.
|
||||
const datos = datosDeReportes(measure('M29-calidad-eeg'), reports(fx.m29Semestres), 'semestre');
|
||||
const s1 = datos.filas.filter(f => f['periodo'] === '2025-S1');
|
||||
expect(s1.map(f => f['categoria'])).toEqual(['BUENO', 'MALO', 'SIN_ANALIZAR']);
|
||||
const categorias = datos['categorias'] as Record<string, { etiqueta: string }>;
|
||||
expect(Object.entries(categorias).map(([codigo, c]) => [codigo, c.etiqueta]))
|
||||
.toEqual([['BUENO', 'Bueno'], ['MALO', 'No aceptable'], ['SIN_ANALIZAR', 'Sin analizar']]);
|
||||
const unPeriodo = datosDeReportes(measure('M29-calidad-eeg'), [reports(fx.m29Semestres)[0]], 'semestre');
|
||||
const figura = c2Figure(unPeriodo, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||
expect(figura.status).toBe('supported');
|
||||
const dibujo = JSON.stringify(figura.status === 'supported' ? figura.figure : {});
|
||||
for (const etiqueta of ['Bueno', 'No aceptable', 'Sin analizar']) expect(dibujo).toContain(etiqueta);
|
||||
expect(dibujo).not.toContain('Malo');
|
||||
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||
.toEqual(['Bueno', 'No aceptable', 'Sin analizar']);
|
||||
});
|
||||
|
||||
it('presenta Aceptable en ambas gráficas cuando M29 lo declara como categoría propia', () => {
|
||||
const actual = measure('M29-calidad-eeg');
|
||||
const conAceptable: Measure = {
|
||||
...actual, extension: [...actual.extension ?? [], { url: `${SD}/categoria`, extension: [
|
||||
{ url: 'codigo', valueCode: 'ACEPTABLE' }, { url: 'etiqueta', valueString: 'ACEPTABLE' },
|
||||
] }],
|
||||
};
|
||||
const datos = datosDeReportes(conAceptable, [reports(fx.m29Semestres)[0]], 'semestre');
|
||||
expect(datos.filas.find(fila => fila['categoria'] === 'ACEPTABLE')).toMatchObject({ n: 0 });
|
||||
const figura = c2Figure(datos, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||
expect(figura.status).toBe('supported');
|
||||
expect(JSON.stringify(figura.status === 'supported' ? figura.figure : {})).toContain('Aceptable');
|
||||
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||
.toEqual(['Bueno', 'No aceptable', 'Sin analizar', 'Aceptable']);
|
||||
});
|
||||
|
||||
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
||||
// Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here
|
||||
// instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period.
|
||||
@@ -126,6 +209,36 @@ describe('Servicios FHIR de indicadores', () => {
|
||||
expect((await answer).filas.length).toBe(2);
|
||||
});
|
||||
|
||||
it('sigue next para recuperar 201 periodos sin cambiar de endpoint ni de selección', async () => {
|
||||
// The links can contain the upstream origin. The second request must stay on the application's FHIR route.
|
||||
const service = TestBed.inject(FhirIndicadoresService);
|
||||
const periodos = periodosDesde('2009-01-01', 'mes', 201);
|
||||
const report = reports(fx.m21Semestres)[0];
|
||||
const entry = periodos.map(p => ({ resource: { ...report, period: { start: p + '-01', end: p + '-28' } } }));
|
||||
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'mes', periodos));
|
||||
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||
const page = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
|
||||
page.flush({ resourceType: 'Bundle', total: 201, entry: entry.slice(0, 200),
|
||||
link: [{ relation: 'next', url: 'http://webapi:5050/tea/fhir/MeasureReport?_offset=200' }] });
|
||||
const next = http.expectOne(r => r.url === '/tea/fhir/MeasureReport' && r.params.get('_offset') === '200');
|
||||
expect(next.request.params.get('measure')).toBe(page.request.params.get('measure'));
|
||||
expect(next.request.params.get('periodo')).toBe(periodos.join(','));
|
||||
expect(next.request.params.get('_count')).toBe('200');
|
||||
next.flush({ resourceType: 'Bundle', total: 201, entry: entry.slice(200) });
|
||||
expect((await answer).periodos).toHaveLength(201);
|
||||
});
|
||||
|
||||
it('rechaza un next que repite el offset sin volver a solicitar reportes', async () => {
|
||||
const service = TestBed.inject(FhirIndicadoresService);
|
||||
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'semestre'));
|
||||
const error = expect(answer).rejects.toThrow('Paginación FHIR inválida');
|
||||
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||
http.expectOne(r => r.url === '/tea/fhir/MeasureReport').flush({ ...fx.m21Semestres,
|
||||
link: [{ relation: 'next', url: '?_offset=0' }] });
|
||||
await error;
|
||||
http.expectNone(r => r.url === '/tea/fhir/MeasureReport');
|
||||
});
|
||||
|
||||
it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => {
|
||||
// Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each
|
||||
// measure computes its own periods or every period is evaluated to list them.
|
||||
@@ -210,6 +323,49 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
|
||||
});
|
||||
|
||||
it('el resumen lleva la edad al EEG y la norma por edad de la métrica cuando la WebApi las manda', async () => {
|
||||
// Pins down: the report's `edad-meses` extension as the EEG's age and a metric observation's `curva-referencia`
|
||||
// sub-extensions read back in order as the age norm (ages, five percentiles, source and state), so the page's
|
||||
// checks accept it. Fails if the adapter stops reading either extension or scrambles the series.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect(detalle.eeg!.edad_meses).toBe(23.6);
|
||||
expect(detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!.curva_referencia).toEqual({
|
||||
fuente: 'tea-ritmo_posterior/3', estado: 'validada', edad_meses: [12, 24, 36],
|
||||
p5: [4, 4.5, 5], p25: [5, 5.5, 6], mediana: [5.5, 6, 6.5], p75: [6, 6.5, 7], p95: [6.5, 7, 7.5] });
|
||||
});
|
||||
|
||||
it('el resumen arma la relación con el ADOS-2 del RiskAssessment y deja fuera la fila incompleta', async () => {
|
||||
// Pins down: the model's version, validation, level and cohort from the resource's extensions, and each
|
||||
// prediction as a row with the metric's and zone's labels, the outcome, OR, interval, q, z, both probabilities
|
||||
// and the observed score; a prediction without its z is dropped instead of failing the page's checks. Fails if
|
||||
// the adapter stops reading the RiskAssessment or lets an incomplete row through.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const relacion = (await answer).relacion_ados2!;
|
||||
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
|
||||
expect(relacion.filas).toEqual([{
|
||||
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
|
||||
resultado: 'ados2_item_11', resultado_etiqueta: 'Mostrar', evento: '>=1', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
|
||||
});
|
||||
|
||||
it('sin edad, norma ni modelo el resumen no inventa esos campos', async () => {
|
||||
// Pins down: a summary without the new extensions or a RiskAssessment (the fixture as the WebApi served it before
|
||||
// the analysis wrote them) leaves `edad_meses`, `curva_referencia` and `relacion_ados2` out, so the page hides
|
||||
// the chart and the panel. Fails if the adapter fills them with defaults.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect('edad_meses' in detalle.eeg!).toBe(false);
|
||||
expect(detalle.eeg!.alteraciones.some(a => 'curva_referencia' in a)).toBe(false);
|
||||
expect('relacion_ados2' in detalle).toBe(false);
|
||||
});
|
||||
|
||||
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
|
||||
// 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.
|
||||
@@ -220,4 +376,27 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
|
||||
expect(mapa.regiones[0].valor_z).toBe(-2.6);
|
||||
});
|
||||
|
||||
it('las regiones del mapa son las zonas del análisis del EEG', () => {
|
||||
// Pins down: Fz is its own region (frontal media) and the central region averages C3, Cz and C4 only, as the
|
||||
// EEG analysis's zones do, so a region on the map is the zone the association model names. Fails if Fz goes
|
||||
// back into the central average or the frontal media region disappears.
|
||||
const mapa = mapaDeElectrodos('picos_paroxisticos', 'Picos paroxísticos', { Fz: 3, C3: 1, Cz: 1.5, C4: 2 });
|
||||
expect(mapa.regiones.map(r => [r.codigo, r.etiqueta, r.valor_z])).toEqual([
|
||||
['frontal_media', 'Frontal media', 3], ['central', 'Central', 1.5]]);
|
||||
});
|
||||
|
||||
it('la vista previa de un EDF y su ADOS-2 se lee como la ficha de un paciente guardado', async () => {
|
||||
// The fixture is what `POST /governance/tea/eeg/preview` answered for a short synthetic EDF with an ADOS-2 report.
|
||||
// Pins that the bundle the server builds without storing anything passes the same converter and checks as a
|
||||
// stored patient's summary. Fails if the server's shape and the converter drift apart.
|
||||
const answer = firstValueFrom(service.vistaPrevia(vistaPreviaBundle));
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush({ concept: [] });
|
||||
const detalle = await answer;
|
||||
expect(detalle.id_seudonimo).toBe('vista-previa');
|
||||
expect(detalle.ados2?.modulo).toBe('2');
|
||||
expect(detalle.ados2?.dominios.length).toBe(2);
|
||||
expect(detalle.eeg?.calidad).toBe('malo');
|
||||
expect(detalle.eeg?.criterios_calidad.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map, Observable, shareReplay, switchMap } from 'rxjs';
|
||||
import { EMPTY, expand, map, Observable, reduce, shareReplay, switchMap } from 'rxjs';
|
||||
import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir';
|
||||
import { periodLabel } from './measure-report';
|
||||
import {
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
|
||||
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
|
||||
} from './indicadores-cama-fhir';
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
|
||||
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
|
||||
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
|
||||
@@ -40,8 +41,8 @@ const POPULATION_GROUP: Record<string, string> = {
|
||||
};
|
||||
|
||||
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures
|
||||
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`).
|
||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
||||
// and CaCu's have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`, `CACU-EU7` -> `cacu_eu7`).
|
||||
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? CACU_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
|
||||
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
|
||||
// Age groups travel as `16_23`; the page names them `16-23`.
|
||||
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
|
||||
@@ -55,11 +56,31 @@ function decimal(score: Score | undefined, name: string): number | null {
|
||||
return typeof value === 'number' ? value : null;
|
||||
}
|
||||
const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||
// A proportion's bounds travel as proportions; the rows hold percentages, like `valor`.
|
||||
const percent = (value: number | null) => value === null ? null : round1(value * 100);
|
||||
|
||||
// Captions the page shows instead of the ones a Measure publishes; the category codes stay those of the data.
|
||||
// TEA's EEG quality shows its invalid exams as «No aceptable».
|
||||
const ROTULOS_DE_CATEGORIA: Readonly<Record<string, Readonly<Record<string, string>>>> = {
|
||||
'M29-calidad-eeg': { MALO: 'No aceptable', ACEPTABLE: 'Aceptable' },
|
||||
};
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
// keeps every category ungrouped.
|
||||
export function categorias(measure: Measure): Record<string, Categoria> {
|
||||
const rotulos = ROTULOS_DE_CATEGORIA[measure.id ?? ''] ?? {};
|
||||
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: rotulos[codigo] ?? etiqueta, color: extension(e, 'color')?.valueString ?? null,
|
||||
grupo: extension(e, 'grupo')?.valueCode ?? null }]] : [];
|
||||
}));
|
||||
}
|
||||
// The groups a composition's categories belong to (`categoria-grupo`: code and caption), in the Measure's order; empty
|
||||
// when the Measure declares none.
|
||||
export function gruposDeCategoria(measure: Measure): Record<string, string> {
|
||||
return Object.fromEntries(extensions(measure, 'categoria-grupo').flatMap(e => {
|
||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||
return codigo && etiqueta ? [[codigo, etiqueta]] : [];
|
||||
}));
|
||||
}
|
||||
function contrato(measure: Measure): string {
|
||||
@@ -134,7 +155,7 @@ function proporcion(populations: Population[] | undefined, score: Score | undefi
|
||||
return {
|
||||
suprimido: 0, numerador, denominador,
|
||||
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
|
||||
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
|
||||
ic_bajo: percent(decimal(score, 'ic-bajo')), ic_alto: percent(decimal(score, 'ic-alto')),
|
||||
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
|
||||
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
|
||||
};
|
||||
@@ -193,13 +214,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 cacu = measure.id !== undefined && Object.hasOwn(CACU_MEASURE_IDS, measure.id);
|
||||
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 +262,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 +294,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 +317,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 +349,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,
|
||||
@@ -349,6 +419,29 @@ export class FhirMeasures {
|
||||
reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Bundle> {
|
||||
return this.http.get<Bundle>(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') });
|
||||
}
|
||||
|
||||
allReports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Report[]> {
|
||||
const path = `/${requireDominio(dominio)}/fhir/MeasureReport`;
|
||||
return this.reports(dominio, measure, params).pipe(
|
||||
map(bundle => ({ bundle, offset: 0 })),
|
||||
expand(({ bundle, offset }) => {
|
||||
const next = bundle.link?.find(link => link.relation === 'next');
|
||||
if (!next) return EMPTY;
|
||||
// A reverse proxy may expose the API's own origin in the link. Keep the request on the original endpoint
|
||||
// with the same measure and filters, advancing only by the offset that the server supplied.
|
||||
const url = new URL(next.url, `http://localhost${path}`);
|
||||
const raw = url.searchParams.get('_offset');
|
||||
const nextOffset = raw === null ? NaN : Number(raw);
|
||||
if (url.pathname !== path || !Number.isSafeInteger(nextOffset) || nextOffset <= offset) {
|
||||
throw new Error('Paginación FHIR inválida');
|
||||
}
|
||||
return this.reports(dominio, measure, params.set('_offset', nextOffset)).pipe(
|
||||
map(page => ({ bundle: page, offset: nextOffset })),
|
||||
);
|
||||
}, 1),
|
||||
reduce((reports, { bundle }) => reports.concat(resources(bundle, 'MeasureReport') as Report[]), [] as Report[]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -366,8 +459,8 @@ export class FhirIndicadoresService extends IndicadoresService {
|
||||
let params = new HttpParams().set('_count', MAX_COUNT);
|
||||
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
|
||||
return this.measures.one(dominio, indicador).pipe(
|
||||
switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
|
||||
map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
|
||||
switchMap(measure => this.measures.allReports(dominio, measure, params).pipe(
|
||||
map(reports => datosValidos(datosDeReportes(measure, reports, tipo, scope), indicador, tipo, periodos, scope)))));
|
||||
}
|
||||
override figura(selection: FigureSelection) {
|
||||
const dominio = requireDominio(selection.dominio ?? 'tea');
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Presentation labels for representations confirmed in the published catalog.
|
||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
||||
// from a prefix. Unknown options keep a neutral label in publication order.
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||
|
||||
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||
fig_c1_barras_alteracion: 'Barras por alteración',
|
||||
|
||||
@@ -26,8 +26,13 @@ export function percentText(value: number | null | undefined, fallback = 'No dis
|
||||
return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback;
|
||||
}
|
||||
|
||||
/** «12.3» from a count over its denominator. */
|
||||
export function shareNumber(k: number, n: number): string {
|
||||
const value = sharePercent(k, n);
|
||||
return value > 0 && value < 0.1 ? String(value) : value.toFixed(1);
|
||||
}
|
||||
|
||||
/** «12.3 %» from a count over its denominator. */
|
||||
export function shareText(k: number, n: number): string {
|
||||
const value = sharePercent(k, n);
|
||||
return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`;
|
||||
return `${shareNumber(k, n)} %`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
// What this module covers: how CaCu's FHIR measures, as the WebApi publishes them, reach the history figures: the
|
||||
// primary group of a proportion (`principal`), the page ids, the unit labels, the reconciliation of a composition and
|
||||
// the periods without units. The Measures are the catalog fixture (`fixtures/cacu_fhir_measures.json`); the reports
|
||||
// are synthetic and carry what the WebApi serialises, `group.code` included: the older bundle fixtures name the group
|
||||
// with `group.id` only, which hides the `principal` / `TOTAL` mismatch this spec pins down.
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { Measure, Report, datosDeReportes, indicadorDeMeasure } from './indicadores-fhir';
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
import { HISTORICO_CACU, historicoDeDominio } from './indicadores-historico-config';
|
||||
import { historicoFigura, HistoricoOpciones } from './indicadores-historico-figures';
|
||||
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||
import camaMeasuresData from './fixtures/cama_fhir_measures.json';
|
||||
|
||||
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const medida = (id: string) => publicadas.find(m => m.id === id)!;
|
||||
const cod = (c: string) => ({ coding: [{ code: c }] });
|
||||
const pob = (c: string, count: number) => ({ code: cod(c), count });
|
||||
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
|
||||
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
|
||||
const SEMESTRE = { start: '2025-01-01', end: '2025-06-30' };
|
||||
const SEMESTRE_2 = { start: '2025-07-01', end: '2025-12-31' };
|
||||
|
||||
// A proportion as the WebApi serialises it: group `principal`, a score only when the denominator is positive.
|
||||
const c1 = (period: { start: string; end: string }, numerador: number, denominador: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('principal'), population: [pob('initial-population', denominador), pob('denominator', denominador), pob('numerator', numerador)],
|
||||
...(denominador > 0 ? { measureScore: { value: numerador / denominador } } : {}) }],
|
||||
} as unknown as Report);
|
||||
// A composition: the categories as the first stratifier, the units as the initial population.
|
||||
const c2 = (m: Measure, period: { start: string; end: string }, conteos: Record<string, number>, unidades?: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('TOTAL'), population: [pob('initial-population', unidades ?? Object.values(conteos).reduce((a, b) => a + b, 0))],
|
||||
stratifier: [{ code: [cod('categoria')], stratum: Object.entries(conteos).map(([c, n]) => ({ value: cod(c), population: [pob('initial-population', n)] })) }] }],
|
||||
} as unknown as Report);
|
||||
// A duration: the median and the quartiles as extensions of the score.
|
||||
const c3r = (period: { start: string; end: string }, n: number, mediana?: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('TOTAL'), population: [pob('initial-population', n + 1), pob('measure-observation', n), pob('measure-population-exclusion', 1)],
|
||||
...(mediana === undefined ? {} : { measureScore: { value: mediana, unit: 'd', extension: [
|
||||
{ url: `${STRUCTURE}/q1`, valueDecimal: mediana - 2 }, { url: `${STRUCTURE}/q3`, valueDecimal: mediana + 3 }] } }) }],
|
||||
} as unknown as Report);
|
||||
const traza = (datos: ReturnType<typeof datosDeReportes>, i: number, opciones?: HistoricoOpciones) =>
|
||||
historicoFigura(datos, 'claro', opciones).figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
|
||||
const CACU: HistoricoOpciones = { unidades: historicoDeDominio('cacu')!.unidades, conciliarC2: true, c2SinPoblacionSinDato: true };
|
||||
|
||||
describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
|
||||
it('EU13 con el grupo `principal` que publica el WebApi: el cero es un valor y el panel no queda vacío', () => {
|
||||
// Pins down: the proportion's group reaches the history as the total. Fails if `principal` stays as it is and the
|
||||
// selector of the total drops every row, which left EU13's panel empty.
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 4, valor: 0 });
|
||||
expect(Object.keys(datos['grupos'] as object)).toEqual(['total']);
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect(traza(datos, 1).y).toEqual([0]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
});
|
||||
it('IND1 se publica como `ind1` y conserva su valor', () => {
|
||||
const datos = datosDeReportes(medida('IND1'), [c1(SEMESTRE, 1, 4), c1(SEMESTRE_2, 1, 4)], 'semestre');
|
||||
expect(datos.id).toBe('ind1');
|
||||
expect(traza(datos, 1).y).toEqual([25, 25]);
|
||||
});
|
||||
it('el intervalo de Wilson publicado usa la misma escala porcentual que el valor', () => {
|
||||
// Fails if the history drops the FHIR bounds or scales them a second time.
|
||||
for (const id of ['CACU-EU13', 'IND1']) {
|
||||
const reporte = c1(SEMESTRE, 1, 4);
|
||||
reporte.group![0].measureScore!.extension = [
|
||||
{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 },
|
||||
{ url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 },
|
||||
];
|
||||
const datos = datosDeReportes(medida(id), [reporte], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
|
||||
expect(traza(datos, 0).y).toEqual([69.9, 4.6]);
|
||||
}
|
||||
});
|
||||
it('un denominador cero es «sin dato», no un cero', () => {
|
||||
// The WebApi omits the score when there is no denominator: the period is listed as missing, not drawn at zero.
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 0), c1(SEMESTRE_2, 1, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ valor: null, denominador: 0 });
|
||||
expect(traza(datos, 1).y).toEqual([null, 25]);
|
||||
expect(historicoFigura(datos, 'claro').sinDato).toEqual(['2025 S1']);
|
||||
});
|
||||
it('sin intervalo publicado la banda queda vacía: el cliente no lo calcula ni lo inventa', () => {
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 1, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ ic_bajo: null, ic_alto: null });
|
||||
expect(traza(datos, 0)).toMatchObject({ name: 'Intervalo de confianza', x: [], y: [] });
|
||||
});
|
||||
it('en CaMa el grupo principal sigue siendo `total`', () => {
|
||||
// Regression: the normalisation CaCu shares with CaMa keeps CaMa's own result.
|
||||
const cama = (resources(camaMeasuresData as unknown as Bundle, 'Measure') as Measure[]).find(m => m.id === 'CAMA-CONFIRMACION-BIRADS45')!;
|
||||
const datos = datosDeReportes(cama, [c1(SEMESTRE, 2, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ grupo: 'total', valor: 50 });
|
||||
});
|
||||
it('los paneles activos usan ids de página y contratos que el catálogo publica', () => {
|
||||
// Pins down the compatibility of the identifiers: every active panel is a measure `dev` publishes, under the id
|
||||
// the page gives it, and with the contract the panel expects.
|
||||
const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)]));
|
||||
const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo);
|
||||
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']);
|
||||
for (const panel of activos) {
|
||||
expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id);
|
||||
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
|
||||
}
|
||||
});
|
||||
it('ningún panel queda reservado: los nueve leen su medida del catálogo', () => {
|
||||
// Pins down: every CaCu history panel is active, the risk bands included, under the page id of its measure.
|
||||
expect(HISTORICO_CACU.filter(p => p.enDesarrollo)).toEqual([]);
|
||||
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Histórico de CaCu: composiciones (C2)', () => {
|
||||
const eu7 = () => medida('CACU-EU7');
|
||||
const conteos = (extra: Record<string, number> = {}) => ({ ...Object.fromEntries(declaradas(eu7()).map((c, i) => [c, [8, 3, 2, 1, 1, 0, 1][i]])), ...extra });
|
||||
|
||||
it('el reporte de EU7 conserva las unidades de cada periodo y la conciliación pasa', () => {
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos())], 'semestre');
|
||||
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 16 });
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(figura.figure.data.map(t => (t['y'] as number[])[0])).toEqual([8, 3, 2, 1, 1, 0, 1]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
});
|
||||
it('una categoría que el Measure no declara rompe la conciliación del Histórico y no cambia el Resumen', () => {
|
||||
// Pins down: a category the report counts but the Measure does not declare (the glandular results are still an open
|
||||
// decision) is no longer a shorter bar. The adapter itself reads the report as before.
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos({ AGC: 2 }))], 'semestre');
|
||||
expect(datos.filas.map(f => f['categoria'])).not.toContain('AGC');
|
||||
expect(() => historicoFigura(datos, 'claro', CACU)).toThrow('Los conteos por categoría no suman las unidades del periodo');
|
||||
expect(() => historicoFigura(datos, 'claro')).not.toThrow();
|
||||
});
|
||||
it('un periodo sin pacientes es «sin dato» en CaCu y no barras en cero', () => {
|
||||
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0), c2(eu7(), SEMESTRE_2, conteos())], 'semestre');
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(figura.sinDato).toEqual(['2025 S1']);
|
||||
expect(figura.figure.data.every(t => (t['y'] as (number | null)[])[0] === null)).toBe(true);
|
||||
expect((figura.figure.data[0]['y'] as number[])[1]).toBe(8);
|
||||
});
|
||||
it('sin la opción de CaCu un periodo sin unidades se dibuja como antes (CaMa no cambia)', () => {
|
||||
// Regression: the rule is the domain's, not the figure module's.
|
||||
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0)], 'semestre');
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
expect(figura.figure.data.every(t => (t['y'] as number[])[0] === 0)).toBe(true);
|
||||
});
|
||||
it('la confirmación por citología declara sus categorías y se concilia igual', () => {
|
||||
const m = medida('CACU-CONFIRMACION-CITOLOGIA');
|
||||
const datos = datosDeReportes(m, [c2(m, SEMESTRE, Object.fromEntries(declaradas(m).map((c, i) => [c, i])))], 'semestre');
|
||||
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 21 });
|
||||
expect(() => historicoFigura(datos, 'claro', CACU)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Histórico de CaCu: tiempos (C3r) y etiquetas de unidad', () => {
|
||||
const m = () => medida('CACU-EU-TIEMPO-REPORTE');
|
||||
it('la mediana y los cuartiles hablan de citologías en CaCu', () => {
|
||||
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12), c3r(SEMESTRE_2, 0)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ mediana: 12, q1: 10, q3: 15, n: 6, unidad: 'dias' });
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(traza(datos, 1, CACU)['text'][0]).toBe('Mediana: 12 días<br>Q1 a Q3: 10 a 15 días<br>6 citologías');
|
||||
expect(figura.comoLeer).toContain('las citologías');
|
||||
expect(figura.comoLeer).not.toContain('mastograf');
|
||||
// A period without observations is missing, not zero.
|
||||
expect(traza(datos, 1, CACU)['y']).toEqual([12, null]);
|
||||
expect(figura.sinDato).toEqual(['2025 S2']);
|
||||
});
|
||||
it('sin la configuración de CaCu el texto de los exámenes sigue siendo el de CaMa', () => {
|
||||
// Regression: `examen` keeps reading «mastografías» wherever the domain does not name it otherwise.
|
||||
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12)], 'semestre');
|
||||
expect(traza(datos, 1)['text'][0]).toContain('6 mastografías');
|
||||
expect(historicoFigura(datos, 'claro').comoLeer).toContain('las mastografías');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing
|
||||
// until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and
|
||||
// the notice. Responses are synthetic, shaped like /cacu/indicadores/<id>/periodos and /datos.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { HISTORICO_CACU } from './indicadores-historico-config';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: { data: { name?: string; y?: (number | null)[]; text?: string[] }[] }; label?: string; }
|
||||
|
||||
const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStart(2, '0')}`);
|
||||
const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1'];
|
||||
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
|
||||
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const RESERVADOS: string[] = [];
|
||||
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
||||
// Every measure the catalog could publish, reserved ones included: publishing them must not activate them.
|
||||
const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item);
|
||||
|
||||
function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) {
|
||||
const contrato = opciones.contrato ?? CONTRATOS[id];
|
||||
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
|
||||
const vacio = (p: string) => p === opciones.sinPoblacion;
|
||||
const filas = contrato === 'C2'
|
||||
? periodos.flatMap(p => [fila(p, { categoria: 'NORMAL', n: vacio(p) ? 0 : 7, orden: 0 }), fila(p, { categoria: 'ASC-US', n: vacio(p) ? 0 : 5, orden: 1 })])
|
||||
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 0, numerador: 0, denominador: 10, ic_bajo: null, ic_alto: null }))
|
||||
: periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' }));
|
||||
return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' ? 'paciente' : 'examen', filas,
|
||||
categorias: { NORMAL: { etiqueta: 'Normal', color: '#9DBFE3' }, 'ASC-US': { etiqueta: 'ASC-US', color: '#2F6DB3' } },
|
||||
...(contrato === 'C2' ? { unidades_periodo: Object.fromEntries(periodos.map(p => [p, vacio(p) ? 0 : 12])) } : {}) };
|
||||
}
|
||||
|
||||
describe('Histórico de CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
|
||||
const abrirDialogo = vi.fn();
|
||||
function montar(catalog: Indicador[] = CATALOGO, active = false) {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [
|
||||
provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } },
|
||||
] });
|
||||
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog);
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
|
||||
// Answers in waves, because the shared request queue runs four at a time. `pedidos` keeps what each data request asked for.
|
||||
const pedidos: { id: string; periodos: string[] }[] = [];
|
||||
function responder(opciones: { fallo?: (r: TestRequest) => boolean; datos?: (id: string) => { contrato?: string; sinPoblacion?: string } } = {}) {
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
const url = r.request.url, id = url.split('/').at(-2)!;
|
||||
if (opciones.fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; }
|
||||
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||
else {
|
||||
const periodos = r.request.params.get('periodos')!.split(',');
|
||||
pedidos.push({ id, periodos });
|
||||
r.flush(datos(id, periodos[0].includes('S') ? 'semestre' : 'mes', periodos, opciones.datos?.(id)));
|
||||
}
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
}
|
||||
beforeEach(() => { pedidos.length = 0; });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
|
||||
const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!;
|
||||
const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo;
|
||||
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Trazabilidad de ' + titulo))!;
|
||||
|
||||
it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => {
|
||||
// Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it.
|
||||
montar();
|
||||
http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
const vistos = new Set<string>();
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
vistos.add(r.request.url.split('/').at(-2)!);
|
||||
const id = r.request.url.split('/').at(-2)!;
|
||||
if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: MESES.map(periodo => ({ periodo, tipo: 'mes' })) });
|
||||
else r.flush(datos(id, 'mes', r.request.params.get('periodos')!.split(',')));
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
|
||||
for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false);
|
||||
});
|
||||
it('dibuja los nueve paneles en orden: los activos con gráfica y los reservados sin consultar', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||
const reservados = paneles().slice(ACTIVOS.length);
|
||||
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
|
||||
expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual(
|
||||
HISTORICO_CACU.slice(ACTIVOS.length).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
||||
});
|
||||
it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => {
|
||||
// Pins down: the state of a reserved panel comes from the config alone.
|
||||
for (const catalogo of [ACTIVOS.map(item), CATALOGO]) {
|
||||
montar(catalogo, true); responder();
|
||||
expect(paneles().slice(ACTIVOS.length).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(RESERVADOS.length).fill('Trabajo en desarrollo'));
|
||||
fixture.destroy(); TestBed.resetTestingModule();
|
||||
}
|
||||
});
|
||||
it('no antepone ningún aviso a los paneles', () => {
|
||||
// Fails if a notice about clinical validation or suppression is shown again above the history's panels.
|
||||
montar();
|
||||
expect(root().querySelector('[data-aviso="historico"]')).toBeNull();
|
||||
expect(root().textContent).not.toContain('sujetos a validación clínica');
|
||||
});
|
||||
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
|
||||
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||
});
|
||||
it('elegir «Todos» pide solo los periodos que faltan y los suma', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
// Going back to five is local: nothing is asked again.
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toEqual([]);
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||
});
|
||||
it.each([false, true])('acumula 5→10→Todos sin duplicados al recibir primero la segunda respuesta: %s', invertir => {
|
||||
// The two expansions are disjoint. Either arrival order must preserve all twelve periods.
|
||||
montar([item('ind1')], true); responder();
|
||||
fixture.componentInstance.elegirVentana(10);
|
||||
fixture.componentInstance.elegirVentana(0);
|
||||
fixture.componentInstance.elegirVentana(0);
|
||||
const ampliaciones = http.match(r => r.url.endsWith('/datos'));
|
||||
const periodos = (r: TestRequest) => r.request.params.get('periodos')!.split(',');
|
||||
expect(ampliaciones.map(periodos)).toEqual([MESES.slice(2, 7), MESES.slice(0, 2)]);
|
||||
for (const r of invertir ? ampliaciones.reverse() : ampliaciones) {
|
||||
r.flush(datos('ind1', 'mes', periodos(r)));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('reintenta la ampliación fallida conservando los cinco periodos y sin repetir periodos cargados', () => {
|
||||
montar([item('ind1')], true); responder();
|
||||
fixture.componentInstance.elegirVentana(0);
|
||||
http.expectOne(r => r.url.endsWith('/datos')).flush('private', { status: 500, statusText: 'Error' });
|
||||
fixture.detectChanges();
|
||||
const panel = panelDe(tituloDe('ind1'));
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(5);
|
||||
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Error');
|
||||
(panel.querySelector('button') as HTMLButtonElement).click();
|
||||
const reintento = http.expectOne(r => r.url.endsWith('/datos'));
|
||||
expect(reintento.request.params.get('periodos')?.split(',')).toEqual(MESES.slice(0, 7));
|
||||
reintento.flush(datos('ind1', 'mes', MESES.slice(0, 7)));
|
||||
fixture.detectChanges();
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
expect(panel.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
it('cambiar a Semestral pide los últimos cinco semestres una vez y volver a Mensual no repite', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toEqual([]);
|
||||
});
|
||||
it('una medida ausente muestra «Trabajo en desarrollo» y no se consulta', () => {
|
||||
montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder();
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo');
|
||||
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
});
|
||||
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
|
||||
montar(CATALOGO, true);
|
||||
responder({ fallo: r => r.request.url.includes('/cacu_eu13/') && r.request.url.endsWith('/datos') });
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(panel.textContent).not.toContain('private');
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
const reintentar = panel.querySelector('button') as HTMLButtonElement;
|
||||
reintentar.click(); fixture.detectChanges(); responder();
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||
});
|
||||
it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => {
|
||||
// Pins down the expected contract: the panel does not draw a C1 where it declared a composition.
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} });
|
||||
const panel = panelDe(tituloDe('cacu_eu7'));
|
||||
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1');
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
});
|
||||
it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => {
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} });
|
||||
expect(graficaDe(tituloDe('cacu_eu13')).figure!.data[1].y).toEqual([0, 0, 0, 0, 0]);
|
||||
expect(panelDe(tituloDe('cacu_eu13')).querySelector('[data-plegable="sin-dato"]')).toBeNull();
|
||||
const eu7 = panelDe(tituloDe('cacu_eu7'));
|
||||
expect(eu7.querySelector('[data-plegable="sin-dato"]')?.textContent).toContain('Periodos sin dato (1)');
|
||||
expect(eu7.textContent).toContain('oct 2025');
|
||||
expect(graficaDe(tituloDe('cacu_eu7')).figure!.data[0].y).toEqual([7, 7, null, 7, 7]);
|
||||
});
|
||||
it('los tiempos hablan de citologías', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
for (const id of ['cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']) {
|
||||
expect(graficaDe(tituloDe(id)).figure!.data[1].text![0]).toContain('20 citologías');
|
||||
expect(panelDe(tituloDe(id)).textContent).toContain('las citologías');
|
||||
expect(panelDe(tituloDe(id)).textContent).not.toContain('mastograf');
|
||||
}
|
||||
});
|
||||
it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => {
|
||||
montar(RESERVADOS.map(item), true);
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('sin periodos con reportes un panel activo muestra «Sin datos»', () => {
|
||||
montar([item('ind1')], true);
|
||||
http.expectOne(r => r.url.endsWith('/periodos')).flush({ id: 'ind1', periodos: [] });
|
||||
fixture.detectChanges();
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('[role="status"]')?.textContent).toBe('Sin datos');
|
||||
expect(graficas()).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -81,13 +81,21 @@ describe('Histórico de CaMa', () => {
|
||||
});
|
||||
it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual([
|
||||
'Días de la toma de la mastografía a su resultado',
|
||||
'Días del resultado de la mastografía al diagnóstico',
|
||||
'Días de tamizaje a diagnóstico',
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'Pacientes con resultado BI-RADS 4, 5 ó 6',
|
||||
'Resultado histopatológico',
|
||||
'Tasa de confirmación histopatológica',
|
||||
]);
|
||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
||||
expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico']);
|
||||
expect(pendientes).toEqual(['Días del resultado de la mastografía al diagnóstico', 'Resultado histopatológico']);
|
||||
expect(paneles()).toHaveLength(7);
|
||||
const titulo = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
||||
expect(paneles()[2].querySelector('h2')?.textContent).toBe(titulo);
|
||||
expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true);
|
||||
const titulo = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||
expect(paneles()[3].querySelector('h2')?.textContent).toBe(titulo);
|
||||
expect(graficas().some(g => g.label?.startsWith('Trazabilidad de ' + titulo))).toBe(true);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
||||
});
|
||||
@@ -96,7 +104,7 @@ describe('Histórico de CaMa', () => {
|
||||
// closed disclosure labelled «Periodos sin dato (n)»; opening it shows every month, as the note read before. Fails if the
|
||||
// list is open from the start, is cut short, or the figure changes.
|
||||
montar(CATALOGO, true); responder(undefined, periodo => !['2025-01', '2025-02'].includes(periodo));
|
||||
const panel = paneles()[1];
|
||||
const panel = paneles()[4];
|
||||
const plegable = panel.querySelector<HTMLDetailsElement>('details[data-plegable="sin-dato"]')!;
|
||||
expect(plegable).not.toBeNull();
|
||||
expect(plegable.open).toBe(false);
|
||||
@@ -117,7 +125,7 @@ describe('Histórico de CaMa', () => {
|
||||
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual');
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
|
||||
});
|
||||
it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
@@ -126,7 +134,7 @@ describe('Histórico de CaMa', () => {
|
||||
const semestrales = responder();
|
||||
expect(semestrales.length).toBeGreaterThan(0);
|
||||
expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true);
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
|
||||
toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -135,7 +143,7 @@ describe('Histórico de CaMa', () => {
|
||||
const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } };
|
||||
expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']);
|
||||
fixture.componentInstance.elegirVentana(5); fixture.detectChanges();
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
|
||||
});
|
||||
it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
@@ -144,10 +152,10 @@ describe('Histórico de CaMa', () => {
|
||||
expect(abrirDialogo).toHaveBeenCalledTimes(1);
|
||||
const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] };
|
||||
expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES);
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) });
|
||||
fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges();
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||
});
|
||||
it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => {
|
||||
// Fails if one failing indicator blanks the others, leaks its body, or cannot be retried.
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Dominio } from './indicadores.models';
|
||||
|
||||
// What each domain's history tab draws, declared as data: the panels and their order, the contract each one is
|
||||
// expected to carry, the labels of its unit and what the tab may ask for. A domain without an entry here (TEA) draws
|
||||
// its whole catalog.
|
||||
|
||||
export type ContratoHistorico = 'C1' | 'C2' | 'C3r';
|
||||
// The mark each contract gets in `historicoFigura`: counts add up to a total, percentages and medians do not.
|
||||
export type GraficaHistorico = 'barras_apiladas' | 'linea_porcentaje' | 'linea_mediana';
|
||||
export interface PanelHistorico {
|
||||
// The page's id of the measure (what `indicadorId` gives).
|
||||
id: string;
|
||||
titulo: string;
|
||||
contrato?: ContratoHistorico;
|
||||
grafica?: GraficaHistorico;
|
||||
enDesarrollo?: boolean;
|
||||
// The FHIR ids the reserved panels will use even if the catalog already publishes them.
|
||||
fhir?: readonly string[];
|
||||
}
|
||||
export interface UnidadHistorico { plural: string; eje: string }
|
||||
export interface HistoricoDominio {
|
||||
paneles: readonly PanelHistorico[];
|
||||
// The unit a measure publishes (`examen`) named as the domain calls it; overrides the figure module's default.
|
||||
unidades?: Readonly<Record<string, UnidadHistorico>>;
|
||||
// How many of the latest periods are requested when the tab opens. Without it, every period is requested.
|
||||
periodosIniciales?: number;
|
||||
// A composition (C2) whose categories do not add up to the report's units is an error, not a shorter bar.
|
||||
conciliarC2?: boolean;
|
||||
// A composition period with no units is «sin dato», not a bar of zeros.
|
||||
c2SinPoblacionSinDato?: boolean;
|
||||
}
|
||||
|
||||
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
|
||||
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
|
||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
|
||||
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6' },
|
||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes con resultado BI-RADS 4, 5 ó 6' },
|
||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
];
|
||||
|
||||
// CaCu's history. The active panels read the measures the catalog publishes; the reserved ones (`enDesarrollo`) never ask.
|
||||
export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
];
|
||||
|
||||
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||
cama: { paneles: HISTORICO_CAMA },
|
||||
cacu: {
|
||||
paneles: HISTORICO_CACU,
|
||||
// `examen` is the citology here.
|
||||
unidades: { examen: { plural: 'citologías', eje: 'Citologías' } },
|
||||
periodosIniciales: 5,
|
||||
conciliarC2: true,
|
||||
c2SinPoblacionSinDato: true,
|
||||
},
|
||||
};
|
||||
|
||||
// The domain's declared history, if it has one and the tab is on.
|
||||
export const historicoDeDominio = (dominio: Dominio): HistoricoDominio | undefined => HISTORICOS[dominio];
|
||||
@@ -118,3 +118,46 @@ describe('Histórico: datos inválidos', () => {
|
||||
expect(() => historicoFigura(datos(), 'claro')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en TEA', () => {
|
||||
const med = (id: string) => figura({ ...base('C3r', MESES, [fila('2025-01', { mediana: 10, q1: 9, q3: 12, n: 9 })], { unidad: 'examen' }), id } as IndicadorDatos);
|
||||
const cats = [{ periodo: '2025-01', categoria: 'A', n: 2, orden: 0, suprimido: 0 }, { periodo: '2025-01', categoria: 'B', n: 3, orden: 1, suprimido: 0 }];
|
||||
it('las tres medianas de CaMa usan el pie de la solicitud y las de otros dominios conservan el suyo', () => {
|
||||
// Fails if a CaMa time figure keeps the general caption, or if the new one leaks into TEA's or CaCu's medians.
|
||||
for (const id of ['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico']) {
|
||||
expect(med(id).comoLeer).toBe('La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.');
|
||||
}
|
||||
expect(med('cacu_eu_tiempo_reporte').comoLeer).toContain('la mitad central');
|
||||
});
|
||||
it('la tasa de confirmación de CaMa dice solo qué representa la línea; otros porcentajes conservan el pie con la banda', () => {
|
||||
// Fails if the confirmation rate keeps the confidence-band sentence, or if another percentage loses it.
|
||||
const pct = (id: string) => figura({ ...base('C1', MESES, [fila('2025-01', { valor: 50, numerador: 1, denominador: 2, ic_bajo: 9, ic_alto: 91 })]), id } as IndicadorDatos);
|
||||
expect(pct('cama_confirmacion_birads45').comoLeer).toBe('La línea representa el porcentaje de confirmación histopatológica.');
|
||||
expect(pct('ind1').comoLeer).toContain('su intervalo de confianza');
|
||||
});
|
||||
it('resultado histopatológico y mastografías BI-RADS 4, 5 ó 6 usan el pie de total por categoría', () => {
|
||||
// Fails if the two keep the old sentence, or if the patients' counts (which carry none) or another count gets it.
|
||||
const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría';
|
||||
for (const id of ['cama_histopatologia_birads', 'cama_birads_456_mastografia']) expect(figura({ ...base('C2', MESES, cats), id } as IndicadorDatos).comoLeer).toBe(pie);
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe('');
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total');
|
||||
});
|
||||
it('M30 dibuja EEG anormal y EEG normal como dos líneas complementarias', () => {
|
||||
// Fails if the normal line stops mirroring the abnormal one over the same denominator, or if a period without
|
||||
// evaluable children is drawn as normal (it stays a gap), or if the caption changes.
|
||||
const m30 = figura({ ...base('C1', MESES, [fila('2025-01', { valor: 62.5, numerador: 5, denominador: 8, ic_bajo: 30.6, ic_alto: 86.3 }),
|
||||
fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos);
|
||||
const f = m30.figure as unknown as Fig;
|
||||
const lineas = f.data.filter(t => t['mode'] === 'lines+markers');
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG anormal', 'EEG normal']);
|
||||
expect(lineas[0]['y']).toEqual([62.5, null, null, null]);
|
||||
expect(lineas[1]['y']).toEqual([37.5, null, null, null]);
|
||||
expect(JSON.stringify(lineas[0]['text'])).toContain('5 de 8');
|
||||
expect(JSON.stringify(lineas[1]['text'])).toContain('3 de 8');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([86.3, 30.6]);
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza (normal)')!['y']).toEqual([69.4, 13.7]);
|
||||
expect(m30.comoLeer).toBe('La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.');
|
||||
expect(m30.notaMetodologica).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette';
|
||||
import { sortedPeriods } from './indicadores-periodos';
|
||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||
|
||||
export interface HistoricoFigura {
|
||||
contrato: string;
|
||||
figure: PlotlyFigure;
|
||||
comoLeer: string;
|
||||
notaMetodologica?: string;
|
||||
suprimidos: string[];
|
||||
sinDato: string[];
|
||||
}
|
||||
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 EEG indicators avoid green; their colours are shared with their age groups' palette.
|
||||
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
|
||||
// CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
|
||||
const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
|
||||
const FONDO_AZUL = '#9DBFE380';
|
||||
@@ -31,12 +29,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');
|
||||
@@ -89,33 +94,63 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<str
|
||||
return { validas, suprimidos, sinDato };
|
||||
}
|
||||
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
|
||||
// CaMa's line charts share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
// CaMa's line charts (and TEA's, which follow them) share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
function colorDeLinea(id: string, tema: Tema) {
|
||||
if (LINEAS[id]) return { linea: LINEAS[id], relleno: LINEAS[id] + '40' };
|
||||
if (id.startsWith('cama_')) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
if (id.startsWith('cama_') || /^M\d+_/.test(id)) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
const linea = c2Theme(tema).line;
|
||||
return { linea, relleno: linea + '40' };
|
||||
}
|
||||
|
||||
export const M30_RESULTADO_EEG = 'M30_resultado_eeg';
|
||||
// Normal takes the cool side of the palette and abnormal the warm one, as in the other domains' compositions.
|
||||
const NORMAL_EEG = C2_PALETTE.frios[3], ANORMAL_EEG = C2_PALETTE.calidos[0];
|
||||
|
||||
const PIE_PORCENTAJE: Readonly<Record<string, string>> = {
|
||||
cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.',
|
||||
[M30_RESULTADO_EEG]: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
};
|
||||
const PIE_MEDIANA: Readonly<Record<string, string>> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id,
|
||||
'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.']));
|
||||
const PIE_CATEGORIAS: Readonly<Record<string, string>> = Object.fromEntries(['cama_histopatologia_birads', 'cama_birads_456_mastografia'].map(id => [id,
|
||||
'Cada barra indica el total de pacientes por periodo en cada categoría']));
|
||||
|
||||
type Trazo = Omit<HistoricoFigura, 'contrato'>;
|
||||
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data);
|
||||
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje');
|
||||
const trazo = data.id === M30_RESULTADO_EEG ? { linea: ANORMAL_EEG, relleno: ANORMAL_EEG + '40' } : colorDeLinea(data.id, tema);
|
||||
const resultadoEeg = data.id === M30_RESULTADO_EEG;
|
||||
const nombre = resultadoEeg ? 'EEG anormal' : 'Porcentaje';
|
||||
const complemento = (llave: string) => campo(validas, llave).map(v => v === null ? null : Math.round(10 * (100 - v)) / 10);
|
||||
// EEG results are two complementary lines; the normal one mirrors the abnormal share and its interval.
|
||||
const normal = data.id === M30_RESULTADO_EEG ? [
|
||||
banda(periodos.map(etiquetaPeriodo), complemento('ic_alto'), complemento('ic_bajo'), 'Intervalo de confianza (normal)', NORMAL_EEG, NORMAL_EEG + '40'),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'EEG normal', x: periodos.map(etiquetaPeriodo), y: complemento('valor'), connectgaps: false,
|
||||
line: { color: NORMAL_EEG, width: 2 }, marker: { color: NORMAL_EEG },
|
||||
text: validas.map(row => row ? `${(row['denominador'] as number) - (row['numerador'] as number)} de ${row['denominador']}` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} %<br>%{text}<extra></extra>' },
|
||||
] : [];
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
|
||||
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: nombre, x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
|
||||
text: validas.map(row => {
|
||||
if (!row) return '';
|
||||
const intervalo = numero(row['ic_bajo']) && numero(row['ic_alto']) ? `<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : '';
|
||||
return `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}${intervalo}`;
|
||||
}),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
...normal,
|
||||
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
...(resultadoEeg ? { notaMetodologica: 'Resultado experimental. La proporción usa el primer EEG de buena calidad de cada niño en el periodo. La clasificación de EEG normal está pendiente de validación.' } : {}),
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
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 {
|
||||
@@ -128,7 +163,7 @@ function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones):
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena);
|
||||
return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout;
|
||||
})() },
|
||||
comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de ${unidad.plural === 'pacientes' ? 'los pacientes' : 'las ' + unidad.plural}.`,
|
||||
comoLeer: PIE_MEDIANA[data.id] ?? `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de ${unidad.plural === 'pacientes' ? 'los pacientes' : 'las ' + unidad.plural}.`,
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
@@ -137,8 +172,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 +186,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,12 +209,12 @@ 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' } },
|
||||
comoLeer: data.id === 'cama_birads_456_paciente' ? ''
|
||||
: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||
: CONTEOS[data.id]?.comoLeer ?? PIE_CATEGORIAS[data.id] ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
@@ -176,30 +226,8 @@ 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) };
|
||||
}
|
||||
// The share of the children in the screening at each period's end who hadn't finished it, from M28's stages.
|
||||
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
|
||||
const periodos = validar(data);
|
||||
const n = (periodo: string, categorias: readonly string[]) => {
|
||||
const valores = categorias.map(c => data.filas.find(f => f['periodo'] === periodo && f['categoria'] === c)?.['n']);
|
||||
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
|
||||
};
|
||||
const puntos = periodos.map(periodo => {
|
||||
const proceso = n(periodo, M28_EN_PROCESO), completo = n(periodo, [M28_COMPLETO]);
|
||||
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
|
||||
});
|
||||
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
|
||||
return {
|
||||
contrato: 'C1',
|
||||
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
|
||||
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} niños` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
|
||||
layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: 'De los niños en el tamizaje al cierre de cada periodo, el porcentaje que todavía no lo completaba con un EEG de buena calidad.',
|
||||
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Covers the history tab in the page: it exists for CaMa only, sits between Resumen and Seguimiento, and its
|
||||
// Covers the history tab in the page: it sits between Indicadores and the risk analysis tab, and its
|
||||
// panel loads nothing until it is opened. Catalogs are synthetic, shaped like /<dominio>/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -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(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
fixture.componentInstance.changeSection('analisis');
|
||||
fixture.detectChanges();
|
||||
@@ -38,20 +38,21 @@ 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();
|
||||
});
|
||||
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(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
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', () => {
|
||||
it('TEA tiene Trazabilidad y Análisis de Riesgo', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Trazabilidad', 'Análisis de Riesgo', '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 Indicadores se oculta', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
const panel = () => root().querySelector('#panel-historico') as HTMLElement;
|
||||
expect(panel().hidden).toBe(true);
|
||||
@@ -62,7 +63,7 @@ describe('Pestaña Histórico', () => {
|
||||
fixture.componentInstance.changeSection('resumen'); fixture.detectChanges();
|
||||
expect(panel().hidden).toBe(true);
|
||||
});
|
||||
it('cambiar de dominio vuelve a Resumen', () => {
|
||||
it('cambiar de dominio vuelve a Indicadores', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
fixture.componentInstance.changeSection('historico'); fixture.detectChanges();
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Covers the series chips of TEA's Trazabilidad: which series a figure offers and how choosing one dims the rest.
|
||||
// Fixture: a figure with two lines, each preceded by its confidence band, as the EEG normal/anormal chart draws it.
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { resaltarSerie, seriesDe } from './indicadores-historico';
|
||||
|
||||
const figura = (): PlotlyFigure => ({ layout: {}, data: [
|
||||
{ type: 'scatter', fill: 'toself', name: 'Intervalo de confianza' },
|
||||
{ type: 'scatter', name: 'EEG anormal', line: { color: '#a00' }, marker: { color: '#a00' } },
|
||||
{ type: 'scatter', fill: 'toself', name: 'Intervalo de confianza (normal)' },
|
||||
{ type: 'scatter', name: 'EEG normal', line: { color: '#06a' } },
|
||||
] });
|
||||
|
||||
describe('Series de la trazabilidad de TEA', () => {
|
||||
it('ofrece una ficha por línea o barra y ninguna por banda', () => {
|
||||
// Fails if a confidence band becomes a chip of its own or a series loses its colour.
|
||||
expect(seriesDe(figura())).toEqual([{ nombre: 'EEG anormal', color: '#a00' }, { nombre: 'EEG normal', color: '#06a' }]);
|
||||
});
|
||||
|
||||
it('al elegir una serie atenúa las demás y sus bandas, y deja intacta la figura publicada', () => {
|
||||
// Fails if the chosen series is dimmed, if its band is dimmed with the other series, or if the original is mutated.
|
||||
const original = figura();
|
||||
const vista = resaltarSerie(original, 'EEG normal');
|
||||
expect(vista.data.map(t => t['opacity'])).toEqual([.15, .15, undefined, undefined]);
|
||||
expect(original.data.every(t => t['opacity'] === undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { Subject } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
@@ -86,22 +86,15 @@ describe('Figuras de histórico', () => {
|
||||
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
|
||||
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
|
||||
});
|
||||
it('el porcentaje en proceso suma las etapas antes del EEG sobre todos los niños en el tamizaje', () => {
|
||||
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
|
||||
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
|
||||
fila('2024-01', 'EEG', 10), fila('2024-01', 'SOLO_MCHAT', 10), fila('2024-01', 'PSICOLOGIA', 10), fila('2024-01', 'NEUROPEDIATRIA', 10),
|
||||
fila('2024-02', 'EEG', 30), fila('2024-02', 'SOLO_MCHAT', 5), fila('2024-02', 'PSICOLOGIA', 5), fila('2024-02', 'NEUROPEDIATRIA', 0)] }, 'claro');
|
||||
expect(figure.data[0]['y']).toEqual([75, 25]);
|
||||
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
|
||||
});
|
||||
it('una escala compartida fija el máximo de las medianas', () => {
|
||||
const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
|
||||
expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]);
|
||||
expect((historicoFigura(data, 'claro').figure.layout['yaxis'] as { range?: number[] }).range).toBeUndefined();
|
||||
});
|
||||
it('M21 y M22 no usan verde en sus líneas', () => {
|
||||
it('las líneas de M21 y M22 siguen el morado de las de CaMa', () => {
|
||||
// Fails if TEA's lines go back to their own age colours or leave CaMa's purple mark.
|
||||
const color = (id: string) => (historicoFigura({ ...base, id, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure.data[1]['line'] as { color: string }).color;
|
||||
expect(color('M21_diagnosticados_con_eeg')).toBe('#2F6DB3'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#A23E8C');
|
||||
expect(color('M21_diagnosticados_con_eeg')).toBe('#9C42C2'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#9C42C2');
|
||||
});
|
||||
it('rechaza contratos sin representación y filas ambiguas', () => {
|
||||
expect(() => historicoFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada');
|
||||
@@ -179,23 +172,53 @@ describe('Pestaña Histórico', () => {
|
||||
expect(c.ventana()).toBe(5);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => {
|
||||
const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']
|
||||
.map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] }));
|
||||
it('ordena y titula las ocho gráficas de Trazabilidad y agrupa los tres pasos de tiempo', () => {
|
||||
const items: Indicador[] = [
|
||||
{ id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1' },
|
||||
{ id: 'M29_calidad_eeg', titulo: 'Calidad del EEG', contrato: 'C2' },
|
||||
{ id: 'M28_casos_por_estado', titulo: 'Casos por estatus', contrato: 'C2' },
|
||||
{ id: 'M27_dias_ados2_diagnostico', titulo: 'Días de ADOS-2 a diagnóstico', contrato: 'C3r' },
|
||||
{ id: 'M26_dias_mchat_ados2', titulo: 'Días de M-CHAT a ADOS-2', contrato: 'C3r' },
|
||||
{ id: 'M25_dias_mchat_diagnostico', titulo: 'Días de M-CHAT a diagnóstico positivo', contrato: 'C3r' },
|
||||
{ id: 'M24_confirmacion_diagnostico', titulo: 'Porcentaje de confirmación diagnóstica', contrato: 'C1' },
|
||||
{ id: 'M23_pacientes_evaluados', titulo: 'Pacientes evaluados por resultado diagnóstico', contrato: 'C2' },
|
||||
{ id: 'M22_diagnosticados_sin_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1' },
|
||||
{ id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1' },
|
||||
].map(item => ({ ...item, figuras: [], tipos_periodo: ['mes'] }));
|
||||
fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render();
|
||||
const pasos = ['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo'];
|
||||
const titulos = () => Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.panel h2'), el => el.textContent?.trim());
|
||||
expect(titulos().slice(0, 3)).toEqual(pasos);
|
||||
for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] });
|
||||
for (const { id } of items) {
|
||||
const c2 = id.startsWith('M28');
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
|
||||
filas: c2 ? [{ periodo: '2024-01', categoria: 'EEG', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'SOLO_MCHAT', n: 1, orden: 1, suprimido: 0 }, { periodo: '2024-01', categoria: 'PSICOLOGIA', n: 0, orden: 2, suprimido: 0 }, { periodo: '2024-01', categoria: 'NEUROPEDIATRIA', n: 0, orden: 3, suprimido: 0 }]
|
||||
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
|
||||
for (const { id, contrato } of items) {
|
||||
const periodo = '2024-01';
|
||||
const fila = contrato === 'C1' ? c1(periodo, 50) : contrato === 'C2' ? c2(periodo, 'A', 3, 0)
|
||||
: { periodo, suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 };
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato, tipo_periodo: 'mes', periodos: [periodo], filas: [fila] });
|
||||
}
|
||||
render();
|
||||
const paneles = fixture.componentInstance.paneles();
|
||||
expect(paneles.map(p => p.item.id)).toEqual(['M28_casos_por_estado', 'en_proceso', 'tiempos']);
|
||||
const grupo = paneles[2] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||
expect(titulos()).toEqual([
|
||||
'Tiempos del tamizaje', 'Progresión del proceso diagnóstico', 'Porcentaje de confirmación diagnóstica',
|
||||
'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
'Flujo del proceso diagnóstico y estudios de EEG', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal',
|
||||
]);
|
||||
const grupo = paneles[0] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
|
||||
expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3);
|
||||
expect(Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.pasos h3'), el => el.textContent?.trim())).toEqual(pasos);
|
||||
// The notes live in the round help, not as text under the chart.
|
||||
expect((fixture.nativeElement as HTMLElement).querySelector('.panel:last-child p.nota')).toBeNull();
|
||||
const ayuda = (fixture.nativeElement as HTMLElement).querySelector('.panel:last-child app-indicador-ayuda') as HTMLElement;
|
||||
ayuda.querySelector('button')!.click(); fixture.detectChanges();
|
||||
expect(ayuda.querySelector('.ayuda-texto')!.textContent).toContain('Resultado experimental.');
|
||||
});
|
||||
it('TEA ordena sus paneles como se pidió y deja al final lo que la lista no nombra', () => {
|
||||
// Fails if the catalog's own order shows through, if M30 does not close the list or if an unnamed indicator is dropped.
|
||||
const ids = ['M30_resultado_eeg', 'M29_calidad_eeg', 'otro', 'M28_casos_por_estado', 'M22_diagnosticados_sin_eeg', 'M21_diagnosticados_con_eeg', 'M24_confirmacion_diagnostico', 'M23_pacientes_evaluados'];
|
||||
fixture.componentRef.setInput('catalog', ids.map(id => ({ id, titulo: id, contrato: 'C2', figuras: [], tipos_periodo: ['mes'] })));
|
||||
render();
|
||||
expect(fixture.componentInstance.paneles().map(p => p.item.id)).toEqual(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg',
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg', 'M30_resultado_eeg', 'otro']);
|
||||
});
|
||||
it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => {
|
||||
const c = fixture.componentInstance;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } from '@angular/core';
|
||||
import { Component, computed, DestroyRef, effect, inject, input, output, signal, untracked, viewChild } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
@@ -6,61 +6,98 @@ import { MatDialog } from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelect, MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs';
|
||||
import { defer, map, Subscription } from 'rxjs';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures';
|
||||
import { cronologico, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||
import { IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
import { HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
|
||||
import { TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD } from './indicadores-kpi';
|
||||
|
||||
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 }[] });
|
||||
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
const CASOS = 'M28_casos_por_estado';
|
||||
interface Carga {
|
||||
disponibles?: string[];
|
||||
datos?: IndicadorDatos;
|
||||
errorPeriodos?: string;
|
||||
consultados: ReadonlySet<string>;
|
||||
enCurso: ReadonlySet<string>;
|
||||
fallos: ReadonlyMap<string, string>;
|
||||
}
|
||||
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato'] }; rango?: string; mensaje?: string } & (
|
||||
{ estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'error' }
|
||||
| { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
|
||||
class ContratoHistoricoInvalido extends Error {}
|
||||
const TIEMPOS = TEA_FIGURAS_OPORTUNIDAD;
|
||||
const TITULOS_TEA: Readonly<Record<string, string>> = {
|
||||
M23_pacientes_evaluados: 'Progresión del proceso diagnóstico',
|
||||
M28_casos_por_estado: 'Flujo del proceso diagnóstico y estudios de EEG',
|
||||
};
|
||||
const PERSONALIZADO = -1;
|
||||
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
const nuevos = new Set(b.periodos.filter(p => !a.periodos.includes(p)));
|
||||
const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []),
|
||||
...(Array.isArray(b['reportes']) ? b['reportes'].filter(r => nuevos.has(r.periodo)) : [])];
|
||||
const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) };
|
||||
return { ...a, periodos: [...a.periodos, ...nuevos], filas: [...a.filas, ...b.filas.filter(f => nuevos.has(f['periodo'] as string))],
|
||||
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
|
||||
}
|
||||
|
||||
// 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' },
|
||||
];
|
||||
|
||||
// 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[] {
|
||||
// Keep the individual cards available for loading, error and empty states.
|
||||
function agruparTiempos(paneles: Panel[]): Panel[] {
|
||||
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
|
||||
const listos = pasos.every(p => p?.estado === 'listo');
|
||||
return paneles.flatMap((panel): Panel[] => {
|
||||
if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') {
|
||||
const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract<Panel, { estado: 'listo' }>).figura }));
|
||||
const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))];
|
||||
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras,
|
||||
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos del tamizaje', contrato: 'C3r' }, pasos: figuras,
|
||||
figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.',
|
||||
suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }];
|
||||
}
|
||||
if (listos && TIEMPOS.includes(panel.item.id)) return [];
|
||||
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
|
||||
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de niños en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
|
||||
}
|
||||
return [panel];
|
||||
});
|
||||
}
|
||||
|
||||
interface SerieResaltable { nombre: string; color: string }
|
||||
const nombreDe = (trazo: Record<string, unknown>) => typeof trazo['name'] === 'string' ? trazo['name'] : '';
|
||||
// Bands are drawn with their line: they are not series of their own.
|
||||
const esBanda = (trazo: Record<string, unknown>) => trazo['fill'] === 'toself';
|
||||
function colorDe(trazo: Record<string, unknown>): string {
|
||||
const marca = trazo['marker'] as { color?: unknown } | undefined, linea = trazo['line'] as { color?: unknown } | undefined;
|
||||
const color = typeof marca?.color === 'string' ? marca.color : linea?.color;
|
||||
return typeof color === 'string' ? color : 'currentColor';
|
||||
}
|
||||
export function seriesDe(figura: PlotlyFigure): SerieResaltable[] {
|
||||
return figura.data.filter(trazo => !esBanda(trazo) && nombreDe(trazo)).map(trazo => ({ nombre: nombreDe(trazo), color: colorDe(trazo) }));
|
||||
}
|
||||
// Dims every series but the chosen one; a band follows the line drawn right after it.
|
||||
export function resaltarSerie(figura: PlotlyFigure, elegida: string): PlotlyFigure {
|
||||
const data = figura.data.map((trazo, i) => {
|
||||
const propio = esBanda(trazo) ? nombreDe(figura.data[i + 1] ?? {}) : nombreDe(trazo);
|
||||
return propio === elegida ? trazo : { ...trazo, opacity: .15 };
|
||||
});
|
||||
return { ...figura, data };
|
||||
}
|
||||
|
||||
// TEA's panels in the order of the request; whatever it does not name keeps the catalog's order after them.
|
||||
const ORDEN_TEA = [...TIEMPOS, ...TEA_FIGURAS_CLINICAS, M30_RESULTADO_EEG];
|
||||
function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
const lugar = (panel: Panel) => { const i = orden.indexOf(panel.item.id); return i < 0 ? orden.length : i; };
|
||||
return paneles.map((panel, i) => ({ panel, i })).sort((a, b) => lugar(a.panel) - lugar(b.panel) || a.i - b.i).map(({ panel }) => panel);
|
||||
}
|
||||
|
||||
// Evolution of each indicator: the granularity and how many of the latest periods to show.
|
||||
// Nothing is requested until the tab is first opened, and each granularity is requested once.
|
||||
@Component({
|
||||
selector: 'app-indicadores-historico',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart, IndicadorAyuda],
|
||||
template: `
|
||||
<div class="controles compacto">
|
||||
<h2>Filtros</h2>
|
||||
@@ -84,30 +121,47 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
<div class="paneles">
|
||||
@for (panel of paneles(); track panel.item.id) {
|
||||
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
|
||||
@if (dominio() === 'tea' && panel.estado === 'listo' && panel.figura.comoLeer) {
|
||||
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + panel.item.titulo"><p class="ayuda-texto">{{ panel.figura.comoLeer }}@if (panel.figura.notaMetodologica) { {{ panel.figura.notaMetodologica }} }</p></app-indicador-ayuda>
|
||||
}
|
||||
<h2>{{ panel.item.titulo }}</h2>
|
||||
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
||||
@if (panel.mensaje) {
|
||||
<div role="alert"><p>Error. {{ panel.mensaje }}</p>
|
||||
<button type="button" mat-stroked-button (click)="reintentar(panel.item.id)">Reintentar consulta</button></div>
|
||||
}
|
||||
@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 ('desarrollo') { <p role="status">Trabajo en desarrollo</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') {
|
||||
<div role="alert"><p>{{ panel.mensaje }}</p>
|
||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
|
||||
@case ('vacio') {
|
||||
<p role="status">{{ dominio() === 'cacu' ? 'Sin datos' : 'Sin reportes publicados para este intervalo de análisis.' }}</p>
|
||||
}
|
||||
@case ('listo') {
|
||||
@if (panel.pasos; as pasos) {
|
||||
<div class="pasos">
|
||||
@for (paso of pasos; track paso.titulo) {
|
||||
<section><h3>{{ paso.titulo }}</h3>
|
||||
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="'Histórico de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="etiquetaVista() + ' de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
||||
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
@if (series(panel); as lista) {
|
||||
@if (dominio() === 'tea' && lista.length > 1) {
|
||||
<div class="series" role="group" aria-label="Resaltar una serie">
|
||||
@for (serie of lista; track serie.nombre) {
|
||||
<button type="button" [style.--swatch]="serie.color" [attr.aria-pressed]="resaltados()[panel.item.id] === serie.nombre" (click)="resaltar(panel.item.id, serie.nombre)">
|
||||
<span class="swatch" [style.background]="serie.color" aria-hidden="true"></span>{{ serie.nombre }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="vistas()[panel.item.id] ?? panel.figura.figure"
|
||||
[label]="etiquetaVista() + ' de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
}
|
||||
@if (panel.figura.comoLeer) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.comoLeer && dominio() !== 'tea') { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.suprimidos.length) {
|
||||
<details class="nota-pie">
|
||||
<summary>Datos suprimidos</summary>
|
||||
@@ -149,9 +203,9 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
|
||||
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
.panel { position: relative; box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; padding-right: 2.5rem; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.nota-pie { margin-top: var(--issste-space-3); padding-top: var(--issste-space-2); border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font-size: 0.8125rem; line-height: 1.4; }
|
||||
@@ -159,6 +213,14 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
.nota-pie summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.nota-pie p { margin-top: var(--issste-space-2); font: inherit; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
app-indicador-ayuda p { margin: 0; }
|
||||
.series { display: flex; flex-wrap: wrap; gap: .25rem .75rem; margin-top: var(--issste-space-3); }
|
||||
// The look of CaMa's category chips: rounded, outlined with the series colour, tinted when chosen.
|
||||
.series button { display: inline-flex; align-items: center; gap: .45rem; min-height: 36px; padding: .25rem .75rem; border: 1px solid color-mix(in srgb, var(--swatch) 55%, var(--issste-border));
|
||||
border-radius: .75rem; background: var(--issste-surface); color: inherit; font: inherit; font-size: .875rem; cursor: pointer; }
|
||||
.series button[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); font-weight: 600; }
|
||||
.series button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.swatch { width: .75rem; height: .75rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 2px; }
|
||||
.panel.ancho { grid-column: 1 / -1; }
|
||||
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||
@@ -168,12 +230,40 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
})
|
||||
export class IndicadoresHistorico {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
// The series each panel's chart draws, which a chip can highlight; one selection per panel.
|
||||
readonly resaltados = signal<Readonly<Record<string, string>>>({});
|
||||
series(panel: Panel): readonly SerieResaltable[] { return panel.estado === 'listo' ? seriesDe(panel.figura.figure) : []; }
|
||||
resaltar(id: string, nombre: string) {
|
||||
this.resaltados.update(actual => {
|
||||
const { [id]: previo, ...resto } = actual;
|
||||
return previo === nombre ? resto : { ...actual, [id]: nombre };
|
||||
});
|
||||
}
|
||||
// The figure of each panel with a selected series; the others keep their published figure untouched.
|
||||
readonly vistas = computed<Readonly<Record<string, PlotlyFigure>>>(() => {
|
||||
const elegidas = this.resaltados();
|
||||
return Object.fromEntries(this.paneles().flatMap(panel => {
|
||||
const nombre = elegidas[panel.item.id];
|
||||
return nombre && panel.estado === 'listo' ? [[panel.item.id, resaltarSerie(panel.figura.figure, nombre)]] : [];
|
||||
}));
|
||||
});
|
||||
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());
|
||||
readonly catalogLoading = input(false);
|
||||
readonly catalogError = input('');
|
||||
readonly retryCatalog = output<void>();
|
||||
readonly etiquetaVista = computed(() => 'Trazabilidad');
|
||||
// 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()));
|
||||
// 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 => !entrada.enDesarrollo).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 +273,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 => this.config()?.periodosIniciales ? carga.disponibles ?? [] : carga.datos?.periodos ?? []))]));
|
||||
private readonly totalDisponibles = computed(() => Math.max(0, ...Object.values(this.cargas()[this.tipo()] ?? {})
|
||||
.map(carga => (this.config()?.periodosIniciales ? 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();
|
||||
@@ -202,14 +300,13 @@ export class IndicadoresHistorico {
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly periodos = inject(IndicadoresPeriodos);
|
||||
private readonly cargas = signal<Partial<Record<TipoPeriodo, Record<string, Carga>>>>({});
|
||||
private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>();
|
||||
private solicitada?: string;
|
||||
private catalogoCargado?: readonly Indicador[];
|
||||
private peticiones = new Subscription();
|
||||
private ambito?: { dominio: Dominio; catalogo: readonly Indicador[] };
|
||||
|
||||
// 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;
|
||||
@@ -221,64 +318,150 @@ export class IndicadoresHistorico {
|
||||
// Top of the shared scale: the highest third quartile of the steps, in the periods on screen.
|
||||
const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => {
|
||||
const carga = cargas?.[id];
|
||||
if (carga?.estado !== 'listo') return [];
|
||||
if (!carga?.datos) return [];
|
||||
const visibles = this.recortar(carga.datos.periodos);
|
||||
return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0);
|
||||
})) * 1.05;
|
||||
const panelDe = (item: Indicador): Panel & { datos?: IndicadorDatos } => {
|
||||
const panelDe = (item: Indicador): Panel => {
|
||||
if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' };
|
||||
const carga = cargas?.[item.id];
|
||||
if (!carga) return { item, estado: 'cargando' };
|
||||
if (carga.estado !== 'listo') return { item, ...carga };
|
||||
const periodos = this.recortar(carga.datos.periodos);
|
||||
if (!periodos.length) return { item, estado: 'vacio' };
|
||||
const necesarios = this.necesarios(carga.disponibles ?? [], tipo);
|
||||
const mensaje = carga.errorPeriodos ?? necesarios.map(p => carga.fallos.get(p)).find(Boolean);
|
||||
const periodos = this.config()?.periodosIniciales
|
||||
? necesarios.filter(p => carga.datos?.periodos.includes(p))
|
||||
: this.recortar(carga.datos?.periodos ?? []);
|
||||
if (!periodos.length || !carga.datos) {
|
||||
if (mensaje) return { item, estado: 'error', mensaje };
|
||||
return { item, estado: !carga.disponibles || necesarios.some(p => carga.enCurso.has(p)) ? 'cargando' : 'vacio' };
|
||||
}
|
||||
const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) };
|
||||
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 propias = this.config();
|
||||
const opciones = { ...(TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}),
|
||||
...(propias ? { unidades: propias.unidades, conciliarC2: propias.conciliarC2, c2SinPoblacionSinDato: propias.c2SinPoblacionSinDato } : {}) };
|
||||
const figura = historicoFigura(datos, tema, opciones);
|
||||
if (this.dominio() === 'cacu' && figura.sinDato.length === periodos.length) {
|
||||
return { item, estado: mensaje ? 'error' : 'vacio', mensaje };
|
||||
}
|
||||
return { item, rango, estado: 'listo', figura, mensaje };
|
||||
} catch (error) {
|
||||
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
||||
}
|
||||
};
|
||||
if (this.dominio() === 'cama') {
|
||||
if (!this.publicados().length) return [];
|
||||
return HISTORICO_CAMA.map((entrada): Panel => {
|
||||
const config = this.config();
|
||||
if (config) {
|
||||
const cacu = this.dominio() === 'cacu';
|
||||
if (!cacu && !this.publicados().length) return [];
|
||||
return config.paneles.map((entrada: PanelHistorico): Panel => {
|
||||
const visible = { id: entrada.id, titulo: entrada.titulo };
|
||||
if (entrada.enDesarrollo) return { item: visible, estado: 'desarrollo' };
|
||||
if (cacu && this.catalogError()) return { item: visible, estado: 'error', mensaje: this.catalogError() };
|
||||
if (cacu && this.catalogLoading()) return { item: visible, estado: 'cargando' };
|
||||
const item = this.catalog().find(i => i.id === entrada.id);
|
||||
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
|
||||
if (!item) return { item: visible, estado: cacu ? 'desarrollo' : 'pendiente' };
|
||||
return { ...panelDe(item), item: { ...visible, contrato: item.contrato } };
|
||||
});
|
||||
}
|
||||
return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
|
||||
const items = this.catalog().filter(item => item.tipos_periodo.includes(tipo));
|
||||
if (this.dominio() !== 'tea') return items.map(panelDe);
|
||||
const paneles = items.map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo }));
|
||||
return agruparTiempos(ordenar(paneles, ORDEN_TEA));
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo))
|
||||
.map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))),
|
||||
takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => {
|
||||
this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) }));
|
||||
});
|
||||
this.destruccion.onDestroy(() => this.peticiones.unsubscribe());
|
||||
effect(() => {
|
||||
const tipo = this.tipo(), items = this.publicados();
|
||||
if (!this.active() || !items.length) return;
|
||||
const dominio = this.dominio(), catalogo = this.catalog(), tipo = this.tipo();
|
||||
const activo = this.active() && !this.catalogLoading() && !this.catalogError();
|
||||
untracked(() => {
|
||||
if (this.catalogoCargado !== this.catalog()) { this.catalogoCargado = this.catalog(); this.cargas.set({}); this.solicitada = undefined; }
|
||||
if (this.cargas()[tipo] || this.solicitada === tipo) return;
|
||||
this.solicitada = tipo;
|
||||
this.solicitudes.next({ tipo, items });
|
||||
if (this.ambito?.catalogo !== catalogo || this.ambito?.dominio !== dominio) {
|
||||
this.peticiones.unsubscribe();
|
||||
this.peticiones = new Subscription();
|
||||
this.cargas.set({});
|
||||
this.ambito = { dominio, catalogo };
|
||||
}
|
||||
if (activo) this.cargarVentana(tipo);
|
||||
});
|
||||
});
|
||||
}
|
||||
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
|
||||
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 })))
|
||||
: of({ estado: 'vacio' })),
|
||||
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
|
||||
|
||||
private necesarios(disponibles: readonly string[], tipo: TipoPeriodo): string[] {
|
||||
if (!this.config()?.periodosIniciales) return [...disponibles];
|
||||
const orden = cronologico(disponibles), ventana = this.ventanas()[tipo] ?? this.config()?.periodosIniciales;
|
||||
if (ventana === PERSONALIZADO) return orden.filter(p => (this.personalizados()[tipo] ?? []).includes(p));
|
||||
return ventana ? orden.slice(-ventana) : orden;
|
||||
}
|
||||
|
||||
private guardarCarga(tipo: TipoPeriodo, id: string, carga: Carga) {
|
||||
this.cargas.update(actual => ({ ...actual, [tipo]: { ...actual[tipo], [id]: carga } }));
|
||||
}
|
||||
|
||||
private cargarVentana(tipo: TipoPeriodo) {
|
||||
if (!this.active() || this.catalogLoading() || this.catalogError()) return;
|
||||
for (const { id, tipos_periodo } of this.publicados()) {
|
||||
if (!tipos_periodo.includes(tipo)) continue;
|
||||
const carga = this.cargas()[tipo]?.[id];
|
||||
if (carga) this.solicitarPeriodos(tipo, id, carga);
|
||||
else this.descubrirPeriodos(tipo, id);
|
||||
}
|
||||
}
|
||||
|
||||
private descubrirPeriodos(tipo: TipoPeriodo, id: string) {
|
||||
const carga: Carga = { consultados: new Set(), enCurso: new Set(), fallos: new Map() };
|
||||
this.guardarCarga(tipo, id, carga);
|
||||
this.peticiones.add(defer(() => this.periodos.periodos(this.dominio(), id)).subscribe({
|
||||
next: periodos => {
|
||||
const descubierta = { ...carga, disponibles: [...new Set(periodos.filter(p => p.tipo === tipo).map(p => p.periodo))] };
|
||||
this.guardarCarga(tipo, id, descubierta);
|
||||
if (this.active() && this.tipo() === tipo) this.solicitarPeriodos(tipo, id, descubierta);
|
||||
},
|
||||
error: error => this.guardarCarga(tipo, id, { ...carga, errorPeriodos: httpMessage(error) }),
|
||||
}));
|
||||
}
|
||||
|
||||
private solicitarPeriodos(tipo: TipoPeriodo, id: string, carga: Carga) {
|
||||
if (!carga.disponibles) return;
|
||||
const faltan = this.necesarios(carga.disponibles, tipo)
|
||||
.filter(p => !carga.consultados.has(p) && !carga.enCurso.has(p) && !carga.fallos.has(p));
|
||||
if (!faltan.length) return;
|
||||
this.guardarCarga(tipo, id, { ...carga, enCurso: new Set([...carga.enCurso, ...faltan]) });
|
||||
const solicitados = new Set(faltan);
|
||||
const vigente = () => {
|
||||
const actual = this.cargas()[tipo]![id];
|
||||
return { ...actual, enCurso: new Set([...actual.enCurso].filter(p => !solicitados.has(p))) };
|
||||
};
|
||||
const config = this.config();
|
||||
const esperado = config?.paneles.find(panel => panel.id === id)?.contrato;
|
||||
this.peticiones.add(defer(() => this.service.datos(this.dominio(), id, tipo, faltan)).pipe(map(datos => {
|
||||
if (esperado && datos.contrato !== esperado) {
|
||||
throw new ContratoHistoricoInvalido(`Contrato inesperado: se esperaba ${esperado} y llegó ${datos.contrato}`);
|
||||
}
|
||||
// Validate each batch before it is allowed to affect a series that already has valid periods.
|
||||
if (esperado && datos.periodos.length) historicoFigura(datos, this.tema(), config);
|
||||
return datos;
|
||||
})).subscribe({
|
||||
next: datos => {
|
||||
const actual = vigente();
|
||||
this.guardarCarga(tipo, id, { ...actual, consultados: new Set([...actual.consultados, ...faltan]),
|
||||
datos: actual.datos ? unir(actual.datos, datos) : datos });
|
||||
},
|
||||
error: error => {
|
||||
const actual = vigente(), fallos = new Map(actual.fallos);
|
||||
const mensaje = error instanceof ContratoHistoricoInvalido ? error.message : httpMessage(error);
|
||||
for (const periodo of faltan) fallos.set(periodo, mensaje);
|
||||
this.guardarCarga(tipo, id, { ...actual, fallos });
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
private readonly destruccion = inject(DestroyRef);
|
||||
elegirVentana(valor: number) {
|
||||
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
|
||||
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
|
||||
this.cargarVentana(this.tipo());
|
||||
}
|
||||
abrirPersonalizado() {
|
||||
const tipo = this.tipo(), periodos = this.disponibles();
|
||||
@@ -286,19 +469,38 @@ export class IndicadoresHistorico {
|
||||
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : this.ventana() ? periodos.slice(-this.ventana()) : periodos;
|
||||
const data: PeriodosDialogoDatos = { tipo, periodos, elegidos };
|
||||
this.dialogo.open<IndicadoresHistoricoPeriodos, PeriodosDialogoDatos, string[]>(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' })
|
||||
.afterClosed().subscribe(resultado => {
|
||||
.afterClosed().pipe(takeUntilDestroyed(this.destruccion)).subscribe(resultado => {
|
||||
if (resultado?.length) {
|
||||
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
|
||||
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
|
||||
if (this.tipo() === tipo) this.cargarVentana(tipo);
|
||||
}
|
||||
// Cancelled, the selector goes back to what's on screen.
|
||||
this.selector()?.writeValue(this.ventana());
|
||||
});
|
||||
}
|
||||
reintentar() {
|
||||
reintentar(id: string) {
|
||||
if (this.catalogError()) {
|
||||
this.retryCatalog.emit();
|
||||
return;
|
||||
}
|
||||
const tipo = this.tipo();
|
||||
this.solicitada = tipo;
|
||||
this.cargas.update(({ [tipo]: _, ...resto }) => resto);
|
||||
this.solicitudes.next({ tipo, items: this.publicados() });
|
||||
const carga = this.cargas()[tipo]?.[id];
|
||||
if (!carga) return;
|
||||
if (carga.errorPeriodos) {
|
||||
this.descubrirPeriodos(tipo, id);
|
||||
return;
|
||||
}
|
||||
const seleccion = this.necesarios(carga.disponibles ?? [], tipo);
|
||||
if (!seleccion.some(periodo => carga.fallos.has(periodo))) {
|
||||
// A figure can fail after its reports were accepted. Reload just that panel.
|
||||
if (!carga.enCurso.size) this.descubrirPeriodos(tipo, id);
|
||||
return;
|
||||
}
|
||||
const fallos = new Map(carga.fallos);
|
||||
for (const periodo of seleccion) fallos.delete(periodo);
|
||||
const corregida = { ...carga, fallos };
|
||||
this.guardarCarga(tipo, id, corregida);
|
||||
this.solicitarPeriodos(tipo, id, corregida);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,11 +126,12 @@ describe('P0-C.1: cinco tarjetas de oportunidad', () => {
|
||||
http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
|
||||
f.detectChanges();
|
||||
const cards = [...f.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
|
||||
expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Tiempo desde la toma de muestra al resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
|
||||
expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]);
|
||||
expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]);
|
||||
for (const card of cards.slice(3)) {
|
||||
expect(card.querySelectorAll('p')).toHaveLength(1); expect(card.querySelector('p')!.textContent).toBe('Indicador no disponible');
|
||||
expect(card.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
|
||||
expect(card.textContent).toContain('aún no está publicado');
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
} finally { f.destroy(); vi.unstubAllGlobals(); http.verify(); }
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ActivatedRoute, provideRouter } from '@angular/router';
|
||||
import { datosDeReportes, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
|
||||
import { CACU_TRATAMIENTO_KPIS, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
|
||||
const PERIOD = '2025-S2';
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: [PERIOD] }, revision: 1 };
|
||||
const measure = (id: string): Measure => ({
|
||||
resourceType: 'Measure', id, title: id, extension: [
|
||||
{ url: 'contrato', valueCode: 'C3r' },
|
||||
{ url: 'tipos-periodo', valueCode: 'semestre' },
|
||||
{ url: 'figuras', valueString: 'fig_c3r_caja' },
|
||||
],
|
||||
});
|
||||
const report = (median: number, q1: number, q3: number, n: number): Report => ({
|
||||
resourceType: 'MeasureReport', period: { start: '2025-07-01', end: '2025-12-31' },
|
||||
group: [{
|
||||
code: { coding: [{ code: 'TOTAL' }] },
|
||||
population: [{ code: { coding: [{ code: 'measure-observation' }] }, count: n }],
|
||||
measureScore: { value: median, unit: 'd', extension: [
|
||||
{ url: 'q1', valueDecimal: q1 },
|
||||
{ url: 'q3', valueDecimal: q3 },
|
||||
] },
|
||||
}],
|
||||
});
|
||||
|
||||
describe('KPI de tratamiento de CaCu', () => {
|
||||
it.each([
|
||||
['CACU-DIAS-TOMA-TRATAMIENTO', 'cacu_dias_toma_tratamiento', 21.5, 8.25, 33.75, 12],
|
||||
['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO', 'cacu_dias_diagnostico_tratamiento', 7.75, 2.5, 14, 9],
|
||||
] as const)('mapea %s y conserva los valores C3r publicados', (fhirId, id, median, q1, q3, n) => {
|
||||
const fhirMeasure = measure(fhirId);
|
||||
const definition = CACU_TRATAMIENTO_KPIS.find(kpi => kpi.id === id)!;
|
||||
expect(indicadorDeMeasure(fhirMeasure)).toMatchObject({ id, contrato: 'C3r' });
|
||||
const data = datosDeReportes(fhirMeasure, [report(median, q1, q3, n)], 'semestre');
|
||||
expect(kpiResult(data, definition, 'cacu', applied)).toEqual({
|
||||
state: 'Disponible', value: median,
|
||||
info: `${n} observaciones. Primer cuartil de ${q1} días y tercer cuartil de ${q3} días.`,
|
||||
});
|
||||
});
|
||||
|
||||
it('distingue una mediana publicada de cero días de la ausencia de observaciones o la supresión', () => {
|
||||
const fhirMeasure = measure('CACU-DIAS-TOMA-TRATAMIENTO');
|
||||
const definition = CACU_TRATAMIENTO_KPIS[0];
|
||||
const empty = datosDeReportes(fhirMeasure, [report(0, 0, 0, 0)], 'semestre');
|
||||
expect(kpiResult(empty, definition, 'cacu', applied)).toEqual({ state: 'Sin valor disponible' });
|
||||
const published = datosDeReportes(fhirMeasure, [report(0, 0, 0, 1)], 'semestre');
|
||||
expect(kpiResult(published, definition, 'cacu', applied).value).toBe(0);
|
||||
const suppressed = { ...published, filas: [{ ...published.filas[0], suprimido: 1 }] };
|
||||
expect(kpiResult(suppressed, definition, 'cacu', applied)).toEqual({ state: 'Dato oculto por tamaño' });
|
||||
});
|
||||
|
||||
it('presenta una sola tarjeta por medida con publicación parcial y conserva el periodo del dato', () => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([]),
|
||||
{ provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } }] });
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
const fixture = TestBed.createComponent(IndicadoresPage), http = TestBed.inject(HttpTestingController);
|
||||
const fhirMeasure = measure('CACU-DIAS-DIAGNOSTICO-TRATAMIENTO');
|
||||
const { id } = indicadorDeMeasure(fhirMeasure);
|
||||
try {
|
||||
http.expectOne('/cacu/indicadores').flush([indicadorDeMeasure(fhirMeasure)]);
|
||||
http.expectOne(`/cacu/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: PERIOD, tipo: 'semestre' }] });
|
||||
fixture.detectChanges();
|
||||
const request = http.expectOne(r => r.url === `/cacu/indicadores/${id}/datos`);
|
||||
expect(request.request.params.get('periodos')).toBe(PERIOD);
|
||||
request.flush(datosDeReportes(fhirMeasure, [report(7.75, 2.5, 14, 9)], 'semestre'));
|
||||
fixture.detectChanges();
|
||||
const root = fixture.nativeElement as HTMLElement;
|
||||
const cards = [...root.querySelectorAll('.kpi-grid app-indicador-kpi-card')];
|
||||
expect(cards.map(card => card.querySelector('h3')?.textContent)).toEqual([
|
||||
'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
expect(cards[0].querySelector('.kpi-state')?.textContent).toBe('Integración pendiente');
|
||||
expect(cards[0].querySelector('.value')).toBeNull();
|
||||
expect(cards[1].querySelector('.value')?.firstChild?.textContent).toBe('7.75');
|
||||
expect(cards[1].querySelector('.period')?.textContent).toContain(PERIOD);
|
||||
// the cards carry no provisional notice: what the measure is lives in its technical sheet
|
||||
expect(cards[1].textContent).not.toContain('Indicador provisional');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')).toBeNull();
|
||||
expect(root.querySelector('.graphic-section app-indicador-catalog-card')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
} finally {
|
||||
fixture.destroy();
|
||||
http.verify();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -73,7 +73,7 @@ it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => {
|
||||
expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
|
||||
const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]);
|
||||
expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0',
|
||||
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' });
|
||||
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.', numerador: 3, denominador: 6 });
|
||||
expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state)
|
||||
.toBe('Selección no consolidable');
|
||||
});
|
||||
|
||||
@@ -8,11 +8,26 @@ export interface KpiDefinition {
|
||||
c1Info?: (numerador: number, denominador: number) => string;
|
||||
// C3r only: a median over zero observations is no value, not zero days.
|
||||
requiresObservations?: boolean;
|
||||
c3rInfo?: (n: number, q1: number, q3: number) => string;
|
||||
note?: string;
|
||||
// C2 only: replaces the domain's explanatory line when the unit counted is not the domain's usual one.
|
||||
c2Info?: string;
|
||||
}
|
||||
// Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID.
|
||||
export const CACU_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
|
||||
id: 'cacu_eu_tiempo_reporte', title: 'Tiempo desde la toma de muestra al resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
|
||||
};
|
||||
const CACU_TRATAMIENTO_C3R = {
|
||||
contrato: 'C3r',
|
||||
unit: 'días (mediana)',
|
||||
requiresObservations: true,
|
||||
c3rInfo: (n, q1, q3) => `${n} ${n === 1 ? 'observación' : 'observaciones'}. Primer cuartil de ${q1} días y tercer cuartil de ${q3} días.`,
|
||||
} satisfies Omit<KpiDefinition, 'id' | 'title'>;
|
||||
|
||||
export const CACU_TRATAMIENTO_KPIS: readonly KpiDefinition[] = [
|
||||
{ ...CACU_TRATAMIENTO_C3R, id: 'cacu_dias_toma_tratamiento', title: 'Tiempo de tamizaje a tratamiento' },
|
||||
{ ...CACU_TRATAMIENTO_C3R, id: 'cacu_dias_diagnostico_tratamiento', title: 'Tiempo de diagnóstico a tratamiento' },
|
||||
];
|
||||
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía a interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
||||
};
|
||||
@@ -34,15 +49,42 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||
// cards read the `titulo` that the API already sends.
|
||||
// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process.
|
||||
// M28's last stage follows neuropediatrics and requires a good EEG.
|
||||
export const M28_COMPLETO = 'EEG';
|
||||
export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA'];
|
||||
// What only TEA's summary paragraph needs: the children by stage and the time of each screening step.
|
||||
// M29's category of the EEGs the analysis found valid.
|
||||
export const M29_BUENO = 'BUENO';
|
||||
export const M29_MALO = 'MALO';
|
||||
// What only TEA's summary paragraph needs: the children by stage, the time of each screening step and the EEGs by quality.
|
||||
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||
{ id: 'M28_casos_por_estado', title: 'Niños en el tamizaje', contrato: 'C2', unit: 'pacientes' },
|
||||
{ id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'M29_calidad_eeg', title: 'Estudios de EEG', contrato: 'C2', unit: 'estudios', c2Info: 'Estudios de EEG realizados en el periodo a niños de la cohorte.' },
|
||||
];
|
||||
// TEA's figures under «Indicadores de oportunidad» and under «Indicadores clínicos», each in display order. Any other
|
||||
// published TEA indicator follows the clinical ones.
|
||||
export const TEA_FIGURAS_OPORTUNIDAD: readonly string[] = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
export const TEA_FIGURAS_CLINICAS: readonly string[] = ['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg',
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg'];
|
||||
// CaCu's available figures in display order; titles are assigned when the catalog publishes them.
|
||||
export interface FiguraOportunidad { id?: string; titulo: string; }
|
||||
export const CACU_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Tiempo de toma de muestra a resultado de citología' },
|
||||
{ id: 'cacu_dias_toma_colposcopia', titulo: 'Tiempo de toma de muestra a resultado de colposcopía' },
|
||||
{ id: 'cacu_dias_toma_biopsia', titulo: 'Tiempo de toma de muestra a resultado de biopsia' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de toma de muestra a diagnóstico' },
|
||||
];
|
||||
// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. An entry
|
||||
// with no `id` has no published indicator yet and draws as pending.
|
||||
export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cama_eu38a', titulo: 'Tiempo de toma de mastografía a interpretación radiológica' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Tiempo de interpretación radiológica a diagnóstico' },
|
||||
{ titulo: 'Tiempo de interpretación radiológica a resultado de biopsia' },
|
||||
{ titulo: 'Tiempo de diagnóstico a tratamiento' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico' },
|
||||
];
|
||||
// CaCu's clinical figures in display order.
|
||||
export const CACU_FIGURAS_CLINICAS: readonly string[] = ['cacu_eu7', 'cacu_confirmacion_citologia'];
|
||||
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
tea: [
|
||||
{ id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' },
|
||||
@@ -101,7 +143,8 @@ const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> =
|
||||
cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
|
||||
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`,
|
||||
};
|
||||
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record<string, number>; }
|
||||
// C1 results also carry the counts the percentage comes from; C2 results, the count of each category.
|
||||
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record<string, number>; numerador?: number; denominador?: number; }
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0;
|
||||
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
|
||||
@@ -137,8 +180,8 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||
if (!count(value)) return empty;
|
||||
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])),
|
||||
info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.'
|
||||
: domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
|
||||
info: definition.c2Info ?? (domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.'
|
||||
: domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.') };
|
||||
}
|
||||
if (definition.contrato === 'C1') {
|
||||
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100) return empty;
|
||||
@@ -148,8 +191,9 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
return { state: 'Error de contrato', info: 'El numerador y el denominador deben ser conteos no negativos compatibles.' };
|
||||
}
|
||||
if (denominator === 0) return empty;
|
||||
return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(numerator, denominator) };
|
||||
return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(numerator, denominator),
|
||||
numerador: numerator, denominador: denominator };
|
||||
}
|
||||
if (!finite(row['mediana']) || !count(row['n']) || ((definition.id === CACU_RESULTADO_KPI.id || definition.requiresObservations) && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
|
||||
return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) };
|
||||
return { state: 'Disponible', value: row['mediana'], info: (definition.c3rInfo ?? C3R_INFO[domain])(row['n'], row['q1'], row['q3']) };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<section class="dashboard" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||
<section class="dashboard" [class.dominio-tea]="dominio === 'tea'" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||
<header>
|
||||
@if (fichaPacienteAbierta()) {
|
||||
<h1 id="dashboard-title">Ficha del paciente</h1>
|
||||
@@ -43,7 +43,7 @@
|
||||
<p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p>
|
||||
}
|
||||
@let kpis = kpiCards;
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
@if ((kpis.length || (dominio === 'tea' && oportunidadSlots().length)) && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
@let resumen = teaResumenPeriodo;
|
||||
<div class="kpi-heading">
|
||||
@@ -52,24 +52,35 @@
|
||||
</div>
|
||||
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
|
||||
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)">
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cama' ? 1 : 0)">
|
||||
@for (card of kpis; track dominio + ':' + card.definition.id) {
|
||||
@if (card.pending) {
|
||||
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
|
||||
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
|
||||
} @else {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="card.definition" [indicador]="kpiIndicator(card.definition.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false"
|
||||
[showPeriod]="filters?.applied.selection.mode === 'todos' && esKpiTratamientoCacu(card.definition.id)" />
|
||||
}
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
|
||||
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
|
||||
} @else if (dominio === 'cama') {
|
||||
@if (dominio === 'cama') {
|
||||
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible"
|
||||
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
|
||||
}
|
||||
</div>
|
||||
@if (oportunidadSlots().length) {
|
||||
@if (dominio === 'cacu' || dominio === 'cama') { <h3 class="subsection-title">Tiempo de tamizaje a diagnóstico</h3> }
|
||||
<div class="catalog-grid">
|
||||
@for (slot of oportunidadSlots(); track slot.item ? cardIdentity(slot.item) : slot.titulo) {
|
||||
@if (slot.item; as item) {
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" [individual]="true" (pinChanged)="togglePinned(item)" />
|
||||
} @else {
|
||||
<app-indicador-figura-pendiente [titulo]="slot.titulo" />
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
@@ -115,20 +126,33 @@
|
||||
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
|
||||
</div>
|
||||
}
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" [tipo]="filters?.applied?.tipo ?? 'semestre'" [periodos]="periodosDelFiltro()" /> }
|
||||
<div class="catalog-grid">
|
||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
@for (item of clinicosItems(); track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
}
|
||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||
</div>
|
||||
@if (dominio === 'cama') {
|
||||
<div class="kpi-grid" style="--kpi-count: 1">
|
||||
@if (confirmacionCamaPendiente) {
|
||||
<app-indicador-kpi-card [title]="confirmacionCama.title" state="Integración pendiente"
|
||||
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
|
||||
} @else {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="confirmacionCama" [indicador]="kpiIndicator(confirmacionCama.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@if (conHistorico) {
|
||||
<section id="panel-historico" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-historico" tabindex="0" [hidden]="activeSection() !== 'historico'">
|
||||
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'" />
|
||||
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'"
|
||||
[catalogLoading]="catalogLoading()" [catalogError]="catalogError()" (retryCatalog)="retryCatalog()" />
|
||||
</section>
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.graphic-section { margin-top: var(--issste-space-6); }
|
||||
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
|
||||
.kpi-section .catalog-grid { margin-top: var(--issste-space-6); }
|
||||
.subsection-title { margin: var(--issste-space-6) 0 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; }
|
||||
.subsection-title + .catalog-grid { margin-top: var(--issste-space-3); }
|
||||
.catalog-grid { align-items: stretch; }
|
||||
.reporte-acciones { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
|
||||
.reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
@@ -31,6 +34,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
|
||||
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
// TEA draws three smaller plots per row.
|
||||
.dominio-tea .catalog-grid { --plot-height: 340px; }
|
||||
@container dashboard (min-width: 1000px) { .dominio-tea .catalog-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-flow: dense; } }
|
||||
|
||||
@media (max-width: 550px) {
|
||||
h1 { font-size: 1.5rem; }
|
||||
|
||||
@@ -227,7 +227,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
|
||||
const result = panel.result();
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
// TEA's reading guide is the round "?" button: its first opening loads the metadata once.
|
||||
const button = fixture.nativeElement.querySelector('.ayuda-boton') as HTMLButtonElement;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
button.click(); fixture.detectChanges();
|
||||
if (i === 0) {
|
||||
@@ -287,7 +288,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
});
|
||||
it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => {
|
||||
load(); toggle(); flushAll();
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle');
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .ayuda-boton');
|
||||
input.focus(); cards()[0].setVisible(false); fixture.detectChanges(); expect(document.activeElement).toBe(input);
|
||||
const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf<HTMLElement>).map(e => e.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
|
||||
@@ -17,10 +17,13 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { esSocioConteos } from './indicadores-conteos-pareados';
|
||||
import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi';
|
||||
import { TeaResumenPeriodo } from './tea-resumen-periodo';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { IndicadorFiguraPendiente } from './indicador-figura-pendiente';
|
||||
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
@@ -31,34 +34,48 @@ 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';
|
||||
import { M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'resumen', label: 'Resumen' },
|
||||
{ id: 'seguimiento', label: 'Seguimiento' },
|
||||
{ id: 'resumen', label: 'Indicadores' },
|
||||
{ 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,
|
||||
// between its history and its follow-up list.
|
||||
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
const SECTIONS_TEA: typeof SECTIONS = [
|
||||
{ id: 'resumen', label: 'Resumen' }, { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2],
|
||||
];
|
||||
const SECTIONS_CACU: typeof SECTIONS = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
|
||||
export const CAMA_ANALYSIS_ENABLED = false;
|
||||
// TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them.
|
||||
function ordenTea(catalog: Indicador[]): Indicador[] {
|
||||
const named = [...TEA_FIGURAS_OPORTUNIDAD, ...TEA_FIGURAS_CLINICAS];
|
||||
const first = named.flatMap(id => catalog.filter(item => item.id === id));
|
||||
return [...first, ...catalog.filter(item => !named.includes(item.id))];
|
||||
}
|
||||
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
|
||||
SECTIONS_WITH_HISTORY[0], { id: 'historico', label: 'Trazabilidad' },
|
||||
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
|
||||
{ id: 'seguimiento', label: 'Análisis de Riesgos' }, SECTIONS_WITH_HISTORY[3]];
|
||||
SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorFiguraPendiente, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
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 sections(): typeof SECTIONS {
|
||||
if (this.dominio === 'tea') return SECTIONS_TEA;
|
||||
if (this.dominio === 'cacu') return SECTIONS_CACU;
|
||||
return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS;
|
||||
}
|
||||
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);
|
||||
@@ -171,7 +188,7 @@ export class IndicadoresPage {
|
||||
}
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
this.sizeObserver ??= new ResizeObserver(this.viewportChanged);
|
||||
const targets = [this.document.querySelector('.institutional-header'), this.element.nativeElement.querySelector('.catalog-grid')]
|
||||
const targets = [this.document.querySelector('.institutional-header'), ...this.element.nativeElement.querySelectorAll('.catalog-grid')]
|
||||
.filter((target): target is Element => target !== null);
|
||||
for (const target of this.sizeTargets) {
|
||||
if (!targets.includes(target)) { this.sizeObserver.unobserve(target); this.sizeTargets.delete(target); }
|
||||
@@ -326,14 +343,24 @@ export class IndicadoresPage {
|
||||
private cardsDeCama(catalog: Indicador[]) {
|
||||
const ids = catalog.map(item => item.id);
|
||||
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
|
||||
// The histopathology card keeps its place, first, whether pending or published.
|
||||
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
|
||||
// The exams' and patients' counts come first, then the histopathology card (pending or published); the confirmation rate follows them.
|
||||
return [...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA)];
|
||||
}
|
||||
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
|
||||
get histopatologiaPendiente() {
|
||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
/** The periods the page's filter applies, for the charts that follow it with no filter of their own (the screening
|
||||
* route); `undefined` when it applies every period. */
|
||||
periodosDelFiltro(): readonly string[] | undefined {
|
||||
const seleccion = this.filters?.applied.selection;
|
||||
return seleccion?.mode === 'explicit' ? seleccion.periodos : undefined;
|
||||
}
|
||||
// CaCu's screening route chart, once the catalog publishes every measure it reads.
|
||||
get screeningRouteAvailable() {
|
||||
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
|
||||
}
|
||||
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
|
||||
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
|
||||
@@ -349,11 +376,15 @@ export class IndicadoresPage {
|
||||
return [...definitions.slice(0, diagnosis < 0 ? definitions.length : diagnosis), CACU_RESULTADO_KPI,
|
||||
...definitions.slice(diagnosis < 0 ? definitions.length : diagnosis)];
|
||||
}
|
||||
// What the KPI grid draws. CaMa adds explicit pending cards for opportunity indicators the catalog does not publish.
|
||||
// CaCu's treatment cards follow the existing KPIs without changing the initial-period anchor.
|
||||
get kpiCards(): KpiCardSlot[] {
|
||||
if (this.dominio === 'cama') return camaKpiCards(id => this.catalog().some(item => item.id === id));
|
||||
return this.opportunityKpis.map(definition => ({ definition, pending: false }));
|
||||
const cards = this.opportunityKpis.map(definition => ({ definition, pending: false }));
|
||||
if (this.dominio !== 'cacu') return cards;
|
||||
const tratamiento = CACU_TRATAMIENTO_KPIS.map(definition => ({ definition, pending: !this.kpiIndicator(definition.id) }));
|
||||
return cards.length || tratamiento.some(card => !card.pending) ? [...cards, ...tratamiento] : [];
|
||||
}
|
||||
esKpiTratamientoCacu(id: string) { return this.dominio === 'cacu' && CACU_TRATAMIENTO_KPIS.some(kpi => kpi.id === id); }
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
// Ids of the indicators to render; null shows the whole catalog.
|
||||
@@ -363,9 +394,12 @@ export class IndicadoresPage {
|
||||
// Stable presentation order. Pins no longer reorder the summary.
|
||||
readonly catalogOrder = computed(() => {
|
||||
const catalog = this.catalog();
|
||||
// The route chart draws its own measures: they get no card of their own once it is there.
|
||||
const route = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : [];
|
||||
return this.dominio === 'cacu'
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))]
|
||||
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
|
||||
: this.dominio === 'tea' ? ordenTea(catalog.filter(item => item.id !== M30_RESULTADO_EEG && (!item.vistas || item.vistas.includes('resumen'))))
|
||||
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
});
|
||||
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
|
||||
@@ -379,6 +413,44 @@ export class IndicadoresPage {
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
|
||||
});
|
||||
// The figures of «Indicadores de oportunidad»: TEA's time figures under its summary and CaMa's times, each a pending
|
||||
// slot while the catalog does not publish its indicator; CaCu's, only when its screening route chart isn't shown. The
|
||||
// rest are the clinical ones.
|
||||
// The domain is not a signal: each result reads the items first, so a new catalog recomputes it whichever domain it was last for.
|
||||
readonly oportunidadSlots = computed((): { item?: Indicador; titulo: string }[] => {
|
||||
const items = this.searchResults().items;
|
||||
if (this.dominio === 'tea') return items.filter(item => TEA_FIGURAS_OPORTUNIDAD.includes(item.id)).map(item => ({ item, titulo: item.titulo }));
|
||||
if (this.dominio === 'cama') {
|
||||
// CaMa's time indicators have no card in the ordered list (the summary keeps them out), so look in the catalog
|
||||
// restricted to the selection. The slot names the figure as the request does, whatever title the catalog gives.
|
||||
if (!this.catalog().length) return [];
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
return CAMA_FIGURAS_OPORTUNIDAD.map(figura => {
|
||||
const item = figura.id ? this.catalog().find(candidate => candidate.id === figura.id && selected.has(candidate.id)) : undefined;
|
||||
return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo };
|
||||
});
|
||||
}
|
||||
// With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to
|
||||
// each event. Without it, each time the catalog publishes with a figure keeps its own.
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return [];
|
||||
return CACU_FIGURAS_OPORTUNIDAD.flatMap(figura => {
|
||||
const item = items.find(candidate => candidate.id === figura.id && candidate.figuras.length > 0);
|
||||
return item ? [{ item, titulo: item.titulo }] : [];
|
||||
});
|
||||
});
|
||||
readonly clinicosItems = computed(() => {
|
||||
const items = this.searchResults().items;
|
||||
if (this.dominio === 'cacu') {
|
||||
// The opportunity section already presents the time figures and the treatment KPIs.
|
||||
const clinicos = items.filter(item => item.figuras.length && !this.esKpiTratamientoCacu(item.id)
|
||||
&& !CACU_FIGURAS_OPORTUNIDAD.some(figura => figura.id === item.id));
|
||||
return [...CACU_FIGURAS_CLINICAS.flatMap(id => clinicos.filter(item => item.id === id)), ...clinicos.filter(item => !CACU_FIGURAS_CLINICAS.includes(item.id))];
|
||||
}
|
||||
return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items;
|
||||
});
|
||||
// CaMa's confirmation rate closes its clinical section: a number card, pending while the catalog does not publish it.
|
||||
readonly confirmacionCama = CAMA_CONFIRMACION_KPI;
|
||||
get confirmacionCamaPendiente() { return !this.catalog().some(item => item.id === CAMA_CONFIRMACION_KPI.id); }
|
||||
readonly catalogLoading = signal(true);
|
||||
readonly catalogError = signal('');
|
||||
tema: Tema = 'claro';
|
||||
@@ -424,8 +496,8 @@ export class IndicadoresPage {
|
||||
private scrollToIndicator(key: string) {
|
||||
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()) return;
|
||||
const target = this.document.getElementById(identityElementId(key));
|
||||
const grid = this.element.nativeElement.querySelector('.catalog-grid');
|
||||
if (!target || !grid?.contains(target)) return;
|
||||
const grid = target?.closest('.catalog-grid');
|
||||
if (!target || !grid) return;
|
||||
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
|
||||
target.querySelector('h2')?.focus({ preventScroll: true });
|
||||
@@ -495,7 +567,9 @@ export class IndicadoresPage {
|
||||
this.catalogLoading.set(false);
|
||||
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
|
||||
this.catalog.set(this.dominio === 'cama' ? items.map(item => item.id === 'cama_birads_456_mastografia'
|
||||
? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item) : items);
|
||||
? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item)
|
||||
: this.dominio === 'cacu' ? items.map(item => ({ ...item, titulo: CACU_FIGURAS_OPORTUNIDAD.find(figura => figura.id === item.id)?.titulo ?? item.titulo }))
|
||||
: items);
|
||||
this.filtersEdited();
|
||||
this.catalogError.set(error);
|
||||
this.availabilityRequests.next();
|
||||
|
||||
@@ -163,7 +163,8 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
|
||||
expect(e.page.seleccionSeguimiento()).toBeUndefined();
|
||||
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
|
||||
dominio === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
dominio === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
e.page.changeDominio('cama'); e.harness.detectChanges();
|
||||
|
||||
@@ -11,7 +11,7 @@ describe('Regresión del mapeo FHIR en CaCu y TEA', () => {
|
||||
it('las 16 medidas se mapean igual que antes: ids, catálogo, ficha y filas de datos', () => {
|
||||
// Pins down: ids, catalog entries, sheets and data rows of CaCu's seven and TEA's nine measures, over real reports,
|
||||
// equal the recorded ones; an error counts as a result too. Fails if a change meant for CaMa (its id table, its
|
||||
// group name, its undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
|
||||
// undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
|
||||
// regenerate the recorded mapping and say why in the change.
|
||||
const actual = mapeoDeCacuYTea({ indicadorId, indicadorDeMeasure, metadatosDeMeasure, datosDeReportes });
|
||||
expect(Object.keys(actual)).toEqual(Object.keys(esperado));
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// What this module covers: the screening route chart in CaCu's page: it appears only when the catalog publishes the seven
|
||||
// measures it reads, and then those measures that nothing else draws lose their own cards. Catalogs are synthetic,
|
||||
// shaped like /cacu/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
|
||||
|
||||
// Each measure carries the figure of its contract, as the published ones do: the Indicadores tab draws no card for an indicator without figures.
|
||||
const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [contrato === 'C2' ? 'fig_c2_donas' : 'fig_c3r_caja'], tipos_periodo: ['semestre', 'mes'] });
|
||||
|
||||
describe('Ruta del tamizaje: página de CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
function abrir(domain: Dominio, catalog: unknown[]) {
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
|
||||
http.match(() => true);
|
||||
}
|
||||
const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route');
|
||||
const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id);
|
||||
|
||||
it('con las siete medidas publicadas aparece la gráfica y ninguna de sus medidas tiene tarjeta', () => {
|
||||
// Pins down: the chart replaces the cards of every time it draws, the cytology's and the diagnosis' included (the
|
||||
// «Tiempo de tamizaje a diagnóstico» figures). Fails if the chart stops appearing, or a time it draws also shows as
|
||||
// a card.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).not.toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of ROUTE_IDS) expect(ids).not.toContain(id);
|
||||
expect(ids).toContain('cacu_eu7');
|
||||
});
|
||||
it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => {
|
||||
// Fails if the chart appears with a measure missing, or the cards of the others disappear anyway.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.filter(id => id !== 'cacu_dias_toma_biopsia').map(id => item(id))]);
|
||||
expect(ruta()).toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of ROUTE_ONLY_IDS.filter(id => id !== 'cacu_dias_toma_biopsia')) expect(ids).toContain(id);
|
||||
});
|
||||
it('las otras áreas no la tienen', () => {
|
||||
// Fails if the CaCu chart leaks into TEA or CaMa.
|
||||
abrir('cama', [item('cama_eu38a'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -33,15 +33,14 @@ describe('Secciones compartidas por dominio', () => {
|
||||
});
|
||||
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
|
||||
|
||||
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
|
||||
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas e Indicadores seleccionado', async domain => {
|
||||
const harness = await RouterTestingHarness.create();
|
||||
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||
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'];
|
||||
const esperadas = domain === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', '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)!;
|
||||
@@ -59,6 +58,10 @@ describe('Secciones compartidas por dominio', () => {
|
||||
harness.detectChanges();
|
||||
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
|
||||
expect(tracking.hidden).toBe(false);
|
||||
if (domain === 'tea') {
|
||||
expect(tracking.querySelector('h2')?.textContent).toBe('Alteraciones de EEG relacionadas al TEA');
|
||||
expect(tracking.querySelector('select[name="estatus"]')?.closest('label')?.firstChild?.textContent?.trim()).toBe('Estatus de EEG');
|
||||
}
|
||||
expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible');
|
||||
if (domain === 'cama') {
|
||||
// An unavailable cohort has no table and offers a retry.
|
||||
@@ -76,7 +79,7 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes.
|
||||
});
|
||||
|
||||
it('cambiar de dominio reinicia Resumen tanto por router como por coordinación de página', async () => {
|
||||
it('cambiar de dominio reinicia Indicadores tanto por router como por coordinación de página', async () => {
|
||||
const harness = await RouterTestingHarness.create();
|
||||
for (const domain of DOMINIOS) {
|
||||
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||
|
||||
@@ -36,7 +36,8 @@ describe('Seguimiento de CaMa: ficha del paciente', () => {
|
||||
// Fails if the export buttons leave the title row or come back under the table.
|
||||
it('has the export buttons in the row of the section title, and nothing after the pagination', () => {
|
||||
const row = root().querySelector('.title-row')!;
|
||||
expect(row.querySelector('h2')!.textContent).toContain('Seguimiento de');
|
||||
// Fails if the section heading goes back to «Seguimiento de …» instead of the name of the section tab.
|
||||
expect(row.querySelector('h2')!.textContent).toBe('Análisis de riesgos');
|
||||
expect([...row.querySelectorAll('button')].map(b => b.textContent!.trim())).toEqual(['Exportar Excel (.xlsx)', 'Exportar PDF']);
|
||||
expect(root().querySelector('nav')!.nextElementSibling).toBeNull();
|
||||
expect(root().textContent).not.toContain('Exportar resultados');
|
||||
|
||||
@@ -195,13 +195,12 @@ describe('Seguimiento de CaMa (tabla)', () => {
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toBe('La respuesta del servicio no tiene el formato esperado.');
|
||||
expect(root().querySelector('table')).toBeNull(); expect(root().textContent).not.toContain('M-0081');
|
||||
});
|
||||
it('un tamaño de página inválido no sale del navegador', async () => {
|
||||
it('un tamaño de página mayor al máximo se acota y no sale del navegador sin acotar', async () => {
|
||||
await cargado();
|
||||
const tam = campo('Registros por página').querySelector('input') as HTMLInputElement;
|
||||
tam.value = '500'; tam.dispatchEvent(new Event('input')); fixture.detectChanges();
|
||||
tam.value = '500'; tam.dispatchEvent(new Event('input')); tam.dispatchEvent(new Event('change')); fixture.detectChanges();
|
||||
boton('Consultar').click(); fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha');
|
||||
expect(parametros(solicitud())).toMatchObject({ page_size: '200' });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { TrackingExportBar } from './export/tracking-export-bar';
|
||||
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
|
||||
import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
|
||||
import {
|
||||
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
|
||||
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, acotarTamano, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
|
||||
SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor,
|
||||
} from './seguimiento-tabla.service';
|
||||
|
||||
@@ -48,7 +48,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
|
||||
}
|
||||
<div [hidden]="!!ficha()">
|
||||
<div class="title-row">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
<h2>Análisis de riesgos</h2>
|
||||
@if (data(); as respuesta) {
|
||||
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready' && !diferencia()" [seleccion]="etiquetaDatos()" />
|
||||
}
|
||||
@@ -76,7 +76,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
|
||||
@for (o of filtro.opciones; track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" /></label>
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
|
||||
<button type="submit" [disabled]="estado() === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@switch (estado()) {
|
||||
@@ -163,6 +163,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
private readonly consultas = new Subject<Consulta | null>();
|
||||
readonly etiquetaVentana = etiquetaVentana;
|
||||
readonly tamanoMaximo = PAGE_SIZE_MAX;
|
||||
readonly acotar = acotarTamano;
|
||||
readonly estado = signal<Estado>('idle');
|
||||
readonly mensaje = signal('');
|
||||
readonly data = signal<SeguimientoTablaResponse | undefined>(undefined);
|
||||
@@ -315,7 +316,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
this.appliedEtiqueta = etiqueta;
|
||||
// Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one.
|
||||
const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte;
|
||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros,
|
||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: acotarTamano(this.draft.page_size), filtros,
|
||||
contexto: otroCorte ? undefined : contexto };
|
||||
// A new query of the cohort starts from nothing on screen: what was there belongs to the previous one.
|
||||
if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); }
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// Covers how the Indicadores tab arranges TEA's figures: the time figures under «Indicadores de oportunidad», the
|
||||
// clinical ones under «Indicadores clínicos», each in its order, and the tab's name in the three domains.
|
||||
// Fixtures: a TEA catalog shaped like /tea/indicadores, published out of order on purpose.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { Dominio } from './indicadores.models';
|
||||
|
||||
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||
const TEA = [
|
||||
item('M30_resultado_eeg', 'Porcentaje de EEG normal y anormal', 'C1', ['fig_c1_barras_alteracion']),
|
||||
item('M29_calidad_eeg', 'Calidad del EEG', 'C2', ['fig_c2_barras']),
|
||||
item('M28_casos_por_estado', 'Casos por estatus', 'C2', ['fig_c2_barras']),
|
||||
item('M27_dias_ados2_diagnostico', 'Días de ADOS-2 a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
item('M26_dias_mchat_ados2', 'Días de M-CHAT a ADOS-2', 'C3r', ['fig_c3r_caja']),
|
||||
item('M25_dias_mchat_diagnostico', 'Días de M-CHAT a diagnóstico positivo', 'C3r', ['fig_c3r_caja']),
|
||||
item('M24_confirmacion_diagnostico', 'Porcentaje de confirmación diagnóstica', 'C1', ['fig_c1_barras_apiladas_edad']),
|
||||
item('M23_pacientes_evaluados', 'Pacientes evaluados por resultado diagnóstico', 'C2', ['fig_c2_barras']),
|
||||
item('M22_diagnosticados_sin_eeg', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', 'C1', ['fig_c1_barras_edad']),
|
||||
item('M21_diagnosticados_con_eeg', 'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'C1', ['fig_c1_barras_edad']),
|
||||
];
|
||||
|
||||
describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
// The KPI and period requests are not what these tests are about.
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
function open(domain: Dominio, catalog: unknown[]) {
|
||||
// The page starts in TEA, whose catalog is already answered: leave it first to load it again.
|
||||
if (domain === fixture.componentInstance.dominio) {
|
||||
fixture.componentInstance.changeDominio(domain === 'cacu' ? 'cama' : 'cacu'); fixture.detectChanges();
|
||||
http.match(() => true);
|
||||
}
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
|
||||
http.match(() => true); fixture.detectChanges();
|
||||
}
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const titles = (selector: string) => [...root().querySelectorAll(selector + ' app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
|
||||
it('las figuras de tiempo van en oportunidad y las clínicas en su orden, sin duplicarse', () => {
|
||||
// M30 belongs to Trazabilidad even when the catalog publishes it.
|
||||
open('tea', TEA);
|
||||
expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo']);
|
||||
expect(titles('.graphic-section')).toEqual([
|
||||
'Pacientes evaluados por resultado diagnóstico', 'Porcentaje de confirmación diagnóstica',
|
||||
'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
'Casos por estatus', 'Calidad del EEG']);
|
||||
expect(root().querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
expect(fixture.componentInstance.catalogOrder().map(item => item.id)).not.toContain('M30_resultado_eeg');
|
||||
});
|
||||
|
||||
it('un indicador no publicado deja el resto en su orden', () => {
|
||||
// Fails if the order depends on every figure being published.
|
||||
open('tea', TEA.filter(entry => entry.id !== 'M27_dias_ados2_diagnostico' && entry.id !== 'M23_pacientes_evaluados'));
|
||||
expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de M-CHAT a diagnóstico positivo']);
|
||||
expect(titles('.graphic-section').slice(0, 2)).toEqual(['Porcentaje de confirmación diagnóstica', 'Porcentaje de pacientes con diagnóstico de TEA con EEG']);
|
||||
});
|
||||
|
||||
it('CaMa no recibe el resumen ni el orden de TEA en oportunidad', () => {
|
||||
// Fails if TEA's summary or its figure order leaks into CaMa's opportunity strip (CaMa has its own time section).
|
||||
open('cama', [item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja'])]);
|
||||
expect(root().querySelector('app-tea-resumen-periodo')).toBeNull();
|
||||
});
|
||||
|
||||
it('la primera pestaña se llama Resumen en TEA e Indicadores en CaCu y CaMa', () => {
|
||||
// Fails if TEA's first tab loses its name, if CaCu or CaMa take it, or if the section id changes.
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) {
|
||||
open(domain, [item(domain + '_x', 'Indicador', 'C2', ['fig_c2_barras'])]);
|
||||
const first = root().querySelector('[role="tab"]') as HTMLElement;
|
||||
expect(first.textContent?.trim()).toBe(domain === 'tea' ? 'Resumen' : 'Indicadores');
|
||||
expect(first.id).toBe('tab-resumen');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -39,7 +39,7 @@ const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFi
|
||||
const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0;
|
||||
const fail = (message: string): never => { throw new TiemposIncompatibles(message); };
|
||||
|
||||
function caja(fila: Record<string, unknown> | undefined): Caja {
|
||||
export function caja(fila: Record<string, unknown> | undefined): Caja {
|
||||
if (!fila) return { estado: 'No disponible' };
|
||||
if (fila['suprimido'] === 1) return { estado: 'Suprimido' };
|
||||
const { n, q1, mediana, q3 } = fila;
|
||||
|
||||
@@ -3,8 +3,15 @@
|
||||
[registrosTemporales]="pacienteDetalle.registrosTemporales()"
|
||||
(registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" />
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
@if (dominio !== 'cama') { <h2>Seguimiento de {{ domainLabel }}</h2> }
|
||||
@if (teaFicha) {
|
||||
<section class="ficha-tea" aria-label="Resumen del paciente">
|
||||
<button type="button" (click)="volverDeTea()">Volver a Seguimiento</button>
|
||||
<h2>Paciente {{ teaFicha }}</h2>
|
||||
<app-tea-paciente-resumen [id]="teaFicha" modo="resumen" />
|
||||
</section>
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado' || !!teaFicha">
|
||||
@if (dominio !== 'cama') { <h2>{{ titulo }}</h2> }
|
||||
@if (dominio === 'cama') {
|
||||
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" (fichaAbierta)="cambiaFichaCama($event)"
|
||||
(volverAlAnalisis)="volverAlAnalisis.emit()" />
|
||||
@@ -22,8 +29,8 @@
|
||||
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
||||
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
||||
</select></label>
|
||||
<label>{{ dominio === 'tea' ? 'Alteraciones EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
|
||||
<option [ngValue]="undefined">{{ dominio === 'tea' ? 'Todas' : 'Todos' }}</option>
|
||||
<label>{{ dominio === 'tea' ? 'Estatus de EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
|
||||
<option [ngValue]="undefined">Todos</option>
|
||||
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
|
||||
</select></label>
|
||||
@if (dominio === 'tea') {
|
||||
@@ -48,7 +55,19 @@
|
||||
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></label>
|
||||
@if (dominio === 'cacu') {
|
||||
@if (columnasDelEstatus(draft.estatus).length) {
|
||||
<label>Horizonte de la probabilidad <select name="horizonte" [(ngModel)]="draft.horizonte">
|
||||
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@if (columnasDelEstatus(draft.estatus).length) {
|
||||
<label>Ordenar por <select name="orden" [(ngModel)]="draft.orden">
|
||||
@for (o of ordenes(); track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
|
||||
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@if (status === 'loading') { <p role="status">Cargando seguimiento…</p> }
|
||||
@@ -82,13 +101,14 @@
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estado del caso</th><th scope="col">Último EEG</th><th scope="col">Puntaje M-CHAT</th><th scope="col">CSS ADOS-2</th><th scope="col">Alteraciones EEG</th></tr></thead>
|
||||
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estado del caso</th><th scope="col">Último EEG</th><th scope="col">Puntaje M-CHAT</th><th scope="col">CSS ADOS-2</th><th scope="col">Estatus de EEG</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track item.id_seudonimo) {
|
||||
<tr class="tea-row" [class.abierta]="teaAbierto === item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
<td><button class="row-toggle" type="button" [attr.aria-expanded]="teaAbierto === item.id_seudonimo" [attr.aria-controls]="'tea-detalle-' + item.id_seudonimo"
|
||||
[attr.aria-label]="(teaAbierto === item.id_seudonimo ? 'Ocultar' : 'Ver') + ' resumen del paciente ' + item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
<span class="chevron" aria-hidden="true"></span>{{ item.id_seudonimo }}</button></td>
|
||||
<span class="chevron" aria-hidden="true"></span></button>
|
||||
<button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirTea(item.id_seudonimo, $event)">{{ item.id_seudonimo }}</button></td>
|
||||
<td>{{ item.grupo_edad }}</td>
|
||||
<td><span class="estado-caso" [attr.data-estado]="item.estado_caso">{{ etiquetaEstado[item.estado_caso] }}</span>
|
||||
@if (item.pendientes.length) { <small>Falta: {{ item.pendientes.join(', ') }}</small> }</td>
|
||||
@@ -97,7 +117,7 @@
|
||||
<td>{{ item.css_ados2 ?? 'No disponible' }}@if (item.modulo_ados2) { <small>Módulo {{ item.modulo_ados2 }}</small> }</td>
|
||||
<td>@if (item.alteraciones_eeg; as eeg) { <span class="eeg" [class.eeg-anormal]="eeg === 'anormal'">{{ eeg === 'anormal' ? 'Anormal' : 'Normal' }}</span> } @else { No disponible }</td></tr>
|
||||
@if (teaAbierto === item.id_seudonimo) {
|
||||
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" /></td></tr>
|
||||
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" (completo)="abrirTea($event)" /></td></tr>
|
||||
}
|
||||
} @empty { <tr><td colspan="7">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
@@ -107,16 +127,18 @@
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Última biopsia</th>@for (c of columnasProbabilidad(); track c) {<th scope="col">{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)</th>}<th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track identidad(item).id) {
|
||||
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="identidad(item).id">
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultima_biopsia; as b) { {{ b.grado ?? 'Sin grado' }}<small>Fecha: {{ b.fecha }}</small> } @else { No disponible }</td>
|
||||
@for (c of columnasProbabilidad(); track c) { <td class="probabilidad">{{ probabilidad(item, c) ?? 'No disponible' }}</td> }
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
</tr>
|
||||
} @empty { <tr><td colspan="8">No hay registros para los filtros aplicados.</td></tr> }
|
||||
} @empty { <tr><td [attr.colspan]="9 + columnasProbabilidad().length">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -29,7 +29,7 @@ nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top
|
||||
tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; }
|
||||
tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link { display: inline-flex; align-items: center; min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: 999px; border: 1px solid var(--issste-border); font-weight: 600; }
|
||||
.eeg-anormal { border-color: var(--issste-accent); color: var(--issste-accent); }
|
||||
@@ -42,3 +42,4 @@ tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(i
|
||||
@media (prefers-reduced-motion: reduce) { .chevron, tbody tr.tea-row { transition: none; } }
|
||||
tbody tr.tea-detalle > td { padding: 1rem; border-top: 0; background: var(--issste-background); }
|
||||
// TEA patient window (mock: odd-numbered patients), laid out like CaCu's patient page.
|
||||
.ficha-tea > button { margin-bottom: .5rem; }
|
||||
|
||||
@@ -4,7 +4,9 @@ import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, Subject, switchMap } from 'rxjs';
|
||||
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, probabilidadAl, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { porcentaje } from './paciente-detalle/paciente-riesgo.presentacion';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
@@ -25,11 +27,18 @@ import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
export class IndicadoresTracking implements OnChanges {
|
||||
@Input({ required: true }) domainLabel = '';
|
||||
@Input() dominio: Dominio = 'tea';
|
||||
// The section's heading: TEA's follows its EEG, CaCu's names the risk models it will hold; the other domains keep the follow-up one.
|
||||
get titulo() {
|
||||
return this.dominio === 'tea' ? 'Alteraciones de EEG relacionadas al TEA'
|
||||
: this.dominio === 'cacu' ? 'Modelos de riesgo asociados a cáncer cervicouterino' : 'Seguimiento de ' + this.domainLabel;
|
||||
}
|
||||
@Input() active = false;
|
||||
/** CaMa: the patients of a curve or a cell of the analysis, for its follow-up list. */
|
||||
@Input() seleccion?: SeleccionSeguimiento;
|
||||
/** CaMa: the way back to the analysis the selection came from. */
|
||||
readonly volverAlAnalisis = output<void>();
|
||||
readonly tamanoMaximo = PAGE_SIZE_MAX;
|
||||
readonly acotar = acotarTamano;
|
||||
private readonly service = inject(CacuSeguimientoService);
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly teaService = inject(TeaSeguimientoService);
|
||||
@@ -52,10 +61,35 @@ export class IndicadoresTracking implements OnChanges {
|
||||
teaData?: TeaSeguimientoResponse;
|
||||
// One open summary at a time, like an accordion.
|
||||
teaAbierto?: string;
|
||||
/** The TEA patient whose whole record shows in place of the list. */
|
||||
teaFicha?: string;
|
||||
private controlTea?: HTMLElement;
|
||||
statuses: SeguimientoStatus[] = [];
|
||||
private metadataLoaded = false;
|
||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
|
||||
/** CaCu: the horizons the models give (years), for the probability columns and the order; 5 until the list says. */
|
||||
horizontes(): number[] { return this.data?.horizontes_disponibles?.length ? this.data.horizontes_disponibles : [0, 1, 3, 5]; }
|
||||
horizonteMostrado(): number { return this.data?.filtros.horizonte ?? this.draft.horizonte ?? 5; }
|
||||
readonly etiquetaProbabilidad = ETIQUETA_PROBABILIDAD;
|
||||
/** The probability columns of a follow-up status (its scenario's models); none for every patient. */
|
||||
columnasDelEstatus(estatus: string | null | undefined): readonly ProbabilidadClave[] {
|
||||
return estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : [];
|
||||
}
|
||||
/** The probability columns of the list shown: those of the status it was filtered by. */
|
||||
columnasProbabilidad(): readonly ProbabilidadClave[] { return this.columnasDelEstatus(this.data?.filtros.estatus); }
|
||||
/** "Ordenar por": the most recent study, or one of the columns of the status chosen in the form. */
|
||||
ordenes(): { codigo: string; etiqueta: string }[] {
|
||||
return [{ codigo: 'reciente', etiqueta: 'Estudio más reciente' },
|
||||
...this.columnasDelEstatus(this.draft.estatus).map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))];
|
||||
}
|
||||
/** A probability cell: "12.5 % (8.1 – 18 %)", or `null` when no model gives it at the horizon shown. */
|
||||
probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave): string | null {
|
||||
const h = probabilidadAl(item, clave, this.horizonteMostrado());
|
||||
if (!h) return null;
|
||||
const ic = h.ic_bajo !== null && h.ic_alto !== null ? ` (${porcentaje(h.ic_bajo)} – ${porcentaje(h.ic_alto)} %)` : '';
|
||||
return `${porcentaje(h.probabilidad)} %${ic}`;
|
||||
}
|
||||
private applied: SeguimientoQuery = { ...this.draft };
|
||||
readonly latestStudy = latestStudy;
|
||||
readonly gruposEdad = GRUPOS_EDAD_TEA;
|
||||
@@ -79,7 +113,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.statuses = data.estatus_disponibles;
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, orden: data.filtros.orden, horizonte: data.filtros.horizonte, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.draft = { ...this.applied };
|
||||
if (!this.metadataLoaded) {
|
||||
this.metadataLoaded = true;
|
||||
@@ -110,6 +144,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
// Changing domain removes the table that holds CaMa's record, so the page is told here that no record shows.
|
||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado' || this.camaFichaAbierta()) this.fichaPacienteAbierta.emit(false);
|
||||
this.camaFichaAbierta.set(false);
|
||||
if (this.teaFicha) this.fichaPacienteAbierta.emit(false);
|
||||
this.teaFicha = undefined; this.controlTea = undefined;
|
||||
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
||||
@@ -119,11 +155,16 @@ export class IndicadoresTracking implements OnChanges {
|
||||
}
|
||||
private load(q: SeguimientoQuery) {
|
||||
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
|
||||
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
|
||||
if (!validSeguimientoQuery(q)) { this.message = `Revisa la fecha, la ventana y el tamaño de página (1 a ${PAGE_SIZE_MAX}).`; return; }
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
}
|
||||
apply() { this.load({ ...this.draft, page: 1 }); }
|
||||
apply() {
|
||||
this.draft.page_size = acotarTamano(this.draft.page_size);
|
||||
// an order by a column the chosen status doesn't show goes back to the most recent study
|
||||
if (this.draft.orden && this.draft.orden !== 'reciente' && !this.columnasDelEstatus(this.draft.estatus).includes(this.draft.orden)) this.draft.orden = 'reciente';
|
||||
this.load({ ...this.draft, page: 1 });
|
||||
}
|
||||
retry() { this.load(this.applied); }
|
||||
navigate(page: number) {
|
||||
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
|
||||
@@ -152,6 +193,18 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
|
||||
this.teaAbierto = this.teaAbierto === id ? undefined : id;
|
||||
}
|
||||
abrirTea(id: string, evento?: Event) {
|
||||
evento?.stopPropagation();
|
||||
this.controlTea = evento?.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined;
|
||||
this.teaFicha = id;
|
||||
this.fichaPacienteAbierta.emit(true);
|
||||
}
|
||||
volverDeTea() {
|
||||
this.teaFicha = undefined;
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
const control = this.controlTea;
|
||||
afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector });
|
||||
}
|
||||
volverASeguimiento() {
|
||||
this.pacienteDetalle.cerrar();
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
|
||||
@@ -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; }
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
@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 (escenarios().length === 0) { <p role="status">La paciente no cumple las condiciones de ningún escenario clínico de recurrencia.</p> }
|
||||
@else {
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario() ? clave(escenario()!) : ''" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track clave(f)) { <option [value]="clave(f)" [selected]="f === escenario()">{{ f.escenario }} ({{ f.cohorte_nombre }})</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 (escenario()) {
|
||||
<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>
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
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, FiguraRecurrencia } from './cama-recurrencia.service';
|
||||
|
||||
export const HORIZONTE_PREDETERMINADO = 60;
|
||||
|
||||
/**
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo» for one patient: the clinical scenarios her own age, tumor size, grade and
|
||||
* receptors place her in, from either external cohort (METABRIC or SCAN-B, named with each scenario and never mixed in one figure).
|
||||
* The scenario chosen decides the curve and the label at once; the label has a horizon (12, 36 or 60 months, 60 by default).
|
||||
*/
|
||||
@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);
|
||||
/** 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 elegido = signal<string | null>(null);
|
||||
readonly horizonte = signal<number>(HORIZONTE_PREDETERMINADO);
|
||||
/** The figures of her scenarios, in the order the server ranked them. */
|
||||
readonly escenarios = computed(() => {
|
||||
const r = this.respuesta();
|
||||
if (!r) return [];
|
||||
return r.deLaPaciente.map(s => r.escenarios.find(f => f.cohorte === s.cohorte && f.escenario === s.escenario))
|
||||
.filter((f): f is FiguraRecurrencia => !!f);
|
||||
});
|
||||
readonly escenario = computed(() => this.escenarios().find(f => clave(f) === this.elegido()) ?? this.escenarios()[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;
|
||||
});
|
||||
readonly clave = clave;
|
||||
|
||||
elegirEscenario(valor: string): void { this.elegido.set(valor); }
|
||||
elegirHorizonte(meses: number): void { this.horizonte.set(meses); }
|
||||
}
|
||||
|
||||
function clave(f: FiguraRecurrencia): string { return `${f.cohorte}|${f.escenario}`; }
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
<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 (opciones().length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@else {
|
||||
@if (opciones().length === 1) { <p class="selector">Escenario clínico de la paciente: <strong>{{ escenario() }}</strong></p> }
|
||||
@else {
|
||||
<label class="selector">Escenarios clínicos de la paciente
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of opciones(); 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>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
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» of the clinical scenario the patient's own data place her in; when they place
|
||||
* her in several, a menu of those. The scenario decides the curve and the label at once, computed from the data ingested so far with the
|
||||
* model in production.
|
||||
*/
|
||||
@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);
|
||||
/** Her scenarios; every scenario only if the server could not place her. */
|
||||
readonly opciones = computed(() => { const m = this.menu(); return m ? (m.deLaPaciente.length ? m.deLaPaciente : m.escenarios) : []; });
|
||||
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,197 @@
|
||||
// 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 }, { nombre: 'Estadio IV', n: 30 }],
|
||||
deLaPaciente: [{ nombre: 'Estadio I', n: 80 }, { nombre: '< 45 años', n: 100 }], 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 a scenario her data do not place her in.
|
||||
it('opens on the patient\'s scenario and offers only hers', () => {
|
||||
const f = montar();
|
||||
const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim());
|
||||
|
||||
expect(opciones).toEqual(['Estadio I', '< 45 años']);
|
||||
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, 'Escenarios clínicos de la paciente', '< 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 supervivencia de una paciente con un solo escenario', () => {
|
||||
// Fails if a patient whose data place her in one scenario is asked to choose: the scenario is named and drawn, with no menu.
|
||||
it('names her one scenario and draws it without a menu', () => {
|
||||
const consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: null }));
|
||||
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }],
|
||||
deLaPaciente: [{ nombre: 'Toda la cohorte', n: 500 }], predeterminado: 'Toda la cohorte' }), consulta } }] });
|
||||
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
|
||||
f.componentRef.setInput('pacId', '9');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
|
||||
expect((f.nativeElement as HTMLElement).querySelector('select')).toBeNull();
|
||||
expect(texto(f)).toContain('Escenario clínico de la paciente: Toda la cohorte');
|
||||
expect(consulta).toHaveBeenCalledExactlyOnceWith('Toda la cohorte');
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
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' },
|
||||
de_la_paciente: [{ cohorte: 'scanb', escenario: 'Grado 3' }, { cohorte: 'metabric', escenario: '< 45 años' }] });
|
||||
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 menu offers a cohort selector or scenarios the patient's covariates do not place her in, or does not open on the first.
|
||||
it('offers only the patient\'s scenarios, each with its cohort, and opens on the first', () => {
|
||||
const f = montar();
|
||||
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].some(l => l.textContent!.includes('Cohorte'))).toBe(false);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['Grado 3 (SCAN-B)', '< 45 años (METABRIC)']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her first scenario, the label at 60 months
|
||||
});
|
||||
|
||||
// Fails if choosing another of her scenarios leaves the previous curve or label on screen: the cohorts are never mixed.
|
||||
it('changes the curve and the label together when she has another scenario chosen, and keeps one curve', () => {
|
||||
const f = montar();
|
||||
|
||||
elegir(f, 'Escenario clínico', 'metabric|< 45 años');
|
||||
|
||||
expect(texto(f)).toContain('Marca=metabric-60');
|
||||
expect(texto(f)).not.toContain('Marca=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');
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user