Compare commits

..

6 Commits

Author SHA1 Message Date
Angel Capetillo Zavala fb54cfb188 Merge feature/tea-eeg-analysis into dev (TEA age norm and ADOS-2 relation) 2026-11-21 12:23:41 -06:00
alberto 4e9b25bd8f feat(tea): read the age-norm curve, the age at the EEG and the ADOS-2 relation from the WebApi's FHIR answer 2026-11-21 11:17:59 -06:00
alberto 68e2930e65 chore(tea): drop the local simulated-server mode; TEA follow-up reads only the WebApi 2026-11-21 01:30:45 -06:00
ulises fa029d69b8 Seguimiento TEA: gráfica de la norma por edad con el paciente
El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas
5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises 67ae7f482f TEA: el panel de relación con el ADOS-2 muestra solo las zonas alteradas del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises 304c563845 TEA: panel «Relación con el ADOS-2» en la ficha del paciente (prototipo) y modo simulado local
El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del
paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado.
El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración
«simulado» de Angular) es solo para trabajar en local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
51 changed files with 457 additions and 1717 deletions
-15
View File
@@ -62,17 +62,6 @@
"optimization": false, "optimization": false,
"extractLicenses": false, "extractLicenses": false,
"sourceMap": true "sourceMap": true
},
"simulado": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/app/app.config.ts",
"with": "src/app/app.config.simulado.ts"
}
]
} }
}, },
"defaultConfiguration": "production" "defaultConfiguration": "production"
@@ -88,10 +77,6 @@
}, },
"development": { "development": {
"buildTarget": "WebApp:build:development" "buildTarget": "WebApp:build:development"
},
"simulado": {
"buildTarget": "WebApp:build:simulado",
"proxyConfig": "simulado/proxy.simulado.json"
} }
}, },
"defaultConfiguration": "development" "defaultConfiguration": "development"
-38
View File
@@ -1,38 +0,0 @@
# 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.
-47
View File
@@ -1,47 +0,0 @@
{
"/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
}
}
-110
View File
@@ -1,110 +0,0 @@
"""
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()
-21
View File
@@ -1,21 +0,0 @@
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 },
]
};
@@ -7,19 +7,14 @@ const HISTOLOGIA: Readonly<Record<string, string>> = {
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido', CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
}; };
const ESCENARIOS: Readonly<Record<string, string>> = { POST_TRATAMIENTO: 'Post-tratamiento', EN_OBSERVACION: 'En observación' };
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */ /** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo; export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */ /** «50-59» as «50 a 59 años». Any other text is returned as it came. */
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo; export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo; export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
/** The patient's clinical scenario at the cut-off: «Post-tratamiento» or «En observación». */
export const etiquetaEscenario = (codigo: string) => ESCENARIOS[codigo] ?? codigo;
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia, escenario_clinico: etiquetaEscenario,
};
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */ /** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo); export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
+1 -1
View File
@@ -6,7 +6,7 @@ export interface Concept { coding?: Coding[]; text?: string }
export interface Quantity { value?: number; unit?: string } export interface Quantity { value?: number; unit?: string }
export interface Extension { export interface Extension {
url: string; url: string;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string }; valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
extension?: Extension[]; extension?: Extension[];
} }
@@ -16,7 +16,7 @@ import { c2Capability, c2Figure } from './indicadores-c2-adapter';
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2'; import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut'; import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones'; import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
import { c2GeneralSelection } from './indicadores-c2-general-selection'; import { c2GeneralSelection } from './indicadores-c2-general-selection';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
@@ -25,48 +25,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
selector: 'app-indicador-figure-panel', selector: 'app-indicador-figure-panel',
imports: [IndicadorFigureCard, MatTooltipModule], imports: [IndicadorFigureCard, MatTooltipModule],
template: ` template: `
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId"> <section class="figure-panel" [attr.aria-labelledby]="titleId">
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3> <h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
@if (sidebar) {
<aside class="strata-sidebar" aria-label="Estratificación">
<fieldset class="sidebar-group">
<legend>Estratificar por</legend>
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
(click)="changeDimension('')">Sin estratificar</button>
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
@if (dimension && estratos.length > 1) {
<fieldset class="sidebar-group">
<legend>Mostrar</legend>
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
@for (e of estratos; track e.valor) {
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
}
</div>
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
</fieldset>
}
@if (dimension) {
<fieldset class="sidebar-group">
<legend>Medida</legend>
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
</fieldset>
}
</aside>
}
<header class="panel-controls"> <header class="panel-controls">
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p> <p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) { @if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
@@ -76,7 +36,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }} {{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
</span> </span>
} }
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) { @if (figuraId === 'fig_c2_barras' && capabilities.length) {
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"> <fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
<legend>Distribución</legend> <legend>Distribución</legend>
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución"> <div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
@@ -89,16 +49,10 @@ import { MatTooltipModule } from '@angular/material/tooltip';
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada"> <div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
@for (d of capabilities; track d) { @for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d" <button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button> (click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
} }
</div> </div>
} }
@if (dimension) {
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
}
</fieldset> </fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> } @if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
} }
@@ -117,8 +71,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> } @if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> } @if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
<details><summary>Valores publicados</summary> <details><summary>Valores publicados</summary>
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody> <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><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> } @for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
</tbody></table></div> </tbody></table></div>
</details> </details>
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> } @if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
@@ -163,30 +117,6 @@ import { MatTooltipModule } from '@angular/material/tooltip';
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; } .donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
.donut-periods button:disabled { opacity: .45; } .donut-periods button:disabled { opacity: .45; }
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } .donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
shared with the neighbouring panel, so the bars line up with the donut. */
:host { container-type: inline-size; }
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
.sidebar-list { display: grid; gap: .25rem; }
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.sidebar-reset { margin-top: .5rem; }
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
@container (max-width: 559px) {
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
.strata-sidebar { position: static; }
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
}
.visually-hidden { .visually-hidden {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
@@ -235,39 +165,7 @@ export class IndicadorFigurePanel implements OnChanges {
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state; return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
} }
dimension: DimensionEstrato | '' = ''; dimension: DimensionEstrato | '' = '';
readonly etiquetaDimension = etiquetaDimension;
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
private medidaElegida?: MedidaEstrato;
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
changeMedida(medida: MedidaEstrato) {
if (medida === this.medida) return;
this.medidaElegida = medida;
this.representStratified();
}
cells: StratifiedCell[] = []; cells: StratifiedCell[] = [];
/** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */
get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; }
estratos: StratumOption[] = [];
ocultos = new Set<string>();
toggleEstrato(valor: string) {
const ocultos = new Set(this.ocultos);
if (ocultos.has(valor)) ocultos.delete(valor);
else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor);
else return;
this.ocultos = ocultos;
this.representStratified();
}
mostrarTodos() {
if (!this.ocultos.size) return;
this.ocultos = new Set();
this.representStratified();
}
private representStratified() {
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
try { this.result.set(this.presentStratified(this.stratifiedData)); }
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
}
}
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); } get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); } get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
private stratifiedData?: IndicadorDatos; private stratifiedData?: IndicadorDatos;
@@ -279,18 +177,14 @@ export class IndicadorFigurePanel implements OnChanges {
changeDimension(value: DimensionEstrato | '') { changeDimension(value: DimensionEstrato | '') {
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return; if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
if (this.dimension === value) return; if (this.dimension === value) return;
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set(); this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
this.requestFigure();
} }
chooseStratified() { chooseStratified() {
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]); if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
} }
private presentStratified(data: IndicadorDatos): FigureState { private presentStratified(data: IndicadorDatos): FigureState {
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {}; const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
this.estratos = stratumOptions(data); const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
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; this.cells = adapted.cells;
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id, return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }), tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
@@ -455,9 +349,7 @@ export class IndicadorFigurePanel implements OnChanges {
} }
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) { if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
this.dimension = ''; this.estratos = []; this.ocultos = new Set();
}
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; } if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
this.titleId = identityElementId(identity) + '-title'; this.titleId = identityElementId(identity) + '-title';
@@ -9,7 +9,7 @@ import { strFromU8, unzipSync } from 'fflate';
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf'; import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf';
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaEscenario, etiquetaHistologia } from './etiquetas-cohorte'; import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte';
import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing'; import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service'; import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
@@ -33,17 +33,6 @@ describe('Etiquetas de la cohorte', () => {
expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA'); expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA');
expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia)) expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia))
.toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']); .toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']);
expect(['POST_TRATAMIENTO', 'EN_OBSERVACION', 'CONTROL'].map(etiquetaEscenario)).toEqual(['Post-tratamiento', 'En observación', 'CONTROL']);
});
it('el escenario clínico de una fila se lee «Post-tratamiento» o «En observación» en la lista y en la ficha, con su código guardado', () => {
// Fails if the list or the record show the scenario's code, or the code the filter sends is lost.
const cruda = listaCohorte();
const items = cruda['items'] as Record<string, unknown>[];
items[0]['escenario_clinico'] = 'POST_TRATAMIENTO'; items[1]['escenario_clinico'] = 'EN_OBSERVACION';
const r = seguimientoTablaResponse(cruda);
expect(r.items[0]).toMatchObject({ escenario_clinico: 'Post-tratamiento', escenario_clinico_codigo: 'POST_TRATAMIENTO' });
expect(r.items[1]).toMatchObject({ escenario_clinico: 'En observación', escenario_clinico_codigo: 'EN_OBSERVACION' });
expect(toCamaPatientSummary(r.items[0], '2026-01-01')?.clinicalScenario).toBe('Post-tratamiento');
}); });
it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => { it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => {
// Fails if the table, the record and the files can still show the code, or the code is lost for the requests. // Fails if the table, the record and the files can still show the code, or the code is lost for the requests.
@@ -2,12 +2,14 @@
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the // technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into // C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
// the shapes the page reads and passed through the same checks. // the shapes the page reads and passed through the same checks.
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database. // Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database; `conModelo`
// below adds to its patient summary the age at the EEG, a metric's age-norm curve and the ADOS-2 association model,
// in the shape `webapi/fhir/tea.py` emits them.
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http'; import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir'; import { Bundle, Resource, resources } from './fhir';
import { import {
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado, cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
periodosDesde, Report, periodosDesde, Report,
@@ -20,6 +22,49 @@ import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-f
import { IndicadorDatos } from './indicadores.models'; import { IndicadorDatos } from './indicadores.models';
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure; const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
const SD = 'https://isssteleon.org/fhir/StructureDefinition';
const CS = 'https://isssteleon.org/fhir/CodeSystem';
const CURVA = `${SD}/curva-referencia`;
const curva = {
url: CURVA, extension: [
{ url: `${CURVA}/fuente`, valueString: 'tea-ritmo_posterior/3' }, { url: `${CURVA}/estado`, valueString: 'validada' },
...[12, 24, 36].map(v => ({ url: `${CURVA}/edad-meses`, valueDecimal: v })),
...([['p5', [4, 4.5, 5]], ['p25', [5, 5.5, 6]], ['mediana', [5.5, 6, 6.5]], ['p75', [6, 6.5, 7]], ['p95', [6.5, 7, 7.5]]] as [string, number[]][])
.flatMap(([p, vs]) => vs.map(v => ({ url: `${CURVA}/${p}`, valueDecimal: v }))),
],
};
const prediccion = (zona: string, z: number | null) => ({
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] },
probabilityDecimal: 0.41,
extension: [
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' },
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
],
});
// The fixture's patient summary with what the WebApi adds when the analysis and the association model have data.
function conModelo(): Bundle {
const bundle = structuredClone(fx.resumenPaciente) as Bundle;
for (const r of resources(bundle)) {
if (r.resourceType === 'DiagnosticReport') r.extension = [...(r.extension ?? []), { url: `${SD}/edad-meses`, valueDecimal: 23.6 }];
const codigo = (r['code'] as { coding?: { code?: string }[] } | undefined)?.coding?.[0]?.code;
if (r.resourceType === 'Observation' && codigo === 'ritmo_posterior' && !r.id?.startsWith('electrodos-'))
r.extension = [...(r.extension ?? []), curva];
}
const riesgo: Resource = {
resourceType: 'RiskAssessment', id: 'relacion-ados2-P-4A59E9D8B4', status: 'final',
meta: { tag: resources(bundle)[0].meta?.tag },
extension: [{ url: `${SD}/modelo-version`, valueString: '1.0.0' }, { url: `${SD}/modelo-validado`, valueBoolean: false },
{ url: `${SD}/modelo-nivel`, valueString: 'item' }, { url: `${SD}/modelo-n-cohorte`, valueInteger: 40 }],
prediction: [prediccion('occipital', -2.6), prediccion('parietal', null)],
};
bundle.entry = [...(bundle.entry ?? []), { resource: riesgo }];
return bundle;
}
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[]; const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
describe('Indicadores sobre FHIR', () => { describe('Indicadores sobre FHIR', () => {
@@ -210,6 +255,49 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1); expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
}); });
it('el resumen lleva la edad al EEG y la norma por edad de la métrica cuando la WebApi las manda', async () => {
// Pins down: the report's `edad-meses` extension as the EEG's age and a metric observation's `curva-referencia`
// sub-extensions read back in order as the age norm (ages, five percentiles, source and state), so the page's
// checks accept it. Fails if the adapter stops reading either extension or scrambles the series.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
expect(detalle.eeg!.edad_meses).toBe(23.6);
expect(detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!.curva_referencia).toEqual({
fuente: 'tea-ritmo_posterior/3', estado: 'validada', edad_meses: [12, 24, 36],
p5: [4, 4.5, 5], p25: [5, 5.5, 6], mediana: [5.5, 6, 6.5], p75: [6, 6.5, 7], p95: [6.5, 7, 7.5] });
});
it('el resumen arma la relación con el ADOS-2 del RiskAssessment y deja fuera la fila incompleta', async () => {
// Pins down: the model's version, validation, level and cohort from the resource's extensions, and each
// prediction as a row with the metric's and zone's labels, the outcome, OR, interval, q, z, both probabilities
// and the observed score; a prediction without its z is dropped instead of failing the page's checks. Fails if
// the adapter stops reading the RiskAssessment or lets an incomplete row through.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const relacion = (await answer).relacion_ados2!;
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
expect(relacion.filas).toEqual([{
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
});
it('sin edad, norma ni modelo el resumen no inventa esos campos', async () => {
// Pins down: a summary without the new extensions or a RiskAssessment (the fixture as the WebApi served it before
// the analysis wrote them) leaves `edad_meses`, `curva_referencia` and `relacion_ados2` out, so the page hides
// the chart and the panel. Fails if the adapter fills them with defaults.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
expect('edad_meses' in detalle.eeg!).toBe(false);
expect(detalle.eeg!.alteraciones.some(a => 'curva_referencia' in a)).toBe(false);
expect('relacion_ados2' in detalle).toBe(false);
});
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => { it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no // Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes. // value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
@@ -48,9 +48,7 @@ describe('Barras estratificadas: activación y caché',()=>{
toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges(); toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges();
expect(fixture.componentInstance.dimension).toBe('grupo_edad'); expect(fixture.componentInstance.dimension).toBe('grupo_edad');
expect(toggle[1].getAttribute('aria-checked')).toBe('true'); expect(toggle[1].getAttribute('aria-checked')).toBe('true');
// The dimensions, apart from the counts or percentage toggle that follows them. expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2);
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'); } 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',()=>{ it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{
@@ -95,46 +93,3 @@ describe('Barras estratificadas: activación y caché',()=>{
expect(TestBed.inject(IndicadoresSnapshots).reading('cacu',item,applied)?.data).toEqual(general()); 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('&lt;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 ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json';
import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json'; import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json';
import { etiquetaDimension, stratifiedBars, stratifiedCapabilities, stratumOptions } from './indicadores-stratified'; import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified';
import { DimensionEstrato, Indicador } from './indicadores.models'; import { DimensionEstrato, Indicador } from './indicadores.models';
const age = { ...ageJson, tipo_periodo: 'semestre' as const }; const age = { ...ageJson, tipo_periodo: 'semestre' as const };
@@ -61,52 +61,3 @@ describe('Contratos simulados de estratificación de los analistas', () => {
expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow(); 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,19 +4,9 @@ import { c2Theme, seriesColors } from './indicadores-c2-palette';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v); const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// 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[] { export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
return item.contrato === 'C2' && Array.isArray(item.filtros) return item.contrato === 'C2' && Array.isArray(item.filtros)
? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d ? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0 && typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : []; && f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
} }
@@ -27,37 +17,24 @@ export function declaraEstrato(item: Indicador, estrato: DimensionEstrato): bool
const declarados = (item as Indicador & { estratos?: unknown }).estratos; const declarados = (item as Indicador & { estratos?: unknown }).estratos;
return item.contrato === 'C2' && Array.isArray(declarados) && declarados.includes(estrato); 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 StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
export interface StratumOption { valor: string; etiqueta: string; } export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } {
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 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']) || !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos'])
|| Object.keys(data['grupos']).length !== 1 || Object.keys(data['grupos']).length !== 1
|| !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length || !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length
|| !data['valores_estrato'].every(v => typeof v === 'string') || !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'); || new Set(data['valores_estrato']).size !== data['valores_estrato'].length || !record(data['etiquetas_estrato'])) throw new Error('Distribución estratificada inválida');
const published = data['valores_estrato'] as string[], labels = data['etiquetas_estrato']; const strata = 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]; const statisticalGroup = Object.keys(data['grupos'])[0];
if (published.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas'); if (strata.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas');
const catalog = data['categorias'], groups = data['grupos_de_categoria']; const catalog = data['categorias'], groups = data['grupos_de_categoria'];
const entries = new Map<string, { order: number; label: string; color?: string; parent?: string }>(); const entries = new Map<string, { order: number; label: string; color?: string; parent?: string }>();
const rows = new Map<string, Record<string, unknown>>(); const rows = new Map<string, Record<string, unknown>>();
for (const row of data.filas) { for (const row of data.filas) {
const id = row['categoria'], stratum = row['estrato'], n = row['n']; const id = row['categoria'], stratum = row['estrato'], n = row['n'];
if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id
|| typeof stratum !== 'string' || !published.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden']) || typeof stratum !== 'string' || !strata.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'); || ![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]); const key = JSON.stringify([id, stratum]);
if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas'); if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas');
@@ -74,39 +51,21 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
const cells: StratifiedCell[] = []; const cells: StratifiedCell[] = [];
const theme = c2Theme(tema); const theme = c2Theme(tema);
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id)); const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
// The stratum's total: the one published, or else the sum of its cells when every one is published. A share is const figure: PlotlyFigure = { data: strata.map((s, series) => {
// 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 selected = categories.map(([id, c]) => {
const row = rows.get(JSON.stringify([id, s])); const row = rows.get(JSON.stringify([id, s]));
const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible'; const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible';
const value = status === 'Publicado' ? row!['n'] as number : null; const value = status === 'Publicado' ? row!['n'] as number : null;
const total = totalDe(s); cells.push({ category: c.label, stratum: labels[s] as string, value, status });
const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null; return value;
cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status });
return { value, percent, total };
}); });
const x = selected.map(v => porcentaje ? v.percent : v.value); return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
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 } }, marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' }; hovertemplate: '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
}), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true, }), layout: { title: { text: '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, 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 }, font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 },
xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid } xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, 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 }, 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 } } }; legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } };
return { figure, cells }; return { figure, cells };
@@ -18,16 +18,8 @@ export interface Indicador {
filtros?: IndicadorFiltro[]; filtros?: IndicadorFiltro[];
// Tabs that show it; without this field, all of them. // Tabs that show it; without this field, all of them.
vistas?: string[]; 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';
} }
// CaMa's stratifiers (brca, estadio, tamano, etapa) break down its quantities of interest. export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads';
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 IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; } export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; } export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
@@ -1,105 +0,0 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, map, Observable, of, throwError } from 'rxjs';
// The cohort's survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the
// model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the
// version they come from and says when the data are simulated. A 404 is "no model in production yet".
export interface SerieDeSupervivencia { S: number[]; low: number[]; high: number[]; }
export interface CurvasSupervivencia {
n: number; events: number; median_follow_up_months: number;
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
km: { months: number[]; S: number[]; low: number[]; high: number[] };
km_adjusted: { months: number[]; S: number[] };
weibull: { t: number[]; S: number[] };
weibull_fractional: { t: number[]; S: number[] };
points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia };
etiquetas: Record<string, string>;
}
export interface RespuestaCurvas {
modelo: { nombre: string; version: string };
curvas: CurvasSupervivencia;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length);
const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
function invalid(): never {
throw new Error('Respuesta de curvas de supervivencia inválida');
}
function serie(v: unknown, horizons: number): SerieDeSupervivencia {
if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid();
const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[];
if (low.some((l, i) => l > high[i])) invalid();
return { S: s, low, high };
}
/** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */
export function respuestaCurvas(v: unknown): RespuestaCurvas {
if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid();
const m = v['modelo'] as Record<string, unknown>, c = v['curvas'] as Record<string, unknown>;
if (!text(m['nombre']) || !text(m['version'])) invalid();
const horizons = c['horizons_months'];
if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events'])
|| !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid();
const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points'];
if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length)
|| !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid();
if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid();
for (const curve of [weibull, fractional]) {
if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid();
}
if (!record(points)) invalid();
const p = points as Record<string, unknown>, h = (horizons as number[]).length;
const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record<string, string> : {};
return {
modelo: { nombre: m['nombre'] as string, version: m['version'] as string },
curvas: {
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'],
points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas,
},
};
}
/** What can be selected, and the patient's own value of each covariate (`GET /cama/modelo/curvas/opciones?paciente=`). */
export interface OpcionesCurvas {
n: number; events: number;
covariables: Record<string, { valor: string; n: number }[]>;
periodo: { desde: string; hasta: string };
limites: { miembros_min: number; muertes_min: number };
paciente: Record<string, string> | null;
}
export interface ConsultaCurvas { filtros?: Record<string, string[]>; periodo?: { desde?: string; hasta?: string }; }
/** The selection was refused with a reason (a 422): too few patients, or invalid. */
export class SeleccionRechazada extends Error {}
@Injectable({ providedIn: 'root' })
export class CamaCurvasService {
private readonly http = inject(HttpClient);
/** The values that can be selected, and `pacId`'s own; `null` when there is no model in production or no cohort yet. */
opciones(pacId: string): Observable<OpcionesCurvas | null> {
return this.http.get<{ opciones: OpcionesCurvas }>('/cama/modelo/curvas/opciones', { params: { paciente: pacId } }).pipe(
map(r => r.opciones),
catchError(() => of(null)),
);
}
/** The figure's record for the selection, scored with the production version over the data ingested so far. A refused
* selection fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */
consulta(consulta: ConsultaCurvas): Observable<RespuestaCurvas> {
return this.http.post<unknown>('/cama/modelo/curvas/consulta', consulta).pipe(
map(respuestaCurvas),
catchError(error => error instanceof HttpErrorResponse && error.status === 422
? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'La selección no se puede calcular.')))
: throwError(() => error)),
);
}
}
@@ -11,7 +11,6 @@
<dl class="summary"> <dl class="summary">
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div> <div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div> <div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
<div><dt>Escenario clínico</dt><dd>{{ p.clinicalScenario ?? notAvailable }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div> <div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div> <div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
<div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div> <div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div>
@@ -34,12 +33,6 @@
</ul> </ul>
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
<mat-card class="risk-card" appearance="outlined" aria-labelledby="riesgo-individual-title">
<mat-card-header><h3 id="riesgo-individual-title">Riesgo de muerte</h3></mat-card-header>
<mat-card-content>
<app-paciente-riesgo-tabla [pacId]="p.idField === 'pac_id' ? p.patientId : null" dominio="cama" />
</mat-card-content>
</mat-card>
<mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title"> <mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title">
<mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header> <mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header>
<mat-card-content> <mat-card-content>
@@ -2,8 +2,6 @@
// carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus // carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus
// and back behaviour. Fixture: fixtures/cama_seguimiento.json. // and back behaviour. Fixture: fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { PACIENTE_RIESGO_PROVIDER } from '../paciente-riesgo.provider';
import fixtureData from '../../fixtures/cama_seguimiento.json'; import fixtureData from '../../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service'; import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
import { CamaPatientCard } from './cama-patient-card'; import { CamaPatientCard } from './cama-patient-card';
@@ -18,7 +16,7 @@ describe('Ficha CaMa: resumen', () => {
it('reads every field the follow-up row carries', () => { it('reads every field the follow-up row carries', () => {
const row = complete(); const row = complete();
expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({ expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], clinicalScenario: null, status: row['estatus'], priority: row['prioridad'], patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'], birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'],
daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'], daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'],
}); });
@@ -41,8 +39,6 @@ describe('Ficha CaMa: resumen', () => {
describe('Ficha CaMa: componente', () => { describe('Ficha CaMa: componente', () => {
let fixture: ReturnType<typeof TestBed.createComponent<CamaPatientCard>>; let fixture: ReturnType<typeof TestBed.createComponent<CamaPatientCard>>;
const root = () => fixture.nativeElement as HTMLElement; const root = () => fixture.nativeElement as HTMLElement;
// The record asks for the patient's risk; here she has none, so the card shows what the list carries.
beforeEach(() => TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] }));
function montar(summary: CamaPatientSummary) { function montar(summary: CamaPatientSummary) {
fixture = TestBed.createComponent(CamaPatientCard); fixture = TestBed.createComponent(CamaPatientCard);
fixture.componentRef.setInput('summary', summary); fixture.componentRef.setInput('summary', summary);
@@ -76,11 +72,11 @@ describe('Ficha CaMa: componente', () => {
}); });
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model. // Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
it('has placeholders, with no figures, for recurrence and prognostic factors', () => { it('has placeholders, with no figures, for recurrence, survival and prognostic factors', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!); montar(toCamaPatientSummary(complete(), '2026-10-20')!);
const items = [...root().querySelectorAll('[data-pronostico]')]; const items = [...root().querySelectorAll('[data-pronostico]')];
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'factors']); expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'survival', 'factors']);
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Factores pronóstico']); expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico']);
for (const item of items) { for (const item of items) {
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE); expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
expect(item.textContent).not.toMatch(/\d/); expect(item.textContent).not.toMatch(/\d/);
@@ -3,18 +3,17 @@ import { downloadBlob, exportFilename } from '../../export/download-file';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { PacienteRiesgoTabla } from '../paciente-riesgo-tabla';
import { import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models'; } from './cama-patient.models';
/** /**
* Individual record of a CaMa follow-up patient. It shows what the follow-up list carries and the patient's risk with her * Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
* survival figure; recurrence and prognostic factors are placeholders until a validated model supplies them. * survival and prognostic factors are placeholders until a validated model supplies them.
*/ */
@Component({ @Component({
selector: 'app-cama-patient-card', selector: 'app-cama-patient-card',
imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla], imports: [MatButtonModule, MatCardModule, MatIconModule],
templateUrl: './cama-patient-card.html', templateUrl: './cama-patient-card.html',
styleUrl: './cama-patient-card.scss', styleUrl: './cama-patient-card.scss',
}) })
@@ -1,5 +1,5 @@
// Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only // Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only
// the fields of the record, shows placeholders (no figures) for recurrence and prognostic factors (survival is drawn in the record from the risk evaluation), and // the fields of the record, shows placeholders (no figures) for recurrence, survival and prognostic factors, and
// renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test // renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test
// because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser. // because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser.
import fixtureData from '../../fixtures/cama_seguimiento.json'; import fixtureData from '../../fixtures/cama_seguimiento.json';
@@ -46,10 +46,10 @@ describe('Ficha CaMa: PDF individual', () => {
}); });
// Fails if a placeholder gains a figure or an explanation other than "unavailable". // Fails if a placeholder gains a figure or an explanation other than "unavailable".
it('has placeholders, with no figures, for recurrence, prognostic factors and recommendations', () => { it('has placeholders, with no figures, for recurrence, survival, prognostic factors and recommendations', () => {
const found = texts(definition()['content']); const found = texts(definition()['content']);
for (const t of ['Probabilidad de recurrencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t); for (const t of ['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(2); expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(3);
}); });
// Fails if the document carries a platform identifier field. // Fails if the document carries a platform identifier field.
@@ -21,7 +21,6 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo
...section('Resumen', [ ...section('Resumen', [
[patient.idLabel, patient.patientId], [patient.idLabel, patient.patientId],
['Grupo de edad', patient.ageGroup], ['Grupo de edad', patient.ageGroup],
['Escenario clínico', patient.clinicalScenario],
['Estatus de seguimiento', patient.status], ['Estatus de seguimiento', patient.status],
['Prioridad', patient.priority], ['Prioridad', patient.priority],
['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis], ['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis],
@@ -14,8 +14,6 @@ export interface CamaPatientSummary {
idLabel: string; idLabel: string;
cutoff: string; cutoff: string;
ageGroup: string | null; ageGroup: string | null;
/** «Post-tratamiento» or «En observación» at the cut-off. */
clinicalScenario: string | null;
status: string | null; status: string | null;
priority: string | null; priority: string | null;
birads: string | null; birads: string | null;
@@ -27,10 +25,10 @@ export interface CamaPatientSummary {
daysMammographyToDiagnosis: number | null; daysMammographyToDiagnosis: number | null;
} }
/** Placeholders for results that exist only once a validated model and its clinical definition do (survival is drawn from /** Placeholders for results that exist only once a validated model and its clinical definition do. */
* the patient's risk evaluation, not a placeholder). */
export const PROGNOSIS_PLACEHOLDERS = [ export const PROGNOSIS_PLACEHOLDERS = [
{ key: 'recurrence', label: 'Probabilidad de recurrencia' }, { key: 'recurrence', label: 'Probabilidad de recurrencia' },
{ key: 'survival', label: 'Supervivencia' },
{ key: 'factors', label: 'Factores pronóstico' }, { key: 'factors', label: 'Factores pronóstico' },
] as const; ] as const;
export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.'; export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.';
@@ -53,7 +51,6 @@ export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas:
idLabel: ETIQUETA_IDENTIDAD[identity.campo], idLabel: ETIQUETA_IDENTIDAD[identity.campo],
cutoff, cutoff,
ageGroup: text(row['grupo_edad']), ageGroup: text(row['grupo_edad']),
clinicalScenario: text(row['escenario_clinico']),
status: text(row['estatus']), status: text(row['estatus']),
priority: text(row['prioridad']), priority: text(row['prioridad']),
birads: text(row['birads']), birads: text(row['birads']),
@@ -1,18 +0,0 @@
<section class="survival" aria-labelledby="supervivencia-paciente-titulo">
<h5 id="supervivencia-paciente-titulo">Supervivencia de la paciente</h5>
@if (cruzables().length) {
<fieldset class="compare">
<legend>Comparar con las pacientes que comparten</legend>
@for (c of cruzables(); track c.clave) {
<label><input type="checkbox" [checked]="cruces().includes(c.clave)" (change)="alternar(c.clave)" /> {{ c.etiqueta }}: {{ c.valor }}</label>
}
</fieldset>
}
@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">{{ l.motivo }} Quita algún criterio para comparar con más pacientes.</p> }
@if (l.tipo === 'error') { <p role="status">No se pudo calcular la curva de la cohorte; se muestra solo la de la paciente.</p> }
@if (figura(); as figure) {
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Supervivencia de la paciente" />
}
</section>
@@ -1,3 +0,0 @@
.compare { border: 1px solid var(--mat-sys-outline-variant, #ccc); margin: 0 0 1rem; padding: .5rem .75rem; display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; }
.compare legend { font-weight: 600; padding: 0 .25rem; }
label { display: inline-flex; align-items: center; gap: .35rem; }
@@ -1,141 +0,0 @@
// Covers the patient's survival in her CaMa record: the cohort's curves are asked live (for everyone, then for the covariates
// she is compared on), a refused selection says why, a failure leaves her own curve, and the figure has the SEER pipeline's
// look (the Greenwood band, the Kaplan-Meier steps, the two Weibull, the diamonds) with hers over it. Fixtures: a stub of
// `CamaCurvasService` that records each selection, and a cohort record like `POST /cama/modelo/curvas/consulta` answers.
import { TestBed } from '@angular/core/testing';
import { of, throwError } from 'rxjs';
import { vi } from 'vitest';
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
import { CamaCurvasService, respuestaCurvas, SeleccionRechazada } from './cama-curvas.service';
import { CamaSupervivenciaPaciente } from './cama-supervivencia-paciente.component';
import { COLORES, ETIQUETAS_PREDETERMINADAS, figuraSupervivenciaPaciente } from './cama-supervivencia-paciente';
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)) });
function cohorte(n = 245): any {
return {
modelo: { nombre: 'cama-survival', version: '3' },
curvas: {
version: 1, 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 horizontes = [{ horizonte_anios: 0.5, probabilidad: 0.07 }, { horizonte_anios: 1, probabilidad: 0.18 }, { horizonte_anios: 1.5, probabilidad: 0.25 }];
const opciones = { n: 500, events: 133, covariables: {}, periodo: { desde: '2024-01-01', hasta: '2026-01-01' }, limites: { miembros_min: 30, muertes_min: 5 },
paciente: { grade: 'G2', er: 'POSITIVO', her2: 'NA', age_group: '60-74' } };
describe('Figura de supervivencia de la paciente', () => {
const figura = (c: any = cohorte().curvas) => figuraSupervivenciaPaciente(horizontes, respuestaCurvas(c === null ? cohorte() : { ...cohorte(), curvas: c }).curvas)!;
const traza = (f: any, nombre: string) => f.data.find((t: any) => t.name === nombre) as any;
// Fails if the figure loses a piece of the pipeline's chart: the band, the steps, the two Weibull or the cohort's diamonds.
it('has the cohort\'s Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => {
const f = figura();
expect(f.data.some((t: any) => t.fill === 'tonexty')).toBe(true);
expect(traza(f, ETIQUETAS_PREDETERMINADAS['km_crudo']).line).toMatchObject({ color: COLORES.km, shape: 'hv' });
expect(traza(f, ETIQUETAS_PREDETERMINADAS['weibull']).line.color).toBe(COLORES.weibull);
expect(traza(f, ETIQUETAS_PREDETERMINADAS['weibull_fraccional']).line).toMatchObject({ color: COLORES.fraccional, dash: 'dash' });
const rombos = traza(f, ETIQUETAS_PREDETERMINADAS['puntos']);
expect(rombos.x).toEqual([6, 12, 18]);
expect(rombos.marker).toMatchObject({ symbol: 'diamond', color: COLORES.modelo });
expect(rombos.error_y.array.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]);
});
// Fails if her curve is not on the figure, or sits at other horizons than her evaluation's.
it('draws hers over the cohort\'s: a curve and her diamonds at her horizons', () => {
const f = figura();
const suya = traza(f, ETIQUETAS_PREDETERMINADAS['paciente_puntos']);
expect(suya.x).toEqual([6, 12, 18]);
expect(suya.y.map((v: number) => +v.toFixed(2))).toEqual([0.93, 0.82, 0.75]);
expect(suya.error_y).toBeUndefined();
expect(traza(f, ETIQUETAS_PREDETERMINADAS['paciente']).line.color).toBe(COLORES.paciente);
});
// Fails if the labels, the axes or the title leave the pipeline's: S(t), months from the diagnosis, n and deaths.
it('is labelled and scaled as the pipeline\'s figure', () => {
const l = figura().layout as any;
expect(l.yaxis.title.text).toBe('Supervivencia S(t)');
expect(l.xaxis.title.text).toBe('Meses desde el diagnóstico');
expect(l.yaxis.tickformat).toBe('.2f');
expect(l.title.text).toContain('n=245, fallecidos=67');
expect(l.legend.yanchor).toBe('bottom');
});
// Fails if the subgroup the reader chose is not what the title says.
it('names the subgroup in the title', () => {
const f = figuraSupervivenciaPaciente(horizontes, cohorte().curvas, 'claro', 'Pacientes con Grado de Nottingham G2')!;
expect((f.layout as any).title.text).toContain('Pacientes con Grado de Nottingham G2');
});
});
describe('Supervivencia de la paciente: componente', () => {
let consulta: ReturnType<typeof vi.fn>;
beforeEach(() => {
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()) };
consulta = vi.fn(() => of(respuestaCurvas(cohorte())));
TestBed.configureTestingModule({ providers: [
{ provide: CamaCurvasService, useValue: { opciones: () => of(opciones), consulta } },
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
});
afterEach(() => vi.unstubAllGlobals());
const montar = () => {
const f = TestBed.createComponent(CamaSupervivenciaPaciente);
f.componentRef.setInput('pacId', '7');
f.componentRef.setInput('horizontes', horizontes);
f.detectChanges();
return f;
};
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
// Fails if the cohort's curves are not asked for everyone first, or the covariates she has no value for are offered.
it('asks the cohort live, for everyone, and offers the covariates she has a value for', () => {
const f = montar();
expect(consulta).toHaveBeenCalledWith({ filtros: {} });
expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull();
const t = texto(f);
expect(t).toContain('Grado de Nottingham: G2');
expect(t).toContain('Receptor de estrógeno: POSITIVO');
expect(t).not.toContain('HER2:');
});
// Fails if ticking a covariate does not ask the cohort for the patients who share it, or unticking does not go back.
it('asks for her subgroup when a covariate is ticked, and for everyone when it is unticked', () => {
const f = montar();
f.componentInstance.alternar('grade');
f.detectChanges();
expect(consulta).toHaveBeenLastCalledWith({ filtros: { grade: ['G2'] } });
f.componentInstance.alternar('grade');
f.detectChanges();
expect(consulta).toHaveBeenLastCalledWith({ filtros: {} });
});
// Fails if a refused selection draws a figure, or does not say why.
it('says why when the selection is refused and draws nothing', () => {
consulta.mockReturnValue(throwError(() => new SeleccionRechazada('La selección tiene 3 pacientes y 0 defunciones.')));
const f = montar();
expect(texto(f)).toContain('La selección tiene 3 pacientes');
expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull();
});
// Fails if a failed cohort computation leaves her without a figure.
it('draws only her own curve when the cohort\'s cannot be had', () => {
consulta.mockReturnValue(throwError(() => new Error('boom')));
const f = montar();
expect(texto(f)).toContain('se muestra solo la de la paciente');
expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull();
});
});
@@ -1,62 +0,0 @@
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 { HorizonteRiesgoCacu } from '../paciente-riesgo.models';
import { CamaCurvasService, ConsultaCurvas, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service';
import { figuraSupervivenciaPaciente } from './cama-supervivencia-paciente';
/** What the reader calls each covariate of the model. */
export const COVARIABLES: Record<string, string> = {
age_group: 'Grupo de edad', histologic_type: 'Tipo histológico', grade: 'Grado de Nottingham', er: 'Receptor de estrógeno',
pr: 'Receptor de progesterona', her2: 'HER2', ki67_group: 'Ki-67 (%)', size_group: 'Tamaño de la lesión (mm)',
};
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: RespuestaCurvas };
/**
* One patient's survival, on the SEER pipeline's figure of the cohort. The cohort's curves are computed when the record opens,
* from the data ingested so far and the model in production, for everyone or for the patients who share the covariates the
* reader ticks with her (her subgroup, as the pipeline draws its subgroups). Hers is her own prediction on top of them.
*/
@Component({
selector: 'app-cama-supervivencia-paciente',
imports: [PlotlyChart],
templateUrl: './cama-supervivencia-paciente.component.html',
styleUrl: './cama-supervivencia-paciente.component.scss',
})
export class CamaSupervivenciaPaciente {
readonly pacId = input.required<string>();
readonly horizontes = input.required<readonly HorizonteRiesgoCacu[]>();
private readonly service = inject(CamaCurvasService);
/** The covariates she is compared on. */
readonly cruces = signal<readonly string[]>([]);
readonly opciones = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.opciones(id))));
/** The covariates she has a value for, to offer. */
readonly cruzables = computed(() => {
const suyas = this.opciones()?.paciente;
return suyas ? Object.keys(COVARIABLES).filter(c => suyas[c] && suyas[c] !== 'NA').map(c => ({ clave: c, etiqueta: COVARIABLES[c], valor: suyas[c] })) : [];
});
private readonly consulta = computed<ConsultaCurvas>(() => {
const suyas = this.opciones()?.paciente;
return { filtros: Object.fromEntries(this.cruces().filter(c => suyas?.[c]).map(c => [c, [suyas![c]]])) };
});
readonly lectura = toSignal(toObservable(this.consulta).pipe(switchMap(q => this.service.consulta(q).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: { tipo: 'cargando' } as Lectura });
private readonly descripcion = computed(() => {
const suyas = this.opciones()?.paciente;
const partes = this.cruces().filter(c => suyas?.[c]).map(c => `${COVARIABLES[c]} ${suyas![c]}`);
return partes.length ? `Pacientes con ${partes.join(' · ')}` : null;
});
/** The figure: hers over the cohort's, or hers alone when the cohort's cannot be had. */
readonly figura = computed(() => {
const l = this.lectura();
if (l.tipo === 'cargando' || l.tipo === 'rechazada') return null;
return figuraSupervivenciaPaciente(this.horizontes(), l.tipo === 'lista' ? l.datos.curvas : null, 'claro', this.descripcion());
});
alternar(clave: string): void {
this.cruces.update(actuales => actuales.includes(clave) ? actuales.filter(c => c !== clave) : [...actuales, clave]);
}
}
@@ -1,100 +0,0 @@
import { PlotlyFigure, Tema } from '../../indicadores.models';
import { HorizonteRiesgoCacu } from '../paciente-riesgo.models';
import { tieneIntervalo } from '../paciente-riesgo.validation';
import { CurvasSupervivencia } from './cama-curvas.service';
/** The wording of the chart, as the SEER pipeline's own figure has it. The model's run can publish another wording for any
* of these (`[config.etiquetas]`), so the clinicians define it, not the code. */
export const ETIQUETAS_PREDETERMINADAS: Readonly<Record<string, string>> = {
titulo: 'Supervivencia después del primer reporte de biopsia con carcinoma invasor',
eje_x: 'Meses desde el diagnóstico', eje_y: 'Supervivencia S(t)',
km_crudo: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull', weibull_fraccional: 'Weibull fraccional',
puntos: 'LR + HBN combinado (IC 95 % bootstrap)', paciente: 'Paciente: supervivencia estimada',
paciente_puntos: 'Paciente: modelo en cada horizonte',
};
export const COLORES = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a', paciente: '#e08a00' } as const;
/** The curve runs to this many months, as the cohort's does. */
export const MESES_MAXIMOS = 24;
export interface PuntoDeSupervivencia { meses: number; S: number; bajo: number | null; alto: number | null; }
/** The model's survival at each horizon: one minus the mortality of the `RiskAssessment`, its interval turned around. */
export function puntosDeSupervivencia(horizontes: readonly HorizonteRiesgoCacu[]): PuntoDeSupervivencia[] {
return horizontes.filter(h => h.horizonte_anios > 0).map(h => ({
meses: Math.round(h.horizonte_anios * 12), S: 1 - h.probabilidad,
bajo: tieneIntervalo(h) ? 1 - h.ic_alto! : null, alto: tieneIntervalo(h) ? 1 - h.ic_bajo! : null,
})).sort((a, b) => a.meses - b.meses);
}
/** The survival month by month: log-linear between 0 and the horizons (a constant hazard in each interval), and past the
* last one at the last interval's rate. It passes through every point and never rises. */
export function curvaMensual(puntos: readonly PuntoDeSupervivencia[], hasta = MESES_MAXIMOS): { meses: number[]; S: number[] } {
const bordes = [0, ...puntos.map(p => p.meses)], log = [0, ...puntos.map(p => Math.log(Math.max(p.S, 1e-12)))];
const ultimo = bordes.length - 1, pendiente = ultimo > 0 ? (log[ultimo] - log[ultimo - 1]) / (bordes[ultimo] - bordes[ultimo - 1]) : 0;
const meses = Array.from({ length: Math.max(hasta, bordes[ultimo]) + 1 }, (_, m) => m);
const S = meses.map(m => {
if (m >= bordes[ultimo]) return Math.exp(log[ultimo] + pendiente * (m - bordes[ultimo]));
let i = 0;
while (bordes[i + 1] < m) i++;
return Math.exp(log[i] + (log[i + 1] - log[i]) * (m - bordes[i]) / (bordes[i + 1] - bordes[i]));
});
return { meses, S: S.reduce<number[]>((acc, v) => [...acc, Math.min(v, acc.length ? acc[acc.length - 1] : 1)], []) };
}
const etiqueta = (cohorte: CurvasSupervivencia | null, clave: string) => cohorte?.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave;
/**
* The SEER pipeline's survival figure, with the patient on it. The cohort's (when the model's run published it): the
* Kaplan-Meier curve with its Greenwood band, the classic and the fractional Weibull, and the model's survival at each
* horizon as diamonds with their bootstrap interval. The patient's: her survival by the model, a curve through her value at each
* horizon (and its interval, when her evaluation has one).
*/
export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgoCacu[], cohorte: CurvasSupervivencia | null = null, tema: Tema = 'claro', descripcion: string | null = null): PlotlyFigure | null {
const puntos = puntosDeSupervivencia(horizontes);
if (puntos.length === 0) return null;
const curva = curvaMensual(puntos), conIntervalo = puntos.every(p => p.bajo !== null), t = (clave: string) => etiqueta(cohorte, clave);
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
const data: Record<string, unknown>[] = [];
const bajos: number[] = [...curva.S, ...puntos.map(p => p.bajo ?? p.S)];
let hasta = curva.meses[curva.meses.length - 1];
if (cohorte) {
const km = cohorte.km, diamantes = cohorte.points.COMB;
hasta = Math.max(hasta, km.months[km.months.length - 1]);
bajos.push(...km.low, ...cohorte.weibull_fractional.S, ...diamantes.low);
data.push(
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km, width: 2, shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km',
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('km_crudo') + '</extra>' },
{ type: 'scatter', mode: 'lines', x: cohorte.weibull.t, y: cohorte.weibull.S, line: { color: COLORES.weibull, width: 3 }, name: t('weibull'),
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull') + '</extra>' },
{ type: 'scatter', mode: 'lines', x: cohorte.weibull_fractional.t, y: cohorte.weibull_fractional.S, line: { color: COLORES.fraccional, width: 3, dash: 'dash' }, name: t('weibull_fraccional'),
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull_fraccional') + '</extra>' },
{ type: 'scatter', mode: 'markers', name: t('puntos'), x: cohorte.horizons_months, y: diamantes.S,
marker: { symbol: 'diamond', size: 15, color: COLORES.modelo, line: { color: 'white', width: 1.5 } },
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.modelo, thickness: 2, width: 6,
array: diamantes.high.map((hi, i) => hi - diamantes.S[i]), arrayminus: diamantes.S.map((s, i) => s - diamantes.low[i]) },
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('puntos') + '</extra>' });
}
data.push(
{ type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: t('paciente'), line: { color: COLORES.paciente, width: 3 },
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('paciente') + '</extra>' },
{ type: 'scatter', mode: 'markers', name: t('paciente_puntos'), x: puntos.map(p => p.meses), y: puntos.map(p => p.S),
marker: { symbol: 'diamond', size: 14, color: COLORES.paciente, line: { color: 'white', width: 1.5 } },
...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.paciente, thickness: 2, width: 6,
array: puntos.map(p => p.alto! - p.S), arrayminus: puntos.map(p => p.S - p.bajo!) } } : {}),
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('paciente_puntos') + '</extra>' });
const minimo = Math.max(0, Math.floor((Math.min(...bajos) - 0.02) * 20) / 20);
const base = descripcion ?? t('titulo');
const titulo = cohorte ? `${base}<br>n=${cohorte.n.toLocaleString('es-MX')}, fallecidos=${cohorte.events.toLocaleString('es-MX')}` : base;
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
const layout: Record<string, unknown> = {
title: { text: titulo, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
xaxis: { ...eje, title: { text: t('eje_x') }, range: [0, hasta + 0.6], dtick: 5 },
yaxis: { ...eje, title: { text: t('eje_y') }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
};
return { data, layout, config: { responsive: true, displaylogo: false } };
}
@@ -1,128 +0,0 @@
// Covers the patient's risk in CaMa's record: the table asks the CaMa endpoint (and CaCu's calls stay as they were), says
// whose model scored her, shows the mortality at the horizons the model gives (6, 12 and 18 months) and the model's
// index date, and the CaMa card carries the panel. Fixtures: a Bundle like `GET /cama/fhir/RiskAssessment?subject=
// Patient/7` answers it (`riesgoCamaEjemplo`), and a provider that returns it.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { CamaPatientCard } from './cama/cama-patient-card';
import { CamaPatientSummary } from './cama/cama-patient.models';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { INTERVALO, prediccion } from './paciente-riesgo.testing';
import { curvaMensual, figuraSupervivenciaPaciente, puntosDeSupervivencia } from './cama/cama-supervivencia-paciente';
const CS = 'https://isssteleon.org/fhir/CodeSystem';
/** TEST ONLY. Patient 7's current CaMa `RiskAssessment`: mortality at 6, 12 and 18 months from the model's index date. */
function riesgoCamaEjemplo(): any {
const muerte = (p: number, fin: string) => {
const item = prediccion(p, '2025-06-19', fin);
item.outcome = { coding: [{ system: `${CS}/desenlace`, code: 'muerte', display: 'Muerte por cualquier causa' }] };
return item;
};
return {
resourceType: 'Bundle', type: 'searchset', total: 1,
entry: [{
fullUrl: 'http://localhost/cama/fhir/RiskAssessment/3-7',
resource: {
resourceType: 'RiskAssessment', id: '3-7', status: 'final',
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
subject: { reference: 'Patient/7' }, occurrenceDateTime: '2026-01-02T10:00:00Z',
method: { coding: [{ system: `${CS}/modelo`, code: 'cama-survival', version: '1' }] },
prediction: [muerte(0.07, '2025-12-19'), muerte(0.178, '2026-06-19'), muerte(0.251, '2026-12-19')],
},
search: { mode: 'match' },
}],
};
}
const resumen = (idField: 'pac_id' | 'id_seudonimo'): CamaPatientSummary => ({
patientId: '7', idField, idLabel: 'pac_id', cutoff: '2026-01-01', ageGroup: '50-59', status: null, priority: null,
birads: 'B5', mammographyDate: '2025-06-01', histopathology: 'CARCINOMA_INVASOR', biopsyDate: '2025-06-19',
daysMammographyToDiagnosis: null, clinicalScenario: null,
});
describe('Supervivencia individual de la paciente CaMa', () => {
// Fails if a point of the figure is not one minus the mortality of its horizon, or its interval is not turned around.
it('turns each horizon of the evaluation into survival with its interval', () => {
const puntos = puntosDeSupervivencia([
{ horizonte_anios: 0.5, probabilidad: 0.07, ic_bajo: 0.05, ic_alto: 0.1 },
{ horizonte_anios: 1.5, probabilidad: 0.25 }, { horizonte_anios: 1, probabilidad: 0.18 }]);
expect(puntos.map(p => p.meses)).toEqual([6, 12, 18]);
expect(puntos.map(p => +p.S.toFixed(2))).toEqual([0.93, 0.82, 0.75]);
expect(puntos[0].bajo).toBeCloseTo(0.9);
expect(puntos[0].alto).toBeCloseTo(0.95);
expect(puntos[1].bajo).toBeNull();
});
// Fails if the curve misses a point, rises, or stops at the last horizon.
it('draws a curve through every point that never rises and goes on to 24 months', () => {
const puntos = puntosDeSupervivencia([{ horizonte_anios: 0.5, probabilidad: 0.1 }, { horizonte_anios: 1, probabilidad: 0.2 }, { horizonte_anios: 1.5, probabilidad: 0.4 }]);
const { meses, S } = curvaMensual(puntos);
expect(S[0]).toBe(1);
expect(S[6]).toBeCloseTo(0.9); expect(S[12]).toBeCloseTo(0.8); expect(S[18]).toBeCloseTo(0.6);
expect(meses[meses.length - 1]).toBe(24);
expect(S.every((v, i) => i === 0 || v <= S[i - 1] + 1e-12)).toBe(true);
expect(S[24]).toBeLessThan(S[18]);
});
});
describe('Riesgo individual de la paciente CaMa', () => {
const obtener = vi.fn();
beforeEach(() => {
obtener.mockReset().mockImplementation(() => of(riesgoCamaEjemplo()));
TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener } }] });
});
// Fails if the table stops asking the domain it was given, or if CaCu's call changes shape (`obtener(pacId)` only).
it('asks its domain for the patient, and CaCu with the id alone', () => {
const cama = TestBed.createComponent(PacienteRiesgoTabla);
cama.componentRef.setInput('pacId', '7');
cama.componentRef.setInput('dominio', 'cama');
cama.detectChanges();
const cacu = TestBed.createComponent(PacienteRiesgoTabla);
cacu.componentRef.setInput('pacId', '7');
cacu.detectChanges();
expect(obtener).toHaveBeenNthCalledWith(1, '7', 'cama');
expect(obtener).toHaveBeenNthCalledWith(2, '7');
expect(cama.nativeElement.textContent).toContain('Riesgo individual CaMa');
expect(cacu.nativeElement.textContent).toContain('Riesgo individual CaCu');
});
// Fails if the mortality, its outcome, the model or the index date of the Bundle are not what the card shows.
it('shows the model, the index date, the outcome and the mortality at each horizon', () => {
const f = TestBed.createComponent(PacienteRiesgoTabla);
f.componentRef.setInput('pacId', '7');
f.componentRef.setInput('dominio', 'cama');
f.detectChanges();
const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
expect(f.nativeElement.querySelector('app-cama-supervivencia-paciente')).not.toBeNull();
expect(text).toContain('cama-survival');
expect(text).toContain('2025-06-19');
expect(text).toContain('Muerte por cualquier causa');
expect(text).toContain('7 %');
expect(text).toContain('17.8 %');
expect(text).toContain('25.1 %');
expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/);
expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
});
// Fails if the record asks for a risk by a row that has no `pac_id` (a legacy pseudonym), or does not ask when it has one.
it('is asked for by the patient\'s pac_id, and not by a pseudonym', () => {
const conPacId = TestBed.createComponent(CamaPatientCard);
conPacId.componentRef.setInput('summary', resumen('pac_id'));
conPacId.detectChanges();
const conSeudonimo = TestBed.createComponent(CamaPatientCard);
conSeudonimo.componentRef.setInput('summary', resumen('id_seudonimo'));
conSeudonimo.detectChanges();
expect(obtener).toHaveBeenCalledExactlyOnceWith('7', 'cama');
expect(conPacId.nativeElement.querySelector('.risk-card')).not.toBeNull();
expect(conSeudonimo.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(INTERVALO).toContain('intervalo-confianza');
});
});
@@ -1,4 +1,4 @@
<h4>Riesgo individual {{ rotulo() }}</h4> <h4>Riesgo individual CaCu</h4>
@let lectura = estado(); @let lectura = estado();
@switch (lectura.tipo) { @switch (lectura.tipo) {
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> } @case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
@@ -7,24 +7,46 @@
} }
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> } @case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
@case ('disponible') { @case ('disponible') {
@let riesgo = lectura.datos.riesgo; <p class="simulated-label" id="riesgo-simulado">Información simulada · Entorno DEV · Sin evaluación clínica</p>
@if (lectura.datos.cohorte; as cohorte) {
<h5>Cohorte</h5>
<dl class="metadata">
<div><dt>Definición de cohorte</dt><dd>{{ cohorte.url }}</dd></div>
<div><dt>Versión de cohorte</dt><dd>{{ cohorte.version }}</dd></div>
<div><dt>Fecha índice</dt><dd>{{ cohorte.fecha_indice }}</dd></div>
</dl>
<details>
<summary>Variables del modelo PIMM</summary>
<p class="availability">Códigos técnicos del modelo; no constituyen un diagnóstico.</p>
<dl class="metadata">
<div><dt>tipo_censura</dt><dd>{{ cohorte.tipo_censura ?? 'No disponible' }}</dd></div>
<div><dt>c (estado basal)</dt><dd>{{ cohorte.c ?? 'No disponible' }}</dd></div>
<div><dt>l (años desde índice)</dt><dd>{{ cohorte.l ?? 'No disponible' }}</dd></div>
<div><dt>r (años desde índice)</dt><dd>{{ cohorte.r ?? 'No disponible' }}</dd></div>
<div><dt>pap_0 (citología índice)</dt><dd>{{ cohorte.pap_0 ?? 'No disponible' }}</dd></div>
<div><dt>hpv_0 (VPH índice)</dt><dd>{{ cohorte.hpv_0 ?? 'No disponible' }}</dd></div>
</dl>
</details>
} @else {
<p role="status">Sin membresía en la cohorte vigente.</p>
}
@if (lectura.datos.riesgo; as riesgo) {
<h5>Modelo y evaluación</h5> <h5>Modelo y evaluación</h5>
<dl class="metadata"> <dl class="metadata">
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div> <div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div> <div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div> <div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div> <div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
</dl> </dl>
@if (riesgo.horizontes.length) { @if (riesgo.horizontes.length) {
<div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0"> <div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0">
<table> <table aria-describedby="riesgo-simulado">
<caption>Probabilidades por horizonte desde la fecha índice</caption> <caption>Probabilidades simuladas por horizonte desde la fecha índice</caption>
<thead><tr> <thead><tr>
<th scope="col">Horizonte (años)</th> <th scope="col">Horizonte (años)</th>
<th scope="col">Probabilidad (%)</th> <th scope="col">Probabilidad (%)</th>
<th scope="col">Intervalo de confianza (%)</th> <th scope="col">Intervalo de confianza (%)</th>
<th scope="col">Estado de evaluación</th>
</tr></thead> </tr></thead>
<tbody> <tbody>
@for (h of riesgo.horizontes; track h.horizonte_anios) { @for (h of riesgo.horizontes; track h.horizonte_anios) {
@@ -32,15 +54,14 @@
<th scope="row">{{ h.horizonte_anios }}</th> <th scope="row">{{ h.horizonte_anios }}</th>
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td> <td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td> <td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
<td>{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</td>
</tr> </tr>
} }
</tbody> </tbody>
</table> </table>
</div> </div>
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> } } @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
@if (dominio() === 'cama' && pacId(); as id) { } @else { <p role="status">Sin riesgo disponible: no hay lote vigente.</p> }
<app-cama-supervivencia-paciente [pacId]="id" [horizontes]="riesgo.horizontes" />
}
} }
} }
<p class="recommendations">Recomendaciones no disponibles.</p> <p class="recommendations">Recomendaciones no disponibles.</p>
@@ -1,13 +1,11 @@
import { Component, computed, effect, inject, input } from '@angular/core'; import { Component, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common'; import { DecimalPipe } from '@angular/common';
import { CamaSupervivenciaPaciente } from './cama/cama-supervivencia-paciente.component';
import { DominioRiesgo } from './paciente-riesgo.models';
import { PacienteRiesgoState } from './paciente-riesgo.state'; import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation'; import { tieneIntervalo } from './paciente-riesgo.validation';
@Component({ @Component({
selector: 'app-paciente-riesgo-tabla', selector: 'app-paciente-riesgo-tabla',
imports: [DecimalPipe, CamaSupervivenciaPaciente], imports: [DecimalPipe],
providers: [PacienteRiesgoState], providers: [PacienteRiesgoState],
templateUrl: './paciente-riesgo-tabla.html', templateUrl: './paciente-riesgo-tabla.html',
styleUrl: './paciente-riesgo-tabla.scss', styleUrl: './paciente-riesgo-tabla.scss',
@@ -15,13 +13,11 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
export class PacienteRiesgoTabla { export class PacienteRiesgoTabla {
/** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */ /** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */
readonly pacId = input.required<string | null>(); readonly pacId = input.required<string | null>();
/** The domain whose model scored her: CaCu unless said otherwise. */
readonly dominio = input<DominioRiesgo>('cacu');
readonly rotulo = computed(() => this.dominio() === 'cama' ? 'CaMa' : 'CaCu');
private readonly state = inject(PacienteRiesgoState); private readonly state = inject(PacienteRiesgoState);
readonly estado = this.state.estado; readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo; readonly tieneIntervalo = tieneIntervalo;
constructor() { constructor() {
effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); }); effect(() => this.state.pacId.set(this.pacId()));
} }
} }
@@ -1,44 +1,48 @@
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
export type EstadoEvaluacionCacu = 'preliminary' | 'final'; export type EstadoEvaluacionCacu = 'preliminary' | 'final';
export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo';
/** The domain whose patient's risk is read: its FHIR endpoint is `/<dominio>/fhir`. CaCu unless said otherwise. */ export interface CohorteRiesgoCacu {
export type DominioRiesgo = 'cacu' | 'cama'; url: string;
version: string;
fecha_indice: string;
tipo_censura: TipoCensuraCacu | null;
c: number | null;
l: number | null;
r: number | null;
pap_0: string | null;
hpv_0: string | null;
}
export interface HorizonteRiesgoCacu { export interface HorizonteRiesgoCacu {
/** Years from the risk's index date: the length of the prediction's `whenPeriod`; 0 is the immediate risk. */
horizonte_anios: number; horizonte_anios: number;
/** Transport values remain probabilities in [0, 1], never percentages. */ /** Transport values remain probabilities in [0, 1], never percentages. */
probabilidad: number; probabilidad: number;
ic_bajo?: number | null; ic_bajo?: number | null;
ic_alto?: number | null; ic_alto?: number | null;
estado: EstadoEvaluacionCacu;
} }
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
export interface LoteRiesgoCacu { export interface LoteRiesgoCacu {
/** The resource's id, `<lote_id>-<pac_id>`. */ lote_id: number;
id: string;
modelo_nombre: string; modelo_nombre: string;
modelo_version: string; modelo_version: string;
/** The model's index date for this patient (the predictions' `whenPeriod.start`): the horizons count from it. */
fecha_indice: string;
evaluado_en: string; evaluado_en: string;
estado_lote: EstadoEvaluacionCacu; estado_lote: EstadoEvaluacionCacu;
/** The prediction's outcome code (e.g. `cin2_mas`) and its display. */
desenlace: string;
desenlace_texto: string | null;
horizontes: HorizonteRiesgoCacu[]; horizontes: HorizonteRiesgoCacu[];
} }
/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */ /** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
export interface RiesgoPacienteCacu { export interface RiesgoPacienteCacu {
simulado: true; simulado: true;
riesgo: LoteRiesgoCacu; cohorte: CohorteRiesgoCacu | null;
riesgo: LoteRiesgoCacu | null;
} }
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */ /** `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider { export interface PacienteRiesgoProvider {
obtener(pacId: string, dominio?: DominioRiesgo): Observable<unknown>; obtener(pacId: string): Observable<unknown>;
} }
export type PacienteRiesgoEstado = export type PacienteRiesgoEstado =
@@ -1,18 +1,14 @@
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http'; import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, InjectionToken } from '@angular/core'; import { inject, InjectionToken } from '@angular/core';
import { catchError, of, throwError } from 'rxjs'; import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models'; import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// The patient's risk is a FHIR `RiskAssessment` searched by `subject=Patient/<pac_id>`, the identifier a follow-up row // The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
// carries as `pac_id`, in the domain's endpoint (`/cacu/fhir`, or `/cama/fhir`); an empty Bundle (or a 404) is a patient
// without risk data.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', { export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => { providedIn: 'root', factory: () => {
const http = inject(HttpClient); const http = inject(HttpClient);
return { return {
obtener: (pacId: string, dominio = 'cacu') => http.get<unknown>(`/${dominio}/fhir/RiskAssessment`, { obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
params: new HttpParams().set('subject', `Patient/${pacId}`),
}).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
), ),
}; };
@@ -4,7 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
import { of, Subject, throwError } from 'rxjs'; import { of, Subject, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models'; import { PacienteRiesgoProvider } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing'; import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
describe('RIESGO-CACU-02: presentación y aislamiento', () => { describe('RIESGO-CACU-02: presentación y aislamiento', () => {
@@ -22,10 +22,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.inject(HttpTestingController).verify(); TestBed.inject(HttpTestingController).verify();
}); });
it('pide el RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => { it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
const f = setup(), root: HTMLElement = f.nativeElement; const f = setup(), root: HTMLElement = f.nativeElement;
TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42') TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
.flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' }); .flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
f.detectChanges(); f.detectChanges();
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.'); expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.textContent).toContain('Recomendaciones no disponibles'); expect(root.textContent).toContain('Recomendaciones no disponibles');
@@ -33,33 +33,27 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0); expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
}); });
it('un Bundle vacío es una paciente sin riesgo confirmado', () => { it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
const f = setup({ obtener: () => of({ resourceType: 'Bundle', type: 'searchset', total: 0 }) });
expect(f.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(f.nativeElement.querySelector('table')).toBeNull();
});
it('renderiza el ejemplo contractual, metadatos y porcentajes sin alterar los datos', () => {
const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data)); const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data));
data.riesgo!.horizontes[1].estado = 'preliminary';
const baseline = structuredClone(data); const baseline = structuredClone(data);
const f = setup({ obtener }), root: HTMLElement = f.nativeElement; const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
expect(obtener).toHaveBeenCalledExactlyOnceWith('42'); expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
expect(root.querySelectorAll('thead th')).toHaveLength(3); expect(root.querySelectorAll('thead th')).toHaveLength(4);
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %'); expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
expect(root.textContent).toContain('Final (final)'); expect(root.textContent).toContain('Final (final)');
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) { expect(root.textContent).toContain('Preliminar (preliminary)');
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) {
expect(root.textContent).toContain(value); expect(root.textContent).toContain(value);
} }
// The record no longer shows the cohort's internals (its definition, version or model variables). expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado');
expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/); expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV');
// The record never says its data are test data: with real information it makes real predictions.
expect(root.textContent).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica|simuladas/);
expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/); expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/);
// The resource id (batch and patient) stays in the contract, never in a UI label. // Internal batch key stays in the contract, never in a UI label.
expect(root.textContent).not.toMatch(/lote_id|12-42/); expect(root.textContent).not.toContain('lote_id');
expect(data).toEqual(baseline); expect(data).toEqual(baseline);
}); });
@@ -73,15 +67,17 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(getComputedStyle(scroll).maxWidth).toBe('100%'); expect(getComputedStyle(scroll).maxWidth).toBe('100%');
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem'); expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky'); expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM');
expect(root.textContent).toContain('no constituyen un diagnóstico');
}); });
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => { it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
const data = riesgoCacuEjemplo(); const data = riesgoCacuEjemplo();
data.entry[0].resource.status = 'preliminary'; data.riesgo!.estado_lote = 'preliminary';
data.entry[0].resource.prediction = [ data.riesgo!.horizontes = [
prediccion(0, '2026-06-01', '2026-12-01', [0, 0]), { horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' },
prediccion(1, '2026-06-01', '2034-06-01'), { horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' },
prediccion(0.00123, '2026-06-01', '2038-09-01'), { horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' },
]; ];
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
@@ -90,9 +86,31 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(root.textContent).toContain('Preliminar (preliminary)'); expect(root.textContent).toContain('Preliminar (preliminary)');
}); });
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => { it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
const data = riesgoCacuEjemplo(); const data = riesgoCacuEjemplo();
if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag; data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null };
const f = setup({ obtener: () => of(data) });
const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent);
expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']);
expect(f.nativeElement.textContent).not.toMatch(/undefined|null/);
});
it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => {
const data = riesgoCacuEjemplo();
if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null;
if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null;
if (caso === 'horizontes') data.riesgo!.horizontes = [];
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente');
if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente');
if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados');
if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull();
expect(root.textContent).toContain('Información simulada');
expect(root.textContent).toContain('Recomendaciones no disponibles');
});
it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => {
const data = { ...riesgoCacuEjemplo(), simulado };
const f = setup({ obtener: () => of(data) }); const f = setup({ obtener: () => of(data) });
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
expect(f.nativeElement.textContent).not.toContain('modelo-cacu'); expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
@@ -100,7 +118,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
}); });
it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => { it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12; const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
const f = setup({ obtener: () => of(data) }); const f = setup({ obtener: () => of(data) });
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0); expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
@@ -116,14 +134,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
it('aísla estado y fixture entre instancias sin reutilizar información', () => { it('aísla estado y fixture entre instancias sin reutilizar información', () => {
const source = new Subject<unknown>(), f = setup({ obtener: () => source }); const source = new Subject<unknown>(), f = setup({ obtener: () => source });
const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges(); const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges();
data.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges(); data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %'); expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
f.destroy(); f.destroy();
const otra = TestBed.createComponent(PacienteRiesgoTabla); const otra = TestBed.createComponent(PacienteRiesgoTabla);
otra.componentRef.setInput('pacId', '43'); otra.detectChanges(); otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual'); expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
expect(otra.nativeElement.querySelector('table')).toBeNull(); expect(otra.nativeElement.querySelector('table')).toBeNull();
expect(riesgoCacuEjemplo().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08); expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
otra.destroy(); expect(source.observed).toBe(false); otra.destroy(); expect(source.observed).toBe(false);
}); });
@@ -1,7 +1,7 @@
import { Injectable, computed, inject, signal } from '@angular/core'; import { Injectable, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop'; import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs'; import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
import { DominioRiesgo, PacienteRiesgoEstado } from './paciente-riesgo.models'; import { PacienteRiesgoEstado } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoPacienteResponse } from './paciente-riesgo.validation'; import { riesgoPacienteResponse } from './paciente-riesgo.validation';
@@ -12,15 +12,10 @@ export class PacienteRiesgoState {
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER); private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
// `undefined` until the input is set; `null` is a patient without `pac_id`. // `undefined` until the input is set; `null` is a patient without `pac_id`.
readonly pacId = signal<string | null | undefined>(undefined); readonly pacId = signal<string | null | undefined>(undefined);
readonly dominio = signal<DominioRiesgo>('cacu'); readonly estado = toSignal(toObservable(this.pacId).pipe(
// The patient and her domain are one query, so changing both never asks for the patient in the wrong domain. switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
private readonly consulta = computed(() => ({ id: this.pacId(), dominio: this.dominio() })); map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
readonly estado = toSignal(toObservable(this.consulta).pipe( : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
switchMap(({ id, dominio }) => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => dominio === 'cacu' ? this.provider.obtener(id) : this.provider.obtener(id, dominio)).pipe(
map((respuesta): PacienteRiesgoEstado => {
const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id);
return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos };
}),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })), catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
startWith(CARGANDO), startWith(CARGANDO),
)), )),
@@ -1,51 +1,20 @@
import { RiesgoPacienteCacu } from './paciente-riesgo.models'; import { RiesgoPacienteCacu } from './paciente-riesgo.models';
const CS = 'https://isssteleon.org/fhir/CodeSystem'; /** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; export function riesgoCacuEjemplo(): RiesgoPacienteCacu {
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
return {
outcome: { coding: [{ system: `${CS}/desenlace`, code: 'cin2_mas', display: 'CIN2+ por biopsia' }] },
probabilityDecimal: p, whenPeriod: { start: inicio, end: fin },
...(ic ? { extension: [{ url: INTERVALO, valueRange: { low: { value: ic[0] }, high: { value: ic[1] } } }] } : {}),
};
}
/** TEST ONLY. The external contract example: a `searchset` Bundle with patient 42's current `RiskAssessment`, as
* `GET /cacu/fhir/RiskAssessment?subject=Patient/42` answers it; never belongs to the selected patient. */
export function riesgoCacuEjemplo(): any {
return {
resourceType: 'Bundle', type: 'searchset', total: 1,
entry: [{
fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/12-42',
resource: {
resourceType: 'RiskAssessment', id: '12-42', status: 'final',
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
subject: { reference: 'Patient/42' }, occurrenceDateTime: '2026-10-01T00:00:00Z',
method: { coding: [{ system: `${CS}/modelo`, code: 'modelo-cacu', version: '2.1.0' }] },
prediction: [
prediccion(0.08, '2026-06-01', '2027-06-01', [0.05, 0.12]),
prediccion(0.21, '2026-06-01', '2029-06-01', [0.15, 0.28]),
prediccion(0.34, '2026-06-01', '2031-06-01', [0.26, 0.44]),
],
},
search: { mode: 'match' },
}],
};
}
/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */
export function riesgoCacuVista(): RiesgoPacienteCacu {
return { return {
simulado: true, simulado: true,
cohorte: {
url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15',
tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO',
},
riesgo: { riesgo: {
id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01', lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0',
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia', evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final',
horizontes: [ horizontes: [
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 }, { horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' },
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 }, { horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' },
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }, { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' },
], ],
}, },
}; };
@@ -1,89 +1,121 @@
import { prediccion, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing'; import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation'; import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation';
import { TipoCensuraCacu } from './paciente-riesgo.models';
const recurso = (v: any) => v.entry[0].resource; describe('RIESGO-CACU-02: frontera del contrato DEV', () => {
it('conserva todos los campos del ejemplo externo y copia los objetos', () => {
describe('RIESGO-CACU-02: frontera del contrato FHIR RiskAssessment (DEV)', () => {
it('lee el Bundle searchset en la vista de la ficha y no comparte objetos con la entrada', () => {
const entrada = riesgoCacuEjemplo(); const entrada = riesgoCacuEjemplo();
const salida = riesgoPacienteResponse(entrada, '42')!; const salida = riesgoPacienteResponse(entrada);
expect(salida).toEqual(riesgoCacuVista()); expect(salida).toEqual(entrada);
salida.riesgo.horizontes[0].probabilidad = 0; salida.riesgo!.horizontes[0].probabilidad = 0;
salida.cohorte!.c = -999;
expect(entrada).toEqual(riesgoCacuEjemplo()); expect(entrada).toEqual(riesgoCacuEjemplo());
}); });
it('un Bundle vacío es una paciente sin riesgo confirmado, con o sin `entry`', () => { it('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0 })).toBeNull(); const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0, entry: [] })).toBeNull(); expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
}); });
it('el horizonte sale del whenPeriod; el inmediato es un periodo de un día', () => { it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])(
'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => {
const entrada = riesgoCacuEjemplo();
entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null;
expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo);
},
);
it('preserva los nulos independientes y el sentinel basal del contrato', () => {
const entrada = riesgoCacuEjemplo(); const entrada = riesgoCacuEjemplo();
recurso(entrada).prediction = [prediccion(0.02, '2026-06-01', '2026-06-01'), prediccion(0.4, '2026-06-01', '2034-06-01')]; entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null };
expect(riesgoPacienteResponse(entrada)!.riesgo.horizontes.map(h => h.horizonte_anios)).toEqual([0, 8]); expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
entrada.riesgo = null;
entrada.cohorte.c = null;
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
entrada.cohorte = null;
expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null });
}); });
it('ordena las predicciones por horizonte y admite campos aditivos de FHIR', () => { it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
const entrada = riesgoCacuEjemplo(); const entrada = riesgoCacuEjemplo();
recurso(entrada).prediction.reverse(); entrada.cohorte = null;
recurso(entrada).note = [{ text: 'simulado' }]; expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
expect(riesgoPacienteResponse(entrada)).toEqual(riesgoCacuVista());
}); });
it.each([[undefined], [[]], [[{ url: 'otra', valueString: 'x' }]]])('sin extensión de intervalo no fabrica límites (%j)', ext => { it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
const entrada = riesgoCacuEjemplo(); const entrada = riesgoCacuEjemplo();
const p = recurso(entrada).prediction[0]; entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({
if (ext === undefined) delete p.extension; else p.extension = ext; horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final',
const h = riesgoPacienteResponse(entrada)!.riesgo.horizontes[0]; }));
expect([h.ic_bajo, h.ic_alto]).toEqual([null, null]); expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
expect(tieneIntervalo(h)).toBe(false); });
it.each([
{}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null },
{ ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 },
])('conserva IC incompletos sin generar límites: %j', limites => {
const entrada = riesgoCacuEjemplo();
entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }];
const salida = riesgoPacienteResponse(entrada);
expect(salida).toEqual(entrada);
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false);
}); });
it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => { it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => {
const entrada = riesgoCacuEjemplo(); const entrada = riesgoCacuEjemplo();
recurso(entrada).status = 'preliminary'; entrada.riesgo!.estado_lote = 'preliminary';
recurso(entrada).prediction = [prediccion(p, '2026-06-01', '2030-06-01', [p, p])]; entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }];
const salida = riesgoPacienteResponse(entrada)!; const salida = riesgoPacienteResponse(entrada);
expect(salida.riesgo.estado_lote).toBe('preliminary'); expect(salida).toEqual(entrada);
expect(salida.riesgo.horizontes[0]).toEqual({ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p }); expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true);
expect(tieneIntervalo(salida.riesgo.horizontes[0])).toBe(true);
}); });
const invalidos: [string, (v: any) => void][] = [ const invalidos: [string, (v: any) => void][] = [
['no es Bundle', v => v.resourceType = 'RiskAssessment'], ['no simulado', v => v.simulado = false],
['Bundle no searchset', v => v.type = 'collection'], ['simulado string', v => v.simulado = 'true'],
['sin total', v => delete v.total], ['sin simulado', v => delete v.simulado],
['entry no lista', v => v.entry = {}], ['sin cohorte', v => delete v.cohorte],
['recurso ajeno', v => recurso(v).resourceType = 'Observation'], ['sin riesgo', v => delete v.riesgo],
['no simulado', v => delete recurso(v).meta], ['cohorte lista', v => v.cohorte = []],
['etiqueta ajena', v => recurso(v).meta.tag[0].code = 'real'], ['URL ajena', v => v.cohorte.url = 'otra'],
['sin id', v => delete recurso(v).id], ['versión ausente', v => delete v.cohorte.version],
['estado desconocido', v => recurso(v).status = 'amended'], ['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'],
['estado anulado', v => recurso(v).status = 'entered-in-error'], ['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'],
['otra paciente', v => recurso(v).subject.reference = 'Patient/43'], ['basal string', v => v.cohorte.c = '0'],
['sujeto no paciente', v => recurso(v).subject.reference = 'Group/42'], ['variable no finita', v => v.cohorte.l = Infinity],
['evaluación sin UTC', v => recurso(v).occurrenceDateTime = '2026-10-01T00:00:00-06:00'], ['variable omitida', v => delete v.cohorte.r],
['evaluación fecha imposible', v => recurso(v).occurrenceDateTime = '2026-02-30T00:00:00Z'], ['pap no textual', v => v.cohorte.pap_0 = 5],
['sin modelo', v => delete recurso(v).method], ['hpv no textual', v => v.cohorte.hpv_0 = false],
['modelo sin versión', v => delete recurso(v).method.coding[0].version], ['lote fraccionario', v => v.riesgo.lote_id = 1.5],
['sin predicciones', v => recurso(v).prediction = []], ['lote string', v => v.riesgo.lote_id = '12'],
['predicción nula', v => recurso(v).prediction[0] = null], ['modelo omitido', v => delete v.riesgo.modelo_nombre],
['sin desenlace', v => delete recurso(v).prediction[0].outcome], ['versión no textual', v => v.riesgo.modelo_version = 2],
['probabilidad string', v => recurso(v).prediction[0].probabilityDecimal = '0.08'], ['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'],
['probabilidad mayor a uno', v => recurso(v).prediction[0].probabilityDecimal = 1.01], ['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'],
['probabilidad negativa', v => recurso(v).prediction[0].probabilityDecimal = -0.01], ['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'],
['sin periodo', v => delete recurso(v).prediction[0].whenPeriod], ['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'],
['periodo con fecha imposible', v => recurso(v).prediction[0].whenPeriod.end = '2027-02-30'], ['sin horizontes', v => delete v.riesgo.horizontes],
['periodo invertido', v => recurso(v).prediction[0].whenPeriod.end = '2025-06-01'], ['horizontes nulos', v => v.riesgo.horizontes = null],
['dos fechas índice', v => recurso(v).prediction[1].whenPeriod.start = '2026-07-01'], ['horizonte nulo', v => v.riesgo.horizontes[0] = null],
['horizontes repetidos', v => recurso(v).prediction[1].whenPeriod.end = '2027-06-01'], ['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'],
['IC invertido', v => recurso(v).prediction[0].extension[0].valueRange = { low: { value: 0.12 }, high: { value: 0.05 } }], ['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN],
['IC fuera de probabilidad', v => recurso(v).prediction[0].extension[0].valueRange.high.value = 0.07], ['horizontes desordenados', v => v.riesgo.horizontes.reverse()],
['IC string', v => recurso(v).prediction[0].extension[0].valueRange.high.value = '0.12'], ['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1],
['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01],
['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01],
['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'],
['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null],
['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN],
['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'],
['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01],
['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01],
['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'],
['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })],
['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07],
]; ];
it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => { it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => {
const entrada = riesgoCacuEjemplo(); mutar(entrada); const entrada = riesgoCacuEjemplo(); mutar(entrada);
expect(() => riesgoPacienteResponse(entrada, '42')).toThrow('Respuesta de riesgo individual DEV inválida'); expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida');
}); });
it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => { it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => {
expect(() => riesgoPacienteResponse(entrada)).toThrow(); expect(() => riesgoPacienteResponse(entrada)).toThrow();
@@ -1,104 +1,54 @@
import { isoDate } from '../cacu-seguimiento.models'; import { isoDate } from '../cacu-seguimiento.models';
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v); const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; const nullableNumber = (v: unknown) => v === null || finite(v);
const estado = (v: unknown): v is 'preliminary' | 'final' => v === 'preliminary' || v === 'final'; const nullableText = (v: unknown) => v === null || typeof v === 'string';
const text = (v: unknown) => typeof v === 'string';
const estado = (v: unknown) => v === 'preliminary' || v === 'final';
const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1; const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
const DAYS_PER_YEAR = 365.25; const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
const SIMULATED = 'simulado';
function utcTimestamp(v: unknown): v is string { function utcTimestamp(v: unknown) {
return typeof v === 'string' return typeof v === 'string'
&& /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v) && /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v)
&& isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v)); && isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v));
} }
function invalid(): never { function cohorteValida(v: unknown) {
throw new Error('Respuesta de riesgo individual DEV inválida'); return v === null || record(v)
&& v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice'])
&& (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string))
&& nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r'])
&& nullableText(v['pap_0']) && nullableText(v['hpv_0']);
} }
/** Years between two ISO dates, to two decimals: a prediction's horizon from its `whenPeriod`. */ function horizonteValido(v: unknown) {
function years(start: string, end: string): number { if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false;
const days = (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000; for (const key of ['ic_bajo', 'ic_alto']) {
return Math.round(days / DAYS_PER_YEAR * 100) / 100; if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false;
}
function interval(prediction: Record<string, unknown>): { ic_bajo: number | null; ic_alto: number | null } {
const extensions = prediction['extension'];
if (extensions === undefined) return { ic_bajo: null, ic_alto: null };
if (!Array.isArray(extensions)) invalid();
const found = extensions.find(e => record(e) && e['url'] === INTERVAL);
if (found === undefined) return { ic_bajo: null, ic_alto: null };
const range = found['valueRange'];
const low = record(range) && record(range['low']) ? range['low']['value'] : undefined;
const high = record(range) && record(range['high']) ? range['high']['value'] : undefined;
if (!probability(low) || !probability(high) || low > high) invalid();
return { ic_bajo: low, ic_alto: high };
}
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
const period = prediction['whenPeriod'];
if (!record(period) || !isoDate(period['start']) || !isoDate(period['end'])) invalid();
const from = period['start'] as string, to = period['end'] as string;
if (start !== undefined && from !== start) invalid(); // one index date per patient
const h = years(from, to);
if (h < 0) invalid();
const ic = interval(prediction);
const p = prediction['probabilityDecimal'];
if (ic.ic_bajo !== null && ic.ic_alto !== null && !(ic.ic_bajo <= p && p <= ic.ic_alto)) invalid();
return { horizonte: { horizonte_anios: h, probabilidad: p, ...ic }, start: from };
}
function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
if (!record(v) || v['resourceType'] !== 'RiskAssessment' || !text(v['id']) || !estado(v['status'])
|| !utcTimestamp(v['occurrenceDateTime'])) invalid();
const subject = v['subject'];
if (!record(subject) || !text(subject['reference']) || !subject['reference'].startsWith('Patient/')
|| (pacId !== null && subject['reference'] !== `Patient/${pacId}`)) invalid();
const method = v['method'];
const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined;
if (!record(model) || !text(model['code']) || !text(model['version'])) invalid();
const predictions = v['prediction'];
if (!Array.isArray(predictions) || predictions.length === 0) invalid();
let start: string | undefined;
const horizontes: HorizonteRiesgoCacu[] = [];
for (const prediction of predictions) {
const found = horizon(prediction, start);
start = found.start;
horizontes.push(found.horizonte);
} }
horizontes.sort((a, b) => a.horizonte_anios - b.horizonte_anios); // Missing/null endpoints are preserved. A complete interval must contain the probability.
if (horizontes.some((h, i) => i > 0 && horizontes[i - 1].horizonte_anios === h.horizonte_anios)) invalid(); return !(probability(v['ic_bajo']) && probability(v['ic_alto']))
const outcome = record(predictions[0]) && record(predictions[0]['outcome']) && Array.isArray(predictions[0]['outcome']['coding']) || v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto'];
? predictions[0]['outcome']['coding'][0] : undefined;
if (!record(outcome) || !text(outcome['code'])) invalid();
return {
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
horizontes,
};
} }
function simulated(resource: Record<string, unknown>): boolean { function riesgoValido(v: unknown) {
const meta = resource['meta']; if (v === null) return true;
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED); if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version'])
|| !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false;
const horizontes = v['horizontes'];
return horizontes.every(horizonteValido)
&& horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']);
} }
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only). /** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */
* `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */ export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu {
export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null { if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) {
if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid(); throw new Error('Respuesta de riesgo individual DEV inválida');
const entries = v['entry'] ?? []; }
if (!Array.isArray(entries)) invalid(); return structuredClone(v) as unknown as RiesgoPacienteCacu;
if (entries.length === 0) return null;
const resource = record(entries[0]) ? entries[0]['resource'] : undefined;
if (!record(resource) || !simulated(resource)) invalid();
return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) };
} }
/** Presentation helper: an incomplete interval must never become a fabricated range. */ /** Presentation helper: an incomplete interval must never become a fabricated range. */
@@ -72,11 +72,7 @@ describe('Tabla de seguimiento con pac_id', () => {
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges(); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
}); });
// Opening a CaMa record asks for the patient's risk; in these tests nobody has one. afterEach(() => { fixture.destroy(); http.verify(); });
afterEach(() => {
http.match(r => r.url === '/cama/fhir/RiskAssessment').forEach(r => { if (!r.cancelled) r.flush({ resourceType: 'Bundle', type: 'searchset', total: 0 }); });
fixture.destroy(); http.verify();
});
const root = () => fixture.nativeElement as HTMLElement; const root = () => fixture.nativeElement as HTMLElement;
const cargar = (respuesta: Record<string, any>) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); }; const cargar = (respuesta: Record<string, any>) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); };
const enlaces = () => [...root().querySelectorAll<HTMLButtonElement>('tbody button.patient-link')]; const enlaces = () => [...root().querySelectorAll<HTMLButtonElement>('tbody button.patient-link')];
@@ -147,7 +147,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR
}), }),
}; };
} }
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true, escenario_clinico: true }; const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true };
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class SeguimientoTablaService { export class SeguimientoTablaService {
@@ -98,7 +98,7 @@
} }
@if (vista === 'norma' && normaActual(e); as m) { @if (vista === 'norma' && normaActual(e); as m) {
<h3>Norma por edad</h3> <h3>Norma por edad</h3>
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}</p> <p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
@if (figuraNorma) { @if (figuraNorma) {
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'" <app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" /> [label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
@@ -144,7 +144,7 @@
<tbody> <tbody>
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) { @for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
<tr [class.alterada]="zonaAlterada(f)"> <tr [class.alterada]="zonaAlterada(f)">
<td><strong>{{ biomarcador[f.biomarcador] ?? f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td> <td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
<td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td> <td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td> <td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
<td> <td>
@@ -7,9 +7,6 @@ import {
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2, TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
} from './tea-seguimiento.service'; } from './tea-seguimiento.service';
const BIOMARCADOR: Record<string, string> = {
picos: 'Picos paroxísticos', husos: 'Husos de sueño', ritmo_posterior: 'Ritmo posterior', gradiente: 'Gradiente anteroposterior',
};
// A zone counts as altered from |z| ≥ 2, as the alteration cards do. // A zone counts as altered from |z| ≥ 2, as the alteration cards do.
const Z_ALTERADO = 2; const Z_ALTERADO = 2;
@@ -162,7 +159,6 @@ export class TeaPacienteResumen implements OnInit {
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; } pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
// Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first. // Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first.
readonly biomarcador = BIOMARCADOR;
zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; } zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; }
filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); } filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); }
direccion(f: TeaRelacionAdos2) { direccion(f: TeaRelacionAdos2) {
@@ -1,14 +1,14 @@
import { inject, Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http'; import { HttpClient, HttpParams } from '@angular/common/http';
import { forkJoin, map, Observable, of, shareReplay } from 'rxjs'; import { forkJoin, map, Observable, of, shareReplay } from 'rxjs';
import { Bundle, code, codeIn, Concept, display, extension, isSimulated, Quantity, referenceId, Resource, resources } from './fhir'; import { Bundle, code, codeIn, Concept, display, extension, extensions, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
import { estratoValor } from './indicadores-fhir'; import { estratoValor } from './indicadores-fhir';
import { SeguimientoQuery } from './cacu-seguimiento.models'; import { SeguimientoQuery } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service'; import { validSeguimientoQuery } from './cacu-seguimiento.service';
import { import {
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad,
TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaCurvaReferencia, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaRelacionAdos2,
TeaSeguimientoService, TeaRelacionModelo, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
} from './tea-seguimiento.service'; } from './tea-seguimiento.service';
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an // TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
@@ -26,6 +26,7 @@ interface Report extends Resource {
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[]; effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
} }
interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] } interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] }
interface Prediction { outcome?: Concept; probabilityDecimal?: number; extension?: Resource['extension'] }
const MAX_COUNT = 200; const MAX_COUNT = 200;
const METRICAS = 'tea-eeg-metrica'; const METRICAS = 'tea-eeg-metrica';
@@ -111,6 +112,18 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
}; };
} }
// The age norm a metric observation carries: one sub-extension per point, read back in order, because a FHIR
// extension holds scalars, not arrays.
function curvaDe(o: Observation): TeaCurvaReferencia | null {
const curva = extension(o, 'curva-referencia');
if (!curva) return null;
const serie = (nombre: string) => extensions(curva, nombre).map(e => e.valueDecimal).filter((v): v is number => typeof v === 'number');
return {
fuente: extension(curva, 'fuente')?.valueString ?? '', estado: extension(curva, 'estado')?.valueString ?? '',
edad_meses: serie('edad-meses'), p5: serie('p5'), p25: serie('p25'), mediana: serie('mediana'), p75: serie('p75'), p95: serie('p95'),
};
}
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't // A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
// cover the child's age (or none is in production yet). // cover the child's age (or none is in production yet).
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion { function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
@@ -123,6 +136,7 @@ function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value; const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value;
const referencia = typeof low === 'number' && typeof high === 'number' const referencia = typeof low === 'number' && typeof high === 'number'
? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null; ? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null;
const curva = evaluable ? curvaDe(o) : null;
return { return {
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo, codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '', unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
@@ -130,6 +144,7 @@ function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado, valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia', sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean), efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
...(curva ? { curva_referencia: curva } : {}),
}; };
} }
@@ -152,6 +167,7 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
const listed = observations.filter(o => ids.has(o.id)); const listed = observations.filter(o => ids.has(o.id));
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad; const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
const duracion = extension(report, 'duracion-min')?.valueDecimal; const duracion = extension(report, 'duracion-min')?.valueDecimal;
const edad = extension(report, 'edad-meses')?.valueDecimal;
// The report lists each metric's electrode map under the same code too; it feeds the maps, not the cards. // The report lists each metric's electrode map under the same code too; it feeds the maps, not the cards.
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS) && !o.id?.startsWith('electrodos-')).map(o => alteracion(o, metricas)); const alteraciones = listed.filter(o => codeIn(o.code, METRICAS) && !o.id?.startsWith('electrodos-')).map(o => alteracion(o, metricas));
// A metric's electrode values are `electrodos-<the metric observation's id>`. // A metric's electrode values are `electrodos-<the metric observation's id>`.
@@ -166,6 +182,7 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
fecha: report.effectiveDateTime.slice(0, 10), fecha: report.effectiveDateTime.slice(0, 10),
duracion_min: duracion === undefined ? null : Math.round(duracion), duracion_min: duracion === undefined ? null : Math.round(duracion),
canales: extension(report, 'canales')?.valueInteger ?? null, canales: extension(report, 'canales')?.valueInteger ?? null,
...(typeof edad === 'number' ? { edad_meses: edad } : {}),
calidad: calidad(report.conclusionCode?.[0]), calidad: calidad(report.conclusionCode?.[0]),
criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio), criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
alteraciones, mapas, alteraciones, mapas,
@@ -173,6 +190,34 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
}; };
} }
// The ADOS-2 association model: one `RiskAssessment`, a prediction per association row with the patient's z and
// probabilities. A row missing a number the panel needs is left out; without rows there is no panel.
export function relacionDeRiesgo(riesgo: Resource | undefined): TeaRelacionModelo | null {
if (!riesgo) return null;
const nivel = extension(riesgo, 'modelo-nivel')?.valueString;
const filas = ((riesgo['prediction'] ?? []) as Prediction[]).map((p): TeaRelacionAdos2 | null => {
const numero = (nombre: string) => extension(p, nombre)?.valueDecimal;
const biomarcador = extension(p, 'biomarcador')?.valueCoding, zona = extension(p, 'zona')?.valueCoding;
const tipo = extension(p, 'tipo')?.valueString, evento = extension(p, 'evento')?.valueString;
const valores = [numero('valor-z'), numero('odds-ratio'), numero('ic-inf'), numero('ic-sup'), numero('q'), p.probabilityDecimal,
numero('probabilidad-referencia')];
if (!biomarcador?.code || !zona?.code || (tipo !== 'item' && tipo !== 'dominio') || !evento || !code(p.outcome)
|| !valores.every(v => typeof v === 'number')) return null;
const [valor_z, or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia] = valores as number[];
return {
biomarcador: biomarcador.display ?? biomarcador.code, zona: zona.code, zona_etiqueta: zona.display ?? zona.code, valor_z,
tipo, resultado: code(p.outcome)!, resultado_etiqueta: display(p.outcome) ?? code(p.outcome)!, evento,
or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia, observado: extension(p, 'observado')?.valueInteger ?? null,
};
}).filter((f): f is TeaRelacionAdos2 => f !== null);
if ((nivel !== 'item' && nivel !== 'dominio') || !filas.length) return null;
return {
validado: extension(riesgo, 'modelo-validado')?.valueBoolean === true, nivel,
n_cohorte: extension(riesgo, 'modelo-n-cohorte')?.valueInteger ?? 0,
version: extension(riesgo, 'modelo-version')?.valueString ?? '', filas,
};
}
function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null { function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null {
if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null; if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null;
return alteracionesDe(report, observations).length ? 'anormal' : 'normal'; return alteracionesDe(report, observations).length ? 'anormal' : 'normal';
@@ -288,12 +333,14 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
const all = resources(bundle); const all = resources(bundle);
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[]; const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
const episode = resources(bundle, 'EpisodeOfCare')[0]; const episode = resources(bundle, 'EpisodeOfCare')[0];
const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]);
return teaPacienteDetalle({ return teaPacienteDetalle({
simulado: all.length > 0 && all.every(isSimulated), simulado: all.length > 0 && all.every(isSimulated),
id_seudonimo: id, id_seudonimo: id,
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code), grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
ados2: ados2DeObservacion(byCode(observations, 'ados2')), ados2: ados2DeObservacion(byCode(observations, 'ados2')),
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas), eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
...(relacion ? { relacion_ados2: relacion } : {}),
}, id); }, id);
})); }));
} }
-16
View File
@@ -10,8 +10,6 @@ import {
ModelVersion, ModelVersion,
PromotionCheck, PromotionCheck,
ReportField, ReportField,
TrainableScenario,
TrainingJob,
OcrJob, OcrJob,
OcrRowStatus, OcrRowStatus,
OcrRowsResponse, OcrRowsResponse,
@@ -41,20 +39,6 @@ export class GovernanceApi {
return this.http.post<{ output: string }>(`/governance/model-versions/${domain}/${scenario}/train`, {}); return this.http.post<{ output: string }>(`/governance/model-versions/${domain}/${scenario}/train`, {});
} }
/** The scenarios that can be trained from here. */
trainableScenarios(): Observable<{ scenarios: TrainableScenario[] }> {
return this.http.get<{ scenarios: TrainableScenario[] }>('/governance/scenarios');
}
/** Starts the training in the background: 202 with the job, 409 with the running one, 503 with no dbt manifest. */
startTrainingJob(domain: string, scenario: string): Observable<{ job: TrainingJob }> {
return this.http.post<{ job: TrainingJob }>(`/governance/model-versions/${domain}/${scenario}/train-jobs`, {});
}
trainingJobs(): Observable<{ jobs: TrainingJob[] }> {
return this.http.get<{ jobs: TrainingJob[] }>('/governance/training-jobs');
}
retireModelVersion(domain: string, scenario: string, version: string): Observable<ModelVersion> { retireModelVersion(domain: string, scenario: string, version: string): Observable<ModelVersion> {
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {}); return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {});
} }
@@ -136,28 +136,3 @@ export interface OcrRunSummary {
failed: number; failed: number;
needs_review: number; needs_review: number;
} }
/** A scenario governance can train (`GET /governance/scenarios`); `produccion` is its version in production, if any. */
export interface TrainableScenario {
domain: string;
scenario: string;
cohort: string | null;
outcome: string | null;
description: string;
kind: 'cohorte' | 'referencia';
produccion: string | null;
}
export type TrainingJobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido';
/** A training in the background (`/governance/training-jobs`), with the tail of its outputs. */
export interface TrainingJob {
id: string;
domain: string;
scenario: string;
iniciado: string;
estado: TrainingJobState;
codigo: number | null;
salida: string;
error: string;
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { Observable } from 'rxjs';
import { PendingRiskBatch } from './risk-batches.types'; import { PendingRiskBatch } from './risk-batches.types';
/** `/<domain>/riesgos/lotes`: risk batches a model produced and nobody has reviewed yet (ADR-MD-008). Only `cacu` /** `/<domain>/riesgos/lotes`: risk batches a model produced and nobody has reviewed yet (ADR-MD-008). Only `cacu`
* and `cama` are served. */ * is served today. */
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class RiskBatchesApi { export class RiskBatchesApi {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
@@ -6,51 +6,22 @@
} }
</mat-button-toggle-group> </mat-button-toggle-group>
<span class="models__spacer"></span> <span class="models__spacer"></span>
@if (offered().length) { <button mat-stroked-button type="button" [disabled]="training()" (click)="train()"
<mat-form-field class="models__scenario" subscriptSizing="dynamic"> matTooltip="Entrena el modelo cacu/cin2_logistic con la cohorte de vigilancia vigente y lo pone en producción">
<mat-label>Modelo a entrenar</mat-label> <mat-icon aria-hidden="true">model_training</mat-icon>Entrenar cacu/cin2_logistic
<mat-select [value]="selected() ?? (offered().length === 1 ? keyOf(offered()[0]) : null)" (selectionChange)="selected.set($event.value)"> </button>
@for (s of offered(); track keyOf(s)) {
<mat-option [value]="keyOf(s)">{{ keyOf(s) }}{{ s.produccion ? ' · en producción v' + s.produccion : '' }}</mat-option>
}
</mat-select>
</mat-form-field>
<button mat-stroked-button type="button" [disabled]="starting() || !(selected() || offered().length === 1)" (click)="train()"
matTooltip="Exporta la cohorte vigente de dbt, entrena una versión y la promueve si ya tiene sus informes">
<mat-icon aria-hidden="true">model_training</mat-icon>Entrenar
</button>
}
<button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar"> <button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar">
<mat-icon aria-hidden="true">refresh</mat-icon> <mat-icon aria-hidden="true">refresh</mat-icon>
</button> </button>
</div> </div>
@if (loading() || starting() || running()) { @if (loading() || training()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar> <mat-progress-bar mode="indeterminate"></mat-progress-bar>
} }
@if (loadError(); as error) { @if (loadError(); as error) {
<p class="models__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p> <p class="models__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
} }
@if (jobs().length) {
<section class="models__jobs" aria-label="Entrenamientos recientes">
<h3>Entrenamientos recientes</h3>
<ul>
@for (job of jobs(); track job.id) {
<li [class.models__job--failed]="job.estado === 'fallido' || job.estado === 'interrumpido'">
<strong>{{ job.domain }}/{{ job.scenario }}</strong> · {{ job.iniciado | date: 'short' }} · {{ estados[job.estado] }}
@if (job.salida || job.error) {
<details>
<summary>Salida</summary>
<pre>{{ job.error || job.salida }}</pre>
</details>
}
</li>
}
</ul>
</section>
}
<table mat-table [dataSource]="versions()" class="models__table"> <table mat-table [dataSource]="versions()" class="models__table">
<ng-container matColumnDef="version"> <ng-container matColumnDef="version">
<th mat-header-cell *matHeaderCellDef>Versión</th> <th mat-header-cell *matHeaderCellDef>Versión</th>
@@ -70,29 +70,3 @@
gap: var(--space-2); gap: var(--space-2);
margin: 0; margin: 0;
} }
.models__scenario {
min-width: 18rem;
}
.models__jobs ul {
list-style: none;
margin: 0;
padding: 0;
}
.models__jobs li {
padding: var(--space-1) 0;
}
.models__job--failed {
color: var(--mat-sys-error);
}
.models__jobs pre {
font-size: 0.8rem;
margin: var(--space-1) 0;
max-height: 12rem;
overflow: auto;
white-space: pre-wrap;
}
@@ -1,83 +0,0 @@
// Covers the model versions panel's training: the scenarios the account can train are offered, a training starts in the
// background and its state is shown while it runs, and the versions are read again when it ends. Fixtures: a stub of
// `GovernanceApi` with the scenarios, the versions and the jobs the test sets, and an account that reaches every domain.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { vi } from 'vitest';
import { AuthService } from '../../../auth/auth.service';
import { GovernanceApi } from '../../api/governance.api';
import { TrainingJob } from '../../api/governance.types';
import { ModelVersionsPanel } from './model-versions-panel';
const SCENARIOS = [
{ domain: 'cacu', scenario: 'cin2_logistic', cohort: 'cacu/x', outcome: 'cin2', description: '', kind: 'cohorte', produccion: null },
{ domain: 'cama', scenario: 'survival', cohort: 'cama/cohorte_total', outcome: 'muerte', description: '', kind: 'cohorte', produccion: '2' },
];
const job = (estado: TrainingJob['estado']): TrainingJob => ({
id: 'j1', domain: 'cama', scenario: 'survival', iniciado: '2026-01-01T00:00:00+00:00', estado, codigo: null, salida: 'trained: version 3', error: '',
});
describe('ModelVersionsPanel training', () => {
let api: Record<string, ReturnType<typeof vi.fn>>;
let jobs: TrainingJob[];
beforeEach(() => {
jobs = [];
api = {
listModelVersions: vi.fn(() => of({ model_versions: [] })),
trainableScenarios: vi.fn(() => of({ scenarios: SCENARIOS })),
trainingJobs: vi.fn(() => of({ jobs })),
startTrainingJob: vi.fn(() => of({ job: job('en_curso') })),
};
TestBed.configureTestingModule({
providers: [
{ provide: GovernanceApi, useValue: api },
{ provide: AuthService, useValue: { puedeVer: () => true, dominios: () => ['cacu', 'cama', 'tea'], esAdministrador: () => true, usuario: () => ({ dominios: ['cacu', 'cama', 'tea'] }) } },
],
});
});
// Fails if the panel goes back to offering one hardcoded scenario, or hides a scenario the account can train.
it('offers every trainable scenario of the domains shown', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
f.detectChanges();
const panel = f.componentInstance;
panel.domain.set(null);
expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cacu/cin2_logistic', 'cama/survival']);
panel.domain.set('cama');
expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cama/survival']);
});
// Fails if the button trains another scenario than the selected one, or waits for the training to end.
it('starts the selected scenario in the background and reads the jobs again', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
f.detectChanges();
const panel = f.componentInstance;
panel.domain.set(null);
panel.selected.set('cama/survival');
panel.train();
expect(api['startTrainingJob']).toHaveBeenCalledExactlyOnceWith('cama', 'survival');
expect(api['trainingJobs']).toHaveBeenCalledTimes(2);
});
// Fails if the running state is lost or the versions are not read again when the running training ends.
it('knows a training is running and reads the versions when it ends', () => {
const f = TestBed.createComponent(ModelVersionsPanel);
jobs = [job('en_curso')];
f.detectChanges();
const panel = f.componentInstance;
expect(panel.running()).toBe(true);
const reads = api['listModelVersions'].mock.calls.length;
jobs = [job('completado')];
panel.refreshJobs();
expect(panel.running()).toBe(false);
expect(api['listModelVersions'].mock.calls.length).toBe(reads + 1);
f.detectChanges();
expect((f.nativeElement as HTMLElement).textContent).toContain('Entrenado y promovido');
});
});
@@ -1,14 +1,11 @@
import { DatePipe } from '@angular/common'; import { DatePipe } from '@angular/common';
import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core'; import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
import { timer } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips'; import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table'; import { MatTableModule } from '@angular/material/table';
@@ -18,27 +15,18 @@ import { AuthService } from '../../../auth/auth.service';
import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios'; import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios';
import { apiErrorMessage } from '../../../connect/api/api.types'; import { apiErrorMessage } from '../../../connect/api/api.types';
import { GovernanceApi } from '../../api/governance.api'; import { GovernanceApi } from '../../api/governance.api';
import { ModelVersion, TrainableScenario, TrainingJob } from '../../api/governance.types'; import { ModelVersion } from '../../api/governance.types';
import { ModelStatusChip } from '../model-status-chip/model-status-chip'; import { ModelStatusChip } from '../model-status-chip/model-status-chip';
import { ModelVersionDialog } from '../model-version-dialog/model-version-dialog'; import { ModelVersionDialog } from '../model-version-dialog/model-version-dialog';
/** Milliseconds between asking for the state of a training that is still running. */ /** The only scenario with a trainer today (ML-cin2_logistic, CaCu): `entrenar`'s own domain and scenario. */
export const SONDEO_MS = 3000; const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
export const ESTADOS: Record<TrainingJob['estado'], string> = {
en_curso: 'En curso',
completado: 'Entrenado y promovido',
entrenado_sin_promover: 'Entrenado; faltan sus informes para promoverlo',
fallido: 'Falló',
interrumpido: 'Interrumpido',
};
/** /**
* Every registered model version with its status (desarrollo, candidata, * Every registered model version with its status (desarrollo, candidata,
* en producción, retirada). The detail dialog holds the promotion * en producción, retirada). The detail dialog holds the promotion
* checklist, lineage, artifacts and reports. The toolbar trains any scenario * checklist, lineage, artifacts and reports. The toolbar also offers
* that has a trainer, in the background, and lists the latest trainings with * training the one scenario with a trainer, over HTTP instead of a shell.
* their state while they run.
*/ */
@Component({ @Component({
selector: 'app-model-versions-panel', selector: 'app-model-versions-panel',
@@ -49,8 +37,6 @@ export const ESTADOS: Record<TrainingJob['estado'], string> = {
MatChipsModule, MatChipsModule,
MatIconModule, MatIconModule,
MatProgressBarModule, MatProgressBarModule,
MatSelectModule,
MatFormFieldModule,
MatSnackBarModule, MatSnackBarModule,
MatTableModule, MatTableModule,
MatTooltipModule, MatTooltipModule,
@@ -75,28 +61,12 @@ export class ModelVersionsPanel implements OnInit {
readonly versions = signal<ModelVersion[]>([]); readonly versions = signal<ModelVersion[]>([]);
readonly loading = signal(false); readonly loading = signal(false);
readonly loadError = signal<string | null>(null); readonly loadError = signal<string | null>(null);
readonly scenarios = signal<TrainableScenario[]>([]); readonly training = signal(false);
readonly selected = signal<string | null>(null);
readonly jobs = signal<TrainingJob[]>([]);
readonly starting = signal(false);
readonly estados = ESTADOS;
/** The scenarios of the domain being shown, and only of the account's domains. */
readonly offered = computed(() =>
this.scenarios().filter((s) => this.auth.puedeVer(s.domain) && (this.domain() === null || s.domain === this.domain())));
readonly running = computed(() => this.jobs().some((j) => j.estado === 'en_curso'));
readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones']; readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones'];
ngOnInit(): void { ngOnInit(): void {
this.reload(); this.reload();
this.api.trainableScenarios().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: ({ scenarios }) => this.scenarios.set(scenarios),
error: () => this.scenarios.set([]),
});
this.refreshJobs();
timer(SONDEO_MS, SONDEO_MS).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
if (this.running()) this.refreshJobs();
});
} }
setDomain(domain: string | null): void { setDomain(domain: string | null): void {
@@ -138,41 +108,22 @@ export class ModelVersionsPanel implements OnInit {
return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value })); return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value }));
} }
/** Asks for the latest trainings; when one that was running has ended, the versions are read again. */
refreshJobs(): void {
const before = this.running();
this.api.trainingJobs().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: ({ jobs }) => {
this.jobs.set(jobs.slice(0, 8));
if (before && !this.running()) this.reload();
},
error: () => undefined,
});
}
train(): void { train(): void {
const key = this.selected() ?? (this.offered().length === 1 ? this.keyOf(this.offered()[0]) : null); this.training.set(true);
const scenario = this.offered().find((s) => this.keyOf(s) === key);
if (!scenario) return;
this.starting.set(true);
this.api this.api
.startTrainingJob(scenario.domain, scenario.scenario) .trainModelVersion(TRAINABLE.domain, TRAINABLE.scenario)
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({ .subscribe({
next: () => { next: () => {
this.starting.set(false); this.training.set(false);
this.snackBar.open(`Entrenamiento de ${key} iniciado.`, 'OK', { duration: 3000 }); this.snackBar.open(`El modelo ${TRAINABLE.domain}/${TRAINABLE.scenario} se entrenó correctamente.`, 'OK', { duration: 3000 });
this.refreshJobs(); this.reload();
}, },
error: (error) => { error: (error) => {
this.starting.set(false); this.training.set(false);
this.snackBar.open(apiErrorMessage(error, 'No se pudo iniciar el entrenamiento.'), 'OK', { duration: 5000 }); this.snackBar.open(apiErrorMessage(error, 'No se pudo entrenar el modelo.'), 'OK', { duration: 5000 });
if (error?.status === 409) this.refreshJobs(); if (error?.status === 409) this.reload();
}, },
}); });
} }
keyOf(s: { domain: string; scenario: string }): string {
return `${s.domain}/${s.scenario}`;
}
} }
@@ -1,10 +1,5 @@
<div class="batches"> <div class="batches">
<div class="batches__toolbar"> <div class="batches__toolbar">
<mat-button-toggle-group hideSingleSelectionIndicator [value]="domain()" (change)="setDomain($event.value)" aria-label="Dominio">
@for (option of domains; track option.id) {
<mat-button-toggle [value]="option.id">{{ option.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
<span class="batches__spacer"></span> <span class="batches__spacer"></span>
<button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar"> <button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar">
<mat-icon aria-hidden="true">refresh</mat-icon> <mat-icon aria-hidden="true">refresh</mat-icon>
@@ -1,48 +0,0 @@
// Covers the risk batches panel's domain choice: it lists the pending batches of the domain shown (CaCu first, CaMa on
// request) and decides a batch in that domain. Fixtures: a stub of `RiskBatchesApi` that records the domain of each call,
// and an account that reaches every domain.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { vi } from 'vitest';
import { AuthService } from '../../../auth/auth.service';
import { RiskBatchesApi } from '../../api/risk-batches.api';
import { RiskBatchesPanel } from './risk-batches-panel';
describe('RiskBatchesPanel domains', () => {
let api: Record<string, ReturnType<typeof vi.fn>>;
beforeEach(() => {
api = {
listPending: vi.fn(() => of([{ lote_id: 5, modelo: 'cama-survival v1', evaluado_en: '2026-01-01T00:00:00Z', n_evaluaciones: 1500, motivo: null }])),
confirm: vi.fn(() => of({ lote_id: 5, evaluaciones_cambiadas: 1500 })),
void: vi.fn(() => of({ lote_id: 5, evaluaciones_cambiadas: 1500 })),
};
TestBed.configureTestingModule({
providers: [{ provide: RiskBatchesApi, useValue: api }, { provide: AuthService, useValue: { puedeVer: () => true } }],
});
});
// Fails if the panel stops asking CaCu first, or never asks CaMa's batches when it is chosen.
it('lists CaCu first and the chosen domain after', () => {
const f = TestBed.createComponent(RiskBatchesPanel);
f.detectChanges();
expect(api['listPending']).toHaveBeenLastCalledWith('cacu');
f.componentInstance.setDomain('cama');
expect(api['listPending']).toHaveBeenLastCalledWith('cama');
});
// Fails if a decision goes to the wrong domain's batches, which would confirm another model's evaluations.
it('confirms a batch in the domain being shown', () => {
const f = TestBed.createComponent(RiskBatchesPanel);
f.detectChanges();
f.componentInstance.setDomain('cama');
const batch = f.componentInstance.batches()[0];
f.componentInstance.reasonFor(batch).setValue('revisado');
f.componentInstance.confirm(batch);
expect(api['confirm']).toHaveBeenCalledExactlyOnceWith('cama', 5, 'revisado');
});
});
@@ -3,7 +3,6 @@ import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
@@ -11,27 +10,21 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table'; import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { AuthService } from '../../../auth/auth.service';
import { apiErrorMessage } from '../../../connect/api/api.types'; import { apiErrorMessage } from '../../../connect/api/api.types';
import { RiskBatchesApi } from '../../api/risk-batches.api'; import { RiskBatchesApi } from '../../api/risk-batches.api';
import { PendingRiskBatch } from '../../api/risk-batches.types'; import { PendingRiskBatch } from '../../api/risk-batches.types';
/** The domains with a model that estimates risks: each has its own batches under `/<domain>/riesgos/lotes`. */ const DOMAIN = 'cacu';
export const RISK_DOMAINS = [
{ id: 'cacu', label: 'Cáncer cervicouterino' },
{ id: 'cama', label: 'Cáncer de mama' },
];
/** /**
* Risk batches a model produced that nobody has confirmed or voided yet (ADR-MD-008): invisible to patient * Risk batches a model produced that nobody has confirmed or voided yet (ADR-MD-008): invisible to patient
* records until someone decides, with a reason. CaCu and CaMa have a model estimating risks. * records until someone decides, with a reason. Only CaCu has a model estimating risks today.
*/ */
@Component({ @Component({
selector: 'app-risk-batches-panel', selector: 'app-risk-batches-panel',
imports: [ imports: [
DatePipe, DatePipe,
MatButtonModule, MatButtonModule,
MatButtonToggleModule,
MatFormFieldModule, MatFormFieldModule,
MatIconModule, MatIconModule,
MatInputModule, MatInputModule,
@@ -46,13 +39,9 @@ export const RISK_DOMAINS = [
}) })
export class RiskBatchesPanel implements OnInit { export class RiskBatchesPanel implements OnInit {
private readonly api = inject(RiskBatchesApi); private readonly api = inject(RiskBatchesApi);
private readonly auth = inject(AuthService);
private readonly snackBar = inject(MatSnackBar); private readonly snackBar = inject(MatSnackBar);
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
/** Only the account's domains. */
readonly domains = RISK_DOMAINS.filter((d) => this.auth.puedeVer(d.id));
readonly domain = signal<string>(this.domains[0]?.id ?? RISK_DOMAINS[0].id);
readonly batches = signal<PendingRiskBatch[]>([]); readonly batches = signal<PendingRiskBatch[]>([]);
readonly loading = signal(false); readonly loading = signal(false);
readonly loadError = signal<string | null>(null); readonly loadError = signal<string | null>(null);
@@ -65,16 +54,11 @@ export class RiskBatchesPanel implements OnInit {
this.reload(); this.reload();
} }
setDomain(domain: string): void {
this.domain.set(domain);
this.reload();
}
reload(): void { reload(): void {
this.loading.set(true); this.loading.set(true);
this.loadError.set(null); this.loadError.set(null);
this.api this.api
.listPending(this.domain()) .listPending(DOMAIN)
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({ .subscribe({
next: (batches) => { next: (batches) => {
@@ -98,11 +82,11 @@ export class RiskBatchesPanel implements OnInit {
} }
confirm(batch: PendingRiskBatch): void { confirm(batch: PendingRiskBatch): void {
this.decide(batch, (reason) => this.api.confirm(this.domain(), batch.lote_id, reason), 'confirmado'); this.decide(batch, (reason) => this.api.confirm(DOMAIN, batch.lote_id, reason), 'confirmado');
} }
void(batch: PendingRiskBatch): void { void(batch: PendingRiskBatch): void {
this.decide(batch, (reason) => this.api.void(this.domain(), batch.lote_id, reason), 'anulado'); this.decide(batch, (reason) => this.api.void(DOMAIN, batch.lote_id, reason), 'anulado');
} }
private decide( private decide(