Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ee87bcb8d0 | |||
| aaeea7a7b0 | |||
| 7f17681409 | |||
| d72c18756f | |||
| fefa28ae7a | |||
| a217ddae38 | |||
| 97fcb37761 |
@@ -62,17 +62,6 @@
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
},
|
||||
"simulado": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true,
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/app/app.config.ts",
|
||||
"with": "src/app/app.config.simulado.ts"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "production"
|
||||
@@ -88,10 +77,6 @@
|
||||
},
|
||||
"development": {
|
||||
"buildTarget": "WebApp:build:development"
|
||||
},
|
||||
"simulado": {
|
||||
"buildTarget": "WebApp:build:simulado",
|
||||
"proxyConfig": "simulado/proxy.simulado.json"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -37,7 +37,8 @@ describe('Encabezado del marco', () => {
|
||||
|
||||
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
|
||||
// Fails if the selector would point at a route the application does not have.
|
||||
const paths = routes.map(r => r.path);
|
||||
// The application's routes live under the guarded parent ('login' is its sibling).
|
||||
const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.path)]);
|
||||
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
|
||||
});
|
||||
it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
|
||||
|
||||
@@ -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 },
|
||||
]
|
||||
};
|
||||
@@ -12,6 +12,8 @@ export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
// La sesión es del navegador (`auth/auth.service.ts`): no hay interceptor
|
||||
// porque la WebApi no responde 401.
|
||||
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`).
|
||||
|
||||
+42
-23
@@ -1,33 +1,52 @@
|
||||
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
|
||||
<header class="site-header">
|
||||
<div class="site-header__content">
|
||||
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
</a>
|
||||
@if (activeDomain(); as domain) {
|
||||
<span class="platform-title">{{ title }}</span>
|
||||
@defer (on immediate) {
|
||||
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
|
||||
} @placeholder {
|
||||
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
|
||||
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
|
||||
}
|
||||
} @else {
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
@if (!sinCromo()) {
|
||||
<header class="site-header">
|
||||
<div class="site-header__content">
|
||||
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
</a>
|
||||
@if (activeDomain(); as domain) {
|
||||
<span class="platform-title">{{ title }}</span>
|
||||
@if (otherDomains().length) {
|
||||
@defer (on immediate) {
|
||||
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
|
||||
} @placeholder {
|
||||
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
|
||||
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
|
||||
}
|
||||
} @else {
|
||||
<!-- An account with a single domain has nothing to switch to: the domain is a label. -->
|
||||
<span class="domain-selector domain-selector--espera">{{ domainLabels[domain] }}</span>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
} @else {
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
@if (usuario(); as sesion) {
|
||||
<button
|
||||
class="site-header__salir"
|
||||
type="button"
|
||||
(click)="salir()"
|
||||
[attr.title]="'Cerrar sesión de ' + sesion.nombre"
|
||||
[attr.aria-label]="'Cerrar sesión de ' + sesion.nombre"
|
||||
>
|
||||
<mat-icon aria-hidden="true">logout</mat-icon>
|
||||
<span class="site-header__salir-nombre">{{ sesion.nombre }}</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
}
|
||||
|
||||
<main class="app-main">
|
||||
<router-outlet />
|
||||
</main>
|
||||
|
||||
@if (!workspace()) {
|
||||
@if (!workspace() && !sinCromo()) {
|
||||
<footer class="site-footer">
|
||||
<div class="site-footer__content">
|
||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
|
||||
+57
-37
@@ -1,49 +1,69 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { Home } from './home';
|
||||
import { authGuard } from './auth/auth.guard';
|
||||
import { dominioGuard } from './auth/dominio.guard';
|
||||
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
|
||||
|
||||
export const routes: Routes = [
|
||||
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||
{
|
||||
path: 'indicadores/tea-estatus',
|
||||
title: 'Casos por estatus | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
||||
data: { workspace: true, breadcrumb: 'Casos por estatus' },
|
||||
path: 'login',
|
||||
title: 'Inicio de sesión | ISSSTELEON',
|
||||
loadComponent: () => import('./auth/login-page').then((m) => m.LoginPage),
|
||||
// Sin encabezado ni pie: la pantalla ocupa la ventana completa.
|
||||
data: { sinCromo: true },
|
||||
},
|
||||
{
|
||||
path: 'conectar',
|
||||
title: 'Conectar datos | ISSSTELEON',
|
||||
// Lazy: the workspace (and the ~15 Material modules it uses) only
|
||||
// downloads when someone actually opens it.
|
||||
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
|
||||
data: { workspace: true, breadcrumb: 'Conectar datos' },
|
||||
// Todo lo demás vive detrás de la sesión; el guard corre en cada ruta hija.
|
||||
path: '',
|
||||
canActivateChild: [authGuard],
|
||||
children: [
|
||||
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||
{
|
||||
path: 'indicadores/tea-estatus',
|
||||
title: 'Casos por estatus | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
||||
canActivate: [dominioGuard],
|
||||
data: { workspace: true, breadcrumb: 'Casos por estatus', dominio: 'tea' },
|
||||
},
|
||||
{
|
||||
path: 'conectar',
|
||||
title: 'Conectar datos | ISSSTELEON',
|
||||
// Lazy: the workspace (and the ~15 Material modules it uses) only
|
||||
// downloads when someone actually opens it.
|
||||
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
|
||||
data: { workspace: true, breadcrumb: 'Conectar datos' },
|
||||
},
|
||||
{
|
||||
path: 'gobernanza',
|
||||
title: 'Gobernanza de modelos | ISSSTELEON',
|
||||
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
|
||||
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
|
||||
},
|
||||
{
|
||||
path: 'bitacora',
|
||||
title: 'Bitácora de cargas | ISSSTELEON',
|
||||
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
|
||||
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
|
||||
},
|
||||
{
|
||||
path: 'kpis',
|
||||
title: 'Indicadores | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
|
||||
// The page reads CaCu's measures: an account of another domain goes to its own.
|
||||
canActivate: [dominioGuard],
|
||||
data: { workspace: true, breadcrumb: 'Indicadores', dominio: 'cacu' },
|
||||
},
|
||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
...DOMINIOS.map(dominio => ({
|
||||
path: `indicadores/${dominio}`,
|
||||
title: 'Indicadores | ISSSTELEON',
|
||||
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
|
||||
canActivate: [dominioGuard],
|
||||
loadComponent: loadIndicadores,
|
||||
})),
|
||||
{ path: '**', redirectTo: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: 'gobernanza',
|
||||
title: 'Gobernanza de modelos | ISSSTELEON',
|
||||
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
|
||||
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
|
||||
},
|
||||
{
|
||||
path: 'bitacora',
|
||||
title: 'Bitácora de cargas | ISSSTELEON',
|
||||
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
|
||||
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
|
||||
},
|
||||
{
|
||||
path: 'kpis',
|
||||
title: 'Indicadores | ISSSTELEON',
|
||||
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
|
||||
data: { workspace: true, breadcrumb: 'Indicadores' },
|
||||
},
|
||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
...DOMINIOS.map(dominio => ({
|
||||
path: `indicadores/${dominio}`,
|
||||
title: 'Indicadores | ISSSTELEON',
|
||||
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
|
||||
loadComponent: loadIndicadores,
|
||||
})),
|
||||
{ path: '**', redirectTo: '' },
|
||||
];
|
||||
|
||||
@@ -120,6 +120,46 @@
|
||||
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Session exit: the same action look as the home buttons, in header size. */
|
||||
.site-header__salir {
|
||||
align-items: center;
|
||||
background: transparent;
|
||||
border: 1px solid var(--color-action);
|
||||
border-radius: 8px;
|
||||
color: var(--color-text);
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
gap: 6px;
|
||||
margin-inline-start: var(--space-4);
|
||||
min-height: 34px;
|
||||
padding: 0 var(--space-3);
|
||||
transition:
|
||||
background-color 0.2s ease,
|
||||
border-color 0.2s ease,
|
||||
color 0.2s ease;
|
||||
}
|
||||
|
||||
.site-header__salir:hover {
|
||||
background: var(--color-action-hover);
|
||||
border-color: var(--color-action);
|
||||
}
|
||||
|
||||
.site-header__salir:focus-visible {
|
||||
outline: 2px solid var(--color-action);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.site-header__salir mat-icon {
|
||||
color: var(--color-action);
|
||||
font-size: 18px;
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
|
||||
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
||||
@media (max-width: 599px) {
|
||||
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
||||
|
||||
+96
-25
@@ -1,46 +1,117 @@
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { of } from 'rxjs';
|
||||
import { App } from './app';
|
||||
import { routes } from './app.routes';
|
||||
import { AuthService, Usuario } from './auth/auth.service';
|
||||
|
||||
const TODOS: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] };
|
||||
|
||||
/**
|
||||
* Doble de la sesión: `App` lee la señal y los guards preguntan si hay sesión y
|
||||
* qué dominios alcanza. Las pruebas de este archivo cubren el marco, no el
|
||||
* inicio de sesión en sí (`auth/auth.service.spec.ts`).
|
||||
*/
|
||||
function authFalso(sesion: Usuario | null) {
|
||||
return {
|
||||
usuario: signal(sesion),
|
||||
autenticado: signal(sesion !== null),
|
||||
sesion: () => of(sesion),
|
||||
puedeVer: (dominio: string) => sesion?.dominios.includes(dominio) ?? false,
|
||||
logout: () => of(undefined),
|
||||
limpiar: () => undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function montar(sesion: Usuario | null): Promise<Router> {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
providers: [
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
{ provide: AuthService, useValue: authFalso(sesion) },
|
||||
],
|
||||
}).compileComponents();
|
||||
return TestBed.inject(Router);
|
||||
}
|
||||
|
||||
describe('App', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
async function render(url: string) {
|
||||
const fixture = TestBed.createComponent(App);
|
||||
fixture.detectChanges();
|
||||
await TestBed.inject(Router).navigateByUrl(url);
|
||||
await TestBed.inject(Router).navigateByUrl(url).catch(() => false);
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
return fixture.nativeElement as HTMLElement;
|
||||
}
|
||||
|
||||
it('renders the ISSSTELEON shell and home page with its footer', async () => {
|
||||
const page = await render('/');
|
||||
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
|
||||
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
|
||||
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
|
||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||
describe('con sesión de administrador', () => {
|
||||
beforeEach(() => montar(TODOS));
|
||||
|
||||
it('renders the ISSSTELEON shell and home page with its footer', async () => {
|
||||
const page = await render('/');
|
||||
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
|
||||
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
|
||||
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
|
||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||
const page = await render('/conectar');
|
||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
|
||||
expect(page.querySelector('.site-footer')).toBeNull();
|
||||
}, 15000);
|
||||
|
||||
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
|
||||
const page = await render('/gobernanza');
|
||||
expect(page.querySelector('app-governance-page')).not.toBeNull();
|
||||
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
|
||||
expect(page.querySelector('.site-footer')).toBeNull();
|
||||
});
|
||||
|
||||
it('el encabezado nombra al usuario de la sesión y ofrece cerrarla', async () => {
|
||||
// Fails if the shell forgets the session: the user would have no way out.
|
||||
const page = await render('/');
|
||||
expect(page.querySelector('.site-header__salir')?.textContent).toContain('Administrador');
|
||||
});
|
||||
});
|
||||
|
||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||
const page = await render('/conectar');
|
||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
|
||||
expect(page.querySelector('.site-footer')).toBeNull();
|
||||
describe('con una cuenta de un solo dominio', () => {
|
||||
beforeEach(() => montar({ usuario: 'cacu', nombre: 'Equipo CaCu', dominios: ['cacu'] }));
|
||||
|
||||
it('no deja abrir el dominio ajeno: la manda al suyo', async () => {
|
||||
// Fails if the domain scope exists only on the server: the interface would show an empty page.
|
||||
await render('/indicadores/cama');
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
|
||||
}, 15000);
|
||||
|
||||
it('el encabezado no ofrece los otros dominios', async () => {
|
||||
const page = await render('/indicadores/cacu');
|
||||
expect(page.querySelector('app-domain-selector')).toBeNull();
|
||||
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('CaCu');
|
||||
});
|
||||
});
|
||||
|
||||
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
|
||||
const page = await render('/gobernanza');
|
||||
expect(page.querySelector('app-governance-page')).not.toBeNull();
|
||||
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
|
||||
expect(page.querySelector('.site-footer')).toBeNull();
|
||||
describe('sin sesión', () => {
|
||||
beforeEach(() => montar(null));
|
||||
|
||||
it('cualquier ruta manda al inicio de sesión y no muestra el marco', async () => {
|
||||
const page = await render('/conectar');
|
||||
expect(TestBed.inject(Router).url).toContain('/login');
|
||||
expect(page.querySelector('.login')).not.toBeNull();
|
||||
expect(page.querySelector('.site-header')).toBeNull();
|
||||
expect(page.querySelector('.site-footer')).toBeNull();
|
||||
expect(page.querySelector('app-connect-page')).toBeNull();
|
||||
});
|
||||
|
||||
it('el destino pedido viaja en returnUrl para volver después de entrar', async () => {
|
||||
await render('/gobernanza');
|
||||
expect(TestBed.inject(Router).url).toContain('returnUrl=%2Fgobernanza');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+22
-2
@@ -1,12 +1,14 @@
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||
import { filter, map } from 'rxjs';
|
||||
import { AuthService } from './auth/auth.service';
|
||||
import { DomainSelector } from './domain-selector';
|
||||
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
@Component({
|
||||
imports: [RouterLink, RouterOutlet, DomainSelector],
|
||||
imports: [MatIconModule, RouterLink, RouterOutlet, DomainSelector],
|
||||
selector: 'app-root',
|
||||
styleUrl: './app.scss',
|
||||
templateUrl: './app.html',
|
||||
@@ -14,6 +16,7 @@ import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
export class App {
|
||||
private readonly router = inject(Router);
|
||||
private readonly route = inject(ActivatedRoute);
|
||||
private readonly auth = inject(AuthService);
|
||||
|
||||
private readonly leafRouteData = toSignal(
|
||||
this.router.events.pipe(
|
||||
@@ -30,7 +33,10 @@ export class App {
|
||||
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
|
||||
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
|
||||
readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
|
||||
/** The login screen (`data.sinCromo`) owns the whole window: no header, no footer. */
|
||||
readonly sinCromo = computed(() => !!this.leafRouteData()['sinCromo']);
|
||||
|
||||
protected readonly usuario = this.auth.usuario;
|
||||
protected readonly title = 'Plataforma de Indicadores';
|
||||
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
|
||||
private readonly url = toSignal(this.router.events.pipe(
|
||||
@@ -38,5 +44,19 @@ export class App {
|
||||
/** On an indicators page the header names its domain and switches to the others. */
|
||||
protected readonly activeDomain = computed(() =>
|
||||
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
|
||||
protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain()));
|
||||
/** Only the domains the account may see: the header never offers a forbidden one. */
|
||||
private readonly permitidos = computed<readonly Dominio[]>(() => {
|
||||
const sesion = this.auth.usuario();
|
||||
return sesion ? DOMINIOS.filter(dominio => sesion.dominios.includes(dominio)) : DOMINIOS;
|
||||
});
|
||||
protected readonly otherDomains = computed(() =>
|
||||
this.permitidos().filter(domain => domain !== this.activeDomain()));
|
||||
|
||||
protected salir(): void {
|
||||
// Whether the server session was already gone, the browser ends up at the login screen.
|
||||
this.auth.logout().subscribe({
|
||||
next: () => void this.router.navigate(['/login']),
|
||||
error: () => void this.router.navigate(['/login']),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { map } from 'rxjs';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Sin sesión no hay ruta protegida: se manda al inicio de sesión y se recuerda
|
||||
* `returnUrl` para volver a donde iba el usuario.
|
||||
*/
|
||||
export const authGuard: CanActivateFn = (_ruta, estado) => {
|
||||
const auth = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
return auth
|
||||
.sesion()
|
||||
.pipe(
|
||||
map(
|
||||
(usuario) =>
|
||||
usuario !== null ||
|
||||
router.createUrlTree(['/login'], { queryParams: { returnUrl: estado.url } }),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
// La sesión vive en el navegador (la WebApi no autentica): estas pruebas fijan
|
||||
// el contrato del servicio —quién entra, qué dominios ve y qué queda guardado—
|
||||
// porque de él dependen el guard de rutas y el recorte de los selectores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let auth: AuthService;
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
TestBed.configureTestingModule({});
|
||||
auth = TestBed.inject(AuthService);
|
||||
});
|
||||
|
||||
it('entra con la contraseña correcta y deja al usuario en la señal', () => {
|
||||
auth.login('cama', 'cama2026').subscribe();
|
||||
|
||||
expect(auth.usuario()).toEqual({ usuario: 'cama', nombre: 'Equipo CaMa', dominios: ['cama'] });
|
||||
expect(auth.autenticado()).toBe(true);
|
||||
});
|
||||
|
||||
it('rechaza una contraseña incorrecta sin abrir sesión', () => {
|
||||
let error: Error | undefined;
|
||||
auth.login('cama', 'otra').subscribe({ error: (e: Error) => (error = e) });
|
||||
|
||||
expect(error?.message).toContain('incorrectos');
|
||||
expect(auth.autenticado()).toBe(false);
|
||||
});
|
||||
|
||||
it('dice qué dominios puede ver la cuenta', () => {
|
||||
auth.login('cama', 'cama2026').subscribe();
|
||||
|
||||
expect(auth.puedeVer('cama')).toBe(true);
|
||||
expect(auth.puedeVer('cacu')).toBe(false);
|
||||
expect(auth.puedeVer('tea')).toBe(false);
|
||||
});
|
||||
|
||||
it('el administrador ve los tres dominios', () => {
|
||||
auth.login('admin', 'admin2026').subscribe();
|
||||
expect(['cacu', 'cama', 'tea'].every((dominio) => auth.puedeVer(dominio))).toBe(true);
|
||||
});
|
||||
|
||||
it('cerrar sesión borra al usuario y lo guardado', () => {
|
||||
auth.login('tea', 'tea2026').subscribe();
|
||||
auth.logout().subscribe();
|
||||
|
||||
expect(auth.autenticado()).toBe(false);
|
||||
expect(sessionStorage.getItem('isssteleon.sesion')).toBeNull();
|
||||
});
|
||||
|
||||
it('la sesión sobrevive a una recarga de la pestaña', () => {
|
||||
// Fails if the login is kept only in memory: a refresh would log the team out mid-task.
|
||||
auth.login('cacu', 'cacu2026').subscribe();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({});
|
||||
expect(TestBed.inject(AuthService).usuario()?.usuario).toBe('cacu');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Injectable, computed, signal } from '@angular/core';
|
||||
import { Observable, of, throwError } from 'rxjs';
|
||||
|
||||
/** El usuario de la sesión, con los dominios que la interfaz le deja ver. */
|
||||
export interface Usuario {
|
||||
readonly usuario: string;
|
||||
readonly nombre: string;
|
||||
readonly dominios: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cuentas de la interfaz. La WebApi no tiene autenticación: el inicio de sesión
|
||||
* y el recorte por dominio viven aquí, en el navegador, para ordenar el trabajo
|
||||
* de cada equipo. No son seguridad: cualquiera puede leer esta lista en el
|
||||
* paquete de la aplicación y la API responde a quien la llame.
|
||||
*/
|
||||
const CUENTAS: readonly (Usuario & { contrasena: string })[] = [
|
||||
{ usuario: 'admin', contrasena: 'admin2026', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] },
|
||||
{ usuario: 'cacu', contrasena: 'cacu2026', nombre: 'Equipo CaCu', dominios: ['cacu'] },
|
||||
{ usuario: 'cama', contrasena: 'cama2026', nombre: 'Equipo CaMa', dominios: ['cama'] },
|
||||
{ usuario: 'tea', contrasena: 'tea2026', nombre: 'Equipo TEA', dominios: ['tea'] },
|
||||
];
|
||||
|
||||
/** La sesión se guarda por pestaña: cerrar el navegador pide entrar de nuevo. */
|
||||
const CLAVE = 'isssteleon.sesion';
|
||||
|
||||
/**
|
||||
* Sesión local de la aplicación. Es la única fuente de verdad del usuario: el
|
||||
* guard pregunta aquí, los paneles filtran dominios con `puedeVer` y salir solo
|
||||
* borra el registro del navegador.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthService {
|
||||
private readonly usuarioActual = signal<Usuario | null>(this.leer());
|
||||
readonly usuario = this.usuarioActual.asReadonly();
|
||||
readonly autenticado = computed(() => this.usuarioActual() !== null);
|
||||
|
||||
/** Si la cuenta puede ver ese dominio. Sin sesión no se opina (los guards deciden). */
|
||||
puedeVer(dominio: string): boolean {
|
||||
const sesion = this.usuarioActual();
|
||||
return sesion ? sesion.dominios.includes(dominio) : true;
|
||||
}
|
||||
|
||||
/** La sesión guardada en esta pestaña; se resuelve al instante, sin servidor. */
|
||||
sesion(): Observable<Usuario | null> {
|
||||
return of(this.usuarioActual());
|
||||
}
|
||||
|
||||
/** Valida contra la lista local; un error marca las credenciales como incorrectas. */
|
||||
login(usuario: string, contrasena: string): Observable<Usuario> {
|
||||
const cuenta = CUENTAS.find((c) => c.usuario === usuario.trim() && c.contrasena === contrasena);
|
||||
if (!cuenta) return throwError(() => new Error('usuario o contraseña incorrectos'));
|
||||
const sesion: Usuario = { usuario: cuenta.usuario, nombre: cuenta.nombre, dominios: [...cuenta.dominios] };
|
||||
this.establecer(sesion);
|
||||
return of(sesion);
|
||||
}
|
||||
|
||||
logout(): Observable<void> {
|
||||
this.limpiar();
|
||||
return of(undefined);
|
||||
}
|
||||
|
||||
limpiar(): void {
|
||||
this.usuarioActual.set(null);
|
||||
try {
|
||||
sessionStorage.removeItem(CLAVE);
|
||||
} catch {
|
||||
// Almacenamiento deshabilitado: la sesión dura lo que la pestaña en memoria.
|
||||
}
|
||||
}
|
||||
|
||||
private establecer(sesion: Usuario): void {
|
||||
this.usuarioActual.set(sesion);
|
||||
try {
|
||||
sessionStorage.setItem(CLAVE, JSON.stringify(sesion));
|
||||
} catch {
|
||||
// Idem: sin almacenamiento, la sesión no sobrevive a una recarga.
|
||||
}
|
||||
}
|
||||
|
||||
private leer(): Usuario | null {
|
||||
try {
|
||||
const crudo = sessionStorage.getItem(CLAVE);
|
||||
if (!crudo) return null;
|
||||
const sesion = JSON.parse(crudo) as Usuario;
|
||||
return typeof sesion?.usuario === 'string' && Array.isArray(sesion.dominios) ? sesion : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Usuario } from './auth.service';
|
||||
|
||||
/** Same key AuthService persists the visual session under. */
|
||||
const CLAVE_SESION = 'isssteleon.sesion';
|
||||
|
||||
/**
|
||||
* Seeds the browser-only visual session before the router and AuthService are created,
|
||||
* so routes behind authGuard render instead of redirecting to /login. Pair every call
|
||||
* with `limpiarSesionVisual()` in afterEach so the session never leaks between tests.
|
||||
*/
|
||||
export function iniciarSesionVisual(sesion: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] }): void {
|
||||
sessionStorage.setItem(CLAVE_SESION, JSON.stringify(sesion));
|
||||
}
|
||||
|
||||
export function limpiarSesionVisual(): void {
|
||||
sessionStorage.removeItem(CLAVE_SESION);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { map } from 'rxjs';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Cada cuenta ve solo sus dominios: una ruta con `data.dominio` ajeno manda a la
|
||||
* cuenta a su primer dominio. Sin sesión no decide nada (`authGuard` ya la
|
||||
* mandó al inicio de sesión).
|
||||
*/
|
||||
export const dominioGuard: CanActivateFn = (ruta) => {
|
||||
const auth = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
const pedido = ruta.data?.['dominio'] as string | undefined;
|
||||
return auth.sesion().pipe(
|
||||
map((usuario) => {
|
||||
if (!usuario || !pedido || usuario.dominios.includes(pedido)) return true;
|
||||
const propio = usuario.dominios[0];
|
||||
return propio ? router.createUrlTree(['/indicadores', propio]) : router.createUrlTree(['/']);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Helpers for the screens that list domains (cargar información, gobernanza):
|
||||
* an account only ever sees its own, and «Todos» only belongs to one that
|
||||
* reaches every domain — the administrator.
|
||||
*/
|
||||
|
||||
/** De la lista dada, las entradas cuyo dominio alcanza la cuenta. */
|
||||
export function dominiosPermitidos<T extends { id: string }>(auth: AuthService, dominios: readonly T[]): T[] {
|
||||
return dominios.filter((dominio) => auth.puedeVer(dominio.id));
|
||||
}
|
||||
|
||||
/** Si la cuenta alcanza todos: solo entonces tiene sentido ofrecer «Todos». */
|
||||
export function alcanzaTodos(auth: AuthService, dominios: readonly { id: string }[]): boolean {
|
||||
return dominios.every((dominio) => auth.puedeVer(dominio.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* El dominio con el que abre una pantalla: el único que alcanza la cuenta, o
|
||||
* `null` («Todos») cuando alcanza varios. Sin sesión resuelta devuelve `null`,
|
||||
* que es el comportamiento de siempre.
|
||||
*/
|
||||
export function dominioInicial<T extends string>(auth: AuthService, dominios: readonly { id: T }[]): T | null {
|
||||
const propios = dominiosPermitidos(auth, dominios);
|
||||
return propios.length === 1 ? propios[0].id : null;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<section class="login" aria-labelledby="login-titulo">
|
||||
<div class="login__caja">
|
||||
<img class="login__logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
|
||||
<h1 class="login__titulo" id="login-titulo">Inicio de sesión</h1>
|
||||
|
||||
<form class="login__formulario" (ngSubmit)="ingresar()" novalidate>
|
||||
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
|
||||
<input
|
||||
matInput
|
||||
name="usuario"
|
||||
[(ngModel)]="usuario"
|
||||
placeholder="Usuario"
|
||||
aria-label="Usuario"
|
||||
autocomplete="username"
|
||||
autocapitalize="none"
|
||||
spellcheck="false"
|
||||
/>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
|
||||
<input
|
||||
matInput
|
||||
name="contrasena"
|
||||
[(ngModel)]="contrasena"
|
||||
[type]="verContrasena() ? 'text' : 'password'"
|
||||
placeholder="Contraseña"
|
||||
aria-label="Contraseña"
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
<button
|
||||
mat-icon-button
|
||||
matSuffix
|
||||
type="button"
|
||||
class="login__ojo"
|
||||
(click)="mostrarContrasena()"
|
||||
[attr.aria-label]="verContrasena() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
|
||||
[attr.aria-pressed]="verContrasena()"
|
||||
>
|
||||
<mat-icon>{{ verContrasena() ? 'visibility_off' : 'visibility' }}</mat-icon>
|
||||
</button>
|
||||
</mat-form-field>
|
||||
|
||||
@if (error(); as mensaje) {
|
||||
<p class="login__error" role="alert">{{ mensaje }}</p>
|
||||
}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
class="login__ingresar"
|
||||
[disabled]="!usuario.trim() || !contrasena || enviando()"
|
||||
>
|
||||
{{ enviando() ? 'Ingresando…' : 'Ingresar' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p class="login__legal">©{{ anio }} Todos los derechos reservados.</p>
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1,170 @@
|
||||
:host {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
/* The button borrows the home actions' palette: white with a thin gray border
|
||||
until the form is complete, then `--color-action` (see styles.scss). */
|
||||
--login-fondo: #f8f9fa;
|
||||
--login-borde: #e9ecef;
|
||||
}
|
||||
|
||||
.login {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
justify-content: center;
|
||||
/* The whole block sits a little below the middle: the logo above it gives the screen its weight. */
|
||||
padding: var(--space-9) var(--space-5) var(--space-8);
|
||||
}
|
||||
|
||||
.login__caja {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
max-width: 340px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* The brand opens the screen and is the biggest thing on it: it is what fills the empty space. */
|
||||
.login__logo {
|
||||
align-self: center;
|
||||
display: block;
|
||||
margin-bottom: 0;
|
||||
width: 260px;
|
||||
animation: login-logo-entrada 600ms ease-out both;
|
||||
}
|
||||
|
||||
@keyframes login-logo-entrada {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.login__logo {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.login__titulo {
|
||||
align-items: center;
|
||||
color: var(--color-text);
|
||||
display: flex;
|
||||
font-family: var(--font-heading);
|
||||
font-size: 1.375rem;
|
||||
font-weight: 600;
|
||||
gap: var(--space-4);
|
||||
margin: 0 0 var(--space-2);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The two rules that flank the title, as in the reference screen. */
|
||||
.login__titulo::before,
|
||||
.login__titulo::after {
|
||||
background: var(--color-border);
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
.login__formulario {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.login__campo {
|
||||
width: 100%;
|
||||
--mat-form-field-container-height: 44px;
|
||||
--mat-form-field-container-vertical-padding: 12px;
|
||||
}
|
||||
|
||||
.login__ojo {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
/* Edge paints its own reveal control over the password field; the eye in the field is ours. */
|
||||
.login__campo input::-ms-reveal,
|
||||
.login__campo input::-ms-clear {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.login__error {
|
||||
color: var(--mat-sys-error);
|
||||
font-size: 0.875rem;
|
||||
margin: calc(-1 * var(--space-1)) 0 0;
|
||||
}
|
||||
|
||||
/* The button shares the fields' width: one column, one border, no icon and no underline.
|
||||
Its border turns teal when the form is complete, and it fades in instead of switching. */
|
||||
.login__ingresar {
|
||||
align-items: center;
|
||||
background: var(--login-fondo);
|
||||
border: 1px solid var(--login-borde);
|
||||
border-radius: 10px;
|
||||
color: var(--color-text-secondary);
|
||||
cursor: default;
|
||||
display: flex;
|
||||
font: inherit;
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 500;
|
||||
justify-content: center;
|
||||
margin-top: var(--space-2);
|
||||
min-height: 46px;
|
||||
padding: 0 var(--space-5);
|
||||
text-decoration: none;
|
||||
transition:
|
||||
background-color 260ms ease,
|
||||
border-color 260ms ease,
|
||||
color 260ms ease;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.login__ingresar:not(:disabled) {
|
||||
border-color: var(--color-action);
|
||||
color: var(--color-text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.login__ingresar:hover:not(:disabled) {
|
||||
background: var(--color-action-hover);
|
||||
border-color: var(--color-action);
|
||||
}
|
||||
|
||||
.login__ingresar:focus-visible {
|
||||
outline: 2px solid var(--color-action);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.login__ingresar:disabled {
|
||||
background: var(--login-fondo);
|
||||
border-color: var(--login-borde);
|
||||
}
|
||||
|
||||
.login__legal {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 0.8125rem;
|
||||
margin: var(--space-4) 0 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.login {
|
||||
padding: var(--space-7) var(--space-4);
|
||||
}
|
||||
|
||||
.login__caja {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.login__logo {
|
||||
width: 208px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Component, OnInit, inject, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
/**
|
||||
* Inicio de sesión: valida contra las cuentas locales de `AuthService` y, si el
|
||||
* usuario ya tiene sesión, salta al destino. `returnUrl` lo pone el guard cuando
|
||||
* una ruta protegida lo trajo aquí.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-login-page',
|
||||
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
|
||||
styleUrl: './login-page.scss',
|
||||
templateUrl: './login-page.html',
|
||||
})
|
||||
export class LoginPage implements OnInit {
|
||||
private readonly auth = inject(AuthService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly ruta = inject(ActivatedRoute);
|
||||
|
||||
protected usuario = '';
|
||||
protected contrasena = '';
|
||||
protected readonly verContrasena = signal(false);
|
||||
protected readonly enviando = signal(false);
|
||||
protected readonly error = signal<string | null>(null);
|
||||
protected readonly anio = new Date().getFullYear();
|
||||
|
||||
ngOnInit(): void {
|
||||
// Quien ya inició sesión y abre /login vuelve derecho a la aplicación.
|
||||
this.auth.sesion().subscribe((usuario) => {
|
||||
if (usuario) void this.router.navigateByUrl(this.destino());
|
||||
});
|
||||
}
|
||||
|
||||
protected ingresar(): void {
|
||||
if (!this.usuario.trim() || !this.contrasena || this.enviando()) return;
|
||||
this.enviando.set(true);
|
||||
this.error.set(null);
|
||||
this.auth.login(this.usuario.trim(), this.contrasena).subscribe({
|
||||
next: () => void this.router.navigateByUrl(this.destino()),
|
||||
error: () => {
|
||||
this.enviando.set(false);
|
||||
this.error.set('Usuario o contraseña incorrectos.');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected mostrarContrasena(): void {
|
||||
this.verContrasena.update((visible) => !visible);
|
||||
}
|
||||
|
||||
private destino(): string {
|
||||
const pedido = this.ruta.snapshot.queryParamMap.get('returnUrl');
|
||||
return pedido?.startsWith('/') && !pedido.startsWith('/login') ? pedido : '/';
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
aria-label="Base de datos destino"
|
||||
[matTooltip]="store.domainLocked() ? 'Una carga va a una sola base; quita los flujos para cambiarla' : 'Base de datos destino'"
|
||||
>
|
||||
@for (domain of domains; track domain.id) {
|
||||
@for (domain of domains(); track domain.id) {
|
||||
<mat-button-toggle [value]="domain.id" [attr.aria-label]="domain.description">{{ domain.label }}</mat-button-toggle>
|
||||
}
|
||||
</mat-button-toggle-group>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { DragDropModule } from '@angular/cdk/drag-drop';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { Component, Injector, inject, signal } from '@angular/core';
|
||||
import { Component, Injector, computed, inject, signal } from '@angular/core';
|
||||
import { MatBadgeModule } from '@angular/material/badge';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
@@ -12,6 +12,8 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { Domain, TargetMeta } from '../../api/api.types';
|
||||
import { AuthService } from '../../../auth/auth.service';
|
||||
import { dominiosPermitidos } from '../../../auth/dominios';
|
||||
import { DataConnection, SourceTable } from '../../domain/data-source';
|
||||
import { PdfConnection } from '../../domain/pdf-source';
|
||||
import { SqlConnection } from '../../domain/sql-source';
|
||||
@@ -59,11 +61,13 @@ import { SqlQueryDialog, SqlQueryResult } from '../sql-query-dialog/sql-query-di
|
||||
})
|
||||
export class ConnectPage {
|
||||
readonly store = inject(ConnectWorkspaceStore);
|
||||
private readonly auth = inject(AuthService);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
private readonly injector = inject(Injector);
|
||||
|
||||
readonly domains = DOMAINS;
|
||||
/** Only the account's own databases: the picker never offers a domain the server will reject. */
|
||||
readonly domains = computed(() => dominiosPermitidos(this.auth, DOMAINS));
|
||||
readonly paneOpen = signal(true);
|
||||
readonly validatingAll = signal(false);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Observable, firstValueFrom, of } from 'rxjs';
|
||||
import { AuthService } from '../../auth/auth.service';
|
||||
import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types';
|
||||
import { ImportsApi } from '../api/imports.api';
|
||||
import { SourceGateway } from '../api/source-gateway';
|
||||
@@ -32,6 +33,8 @@ describe('ConnectWorkspaceStore', () => {
|
||||
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
|
||||
{ provide: ImportsApi, useValue: imports },
|
||||
{ provide: SourceGateway, useValue: {} },
|
||||
// Sin sesión resuelta el alcance es todo; el caso restringido se arma en su propia prueba.
|
||||
{ provide: AuthService, useValue: { puedeVer: () => true } },
|
||||
],
|
||||
});
|
||||
store = TestBed.inject(ConnectWorkspaceStore);
|
||||
@@ -52,6 +55,25 @@ describe('ConnectWorkspaceStore', () => {
|
||||
expect(store.domain()).toBe('cacu');
|
||||
});
|
||||
|
||||
it('opens on the account\'s own domain and refuses the others', () => {
|
||||
// Fails if the destination database ignores the session: a CaMa team could load into CaCu's database.
|
||||
TestBed.resetTestingModule();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ConnectWorkspaceStore,
|
||||
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
|
||||
{ provide: ImportsApi, useValue: imports },
|
||||
{ provide: SourceGateway, useValue: {} },
|
||||
{ provide: AuthService, useValue: { puedeVer: (dominio: string) => dominio === 'cama' } },
|
||||
],
|
||||
});
|
||||
const restringido = TestBed.inject(ConnectWorkspaceStore);
|
||||
|
||||
expect(restringido.domain()).toBe('cama');
|
||||
restringido.setDomain('cacu');
|
||||
expect(restringido.domain()).toBe('cama');
|
||||
});
|
||||
|
||||
it('removing a connection removes the flows built on its tables', () => {
|
||||
const { connection } = flowFrom('a.csv', PACIENTE);
|
||||
flowFrom('b.csv', PACIENTE);
|
||||
|
||||
@@ -2,6 +2,8 @@ import { Injectable, computed, inject, signal } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { Observable, catchError, from, of, switchMap, tap } from 'rxjs';
|
||||
import { BatchResult, ConflictStrategy, ConnectorInfo, Domain, TargetMeta, apiErrorMessage } from '../api/api.types';
|
||||
import { AuthService } from '../../auth/auth.service';
|
||||
import { dominiosPermitidos } from '../../auth/dominios';
|
||||
import { ConnectorsApi } from '../api/connectors.api';
|
||||
import { ImportsApi } from '../api/imports.api';
|
||||
import { SourceGateway } from '../api/source-gateway';
|
||||
@@ -29,6 +31,7 @@ export const DOMAINS: { id: Domain; label: string; description: string }[] = [
|
||||
export class ConnectWorkspaceStore {
|
||||
private readonly gateway = inject(SourceGateway);
|
||||
private readonly importsApi = inject(ImportsApi);
|
||||
private readonly auth = inject(AuthService);
|
||||
|
||||
private readonly targetsError = signal<string | null>(null);
|
||||
readonly allTargets = toSignal(
|
||||
@@ -50,7 +53,8 @@ export class ConnectWorkspaceStore {
|
||||
});
|
||||
readonly acceptedExtensions = computed(() => acceptedExtensions(this.connectors()));
|
||||
|
||||
private readonly _domain = signal<Domain>('cacu');
|
||||
/** The destination database: the account's own when it only reaches one. */
|
||||
private readonly _domain = signal<Domain>(this.dominioInicial());
|
||||
private readonly _connections = signal<DataConnection[]>([]);
|
||||
private readonly _flows = signal<ImportFlow[]>([]);
|
||||
private readonly _selectedFlowId = signal<string | null>(null);
|
||||
@@ -128,7 +132,12 @@ export class ConnectWorkspaceStore {
|
||||
});
|
||||
|
||||
setDomain(domain: Domain): void {
|
||||
if (!this.domainLocked()) this._domain.set(domain);
|
||||
if (!this.domainLocked() && this.auth.puedeVer(domain)) this._domain.set(domain);
|
||||
}
|
||||
|
||||
/** The first domain the account may see; every account has at least one (`WebApi` gives none other). */
|
||||
private dominioInicial(): Domain {
|
||||
return dominiosPermitidos(this.auth, DOMAINS)[0]?.id ?? 'cacu';
|
||||
}
|
||||
|
||||
setOnConflict(strategy: ConflictStrategy): void {
|
||||
|
||||
@@ -30,9 +30,9 @@ export function code(concept: Concept | undefined): string | undefined {
|
||||
export function display(concept: Concept | undefined): string | undefined {
|
||||
return concept?.coding?.[0]?.display ?? concept?.text;
|
||||
}
|
||||
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URI such as a URN).
|
||||
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
|
||||
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
|
||||
const url = system.includes(':') ? system : CODE_SYSTEM + system;
|
||||
const url = system.includes('://') ? system : CODE_SYSTEM + system;
|
||||
return concept?.coding?.find(c => c.system === url)?.code;
|
||||
}
|
||||
// The extensions named `name` (the last segment of their URL).
|
||||
|
||||
@@ -5,6 +5,15 @@ p, h3, summary { overflow-wrap: anywhere; }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.selection-status { font-weight: 600; }
|
||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||
.families { display: flex; flex-wrap: wrap; gap: .75rem; }
|
||||
.family { flex: 1 1 16rem; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--issste-border); border-radius: 1rem; background: var(--issste-surface); }
|
||||
.family button { display: inline-flex; align-items: center; gap: .55rem; }
|
||||
.family .parent { width: 100%; justify-content: flex-start; border: 0; border-radius: 0; border-bottom: 1px solid var(--issste-border); font-weight: 650; background: color-mix(in srgb, var(--swatch) 14%, var(--issste-surface)); }
|
||||
.family .children { display: flex; flex-wrap: wrap; gap: .4rem; padding: .55rem; }
|
||||
.family .child { flex: 1 1 8rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); }
|
||||
.family .parent[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 24%, var(--issste-surface)); box-shadow: inset 0 -3px 0 var(--swatch); }
|
||||
.family .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); transform: scale(1.03); }
|
||||
.family .swatch { width: .35rem; height: 1.15rem; border: 0; border-radius: .2rem; background: var(--swatch); }
|
||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.legend > button { justify-self: start; }
|
||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||
|
||||
@@ -13,6 +13,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||
import { recolorFigure } from './indicadores-c2-palette';
|
||||
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
export interface FigureState {
|
||||
@@ -62,7 +63,8 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
}
|
||||
get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; }
|
||||
legendColor(label: string, parent: boolean): string {
|
||||
const trace = this.chartFigure?.data[parent && this.activeParent ? 1 : 0];
|
||||
const painted = this.chartFigure ? recolorFigure(this.chartFigure) : undefined;
|
||||
const trace = painted?.data[parent && this.activeParent ? 1 : 0];
|
||||
const labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined;
|
||||
const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : undefined;
|
||||
return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor';
|
||||
|
||||
@@ -43,20 +43,24 @@
|
||||
</section>
|
||||
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
||||
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
<div class="families">
|
||||
@for (g of m.grupos; track g.id; let gi = $index) {
|
||||
<section class="family">
|
||||
<button type="button" class="parent" [style.--swatch]="g.color" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', gi)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
<div class="children" role="group" [attr.aria-label]="'Resultados de ' + g.etiqueta">
|
||||
@for (c of m.categorias; track c.id; let ci = $index) {
|
||||
@if (c.grupo === g.id) {
|
||||
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -161,14 +161,16 @@ describe('paleta C2 institucional y semántica', () => {
|
||||
it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => {
|
||||
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
||||
const figure = supported(data, { ...selection, tema }).figure;
|
||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]);
|
||||
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
|
||||
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
||||
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
|
||||
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
|
||||
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
|
||||
expect(c2Color('#D98E4A', 0)).toBe('#D98E4A');
|
||||
expect(c2Color('#D98E4A', 0)).toBe(C2_PALETTE.series[0]);
|
||||
expect(c2Color('#B55A1F', 2)).toBe(C2_PALETTE.series[2]);
|
||||
expect(c2Color('#9DBFE3', 1)).toBe('#9DBFE3');
|
||||
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
|
||||
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
||||
import { DonutHierarchy } from './indicadores-donut-drilldown';
|
||||
import { c2Theme, groupBase, seriesColors } from './indicadores-c2-palette';
|
||||
import { basesPorGrupo, C2_PALETTE, c2Theme, seriesColors } from './indicadores-c2-palette';
|
||||
|
||||
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
|
||||
// Normalized presentation nodes and a selection path are independent of Plotly.
|
||||
@@ -81,7 +81,8 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))];
|
||||
const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] };
|
||||
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
|
||||
const colors = seriesColors(categories.map(c => c.color));
|
||||
const colors = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
|
||||
const bases = basesPorGrupo(parentIds);
|
||||
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
|
||||
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
|
||||
@@ -109,7 +110,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
|
||||
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
|
||||
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
|
||||
marker: { colors: parents.map((_, i) => groupBase(i)), line: { color: theme.outline, width: 0.7 } },
|
||||
marker: { colors: parents.map(p => bases.get(p.id.replace(/^group:/, '')) ?? C2_PALETTE.series[0]), line: { color: theme.outline, width: 0.7 } },
|
||||
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
|
||||
}
|
||||
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
|
||||
|
||||
@@ -8,19 +8,22 @@ describe('paleta del logo ISSSTELEON', () => {
|
||||
expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]);
|
||||
});
|
||||
|
||||
it('reemplaza mezclas de partido por entradas distintas y conserva el gris de sin dato', () => {
|
||||
const [azul, rojo, naranja, amarillo, guinda, sinDato, edad] = institutionalize([
|
||||
'#0044CC', '#C41E3A', '#FF6B00', '#FFD100', '#7A2E0E', '#C9CDD2', '#2F6DB3',
|
||||
it('cambia el café y el anaranjado por la serie, y deja azul, rojo, gris y edad', () => {
|
||||
const [cafe, otroCafe, rojo, azul, sinDato, edad] = institutionalize([
|
||||
'#B55A1F', '#D9822B', '#C41E3A', '#0044CC', '#C9CDD2', '#2F6DB3',
|
||||
]);
|
||||
expect([azul, rojo, naranja, amarillo, guinda]).toEqual(C2_PALETTE.series.slice(0, 5));
|
||||
expect(edad).toBe('#2F6DB3');
|
||||
expect([cafe, otroCafe]).toEqual(C2_PALETTE.series.slice(0, 2));
|
||||
expect(rojo).toBe('#C41E3A');
|
||||
expect(azul).toBe('#0044CC');
|
||||
expect(sinDato).toBe('#C9CDD2');
|
||||
expect(edad).toBe('#2F6DB3');
|
||||
});
|
||||
|
||||
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
|
||||
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
|
||||
expect(new Set(colors.slice(0, 3)).size).toBe(3);
|
||||
expect(colors[3]).toBe(groupBase(1));
|
||||
expect(colors[3]).toBe(C2_PALETTE.calidos[0]);
|
||||
expect(colors[0]).not.toBe(C2_PALETTE.calidos[0]);
|
||||
expect(colors[0]).not.toBe(colors[3]);
|
||||
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
|
||||
});
|
||||
@@ -34,8 +37,7 @@ describe('paleta del logo ISSSTELEON', () => {
|
||||
layout: { font: { color: '#081839' }, paper_bgcolor: '#FFFFFF', colorway: ['#EF553B', '#636efa'] },
|
||||
});
|
||||
expect((figure.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]);
|
||||
expect(figure.data[0]['error_x']).toMatchObject({ color: expect.stringMatching(/^rgba\(\d+,\d+,\d+,0\.4\)$/) });
|
||||
expect((figure.data[0]['error_x'] as { color: string }).color).not.toContain('0,68,204');
|
||||
expect((figure.data[0]['error_x'] as { color: string }).color).toBe('rgba(0,68,204,0.4)');
|
||||
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
|
||||
const scale = figure.data[0]['colorscale'] as [number, string][];
|
||||
expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]);
|
||||
@@ -43,11 +45,7 @@ describe('paleta del logo ISSSTELEON', () => {
|
||||
expect(scale[0][1]).not.toBe(scale[1][1]);
|
||||
expect(figure.layout['font']).toEqual({ color: '#081839' });
|
||||
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
|
||||
expect(figure.layout['colorway']).toEqual(C2_PALETTE.series.slice(2, 4));
|
||||
expect(new Set([
|
||||
(figure.data[0]['marker'] as { color: string }).color,
|
||||
...(figure.layout['colorway'] as string[]),
|
||||
]).size).toBe(3);
|
||||
expect(figure.layout['colorway']).toEqual([C2_PALETTE.series[1], '#636efa']);
|
||||
expect(recolorFigure(figure)).toBe(figure);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||
|
||||
// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0).
|
||||
// Neighboring entries differ in hue so series stay distinct, and none is a party colour:
|
||||
// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral.
|
||||
// Sequential fills (heatmaps) use SCALE, from pale lime to deep teal.
|
||||
// Logo lime plus the analogous and complementary hues chosen for the charts.
|
||||
// Cool greens, teal and blue are the normal side. Rose, violet and purple are the abnormal side.
|
||||
// Neutrals stay neutral. Sequential fills run from pale lime to deep teal.
|
||||
const OWNED = new Set<string>();
|
||||
function own(hex: string): string { OWNED.add(hex.toLowerCase()); return hex; }
|
||||
export const C2_PALETTE = Object.freeze({
|
||||
frios: Object.freeze([own('#A8C243'), own('#69C242'), own('#42C25C'), own('#42C29C'), own('#4269C2')]),
|
||||
calidos: Object.freeze([own('#C24269'), own('#9C42C2'), own('#5C42C2'), own('#C2429C'), own('#8E2F62'), own('#7A3496')]),
|
||||
series: Object.freeze([
|
||||
'#5c7014', '#0e7568', '#6a6448', '#3d6b38',
|
||||
'#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38',
|
||||
'#A8C243', '#42C29C', '#C24269', '#9C42C2',
|
||||
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
|
||||
]),
|
||||
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
||||
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
|
||||
@@ -23,17 +26,56 @@ export function isAgeColor(color: string): boolean {
|
||||
const key = parseColor(color)?.key;
|
||||
return !!key && ageKeys.has(key);
|
||||
}
|
||||
export function c2Color(published: string | undefined, index: number): string {
|
||||
// A published swatch stays. The series only fills a category that arrived without one.
|
||||
if (published && (/^#[0-9a-f]{6}$/i.test(published) || isAgeColor(published))) return published;
|
||||
return C2_PALETTE.series[index % C2_PALETTE.series.length];
|
||||
/** Orange, tan and coffee. Age gold and the palette's own stone are not included. */
|
||||
function isCoffeeParsed(item: Parsed | undefined): boolean {
|
||||
if (!item || item.kind === 'neutral' || ageKeys.has(item.key)) return false;
|
||||
return item.hue >= 8 && item.hue <= 46 && item.sat >= 0.28;
|
||||
}
|
||||
export function isCoffeeColor(color: string): boolean {
|
||||
return isCoffeeParsed(parseColor(color));
|
||||
}
|
||||
export type Tono = 'frio' | 'calido' | 'neutro';
|
||||
/** Metadata id: cool for normal groups, warm for abnormal ones. Unknown ids stay neutral. */
|
||||
export function tonoDe(clave: string | undefined | null): Tono {
|
||||
if (!clave) return 'neutro';
|
||||
const id = clave.normalize('NFD').replace(/\p{M}/gu, '').toUpperCase().replace(/[^A-Z0-9]+/g, '_');
|
||||
if (id.includes('SIN_DATO') || id.includes('SIN_BIOPSIA')) return 'neutro';
|
||||
if (id.includes('NO_METAST') || id.includes('SIN_METAST') || id.includes('NO_ANORMAL') || id.includes('NO_MALIG') || id.includes('BENIGN') || id.includes('NO_ALTER')) return 'frio';
|
||||
if (id.includes('METAST') || id.includes('CARCINOMA') || id.includes('ANORMAL') || id.includes('MALIG') || id.includes('INVAS') || id.includes('IN_SITU') || id.includes('LIEAG') || id.includes('ALTER')) return 'calido';
|
||||
if (/^(B4|B4A|B4B|B4C|B5|B6)$/.test(id) || /^BIRADS_[456]/.test(id)) return 'calido';
|
||||
return 'neutro';
|
||||
}
|
||||
function poolDe(tono: Tono): readonly string[] {
|
||||
if (tono === 'calido') return C2_PALETTE.calidos;
|
||||
if (tono === 'frio') return C2_PALETTE.frios;
|
||||
return C2_PALETTE.series;
|
||||
}
|
||||
export function c2Color(published: string | undefined, index: number, tono: Tono = 'neutro'): string {
|
||||
// Coffee takes the cool or warm pool when the category metadata says which. Other published colours stay.
|
||||
if (published && isAgeColor(published)) return published;
|
||||
if (published && isNeutralColor(published)) return published;
|
||||
const pool = poolDe(tono);
|
||||
if (published && isCoffeeColor(published)) return pool[index % pool.length];
|
||||
if (published && /^#[0-9a-f]{6}$/i.test(published)) return published;
|
||||
return pool[index % pool.length];
|
||||
}
|
||||
|
||||
/** One base hue per group, then lighter and darker steps so siblings stay related but distinct. */
|
||||
/** One base per group: cool if the id is normal, warm if it is abnormal, then steps so siblings differ. */
|
||||
export function basesPorGrupo(groups: readonly string[]): ReadonlyMap<string, string> {
|
||||
const seen = { frio: 0, calido: 0, neutro: 0 };
|
||||
const base = new Map<string, string>();
|
||||
for (const id of [...new Set(groups)]) {
|
||||
const tono = tonoDe(id);
|
||||
const pool = poolDe(tono);
|
||||
base.set(id, pool[seen[tono] % pool.length]);
|
||||
seen[tono] += 1;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
export function paintByGroup(groups: readonly string[]): string[] {
|
||||
const order = [...new Set(groups)];
|
||||
const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length]));
|
||||
const stairs = new Map(order.map((id, i) => [id, steps(C2_PALETTE.series[i % C2_PALETTE.series.length], counts.get(id)!)]));
|
||||
const bases = basesPorGrupo(groups);
|
||||
const counts = new Map([...bases.keys()].map(id => [id, groups.filter(g => g === id).length]));
|
||||
const stairs = new Map([...bases].map(([id, color]) => [id, steps(color, counts.get(id)!)]));
|
||||
const cursor = new Map<string, number>();
|
||||
return groups.map(id => {
|
||||
const index = cursor.get(id) ?? 0;
|
||||
@@ -51,7 +93,7 @@ export function institutionalize(colors: readonly string[]): string[] {
|
||||
const foreign: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const item of parsed) {
|
||||
if (!item || item.kind !== 'foreign' || ageKeys.has(item.key) || seen.has(item.key)) continue;
|
||||
if (!item || !isCoffeeParsed(item) || seen.has(item.key)) continue;
|
||||
seen.add(item.key);
|
||||
foreign.push(item.key);
|
||||
}
|
||||
@@ -63,9 +105,14 @@ export function institutionalize(colors: readonly string[]): string[] {
|
||||
});
|
||||
}
|
||||
|
||||
/** Keep a published colour; only a missing one takes the next series entry. */
|
||||
export function seriesColors(published: readonly (string | undefined)[]): string[] {
|
||||
return published.map((color, index) => c2Color(color, index));
|
||||
/** Coffee published colours take the cool or warm pool of their metadata id. */
|
||||
export function seriesColors(published: readonly (string | undefined)[], claves?: readonly (string | undefined)[]): string[] {
|
||||
const seen = { frio: 0, calido: 0, neutro: 0 };
|
||||
return published.map((color, index) => {
|
||||
const tono = tonoDe(claves?.[index]);
|
||||
const slot = tono === 'neutro' ? index : seen[tono]++;
|
||||
return c2Color(color, slot, tono);
|
||||
});
|
||||
}
|
||||
|
||||
const NAMED: Record<string, [number, number, number]> = {
|
||||
@@ -101,10 +148,13 @@ function parseColor(input: string): Parsed | undefined {
|
||||
}
|
||||
const lum = luminance({ r, g, b });
|
||||
const neutral = sat < 0.18;
|
||||
const harmonious = !neutral && (
|
||||
(hue >= 64 && hue <= 188 && sat >= 0.22)
|
||||
const swatch = '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
|
||||
const harmonious = OWNED.has(swatch) || (!neutral && (
|
||||
(hue >= 64 && hue <= 175 && sat >= 0.22)
|
||||
|| (hue >= 200 && hue <= 320 && sat >= 0.22)
|
||||
|| (hue >= 320 && hue < 356 && sat >= 0.28 && sat <= 0.78)
|
||||
|| (hue > 188 && hue <= 230 && sat <= 0.5)
|
||||
|| (hue >= 40 && hue < 64 && sat <= 0.42));
|
||||
|| (hue >= 40 && hue < 64 && sat <= 0.42)));
|
||||
return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' };
|
||||
}
|
||||
function steps(base: string, count: number): string[] {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||
import tasaVisible from './fixtures/cama_tasa_deteccion_visible.json';
|
||||
import tasaSuprimida from './fixtures/cama_tasa_deteccion_suprimido.json';
|
||||
import diasVisible from './fixtures/cama_dias_resultado_visible.json';
|
||||
@@ -86,7 +87,7 @@ describe('CAM-01, CAM-02 y CAM-03: histórico con las respuestas reales', () =>
|
||||
expect(f.contrato).toBe('C2'); expect(f.suprimidos).toEqual([]); expect(f.sinDato).toEqual([]);
|
||||
expect(f.figure.data.map(t => [t['name'], (t['y'] as number[])[0]])).toEqual([
|
||||
['Benigno', 7], ['Lesión de riesgo (B3)', 5], ['Carcinoma in situ', 6], ['Carcinoma invasor', 7], ['Sin biopsia reportada', 6], ['Sin dato', 6]]);
|
||||
expect(f.figure.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', '#D9822B', '#B5482E', '#C9CDD2', '#C9CDD2']);
|
||||
expect(f.figure.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', C2_PALETTE.calidos[0], C2_PALETTE.calidos[1], '#C9CDD2', '#C9CDD2']);
|
||||
expect(f.figure.layout['barmode']).toBe('stack');
|
||||
expect(f.comoLeer).toContain('pacientes');
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
|
||||
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
||||
@@ -106,12 +106,11 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
|
||||
const colores = paintByGroup(conColor.map(g => g.grupo));
|
||||
const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]]));
|
||||
const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color }));
|
||||
const ordenGrupos = [...new Set(conColor.map(g => g.grupo))];
|
||||
const bases = basesPorGrupo(conColor.map(g => g.grupo));
|
||||
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
||||
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
|
||||
const propios = grados.filter(g => g.grupo === id);
|
||||
const indice = ordenGrupos.indexOf(id);
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: indice < 0 ? COLOR_RESPALDO : groupBase(indice),
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: bases.get(id) ?? COLOR_RESPALDO,
|
||||
grados: propios.map(g => g.id) };
|
||||
});
|
||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { c2Color, c2Theme, tonoDe } from './indicadores-c2-palette';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
// Two C2 indicators of the same finding: the exams by BI-RADS category and the patients by their most severe one.
|
||||
@@ -80,7 +80,10 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
|
||||
const publicada = registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : '';
|
||||
return publicada && publicada !== id ? publicada : ETIQUETA_RESPALDO[id] ?? id;
|
||||
};
|
||||
const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO;
|
||||
const color = (id: string, index: number) => {
|
||||
const publicado = registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO;
|
||||
return c2Color(publicado, index, tonoDe(id));
|
||||
};
|
||||
const todas = par.grupos.flatMap(g => g.categorias);
|
||||
if (par.categoriasExamen.some(id => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|
||||
|| todas.some(id => !OPCIONALES.has(id) && (!Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id)))) {
|
||||
@@ -93,7 +96,7 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
|
||||
OPCIONALES.has(id) && !Object.hasOwn(cat, id) ? 0 : cuenta(filas, periodo, id);
|
||||
return periodos.map(periodo => ({
|
||||
periodo,
|
||||
examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: de(filasE, catExamenes, periodo, id) })),
|
||||
examenes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id, index), n: de(filasE, catExamenes, periodo, id) })),
|
||||
// Only the exams the response reports apart; an indicator that lists no such category has none.
|
||||
sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
|
||||
filas: par.grupos.map(g => ({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
|
||||
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||
@@ -125,9 +125,11 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
||||
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
||||
const colores = paintByGroup(baseCategorias.map(c => c.grupo));
|
||||
const claves = baseCategorias.map(c => c.grupo);
|
||||
const bases = basesPorGrupo(claves);
|
||||
const colores = paintByGroup(claves);
|
||||
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map((id, i) => ({ id, etiqueta: nombres[id], color: groupBase(i) }));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], color: bases.get(id)! }));
|
||||
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
|
||||
const totals = porEscenario['totales_estrato'];
|
||||
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -173,15 +173,14 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
|
||||
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
|
||||
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
|
||||
expect(response.resumen_eeg).toMatchObject({ validadas: true, con_eeg_valido: 3, normales: 2, anormales: 1, sin_eeg: 3 });
|
||||
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 });
|
||||
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
|
||||
});
|
||||
|
||||
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
|
||||
// Pins down: the age group from the summary's episode, ADOS-2 domains whose totals add up (the page checks it),
|
||||
// the EEG analysis's checks as its report writes them (value or text, A/N, decisive), each metric's state, effects
|
||||
// and median from the code system and its observation, and one map per evaluable metric from its electrodes'
|
||||
// z-scores. Fails if the summary stops passing the page's checks or a map appears for a metric without electrodes.
|
||||
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each
|
||||
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
|
||||
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
|
||||
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);
|
||||
@@ -189,11 +188,9 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(detalle.grupo_edad).toBe('16-23 meses');
|
||||
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
|
||||
expect(detalle.eeg!.calidad).toBe('bueno');
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'line-noise')).toMatchObject({ valor: 3.5, unidad: 'dB', nivel: 'bueno', decisivo: false, electrodo: null });
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'clean-windows')).toMatchObject({ valor: 95, decisivo: true });
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'triage-level')?.valor).toBe('completo');
|
||||
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' });
|
||||
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
|
||||
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08, referencia: { min: 4.5, max: 7, mediana: 5.75 }, sin_evaluar: null });
|
||||
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 });
|
||||
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import estratoFixture from './fixtures/cama_histopatologia_birads_estrato.json';
|
||||
import generalFixture from './fixtures/cama_histopatologia_birads_general.json';
|
||||
import catalogoFixture from './fixtures/cama_catalogo_f4c.json';
|
||||
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
||||
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
@@ -21,7 +22,7 @@ import { clicHistopatologia, donaHistopatologia, estadoTasa, figuraTasas, Histop
|
||||
periodosHistopatologia, rangoTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
|
||||
|
||||
const estrato = () => structuredClone(estratoFixture) as unknown as IndicadorDatos & { filas: Record<string, any>[]; totales_estrato: Record<string, any>[]; valores_estrato: string[]; categorias: Record<string, any> };
|
||||
const fila = (d: { filas: Record<string, any>[] }, e: string, c: string) => d.filas.find(f => f['estrato'] === e && f['categoria'] === c)!;
|
||||
@@ -34,7 +35,10 @@ describe('Histopatología por BI-RADS: modelo', () => {
|
||||
expect(m.filas.map(f => f.id)).toEqual(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']);
|
||||
expect(m.filas.map(f => f.etiqueta)).toEqual(['BI-RADS 4 sin subtipo', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
|
||||
expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR']);
|
||||
expect(m.categorias.map(c => c.color)).toEqual(['#9DBFE3', '#2F6DB3', '#D9822B', '#B5482E']);
|
||||
expect(m.categorias.map(c => c.color)).toEqual([C2_PALETTE.frios[0], C2_PALETTE.frios[4], C2_PALETTE.calidos[1], C2_PALETTE.calidos[2]]);
|
||||
expect(m.grupos.map(g => g.color)).toEqual([C2_PALETTE.frios[3], C2_PALETTE.calidos[0]]);
|
||||
const tasas = figuraTasas(m, seleccionBase(m), 'claro');
|
||||
expect((tasas.data[0]['marker'] as { color: string[] }).color).toEqual([...C2_PALETTE.calidos]);
|
||||
expect(m.grupos.map(g => [g.id, g.etiqueta, g.categorias])).toEqual([
|
||||
['NO_MALIGNO', 'No maligno', ['BENIGNO', 'RIESGO_B3']], ['MALIGNO', 'Maligno', ['IN_SITU', 'INVASOR']]]);
|
||||
expect(m.base).toBe('MALIGNO');
|
||||
@@ -192,15 +196,21 @@ describe('Histopatología por BI-RADS: tasas, selección y figuras', () => {
|
||||
expect((estrecho.layout['xaxis'] as { title: { text: string }; nticks: number })).toMatchObject({ title: { text: 'Porcentaje' }, nticks: 3 });
|
||||
expect((ancho.layout['yaxis'] as Record<string, unknown>)['ticktext']).toBeUndefined();
|
||||
});
|
||||
it('dona de dos anillos: grupos dentro, categorías fuera; la selección atenúa sin cambiar valores y el centro dice «k de N con resultado»', () => {
|
||||
it('dona de dos anillos: grupos dentro, categorías fuera; la selección agranda el trozo sin cambiar el color y el centro dice «k de N con resultado»', () => {
|
||||
const m = base(), d = donaHistopatologia(m, seleccionBase(m), 'claro');
|
||||
expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
|
||||
expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias', 'grupos', 'categorias']);
|
||||
expect(d.data[1]['values']).toEqual([12, 13]); expect(d.data[2]['values']).toEqual([7, 5, 6, 7]);
|
||||
expect(d.data[4]['values']).toEqual(d.data[2]['values']);
|
||||
expect(d.data[0]['text']).toEqual(['<b>13</b><br>de 25 con resultado']);
|
||||
expect((d.data[2]['marker'] as { colors: string[] }).colors).toEqual(m.categorias.map(c => c.color));
|
||||
expect((d.data[4]['marker'] as { colors: string[] }).colors).toEqual(['rgba(0,0,0,0)', 'rgba(0,0,0,0)', m.categorias[2].color, m.categorias[3].color]);
|
||||
const baseSpan = ((d.data[2]['domain'] as { x: number[] }).x[1] - (d.data[2]['domain'] as { x: number[] }).x[0]);
|
||||
const zoomSpan = ((d.data[4]['domain'] as { x: number[] }).x[1] - (d.data[4]['domain'] as { x: number[] }).x[0]);
|
||||
expect(zoomSpan).toBeGreaterThan(baseSpan);
|
||||
const otra = donaHistopatologia(m, { grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }, 'claro');
|
||||
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
||||
const colores = (otra.data[2]['marker'] as { colors: string[] }).colors;
|
||||
expect(colores[1]).toMatch(/,1\)$/); expect(colores[0]).toMatch(/,0.3\)$/);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors).toEqual(m.categorias.map(c => c.color));
|
||||
expect((otra.data[4]['marker'] as { colors: string[] }).colors[1]).toBe(m.categorias[1].color);
|
||||
expect(otra.data[0]['text']).toEqual(['<b>5</b><br>de 25 con resultado']);
|
||||
});
|
||||
it('el histórico usa el C2 general con las seis categorías, sin necesidad del estrato', () => {
|
||||
@@ -231,7 +241,7 @@ describe('Histopatología por BI-RADS: componente', () => {
|
||||
expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO);
|
||||
r.flush(body as Record<string, unknown>); f.detectChanges();
|
||||
}
|
||||
const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
|
||||
const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.families button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
|
||||
|
||||
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
@@ -240,8 +250,11 @@ describe('Histopatología por BI-RADS: componente', () => {
|
||||
flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
|
||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
|
||||
expect([...f.nativeElement.querySelectorAll('.keys button')].map((b: Element) => b.textContent!.trim()))
|
||||
.toEqual(['No maligno', 'Maligno', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']);
|
||||
expect([...f.nativeElement.querySelectorAll('.families button')].map((b: Element) => b.textContent!.trim()))
|
||||
.toEqual(['No maligno', 'Benigno', 'Lesión de riesgo (B3)', 'Maligno', 'Carcinoma in situ', 'Carcinoma invasor']);
|
||||
expect(f.nativeElement.querySelectorAll('.family')).toHaveLength(2);
|
||||
expect([...f.nativeElement.querySelectorAll('.family')[1].querySelectorAll('button')].map((b: Element) => b.textContent!.trim()))
|
||||
.toEqual(['Maligno', 'Carcinoma in situ', 'Carcinoma invasor']);
|
||||
const grafica = f.nativeElement.querySelector('.figures') as HTMLElement;
|
||||
const seleccion = f.nativeElement.querySelector('.selection-status') as HTMLElement;
|
||||
expect(grafica.nextElementSibling?.classList.contains('legend')).toBe(true);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { C2_PALETTE, c2Color, c2Theme, tonoDe } from './indicadores-c2-palette';
|
||||
import { Celda, wilson } from './indicadores-confirmacion-citologia';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||
@@ -31,6 +31,11 @@ const APARTE_IDS: readonly string[] = APARTE.map(a => a.id);
|
||||
// The group the base view reads: the malignant results, the true positives of the suspicion.
|
||||
const CATEGORIA_BASE = 'INVASOR';
|
||||
const COLOR_RESPALDO = '#8A9199';
|
||||
// Chosen from the logo scheme: cool for a normal result, warm for an abnormal one, each slice a different hue.
|
||||
const COLOR_RESULTADO: Readonly<Record<string, string>> = {
|
||||
BENIGNO: C2_PALETTE.frios[0], RIESGO_B3: C2_PALETTE.frios[4], IN_SITU: C2_PALETTE.calidos[1], INVASOR: C2_PALETTE.calidos[2],
|
||||
};
|
||||
const COLOR_GRUPO: Readonly<Record<string, string>> = { NO_MALIGNO: C2_PALETTE.frios[3], MALIGNO: C2_PALETTE.calidos[0] };
|
||||
|
||||
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
|
||||
export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; }
|
||||
@@ -77,9 +82,16 @@ function promedio(colores: string[]): string {
|
||||
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
|
||||
.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
const ZOOM_GRUPO = 1.12;
|
||||
const ZOOM_HIJO = 1.08;
|
||||
const ZOOM_ELEGIDO = 1.16;
|
||||
const ZOOM_PADRE = 1.06;
|
||||
const CAJA_GRUPO = [0.2, 0.8, 0.2, 0.8] as const;
|
||||
const CAJA_CATEGORIA = [0.1, 0.9, 0.1, 0.9] as const;
|
||||
function caja(base: readonly [number, number, number, number], zoom: number) {
|
||||
const [x0, x1, y0, y1] = base;
|
||||
const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, hx = (x1 - x0) / 2 * zoom, hy = (y1 - y0) / 2 * zoom;
|
||||
return { x: [cx - hx, cx + hx], y: [cy - hy, cy + hy] };
|
||||
}
|
||||
|
||||
/** Validated periods of one stratified response, in request order or sorted. */
|
||||
@@ -105,15 +117,22 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
|
||||
if (Object.keys(cats).some(id => !conocidas.includes(id)) || OBLIGATORIAS.some(id => !Object.hasOwn(cats, id))) {
|
||||
return fail('El catálogo no publica las categorías esperadas de la biopsia.');
|
||||
}
|
||||
const curso = { frio: 0, calido: 0, neutro: 0 };
|
||||
const categorias: Categoria[] = CON_RESULTADO.filter(id => Object.hasOwn(cats, id)).map(id => {
|
||||
const c = cats[id];
|
||||
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && c['color'] !== undefined && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|
||||
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Categorías de biopsia incompatibles.');
|
||||
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null | undefined) ?? COLOR_RESPALDO, grupo: c['grupo'] };
|
||||
const publicado = (c['color'] as string | null | undefined) ?? COLOR_RESPALDO;
|
||||
const tono = tonoDe(c['grupo']) === 'neutro' ? tonoDe(c['etiqueta']) : tonoDe(c['grupo']);
|
||||
const asignado = c['color'] == null ? c2Color(publicado, curso[tono]++, tono) : COLOR_RESULTADO[id] ?? c2Color(publicado, curso[tono]++, tono);
|
||||
return { id, etiqueta: c['etiqueta'], color: asignado, grupo: c['grupo'] };
|
||||
});
|
||||
const grupos: GrupoCategorias[] = [...new Set(categorias.map(c => c.grupo))].map(id => {
|
||||
const propias = categorias.filter(c => c.grupo === id);
|
||||
return { id, etiqueta: id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!, color: promedio(propias.map(c => c.color)), categorias: propias.map(c => c.id) };
|
||||
const etiqueta = id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!;
|
||||
const tono = tonoDe(id) === 'neutro' ? tonoDe(etiqueta) : tonoDe(id);
|
||||
const color = COLOR_GRUPO[id] ?? (tono === 'calido' ? '#C24269' : tono === 'frio' ? '#42C29C' : promedio(propias.map(c => c.color)));
|
||||
return { id, etiqueta, color, categorias: propias.map(c => c.id) };
|
||||
});
|
||||
if (grupos.length !== 2) return fail('Se esperaban dos grupos de resultados.');
|
||||
const base = categorias.find(c => c.id === CATEGORIA_BASE)!.grupo;
|
||||
@@ -212,11 +231,14 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
|
||||
const p = c2Theme(tema);
|
||||
const valores = tasas(m, sel);
|
||||
const color = sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color;
|
||||
const tono = tonoDe(sel.categoria ?? sel.grupo);
|
||||
const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color];
|
||||
const y = valores.map(t => t.fila.etiqueta);
|
||||
const colores = sel.categoria ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
|
||||
return { data: [{
|
||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: { size: 12, color }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
||||
marker: { size: 12, color: colores }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color: colores, thickness: 2, width: 6,
|
||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||
@@ -234,7 +256,7 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Donut on the right: result groups inside, categories outside; selection dims, values stay. Empty over an incomplete matrix. */
|
||||
/** Donut on the right: groups inside, categories outside. Selection zooms those slices; colours stay. */
|
||||
export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema): PlotlyFigure {
|
||||
if (m.conResultado === null || m.conResultado === 0) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado;
|
||||
@@ -244,16 +266,30 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes con resultado, %{customdata[1]}<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
const zoomGrupo = (id: string, hijos: readonly string[]) =>
|
||||
sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1;
|
||||
const zoomCategoria = (id: string) => sel.categoria === id ? ZOOM_ELEGIDO : !sel.categoria && activos.has(id) ? ZOOM_HIJO : 1;
|
||||
const zoomDe = (values: number[]) => Math.max(1, ...values);
|
||||
const tinta = (colores: string[], zoom: number[]) => colores.map((color, i) => zoom[i] > 1 ? color : 'rgba(0,0,0,0)');
|
||||
const gruposZoom = m.grupos.map(g => zoomGrupo(g.id, g.categorias));
|
||||
const categoriasZoom = m.categorias.map(c => zoomCategoria(c.id));
|
||||
const anillo = (name: string, values: number[], labels: string[], hole: number, base: readonly [number, number, number, number], zoom: number[], colores: string[]) => ({
|
||||
...comun, ...hover, name, values, labels, hole, customdata: custom(values),
|
||||
domain: caja(base, zoomDe(zoom)),
|
||||
marker: { colors: tinta(colores, zoom), line: { color: 'rgba(0,0,0,0)', width: 0 } },
|
||||
});
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside',
|
||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con resultado`], textfont: { size: 16, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: caja(CAJA_GRUPO, 1),
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, g.categorias.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
marker: { colors: m.grupos.map(g => g.color), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
|
||||
labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: m.categorias.map(c => rgba(c.color, activos.has(c.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
marker: { colors: m.categorias.map(c => c.color), line: { color: p.background, width: 2 } } },
|
||||
anillo('grupos', interior, m.grupos.map(g => escapar(g.etiqueta)), .62, CAJA_GRUPO, gruposZoom, m.grupos.map(g => g.color)),
|
||||
anillo('categorias', exterior, m.categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, m.categorias.map(c => c.color)),
|
||||
], layout: { autosize: true, height: 360, margin: { t: 16, l: 16, r: 16, b: 16 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Covers how the history charts read each contract: what is drawn, what is shaded as suppressed, and what is
|
||||
// never turned into a number. Fixtures are synthetic rows shaped like /cama/indicadores/<id>/datos.
|
||||
import { etiquetaPeriodo, cronologico, historicoFigura } from './indicadores-historico-figures';
|
||||
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
type Fig = { data: Record<string, unknown>[]; layout: Record<string, unknown> };
|
||||
@@ -76,7 +77,7 @@ describe('Histórico: C2 (conteos por categoría)', () => {
|
||||
it('apila las categorías en el orden que publica el indicador, con sus colores y etiquetas', () => {
|
||||
const f = fig(d(completo));
|
||||
expect(f.data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
|
||||
expect((f.data[0]['marker'] as { color: string }).color).toBe('#B55A1F');
|
||||
expect((f.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.calidos[0]);
|
||||
expect(f.data[0]['y']).toEqual([4, 4, 4, 4]);
|
||||
expect(f.layout['barmode']).toBe('stack');
|
||||
expect((f.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes');
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette';
|
||||
import { sortedPeriods } from './indicadores-periodos';
|
||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||
|
||||
@@ -141,13 +141,16 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo])));
|
||||
const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1));
|
||||
const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])));
|
||||
const curso = { frio: 0, calido: 0, neutro: 0 };
|
||||
return {
|
||||
figure: { data: orden.map((id, i) => {
|
||||
const meta = record(catalogo[id]) ? catalogo[id] : {};
|
||||
const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined;
|
||||
const tono = tonoDe(typeof meta['grupo'] === 'string' ? meta['grupo'] : id);
|
||||
const slot = tono === 'neutro' ? i : curso[tono]++;
|
||||
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
|
||||
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
|
||||
marker: { color: c2Color(color, i) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
|
||||
comoLeer: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||
suprimidos, sinDato,
|
||||
|
||||
@@ -7,6 +7,8 @@ import { provideRouter, Router } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { routes } from '../../app.routes';
|
||||
import { LoginPage } from '../../auth/login-page';
|
||||
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
@@ -22,6 +24,7 @@ class ChartStub { figure?: PlotlyFigure; }
|
||||
describe('UX-04 navegación Angular', () => {
|
||||
let http: HttpTestingController;
|
||||
async function setup() {
|
||||
iniciarSesionVisual();
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
@@ -39,7 +42,14 @@ describe('UX-04 navegación Angular', () => {
|
||||
req.flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
return req;
|
||||
}
|
||||
afterEach(() => { http.verify(); vi.unstubAllGlobals(); });
|
||||
afterEach(() => { http.verify(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('sin sesión visual, /indicadores/%s presenta LoginPage y conserva returnUrl', async domain => {
|
||||
const harness = await setup();
|
||||
limpiarSesionVisual();
|
||||
await harness.navigateByUrl('/indicadores/' + domain, LoginPage);
|
||||
expect(TestBed.inject(Router).url).toBe('/login?returnUrl=%2Findicadores%2F' + domain);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('navegación %s mantiene tres enlaces, estado, decoración y foco independiente', async domain => {
|
||||
const harness = await setup();
|
||||
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { routes } from '../../app.routes';
|
||||
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import fixtureData from './fixtures/cama_seguimiento.json';
|
||||
import { CAMA_ANALYSIS_ENABLED, IndicadoresPage } from './indicadores-page';
|
||||
@@ -41,13 +42,14 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
let http: HttpTestingController;
|
||||
const corte = hoyIso();
|
||||
beforeEach(() => {
|
||||
iniciarSesionVisual();
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
|
||||
|
||||
async function entrar() {
|
||||
const harness = await RouterTestingHarness.create();
|
||||
|
||||
@@ -6,6 +6,7 @@ import { provideRouter } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { routes } from '../../app.routes';
|
||||
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresDefinitions } from './indicadores-definitions';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
@@ -24,12 +25,13 @@ const catalog: Indicador[] = [
|
||||
describe('Secciones compartidas por dominio', () => {
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
iniciarSesionVisual();
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
|
||||
|
||||
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
|
||||
const harness = await RouterTestingHarness.create();
|
||||
|
||||
@@ -43,7 +43,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
||||
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
|
||||
const cells: StratifiedCell[] = [];
|
||||
const theme = c2Theme(tema);
|
||||
const palette = seriesColors(categories.map(([, c]) => c.color));
|
||||
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
|
||||
const figure: PlotlyFigure = { data: strata.map((s, series) => {
|
||||
const selected = categories.map(([id, c]) => {
|
||||
const row = rows.get(JSON.stringify([id, s]));
|
||||
|
||||
@@ -61,23 +61,15 @@
|
||||
@if (teaData; as response) {
|
||||
<section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo">
|
||||
<h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3>
|
||||
@if (response.resumen_eeg.validadas) {
|
||||
<dl>
|
||||
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
|
||||
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
|
||||
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
|
||||
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
|
||||
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
|
||||
}
|
||||
</dl>
|
||||
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
|
||||
} @else {
|
||||
<dl>
|
||||
<div><dt>Con EEG válido</dt><dd>{{ response.resumen_eeg.con_eeg_valido }}</dd></div>
|
||||
<div><dt>Sin EEG válido</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
|
||||
</dl>
|
||||
<p>Las alteraciones del EEG se muestran cuando se validen sus curvas de referencia.</p>
|
||||
}
|
||||
<dl>
|
||||
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
|
||||
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
|
||||
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
|
||||
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
|
||||
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
|
||||
}
|
||||
</dl>
|
||||
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
|
||||
</section>
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
|
||||
@@ -12,7 +12,7 @@ import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { ALTERACIONES_EEG, EEG_VALIDO, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
|
||||
@Component({
|
||||
@@ -98,8 +98,6 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.tiposAlteracion = data.tipos_alteracion;
|
||||
// Until the alterations are validated, the EEG filter can only tell a valid EEG from none.
|
||||
this.statuses = data.resumen_eeg.validadas ? ALTERACIONES_EEG : EEG_VALIDO;
|
||||
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.draft = { ...this.applied };
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
|
||||
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacionDe(a) }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
|
||||
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacion[a.clasificacion] }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
|
||||
</div>
|
||||
@for (dom of a.dominios; track dom.codigo) {
|
||||
<div class="dominio">
|
||||
@@ -37,45 +37,39 @@
|
||||
</section>
|
||||
|
||||
<section class="panel calidad" aria-label="Calidad del EEG">
|
||||
<h3>Calidad del EEG</h3>
|
||||
<h3>Calidad del EEG @if (d.eeg) { <span class="mock">Datos de ejemplo</span> }</h3>
|
||||
@if (d.eeg; as e) {
|
||||
<p class="meta">{{ e.fecha }}@if (e.duracion_min !== null) { · {{ e.duracion_min }} min }@if (e.canales !== null) { · {{ e.canales }} canales }</p>
|
||||
<p class="meta">{{ e.fecha }} · {{ e.duracion_min }} min · {{ e.canales }} canales</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
|
||||
<small>{{ e.calidad === 'sin_analizar' ? 'El análisis del EEG aún no lo revisa.' : 'Veredicto del análisis del EEG, según las reglas siguientes.' }}</small>
|
||||
<small>La calificación general es la peor de sus criterios.</small>
|
||||
</div>
|
||||
<dl>
|
||||
@for (c of delEstudio(e); track c.codigo) {
|
||||
<dt>{{ c.etiqueta }}@if (c.decisivo) {<small> (decisiva)</small>}</dt><dd [attr.data-calidad]="c.nivel">{{ valorDe(c) }}</dd>
|
||||
@for (c of e.criterios_calidad; track c.codigo) {
|
||||
<dt>{{ c.etiqueta }}</dt><dd [attr.data-calidad]="c.nivel">{{ c.valor }} {{ c.unidad === 'canales' ? 'de ' + e.canales : c.unidad }}</dd>
|
||||
}
|
||||
</dl>
|
||||
@if (canalesMalos(e).length) {
|
||||
<p class="efectos-titulo">Canales descartados</p>
|
||||
<ul class="canales-malos">
|
||||
@for (c of canalesMalos(e); track $index) { <li><strong>{{ c.electrodo }}</strong> · {{ c.etiqueta }}</li> }
|
||||
</ul>
|
||||
}
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
|
||||
@if (d.eeg; as e) {
|
||||
<div class="alteraciones-zona" [class.abierta]="abierto(e)">
|
||||
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
|
||||
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
|
||||
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
|
||||
<p class="meta">Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.</p>
|
||||
<p class="meta">Referencia neurotípica para {{ d.grupo_edad }} y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<ul class="metricas">
|
||||
@for (m of e.alteraciones; track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado">
|
||||
<div class="metrica">
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : abierto(e) && mapaElegido === m.codigo"
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === m.codigo"
|
||||
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
|
||||
<span class="estado">{{ estado[m.estado] }}</span>
|
||||
</div>
|
||||
@if (m.referencia; as r) {
|
||||
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ r.min }}–{{ r.max }}@if (r.mediana !== null) { (mediana {{ r.mediana }}) } · z = {{ m.valor_z }}</p>
|
||||
@if (m.valor !== null) {
|
||||
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p>
|
||||
} @else {
|
||||
<p class="valor">@if (m.valor !== null) { {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</p>
|
||||
<p class="valor">Sin registro de sueño en el estudio.</p>
|
||||
}
|
||||
@if (m.efectos.length) {
|
||||
<p class="efectos-titulo">Posibles efectos asociados</p>
|
||||
@@ -88,24 +82,8 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@if (abierto(e)) {
|
||||
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
|
||||
@if (mapaActual(e) && normaActual(e)) {
|
||||
<div class="vistas" role="group" aria-label="Qué mostrar">
|
||||
<button type="button" [attr.aria-pressed]="vista === 'zonas'" (click)="verVista('zonas')">Zonas de la cabeza</button>
|
||||
<button type="button" [attr.aria-pressed]="vista === 'norma'" (click)="verVista('norma')">Norma por edad</button>
|
||||
</div>
|
||||
}
|
||||
@if (vista === 'norma' && normaActual(e); as m) {
|
||||
<h3>Norma por edad</h3>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}</p>
|
||||
@if (figuraNorma) {
|
||||
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
|
||||
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<p class="leyenda-norma">La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura).
|
||||
El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).</p>
|
||||
} @else if (mapaActual(e); as mapa) {
|
||||
@if (mapaActual(e); as mapa) {
|
||||
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas">
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
|
||||
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
|
||||
@@ -118,54 +96,9 @@
|
||||
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
|
||||
}
|
||||
</ol>
|
||||
}
|
||||
</section></div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
<section class="panel relacion" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
|
||||
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
|
||||
<p class="meta">Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se
|
||||
asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2.
|
||||
No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}</p>
|
||||
@if (!filasRelacion(rel).length) {
|
||||
<p class="sin-alteraciones">Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara con el ADOS-2 en la cohorte.</p>
|
||||
} @else {
|
||||
<div class="tabla-relacion" role="region" aria-label="Asociaciones por zona" tabindex="0">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Zona del EEG</th><th scope="col">Aspecto del ADOS-2</th><th scope="col">Asociación en la cohorte</th>
|
||||
<th scope="col">Probabilidad para este paciente</th><th scope="col">Lo que muestra su ADOS-2</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
|
||||
<tr [class.alterada]="zonaAlterada(f)">
|
||||
<td><strong>{{ 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>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
|
||||
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
|
||||
<td>
|
||||
<span class="prob">{{ porcentaje(f.probabilidad) }} %</span>
|
||||
<span class="barra" aria-hidden="true">
|
||||
<span class="paciente" [style.width.%]="porcentaje(f.probabilidad)"></span>
|
||||
<span class="referencia" [style.left.%]="porcentaje(f.probabilidad_referencia)"></span>
|
||||
</span>
|
||||
<small>{{ f.evento }} · con z = 0: {{ porcentaje(f.probabilidad_referencia) }} %</small>
|
||||
</td>
|
||||
<td>{{ observado(f) }}@if (coincide(f) !== null) { <small>{{ coincide(f) ? 'Coincide con lo que el modelo esperaba' : 'No coincide con lo que el modelo esperaba' }}</small> }</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="nota">OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La
|
||||
probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0.
|
||||
Solo se muestran las zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ h3 { margin: 0 0 .15rem; font-size: 1rem; }
|
||||
border: 2px solid var(--issste-border); border-radius: var(--issste-radius); font-size: 1.1rem; font-weight: 700; }
|
||||
.css small { margin: 0; font-size: .7rem; font-weight: 400; }
|
||||
.css[data-nivel=alto], .css[data-calidad=malo] { border-color: #B3261E; color: #B3261E; }
|
||||
.css[data-nivel=moderado], .css[data-calidad=sin_analizar] { border-color: #B26A00; color: #B26A00; }
|
||||
.css[data-nivel=moderado], .css[data-calidad=aceptable] { border-color: #B26A00; color: #B26A00; }
|
||||
.css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=bueno] { border-color: var(--issste-accent); }
|
||||
.css[data-calidad] { flex: none; white-space: nowrap; }
|
||||
dd[data-calidad=malo] { color: #B3261E; }
|
||||
@@ -23,6 +23,7 @@ button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outl
|
||||
.leyenda-mapa span { width: .8rem; height: .8rem; border-radius: 2px; }
|
||||
.leyenda-mapa .azul { background: #2166AC; }
|
||||
.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; }
|
||||
dd[data-calidad=aceptable] { color: #B26A00; }
|
||||
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; }
|
||||
.bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; }
|
||||
.bar span { display: block; height: 100%; background: var(--issste-text); }
|
||||
@@ -71,26 +72,3 @@ li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font
|
||||
.efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; }
|
||||
.efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .8rem; }
|
||||
button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; }
|
||||
|
||||
.canales-malos { margin: .25rem 0 0; padding-inline-start: 1.1rem; font-size: .85rem; }
|
||||
|
||||
// Relation with the ADOS-2 (association model): full width, a scrollable table on narrow screens.
|
||||
.relacion { grid-column: 1 / -1; }
|
||||
.tabla-relacion { overflow-x: auto; }
|
||||
.tabla-relacion table { width: 100%; min-width: 44rem; border-collapse: collapse; font-size: .85rem; }
|
||||
.tabla-relacion th, .tabla-relacion td { padding: .45rem .5rem; border-top: 1px solid var(--issste-border); text-align: start; vertical-align: top; }
|
||||
.tabla-relacion thead th { font-size: .8rem; color: var(--issste-text-secondary); font-weight: 600; }
|
||||
.tabla-relacion small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); font-size: .75rem; }
|
||||
.tabla-relacion tr.alterada td:first-child { box-shadow: inset 4px 0 0 #B3261E; }
|
||||
.tabla-relacion .marca { color: #B3261E; font-weight: 600; }
|
||||
.or, .prob { font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.barra { position: relative; display: block; height: .45rem; margin-top: .25rem; border-radius: 999px; background: var(--issste-border); }
|
||||
.barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); }
|
||||
.barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); }
|
||||
.nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); }
|
||||
// The switch between the head map and the age norm, when the metric has both.
|
||||
.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; }
|
||||
.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; }
|
||||
.vistas button + button { border-inline-start: 1px solid var(--issste-border); }
|
||||
.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; }
|
||||
.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); }
|
||||
|
||||
@@ -2,20 +2,12 @@ import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import {
|
||||
CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle,
|
||||
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
|
||||
} 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.
|
||||
const Z_ALTERADO = 2;
|
||||
import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaEegMapa, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
|
||||
const CLASIFICACION: Record<TeaAdos2['clasificacion'], string> = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' };
|
||||
// ADOS-2 calibrated severity score ranges.
|
||||
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
|
||||
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Válido', malo: 'No válido', sin_analizar: 'Sin analizar' };
|
||||
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Bueno', aceptable: 'Aceptable', malo: 'Malo' };
|
||||
const ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' };
|
||||
const INK = '#081839';
|
||||
|
||||
@@ -51,36 +43,6 @@ export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): Pl
|
||||
};
|
||||
}
|
||||
|
||||
// The age norm around the patient: the 5–95 and 25–75 percentile bands, the median line and the patient as a point.
|
||||
const BANDA_EXTERIOR = 'rgba(49,130,189,.16)', BANDA_INTERIOR = 'rgba(49,130,189,.32)', MEDIANA = '#2C6FA6', ALTERADO = '#B3261E';
|
||||
export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure {
|
||||
const c = m.curva_referencia!, x = c.edad_meses, atras = [...x].reverse();
|
||||
const banda = (bajo: number[], alto: number[], color: string, nombre: string) => ({
|
||||
type: 'scatter', mode: 'lines', x: [...x, ...atras], y: [...alto, ...[...bajo].reverse()], fill: 'toself', fillcolor: color,
|
||||
line: { width: 0 }, name: nombre, hoverinfo: 'skip',
|
||||
});
|
||||
const unidad = m.unidad ? ` ${m.unidad}` : '';
|
||||
const alterado = m.estado === 'aumentado' || m.estado === 'disminuido';
|
||||
return {
|
||||
data: [
|
||||
banda(c.p5, c.p95, BANDA_EXTERIOR, 'Del 5 al 95 %'),
|
||||
banda(c.p25, c.p75, BANDA_INTERIOR, 'Del 25 al 75 %'),
|
||||
{ type: 'scatter', mode: 'lines', x, y: c.mediana, name: 'Mediana', line: { color: MEDIANA, width: 2 },
|
||||
hovertemplate: `%{x} meses: mediana %{y:.2f}${unidad}<extra></extra>` },
|
||||
{ type: 'scatter', mode: 'markers', x: [edad], y: [m.valor], name: 'Este paciente',
|
||||
marker: { size: 11, color: alterado ? ALTERADO : INK, line: { color: '#FFFFFF', width: 2 } },
|
||||
hovertemplate: `Este paciente: %{y:.2f}${unidad} a los %{x:.1f} meses (z = ${m.valor_z})<extra></extra>` },
|
||||
],
|
||||
layout: {
|
||||
margin: { l: 52, r: 12, t: 8, b: 44 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
|
||||
showlegend: true, legend: { orientation: 'h', y: -0.28, font: { size: 11 } }, font: { color: INK },
|
||||
xaxis: { title: { text: 'Edad (meses)' }, range: [x[0], x[x.length - 1]], dtick: 6, gridcolor: 'rgba(8,24,57,.08)', fixedrange: true },
|
||||
yaxis: { title: { text: m.unidad || m.etiqueta }, gridcolor: 'rgba(8,24,57,.08)', zeroline: false, fixedrange: true },
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-tea-paciente-resumen',
|
||||
imports: [PlotlyChart],
|
||||
@@ -94,7 +56,7 @@ export class TeaPacienteResumen implements OnInit {
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
|
||||
figura?: PlotlyFigure;
|
||||
mapaElegido?: string;
|
||||
private mapaElegido?: string;
|
||||
private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
// The first solid background around this component: the map has no box of its own.
|
||||
private fondo() {
|
||||
@@ -104,30 +66,14 @@ export class TeaPacienteResumen implements OnInit {
|
||||
}
|
||||
return '#FFFFFF';
|
||||
}
|
||||
// The side panel shows the chosen metric's head map, its age norm, or both with a switch between them.
|
||||
vista: 'zonas' | 'norma' = 'zonas';
|
||||
figuraNorma?: PlotlyFigure;
|
||||
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
|
||||
// The age norm can only be drawn with the curve, the patient's value and their age.
|
||||
private conNorma(eeg: TeaEeg, codigo?: string) {
|
||||
const m = eeg.alteraciones.find(a => a.codigo === codigo);
|
||||
return m && m.curva_referencia && m.valor !== null && typeof eeg.edad_meses === 'number' ? m : undefined;
|
||||
}
|
||||
normaActual(eeg: TeaEeg) { return this.conNorma(eeg, this.mapaElegido); }
|
||||
abierto(eeg: TeaEeg) { return !!this.mapaActual(eeg) || !!this.normaActual(eeg); }
|
||||
private mostrar(eeg: TeaEeg, codigo: string | undefined) {
|
||||
const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo);
|
||||
this.mapaElegido = mapa || norma ? codigo : undefined;
|
||||
this.vista = mapa ? 'zonas' : 'norma';
|
||||
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||
this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number);
|
||||
}
|
||||
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||||
// The chosen card closes the panel again, and the cards take the whole space back.
|
||||
this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo);
|
||||
// The chosen card closes the map again, and the cards take the whole space back.
|
||||
const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo);
|
||||
this.mapaElegido = mapa?.codigo;
|
||||
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||
}
|
||||
verVista(vista: 'zonas' | 'norma') { this.vista = vista; }
|
||||
readonly clasificacion = CLASIFICACIONES_ADOS2;
|
||||
readonly clasificacion = CLASIFICACION;
|
||||
readonly nivelCss = NIVEL_CSS;
|
||||
readonly calidad = CALIDAD;
|
||||
readonly estado = ESTADO;
|
||||
@@ -136,49 +82,15 @@ export class TeaPacienteResumen implements OnInit {
|
||||
this.status.set('loading');
|
||||
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: d => {
|
||||
// Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered.
|
||||
const e = d.eeg;
|
||||
if (e) {
|
||||
const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo));
|
||||
this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo);
|
||||
} else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; }
|
||||
// Opens on the first altered metric, or on the first one if none is altered.
|
||||
const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0];
|
||||
this.mapaElegido = inicial?.codigo;
|
||||
this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined;
|
||||
this.detalle.set(d); this.status.set('ready');
|
||||
},
|
||||
error: () => this.status.set('error'),
|
||||
});
|
||||
}
|
||||
// The study-wide checks, then each bad channel.
|
||||
delEstudio(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo === null); }
|
||||
canalesMalos(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo !== null); }
|
||||
valorDe(c: TeaCriterioCalidad) {
|
||||
return c.valor === null ? '' : typeof c.valor === 'number' ? `${Math.round(c.valor * 100) / 100}${c.unidad ? ' ' + c.unidad : ''}` : c.valor;
|
||||
}
|
||||
// Why a metric couldn't be evaluated, in the reader's terms.
|
||||
sinEvaluar(m: TeaEegAlteracion) {
|
||||
return m.sin_evaluar === 'sin_valor' ? 'No se pudo medir en el estudio.' : 'Sin referencia para la edad del niño.';
|
||||
}
|
||||
clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; }
|
||||
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); }
|
||||
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
|
||||
|
||||
// Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first.
|
||||
readonly biomarcador = BIOMARCADOR;
|
||||
zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; }
|
||||
filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); }
|
||||
direccion(f: TeaRelacionAdos2) {
|
||||
return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad';
|
||||
}
|
||||
porcentaje(p: number) { return Math.round(100 * p); }
|
||||
qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; }
|
||||
observado(f: TeaRelacionAdos2) {
|
||||
if (f.observado === null) return 'Sin dato';
|
||||
if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)';
|
||||
return `CSS ${f.observado}`;
|
||||
}
|
||||
// Whether what the patient shows matches what the model leans to (above or below one half).
|
||||
coincide(f: TeaRelacionAdos2) {
|
||||
if (f.observado === null) return null;
|
||||
const presente = f.tipo === 'item' ? f.observado >= 1 : f.observado >= 8;
|
||||
return presente === (f.probabilidad >= .5);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,8 @@ import { estratoValor } from './indicadores-fhir';
|
||||
import { SeguimientoQuery } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import {
|
||||
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg,
|
||||
TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse,
|
||||
TeaSeguimientoService,
|
||||
RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad,
|
||||
teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
|
||||
} from './tea-seguimiento.service';
|
||||
|
||||
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
|
||||
@@ -20,7 +19,7 @@ interface Observation extends Resource {
|
||||
valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept;
|
||||
interpretation?: Concept[]; dataAbsentReason?: Concept;
|
||||
referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[];
|
||||
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueBoolean?: boolean; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
|
||||
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
|
||||
}
|
||||
interface Report extends Resource {
|
||||
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
|
||||
@@ -29,9 +28,6 @@ interface Metric { code?: string; display?: string; property?: { code: string; v
|
||||
|
||||
const MAX_COUNT = 200;
|
||||
const METRICAS = 'tea-eeg-metrica';
|
||||
// The EEG analysis's quality checks, under the code system of its own validation report.
|
||||
const CRITERIOS = 'urn:tea:validation';
|
||||
const FILTRO_EEG: Record<string, string> = { sin_eeg_valido: 'sin-eeg-valido' };
|
||||
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { H: 'aumentado', L: 'disminuido', N: 'normal' };
|
||||
|
||||
// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average.
|
||||
@@ -81,16 +77,10 @@ export function mapaDeElectrodos(codigo: string, etiqueta: string, valores: Reco
|
||||
return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones };
|
||||
}
|
||||
|
||||
// The module as the page writes it: `MODULO_1` is 1, the toddler module is T.
|
||||
function moduloAdos2(codigo: string | undefined): string | undefined {
|
||||
const modulo = codigo?.replace(/^ados2\.modulo\./, '');
|
||||
return modulo === 'TODDLER' ? 'T' : modulo?.replace(/^MODULO_/, '');
|
||||
}
|
||||
|
||||
export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null {
|
||||
const css = component(o, 'ados2.css')?.valueInteger;
|
||||
if (!o?.effectiveDateTime || typeof css !== 'number') return null;
|
||||
const modulo = moduloAdos2(code(component(o, 'ados2.modulo')?.valueCodeableConcept)) ?? '';
|
||||
const modulo = code(component(o, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '') ?? '';
|
||||
const clasificacion = code(component(o, 'ados2.clasificacion')?.valueCodeableConcept)?.replace('ados2.clasificacion.', '').toLowerCase();
|
||||
const items = (o.component ?? []).filter(c => extension(c, 'dominio'));
|
||||
const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => {
|
||||
@@ -106,52 +96,34 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
|
||||
return {
|
||||
fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '',
|
||||
dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0),
|
||||
clasificacion: clasificacion && Object.hasOwn(CLASIFICACIONES_ADOS2, clasificacion) ? clasificacion as TeaAdos2['clasificacion'] : null, css,
|
||||
clasificacion: (clasificacion ?? 'no_espectro') as TeaAdos2['clasificacion'], css,
|
||||
nivel_css: (RANGOS_CSS.find(r => css >= r.min && css <= r.max)?.codigo ?? 'minimo') as TeaAdos2['nivel_css'],
|
||||
};
|
||||
}
|
||||
|
||||
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
|
||||
// cover the child's age (or none is in production yet).
|
||||
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
const codigo = code(o.code) ?? '';
|
||||
const metrica = metricas.find(m => m.code === codigo);
|
||||
const valor = o.valueQuantity?.value ?? null;
|
||||
const z = component(o, 'z')?.valueQuantity?.value;
|
||||
const evaluable = valor !== null && typeof z === 'number';
|
||||
const evaluable = !o.dataAbsentReason && typeof o.valueQuantity?.value === 'number';
|
||||
const estado = evaluable ? INTERPRETACION[code(o.interpretation?.[0]) ?? ''] ?? 'normal' : 'no_evaluable';
|
||||
const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value;
|
||||
const referencia = typeof low === 'number' && typeof high === 'number'
|
||||
? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null;
|
||||
const range = o.referenceRange?.[0];
|
||||
return {
|
||||
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
|
||||
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
|
||||
referencia: evaluable ? referencia : null,
|
||||
valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
|
||||
sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
|
||||
referencia: { min: range?.low?.value ?? 0, max: range?.high?.value ?? 0 },
|
||||
valor: evaluable ? o.valueQuantity!.value! : null,
|
||||
valor_z: evaluable ? component(o, 'z')?.valueQuantity?.value ?? null : null,
|
||||
estado,
|
||||
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
// One quality check as the EEG analysis reports it: its value or reason, A/N, the bad channel's electrode, whether it
|
||||
// alone invalidates the EEG.
|
||||
function criterio(o: Observation): TeaCriterioCalidad {
|
||||
const parte = (nombre: string) => o.component?.find(c => c.code?.text === nombre);
|
||||
return {
|
||||
codigo: codeIn(o.code, CRITERIOS)!, etiqueta: display(o.code) ?? codeIn(o.code, CRITERIOS)!,
|
||||
valor: o.valueQuantity?.value ?? o.valueString ?? null, unidad: o.valueQuantity?.unit ?? '',
|
||||
nivel: code(o.interpretation?.[0]) === 'A' ? 'malo' : 'bueno',
|
||||
electrodo: parte('electrode')?.valueString ?? null, decisivo: parte('decisive')?.valueBoolean === true,
|
||||
};
|
||||
}
|
||||
|
||||
// The study EEG of `report`, with the observations it lists and the electrode maps of its metrics.
|
||||
export function eegDeReporte(report: Report | undefined, observations: Observation[], metricas: Metric[]): TeaEeg | null {
|
||||
if (!report?.effectiveDateTime) return null;
|
||||
const ids = new Set((report.result ?? []).map(r => referenceId(r)));
|
||||
const listed = observations.filter(o => ids.has(o.id));
|
||||
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
|
||||
const duracion = extension(report, 'duracion-min')?.valueDecimal;
|
||||
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'MALO').toLowerCase() as TeaNivelCalidad;
|
||||
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS)).map(o => alteracion(o, metricas));
|
||||
// A metric's electrode values are `electrodos-<the metric observation's id>`.
|
||||
const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length)))
|
||||
@@ -163,10 +135,14 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
.filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable'));
|
||||
return {
|
||||
fecha: report.effectiveDateTime.slice(0, 10),
|
||||
duracion_min: duracion === undefined ? null : Math.round(duracion),
|
||||
canales: extension(report, 'canales')?.valueInteger ?? null,
|
||||
duracion_min: Math.round(extension(report, 'duracion-min')?.valueDecimal ?? 0),
|
||||
canales: extension(report, 'canales')?.valueInteger ?? 0,
|
||||
calidad: calidad(report.conclusionCode?.[0]),
|
||||
criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
|
||||
criterios_calidad: listed.filter(o => code(o.code)?.startsWith('eeg.calidad_')).map(o => ({
|
||||
codigo: code(o.code)!.replace('eeg.calidad_', ''), etiqueta: display(o.code) ?? '',
|
||||
valor: o.valueInteger ?? o.valueQuantity?.value ?? 0, unidad: typeof o.valueInteger === 'number' ? 'canales' : o.valueQuantity?.unit ?? '',
|
||||
nivel: calidad(o.interpretation?.[0]),
|
||||
})),
|
||||
alteraciones, mapas,
|
||||
ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) },
|
||||
};
|
||||
@@ -190,7 +166,7 @@ export function pacienteDeEpisodio(episode: Resource, included: Resource[], vali
|
||||
const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined;
|
||||
const ados2 = byCode(observations, 'ados2');
|
||||
const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined;
|
||||
const modulo = moduloAdos2(code(component(ados2, 'ados2.modulo')?.valueCodeableConcept));
|
||||
const modulo = code(component(ados2, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '');
|
||||
return {
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
@@ -245,7 +221,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
const corte = query.corte ?? isoDay(this.today());
|
||||
const { desde, hasta } = ventana(corte, query.meses);
|
||||
let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta);
|
||||
if (query.estatus) params = params.set('resultado-eeg', FILTRO_EEG[query.estatus] ?? query.estatus);
|
||||
if (query.estatus) params = params.set('resultado-eeg', query.estatus);
|
||||
if (query.grupo_edad) params = params.set('grupo-edad', grupoCodigo(query.grupo_edad));
|
||||
const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css);
|
||||
if (mchat) params = params.append('mchat', 'ge' + mchat.min).append('mchat', 'le' + mchat.max);
|
||||
@@ -272,7 +248,6 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)),
|
||||
tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [],
|
||||
resumen_eeg: {
|
||||
validadas, con_eeg_valido: validadas ? parameter(resumen, 'normales') + parameter(resumen, 'anormales') : parameter(resumen, 'con_eeg_valido'),
|
||||
normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'),
|
||||
por_alteracion: porAlteracion(resumen, metricas),
|
||||
},
|
||||
@@ -286,11 +261,12 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
}).pipe(map(({ bundle, metricas }) => {
|
||||
const all = resources(bundle);
|
||||
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
|
||||
const episode = resources(bundle, 'EpisodeOfCare')[0];
|
||||
const metric = observations.find(o => codeIn(o.code, METRICAS) && o.referenceRange?.[0]?.text);
|
||||
const edad = metric?.referenceRange?.[0]?.text?.split(': ').pop();
|
||||
return teaPacienteDetalle({
|
||||
simulado: all.length > 0 && all.every(isSimulated),
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
grupo_edad: grupoEdad(edad),
|
||||
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
|
||||
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
|
||||
}, id);
|
||||
|
||||
@@ -4,8 +4,7 @@ import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
|
||||
// The EEG filter: by alteration once the domain expert has validated them, otherwise only by a valid EEG or none.
|
||||
export type AlteracionesEeg = 'normal' | 'anormal' | 'valido' | 'sin_eeg_valido';
|
||||
export type AlteracionesEeg = 'normal' | 'anormal';
|
||||
export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo';
|
||||
export interface TeaSeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
@@ -13,7 +12,7 @@ export interface TeaSeguimientoPaciente {
|
||||
ultimo_eeg: string | null;
|
||||
mchat: number | null;
|
||||
css_ados2: number | null;
|
||||
alteraciones_eeg: 'normal' | 'anormal' | null;
|
||||
alteraciones_eeg: AlteracionesEeg | null;
|
||||
modulo_ados2: string | null;
|
||||
estado_caso: EstadoCaso;
|
||||
// What a case in process still lacks.
|
||||
@@ -22,9 +21,6 @@ export interface TeaSeguimientoPaciente {
|
||||
alteraciones: string[];
|
||||
}
|
||||
export interface TeaResumenEeg {
|
||||
// Without validated alterations only the split by a valid EEG is known: `normales`, `anormales` and `por_alteracion`
|
||||
// stay empty.
|
||||
validadas: boolean; con_eeg_valido: number;
|
||||
normales: number; anormales: number; sin_eeg: number;
|
||||
por_alteracion: { codigo: string; etiqueta: string; n: number }[];
|
||||
}
|
||||
@@ -39,60 +35,28 @@ export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: nu
|
||||
export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] }
|
||||
export interface TeaAdos2 {
|
||||
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
|
||||
clasificacion: ClasificacionAdos2 | null; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||||
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||||
}
|
||||
export type ClasificacionAdos2 = 'autismo' | 'espectro_autista' | 'no_espectro' | 'preocupacion_leve_moderada' | 'preocupacion_severa';
|
||||
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
|
||||
// EEG metrics against age baselines and their associated effects, both pending medical validation.
|
||||
export type TeaNivelCalidad = 'bueno' | 'malo' | 'sin_analizar';
|
||||
// One quality check of the EEG analysis: a study-wide rule, or a bad channel with its electrode and reason.
|
||||
export interface TeaCriterioCalidad {
|
||||
codigo: string; etiqueta: string; valor: number | string | null; unidad: string; nivel: 'bueno' | 'malo';
|
||||
electrodo: string | null; decisivo: boolean;
|
||||
}
|
||||
// Mock: EEG metrics with placeholder reference ranges and associated effects, pending medical review.
|
||||
export type TeaNivelCalidad = 'bueno' | 'aceptable' | 'malo';
|
||||
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
|
||||
export interface TeaEegAlteracion {
|
||||
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number; mediana: number | null } | null;
|
||||
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number };
|
||||
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
|
||||
// Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age.
|
||||
sin_evaluar: 'sin_valor' | 'sin_referencia' | null;
|
||||
// The age norm the reference comes from (percentiles by month), when the analysis sends it.
|
||||
curva_referencia?: TeaCurvaReferencia | null;
|
||||
}
|
||||
export interface TeaCurvaReferencia {
|
||||
fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[];
|
||||
}
|
||||
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
|
||||
export interface TeaEeg {
|
||||
fecha: string; duracion_min: number | null; canales: number | null;
|
||||
// Age at the EEG, to place the patient on the age norms.
|
||||
edad_meses?: number | null;
|
||||
// The overall rating is the EEG analysis's verdict; its checks say why.
|
||||
calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[];
|
||||
fecha: string; duracion_min: number; canales: number;
|
||||
// The overall rating is in words, like Automagic, and is the worst of its criteria, which report numbers.
|
||||
calidad: TeaNivelCalidad; criterios_calidad: { codigo: string; etiqueta: string; valor: number; unidad: string; nivel: TeaNivelCalidad }[];
|
||||
alteraciones: TeaEegAlteracion[];
|
||||
// One map per alteration that could be evaluated, on shared axes.
|
||||
mapas: TeaEegMapa[];
|
||||
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
|
||||
}
|
||||
// The association model (OR) of each EEG alteration by zone with an ADOS-2 item or domain, fitted on the cohort; for
|
||||
// this patient, their z, the probability the model gives them and what their ADOS-2 shows. Pending medical validation.
|
||||
export interface TeaRelacionAdos2 {
|
||||
biomarcador: string; zona: string; zona_etiqueta: string; valor_z: number;
|
||||
tipo: 'item' | 'dominio'; resultado: string; resultado_etiqueta: string; evento: string;
|
||||
or: number; ic_inf: number; ic_sup: number; q: number;
|
||||
probabilidad: number; probabilidad_referencia: number; observado: number | null;
|
||||
}
|
||||
export interface TeaRelacionModelo { validado: boolean; nivel: 'item' | 'dominio'; n_cohorte: number; version: string; filas: TeaRelacionAdos2[] }
|
||||
export interface TeaPacienteDetalle {
|
||||
simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null;
|
||||
// Absent until the WebApi serves the model.
|
||||
relacion_ados2?: TeaRelacionModelo | null;
|
||||
}
|
||||
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null }
|
||||
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
|
||||
export const CLASIFICACIONES_ADOS2: Record<ClasificacionAdos2, string> = {
|
||||
autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro',
|
||||
preocupacion_leve_moderada: 'Preocupación leve a moderada', preocupacion_severa: 'Preocupación de moderada a severa',
|
||||
};
|
||||
export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' };
|
||||
export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses'];
|
||||
// M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary.
|
||||
@@ -107,22 +71,15 @@ export const RANGOS_CSS = [
|
||||
{ codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 },
|
||||
{ codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 },
|
||||
];
|
||||
export const ALTERACIONES_EEG: SeguimientoStatus[] = [
|
||||
{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' },
|
||||
];
|
||||
export const EEG_VALIDO: SeguimientoStatus[] = [{ codigo: 'valido', etiqueta: 'Con EEG válido' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' }];
|
||||
export const ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }];
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
|
||||
const filtroEeg = (v: unknown) => v === null || ['normal', 'anormal', 'valido', 'sin_eeg_valido'].includes(v as string);
|
||||
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
|
||||
// ADOS-2 item codes: 0 to 3, and 7 to 9 for an item that doesn't apply or wasn't scored.
|
||||
const CODIGOS_REACTIVO = [0, 1, 2, 3, 7, 8, 9];
|
||||
const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string');
|
||||
function validResumenEeg(r: unknown): boolean {
|
||||
return record(r) && typeof r['validadas'] === 'boolean' && integer(r['con_eeg_valido'])
|
||||
&& integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
|
||||
return record(r) && integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
|
||||
&& r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n']));
|
||||
}
|
||||
export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
|
||||
@@ -131,7 +88,7 @@ export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || !filtroEeg(filters['alteraciones_eeg'])
|
||||
|| !record(filters) || !eeg(filters['alteraciones_eeg'])
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
|
||||
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
|
||||
@@ -149,52 +106,33 @@ const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
|
||||
const text = (v: unknown) => typeof v === 'string' && v.length > 0;
|
||||
function validAdos(a: unknown): boolean {
|
||||
if (a === null) return true;
|
||||
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || typeof a['algoritmo'] !== 'string' || !score(a['css'], 1, 10)
|
||||
|| !(a['clasificacion'] === null || Object.hasOwn(CLASIFICACIONES_ADOS2, a['clasificacion'] as string))
|
||||
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || !text(a['algoritmo']) || !score(a['css'], 1, 10)
|
||||
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string)
|
||||
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
|
||||
// Items carry an ADOS-2 code (algorithm 0–2); each domain and the total must be the sum of their parts.
|
||||
// Items score 0–3 (algorithm 0–2); each domain and the total must be the sum of their parts.
|
||||
const dominios = a['dominios'] as unknown[];
|
||||
const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos'])
|
||||
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && CODIGOS_REACTIVO.includes(r['puntaje'] as number) && score(r['puntaje_algoritmo'], 0, 2))
|
||||
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && score(r['puntaje'], 0, 3) && score(r['puntaje_algoritmo'], 0, 2))
|
||||
&& d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0)
|
||||
&& d['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
|
||||
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
|
||||
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
|
||||
}
|
||||
// An age norm: ages in increasing order and, at each one, percentiles that never cross.
|
||||
const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const;
|
||||
function validCurva(c: unknown): boolean {
|
||||
if (c === undefined || c === null) return true;
|
||||
if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false;
|
||||
const edades = c['edad_meses'] as unknown[], n = edades.length;
|
||||
if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false;
|
||||
const series = PERCENTILES.map(k => c[k]);
|
||||
return series.every(s => Array.isArray(s) && s.length === n && s.every(finite))
|
||||
&& edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i]));
|
||||
}
|
||||
// A metric that can't be evaluated says why and has no z; one that can has its value, z and reference.
|
||||
// A metric without a value cannot be evaluated; one with a value is out of range exactly when it is altered.
|
||||
function validAlteracion(a: unknown): boolean {
|
||||
const ref = a !== null && record(a) ? a['referencia'] : undefined;
|
||||
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string'
|
||||
|| !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number)
|
||||
&& (ref['mediana'] === null || finite(ref['mediana'])))
|
||||
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false;
|
||||
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !record(a['referencia'])
|
||||
|| !finite(a['referencia']['min']) || !finite(a['referencia']['max']) || (a['referencia']['min'] as number) > (a['referencia']['max'] as number)
|
||||
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false;
|
||||
const estado = a['estado'];
|
||||
if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string)
|
||||
&& (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null);
|
||||
return finite(a['valor']) && finite(a['valor_z']) && ref !== null && a['sin_evaluar'] === null
|
||||
&& ['normal', 'aumentado', 'disminuido'].includes(estado as string);
|
||||
if (estado === 'no_evaluable') return a['valor'] === null && a['valor_z'] === null;
|
||||
return finite(a['valor']) && finite(a['valor_z']) && ['normal', 'aumentado', 'disminuido'].includes(estado as string);
|
||||
}
|
||||
function validEeg(e: unknown): boolean {
|
||||
if (e === null) return true;
|
||||
const optional = (v: unknown) => v === null || integer(v);
|
||||
const edad = record(e) ? e['edad_meses'] : undefined;
|
||||
if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales'])
|
||||
|| !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0)
|
||||
|| !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string)
|
||||
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta'])
|
||||
&& ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean'
|
||||
&& (c['electrodo'] === null || text(c['electrodo'])) && (c['valor'] === null || finite(c['valor']) || text(c['valor'])))) return false;
|
||||
const nivel = (v: unknown) => ['bueno', 'aceptable', 'malo'].includes(v as string);
|
||||
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad'])
|
||||
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad'])
|
||||
&& (c['unidad'] === 'canales' ? integer(c['valor']) && (c['valor'] as number) <= (e['canales'] as number) : finite(c['valor']) && (c['valor'] as number) >= 0))) return false;
|
||||
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
|
||||
const ejes = e['ejes_mapa'];
|
||||
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
|
||||
@@ -205,21 +143,9 @@ function validEeg(e: unknown): boolean {
|
||||
&& m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
|
||||
&& Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z'])));
|
||||
}
|
||||
const probability = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 1;
|
||||
function validRelacion(r: unknown): boolean {
|
||||
if (r === undefined || r === null) return true;
|
||||
return record(r) && typeof r['validado'] === 'boolean' && ['item', 'dominio'].includes(r['nivel'] as string)
|
||||
&& integer(r['n_cohorte'], 1) && text(r['version']) && Array.isArray(r['filas'])
|
||||
&& r['filas'].every(f => record(f) && text(f['biomarcador']) && text(f['zona_etiqueta']) && finite(f['valor_z'])
|
||||
&& ['item', 'dominio'].includes(f['tipo'] as string) && text(f['resultado_etiqueta']) && text(f['evento'])
|
||||
&& finite(f['or']) && finite(f['ic_inf']) && finite(f['ic_sup']) && (f['ic_inf'] as number) <= (f['ic_sup'] as number)
|
||||
&& probability(f['q']) && probability(f['probabilidad']) && probability(f['probabilidad_referencia'])
|
||||
&& (f['observado'] === null || finite(f['observado'])));
|
||||
}
|
||||
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])
|
||||
|| !validRelacion(v['relacion_ados2']))
|
||||
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']))
|
||||
throw new Error('Resumen del paciente inválido');
|
||||
return v as unknown as TeaPacienteDetalle;
|
||||
}
|
||||
|
||||
@@ -13,14 +13,13 @@ const data = {
|
||||
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
|
||||
items: [item, { ...item, id_seudonimo: 'T-0002', ultimo_eeg: null, mchat: null, css_ados2: null, alteraciones_eeg: null, modulo_ados2: null, estado_caso: 'fuera_protocolo', pendientes: [], alteraciones: [] }],
|
||||
tipos_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior' }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos' }],
|
||||
resumen_eeg: { validadas: true, con_eeg_valido: 4, normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] },
|
||||
resumen_eeg: { normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] },
|
||||
};
|
||||
const reactivo = (codigo: string, puntaje: number) => ({ codigo, etiqueta: 'Reactivo ' + codigo, puntaje, puntaje_algoritmo: Math.min(puntaje, 2) });
|
||||
const metrica = (codigo: string, etiqueta: string, extra: object) => ({
|
||||
codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2, mediana: 1.5 }, efectos: [], sin_evaluar: null, ...extra });
|
||||
const metrica = (codigo: string, etiqueta: string, extra: object) => ({ codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2 }, efectos: [], ...extra });
|
||||
const alteraciones = [
|
||||
metrica('ritmo_posterior', 'Ritmo posterior', { valor: 0.9, valor_z: -2.4, estado: 'disminuido', efectos: ['Ritmo más lento de lo esperado para la edad.'] }),
|
||||
metrica('husos_sueno_n2', 'Husos de sueño N2', { valor: null, valor_z: null, estado: 'no_evaluable', referencia: null, sin_evaluar: 'sin_valor' }),
|
||||
metrica('husos_sueno_n2', 'Husos de sueño N2', { valor: null, valor_z: null, estado: 'no_evaluable' }),
|
||||
metrica('husos_sueno_n3', 'Husos de sueño N3', { valor: 1.4, valor_z: 0.2, estado: 'normal' }),
|
||||
metrica('picos_paroxisticos', 'Picos paroxísticos', { valor: 1.5, valor_z: 0.3, estado: 'normal' }),
|
||||
metrica('gradiente_anteroposterior', 'Gradiente anteroposterior', { valor: 1.2, valor_z: -0.4, estado: 'normal' }),
|
||||
@@ -31,12 +30,8 @@ const detalle = {
|
||||
ados2: { fecha: '2026-08-23', modulo: '1', algoritmo: 'Pocas o ninguna palabra', total: 5, total_maximo: 8, clasificacion: 'no_espectro', css: 3, nivel_css: 'bajo',
|
||||
dominios: [{ codigo: 'AS', etiqueta: 'Afecto social', puntaje: 4, maximo: 4, reactivos: [reactivo('A2', 3), reactivo('B1', 2)] },
|
||||
{ codigo: 'CRR', etiqueta: 'Comportamiento restringido y repetitivo', puntaje: 1, maximo: 4, reactivos: [reactivo('D1', 1), reactivo('D2', 0)] }] },
|
||||
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'bueno',
|
||||
criterios_calidad: [
|
||||
{ codigo: 'clean-windows', etiqueta: 'Ventanas limpias', valor: 95, unidad: '%', nivel: 'bueno', electrodo: null, decisivo: true },
|
||||
{ codigo: 'line-noise', etiqueta: 'Ruido de la línea eléctrica', valor: 48, unidad: 'dB', nivel: 'malo', electrodo: null, decisivo: false },
|
||||
{ codigo: 'dead-channel', etiqueta: 'Canal muerto', valor: 'dead channel', unidad: '', nivel: 'malo', electrodo: 'T3', decisivo: false },
|
||||
],
|
||||
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'aceptable',
|
||||
criterios_calidad: [{ codigo: 'amplitud', etiqueta: 'Canales con amplitud extrema', valor: 1, unidad: 'canales', nivel: 'bueno' }, { codigo: 'linea', etiqueta: 'Ruido de la línea eléctrica', valor: 8, unidad: 'dB', nivel: 'aceptable' }],
|
||||
alteraciones,
|
||||
mapas: [mapa('ritmo_posterior', 'Ritmo posterior (puntuación z)', 'Central'), mapa('picos_paroxisticos', 'Picos paroxísticos (puntuación z)', 'Occipital')],
|
||||
ejes_mapa: { x: [-1, 0, 1], y: [-1, 0, 1], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } },
|
||||
@@ -80,7 +75,7 @@ describe('Seguimiento TEA', () => {
|
||||
expect(root.querySelector('input[type=date]')).not.toBeNull();
|
||||
const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!;
|
||||
expect(select.closest('label')?.textContent).toContain('Alteraciones EEG');
|
||||
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal', 'Sin EEG válido']);
|
||||
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal']);
|
||||
fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 };
|
||||
fixture.componentInstance.apply();
|
||||
const filtered = request();
|
||||
@@ -172,41 +167,6 @@ describe('Seguimiento TEA', () => {
|
||||
expect(root.querySelector('section.mapa')).not.toBeNull();
|
||||
http.verify();
|
||||
});
|
||||
it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => {
|
||||
const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48],
|
||||
p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] };
|
||||
const conCurva = detalle.eeg.alteraciones.map(m =>
|
||||
m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m);
|
||||
const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } };
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges();
|
||||
const panel = () => root.querySelector('section.mapa')!;
|
||||
const vistas = () => panel().querySelectorAll<HTMLButtonElement>('.vistas button');
|
||||
// Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age.
|
||||
expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']);
|
||||
expect(panel().textContent).toContain('Zonas más afectadas');
|
||||
vistas()[1].click(); fixture.detectChanges();
|
||||
expect(vistas()[1].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad');
|
||||
expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)');
|
||||
expect(panel().querySelector('.regiones')).toBeNull();
|
||||
// Gradiente has no map: its card opens the norm alone, without the switch.
|
||||
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
|
||||
tarjetas[4].click(); fixture.detectChanges();
|
||||
expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true');
|
||||
expect(vistas().length).toBe(0);
|
||||
expect(panel().textContent).toContain('Gradiente anteroposterior');
|
||||
const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance;
|
||||
const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[];
|
||||
expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']);
|
||||
expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]);
|
||||
const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m);
|
||||
expect(() => teaPacienteDetalle({ ...conNorma, eeg: { ...conNorma.eeg, alteraciones: cruzada } }, 'T-0001')).toThrow();
|
||||
http.verify();
|
||||
});
|
||||
it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => {
|
||||
const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo);
|
||||
const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor;
|
||||
@@ -258,7 +218,7 @@ describe('Seguimiento TEA', () => {
|
||||
const panel = root.querySelector('#tea-detalle-T-0002')!;
|
||||
expect(panel.textContent).toContain('CSS 3');
|
||||
expect(panel.textContent).toContain('Afecto social (AS)');
|
||||
expect(panel.textContent).toContain('Válido');
|
||||
expect(panel.textContent).toContain('Aceptable');
|
||||
// Opens with the map of the first altered metric.
|
||||
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
// Item scores start collapsed.
|
||||
@@ -268,7 +228,7 @@ describe('Seguimiento TEA', () => {
|
||||
expect(metricas.textContent).toContain('Disminuido');
|
||||
expect(metricas.textContent).toContain('Posibles efectos asociados');
|
||||
expect(metricas.textContent).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||
expect(metricas.textContent).toContain('No se pudo medir en el estudio.');
|
||||
expect(metricas.textContent).toContain('Sin registro de sueño en el estudio.');
|
||||
expect(Array.from(metricas.querySelectorAll('.nombre')).map(n => n.textContent)).toEqual(
|
||||
['Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', 'Gradiente anteroposterior']);
|
||||
expect(metricas.textContent).not.toContain('Sin alteraciones en las métricas evaluadas.');
|
||||
@@ -309,29 +269,6 @@ describe('Seguimiento TEA', () => {
|
||||
expect(root.querySelector('#tea-detalle-T-0002')?.textContent).toContain('No se pudo cargar el resumen del paciente.');
|
||||
http.verify();
|
||||
});
|
||||
it('admite las clasificaciones del módulo T, una sin clasificar y los códigos de reactivo que no aplican', () => {
|
||||
const ados2 = detalle.ados2;
|
||||
for (const clasificacion of ['preocupacion_leve_moderada', 'preocupacion_severa', null]) {
|
||||
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...ados2, clasificacion } }, 'T-0001')).not.toThrow();
|
||||
}
|
||||
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...ados2, clasificacion: 'dudoso' } }, 'T-0001')).toThrow();
|
||||
const [as, crr] = ados2.dominios;
|
||||
const noAplica = { ...ados2, dominios: [{ ...as, reactivos: [{ ...as.reactivos[0], puntaje: 8, puntaje_algoritmo: 2 }, as.reactivos[1]] }, crr] };
|
||||
expect(() => teaPacienteDetalle({ ...detalle, ados2: noAplica }, 'T-0001')).not.toThrow();
|
||||
});
|
||||
it('sin alteraciones validadas resume y filtra solo por EEG válido', () => {
|
||||
const fixture = open();
|
||||
const sinValidar = { ...data, resumen_eeg: { validadas: false, con_eeg_valido: 2, normales: 0, anormales: 0, sin_eeg: 1, por_alteracion: [] } };
|
||||
request().flush(sinValidar); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const resumen = root.querySelector('.resumen-eeg')!;
|
||||
expect(Array.from(resumen.querySelectorAll('dt')).map(d => d.textContent)).toEqual(['Con EEG válido', 'Sin EEG válido']);
|
||||
expect(Array.from(resumen.querySelectorAll('dd')).map(d => d.textContent)).toEqual(['2', '1']);
|
||||
const opciones = Array.from(root.querySelectorAll<HTMLOptionElement>('select[name="estatus"] option')).map(o => o.textContent!.trim());
|
||||
expect(opciones).toContain('Con EEG válido');
|
||||
expect(opciones).not.toContain('Anormal');
|
||||
http.verify();
|
||||
});
|
||||
it('valida que los puntajes ADOS-2 sumen y que el mapa sea rectangular', () => {
|
||||
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle({ ...detalle, simulado: false }, 'T-0001')).toThrow();
|
||||
@@ -342,27 +279,25 @@ describe('Seguimiento TEA', () => {
|
||||
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapas: [{ ...detalle.eeg.mapas[0], z: [[0, 0]] }] } }, 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow();
|
||||
});
|
||||
it('la calidad es el veredicto del análisis, con sus reglas y los canales descartados, y se valida', () => {
|
||||
it('la calidad general es una palabra, sus criterios son números y se validan', () => {
|
||||
const fixture = open();
|
||||
request().flush(tres); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||
const panel = root.querySelector('section.calidad')!;
|
||||
const texto = (n: Element) => n.textContent!.replace(/\s+/g, ' ').trim();
|
||||
expect(texto(panel.querySelector('.css')!)).toBe('Válido');
|
||||
expect(Array.from(panel.querySelectorAll('dt, dd')).map(texto)).toEqual(['Ventanas limpias (decisiva)', '95 %', 'Ruido de la línea eléctrica', '48 dB']);
|
||||
expect(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('malo');
|
||||
expect(Array.from(panel.querySelectorAll('.canales-malos li')).map(texto)).toEqual(['T3 · Canal muerto']);
|
||||
expect(panel.querySelector('.css')!.textContent!.trim()).toBe('Aceptable');
|
||||
expect(Array.from(panel.querySelectorAll('dt, dd')).map(n => n.textContent)).toEqual(['Canales con amplitud extrema', '1 de 19', 'Ruido de la línea eléctrica', '8 dB']);
|
||||
expect(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('aceptable');
|
||||
expect(panel.textContent).not.toMatch(/Impedancia|Artefactos|de 100/);
|
||||
const conCriterios = (criterios_calidad: unknown) => ({ ...detalle, eeg: { ...detalle.eeg, criterios_calidad } });
|
||||
expect(() => teaPacienteDetalle(conCriterios(undefined), 'T-0001')).toThrow();
|
||||
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: '', nivel: 'bueno', electrodo: null, decisivo: false };
|
||||
expect(() => teaPacienteDetalle(conCriterios([criterio, { ...criterio, valor: 'completo' }, { ...criterio, valor: null }]), 'T-0001')).not.toThrow();
|
||||
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: 'canales', nivel: 'bueno' };
|
||||
expect(() => teaPacienteDetalle(conCriterios([criterio]), 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, nivel: 'regular' }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, decisivo: 'si' }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, electrodo: '' }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: null }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: 20 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'buena' } }, 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'sin_analizar', duracion_min: null, canales: null } }, 'T-0001')).not.toThrow();
|
||||
http.verify();
|
||||
});
|
||||
it('valida las alteraciones del EEG', () => {
|
||||
@@ -371,35 +306,8 @@ describe('Seguimiento TEA', () => {
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], estado: 'alto' }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], valor: null }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3 }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3, sin_evaluar: 'sin_referencia' }), 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], sin_evaluar: 'sin_valor' }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], referencia: { min: 3, max: 1 } }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow();
|
||||
});
|
||||
// The association model's panel (prototype, simulated data): the field is optional and checked when present.
|
||||
it('valida la relación con el ADOS-2 y solo muestra las zonas alteradas del paciente', () => {
|
||||
const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa',
|
||||
resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002,
|
||||
probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 };
|
||||
const otra = { ...fila, zona: 'parietal', zona_etiqueta: 'Parietal', valor_z: 0.4, q: 0.01 };
|
||||
const rel = (filas: object[]) => ({ ...detalle, relacion_ados2: { validado: false, nivel: 'item', n_cohorte: 46, version: 'v', filas } });
|
||||
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle({ ...detalle, relacion_ados2: null }, 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([fila]), 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, probabilidad: 1.2 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, ic_inf: 0.5 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, tipo: 'zona' }]), 'T-0001')).toThrow();
|
||||
const fixture = open();
|
||||
request().flush(tres); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges();
|
||||
const filas = Array.from(root.querySelectorAll('section.relacion tbody tr'));
|
||||
expect(filas.length).toBe(1);
|
||||
expect(filas[0].classList.contains('alterada')).toBe(true);
|
||||
expect(filas[0].textContent).toContain('q < 0.001');
|
||||
expect(filas[0].textContent).toContain('93 %');
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
|
||||
@if (patientState() === 'listo') {
|
||||
<article class="card"><h3>ADOS-2</h3>@if (ados(); as ados) { <p>Fecha: {{ ados.effectiveDateTime }}</p><dl>@for (c of ados.component; track $index) { <div><dt>{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}</dt><dd>{{ componentValue(c) }}</dd></div> }</dl> } @else { <p>Sin información de ADOS-2.</p> }</article>
|
||||
<article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}@if (electrode(o); as e) { · {{ e }} }</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article>
|
||||
<article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article>
|
||||
@if (alterationsAvailable() && alterations().length) { <article class="card"><h3>Métricas del EEG</h3><dl>@for (o of alterations(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }}</dd></div> }</dl></article> }
|
||||
}
|
||||
</section>
|
||||
|
||||
@@ -174,14 +174,12 @@ export class TeaStatusPage implements OnDestroy {
|
||||
}
|
||||
ados() { return this.patientResources().find(r => r.resourceType === 'Observation' && code(r.code) === 'ados2'); }
|
||||
eeg() { return this.patientResources().find(r => r.resourceType === 'DiagnosticReport' && code(r.code) === 'eeg'); }
|
||||
eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : quality === 'SIN_ANALIZAR' ? 'Sin analizar' : 'Sin dato'; }
|
||||
eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : 'Sin dato'; }
|
||||
eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; }
|
||||
// The EEG analysis's checks: A is out of range, N within.
|
||||
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'N' ? 'dentro de rango' : value === 'A' ? 'fuera de rango' : 'sin dato'; }
|
||||
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && r.code?.coding?.[0]?.system === 'urn:tea:validation'); }
|
||||
electrode(o: Resource): string | undefined { return o.component?.find((c: Resource) => c.code?.text === 'electrode')?.valueString; }
|
||||
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'BUENO' ? 'buena' : value === 'MALO' ? 'mala' : 'sin dato'; }
|
||||
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && code(r.code).startsWith('eeg.calidad_')); }
|
||||
alterationsAvailable() { return this.measures().some(m => m.id.startsWith('M30-')); }
|
||||
alterations() { return this.patientResources().filter(r => r.resourceType === 'Observation' && r.code?.coding?.[0]?.system?.endsWith('/tea-eeg-metrica') && !r.id?.startsWith('electrodos-')); }
|
||||
componentValue(c: Resource) { return c.valueInteger ?? c.valueString ?? (text(c.valueCodeableConcept) || 'Sin dato'); }
|
||||
observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim() : o.valueString ?? 'Sin dato'); }
|
||||
observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}` : 'Sin dato'); }
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<div class="experiments">
|
||||
<div class="experiments__toolbar">
|
||||
<mat-button-toggle-group hideSingleSelectionIndicator [value]="domain()" (change)="setDomain($event.value)" aria-label="Dominio">
|
||||
@for (option of domains; track option.id) {
|
||||
@for (option of domains(); track option.id) {
|
||||
<mat-button-toggle [value]="option.id">{{ option.label }}</mat-button-toggle>
|
||||
}
|
||||
</mat-button-toggle-group>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DatePipe } from '@angular/common';
|
||||
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
|
||||
import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
@@ -10,6 +10,8 @@ import { MatTableModule } from '@angular/material/table';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { Subscription, timer } from 'rxjs';
|
||||
import { apiErrorMessage } from '../../../connect/api/api.types';
|
||||
import { AuthService } from '../../../auth/auth.service';
|
||||
import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios';
|
||||
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
|
||||
import { GovernanceApi } from '../../api/governance.api';
|
||||
import { Experiment, ExperimentDetail, ExperimentStatus } from '../../api/governance.types';
|
||||
@@ -36,11 +38,16 @@ const POLL_MS = 5000;
|
||||
})
|
||||
export class ExperimentsPanel implements OnInit {
|
||||
readonly api = inject(GovernanceApi);
|
||||
private readonly auth = inject(AuthService);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
readonly domains = [{ id: null, label: 'Todos' }, ...DOMAINS.map((d) => ({ id: d.id as string | null, label: d.label }))];
|
||||
readonly domain = signal<string | null>(null);
|
||||
/** Only the account's domains; «Todos» only when it reaches all of them. */
|
||||
readonly domains = computed<{ id: string | null; label: string }[]>(() => [
|
||||
...(alcanzaTodos(this.auth, DOMAINS) ? [{ id: null, label: 'Todos' }] : []),
|
||||
...dominiosPermitidos(this.auth, DOMAINS).map((d) => ({ id: d.id as string | null, label: d.label })),
|
||||
]);
|
||||
readonly domain = signal<string | null>(dominioInicial(this.auth, DOMAINS));
|
||||
readonly experiments = signal<Experiment[]>([]);
|
||||
readonly details = signal<Record<string, ExperimentDetail>>({});
|
||||
readonly loading = signal(false);
|
||||
@@ -57,6 +64,7 @@ export class ExperimentsPanel implements OnInit {
|
||||
}
|
||||
|
||||
setDomain(domain: string | null): void {
|
||||
if (domain !== null && !this.auth.puedeVer(domain)) return;
|
||||
this.domain.set(domain);
|
||||
this.reload();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<div class="models">
|
||||
<div class="models__toolbar">
|
||||
<mat-button-toggle-group hideSingleSelectionIndicator [value]="domain()" (change)="setDomain($event.value)" aria-label="Dominio">
|
||||
@for (option of domains; track option.id) {
|
||||
@for (option of domains(); track option.id) {
|
||||
<mat-button-toggle [value]="option.id">{{ option.label }}</mat-button-toggle>
|
||||
}
|
||||
</mat-button-toggle-group>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DatePipe } from '@angular/common';
|
||||
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
|
||||
import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
@@ -11,6 +11,8 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
|
||||
import { AuthService } from '../../../auth/auth.service';
|
||||
import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios';
|
||||
import { apiErrorMessage } from '../../../connect/api/api.types';
|
||||
import { GovernanceApi } from '../../api/governance.api';
|
||||
import { ModelVersion } from '../../api/governance.types';
|
||||
@@ -45,12 +47,17 @@ const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
|
||||
})
|
||||
export class ModelVersionsPanel implements OnInit {
|
||||
private readonly api = inject(GovernanceApi);
|
||||
private readonly auth = inject(AuthService);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
readonly domains = [{ id: null, label: 'Todos' }, ...DOMAINS.map((d) => ({ id: d.id as string | null, label: d.label }))];
|
||||
readonly domain = signal<string | null>(null);
|
||||
/** Only the account's domains; «Todos» only when it reaches all of them. */
|
||||
readonly domains = computed<{ id: string | null; label: string }[]>(() => [
|
||||
...(alcanzaTodos(this.auth, DOMAINS) ? [{ id: null, label: 'Todos' }] : []),
|
||||
...dominiosPermitidos(this.auth, DOMAINS).map((d) => ({ id: d.id as string | null, label: d.label })),
|
||||
]);
|
||||
readonly domain = signal<string | null>(dominioInicial(this.auth, DOMAINS));
|
||||
readonly versions = signal<ModelVersion[]>([]);
|
||||
readonly loading = signal(false);
|
||||
readonly loadError = signal<string | null>(null);
|
||||
@@ -63,6 +70,7 @@ export class ModelVersionsPanel implements OnInit {
|
||||
}
|
||||
|
||||
setDomain(domain: string | null): void {
|
||||
if (domain !== null && !this.auth.puedeVer(domain)) return;
|
||||
this.domain.set(domain);
|
||||
this.reload();
|
||||
}
|
||||
|
||||
+3
-3
@@ -10,15 +10,15 @@
|
||||
<mat-icon aria-hidden="true">upload_file</mat-icon>
|
||||
<span>Cargar información</span>
|
||||
</a>
|
||||
<a class="home__action home__action--secondary" routerLink="/indicadores">
|
||||
<a class="home__action" routerLink="/indicadores">
|
||||
<mat-icon aria-hidden="true">insights</mat-icon>
|
||||
<span>Indicadores</span>
|
||||
</a>
|
||||
<a class="home__action home__action--secondary" routerLink="/bitacora">
|
||||
<a class="home__action" routerLink="/bitacora">
|
||||
<mat-icon aria-hidden="true">fact_check</mat-icon>
|
||||
<span>Bitácora de cargas</span>
|
||||
</a>
|
||||
<a class="home__action home__action--secondary" routerLink="/gobernanza">
|
||||
<a class="home__action" routerLink="/gobernanza">
|
||||
<mat-icon aria-hidden="true">verified</mat-icon>
|
||||
<span>Gobernanza de modelos</span>
|
||||
</a>
|
||||
|
||||
+6
-14
@@ -54,8 +54,8 @@ h1 {
|
||||
.home__action {
|
||||
align-items: center;
|
||||
text-decoration: none;
|
||||
background: #f8f9fa;
|
||||
border: 1px solid #e9ecef;
|
||||
background: transparent;
|
||||
border: 1px solid var(--color-action);
|
||||
border-radius: 8px;
|
||||
color: var(--color-text);
|
||||
cursor: pointer;
|
||||
@@ -72,9 +72,10 @@ h1 {
|
||||
transform 0.2s ease;
|
||||
}
|
||||
|
||||
/* The four actions share one look: the first one used to be the filled variant. */
|
||||
.home__action:hover {
|
||||
background: #e9ecef;
|
||||
border-color: #5f9ea0;
|
||||
background: var(--color-action-hover);
|
||||
border-color: var(--color-action);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
@@ -88,18 +89,9 @@ h1 {
|
||||
}
|
||||
|
||||
.home__action mat-icon {
|
||||
color: #5f9ea0;
|
||||
color: var(--color-action);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.home__action--secondary {
|
||||
background: transparent;
|
||||
border-color: #5f9ea0;
|
||||
}
|
||||
|
||||
.home__action--secondary:hover {
|
||||
background: #f1f6f6;
|
||||
}
|
||||
.steps {
|
||||
align-items: center;
|
||||
color: var(--color-text-secondary);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { AfterViewInit, Component, inject, ElementRef, Input, OnChanges, OnDestr
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||
import { recolorFigure } from '../../features/indicadores/indicadores-c2-palette';
|
||||
import { PlotlyController } from './plotly-controller';
|
||||
import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
|
||||
@@ -68,12 +69,12 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
||||
this.observer = new ResizeObserver(this.windowResize);
|
||||
this.observer.observe(this.host.nativeElement);
|
||||
} else window.addEventListener('resize', this.windowResize);
|
||||
this.controller.setFigure(this.figure);
|
||||
this.controller.setFigure(recolorFigure(this.figure));
|
||||
// Also supply the initial width in browsers without ResizeObserver.
|
||||
this.windowResize();
|
||||
}
|
||||
ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); }
|
||||
retry() { this.controller?.setFigure(this.figure); }
|
||||
ngOnChanges() { if (this.figure) this.controller?.setFigure(recolorFigure(this.figure)); }
|
||||
retry() { this.controller?.setFigure(recolorFigure(this.figure)); }
|
||||
ngOnDestroy() {
|
||||
this.observer?.disconnect();
|
||||
if (this.widthFrame !== undefined) cancelAnimationFrame(this.widthFrame);
|
||||
|
||||
@@ -280,6 +280,10 @@ describe('PlotlyController transiciones opcionales', () => {
|
||||
expect(dimmed.data[1]['values']).toEqual([4, 6]); expect(dimmed.data[1]['text']).toEqual(['4', '6']);
|
||||
expect((dimmed.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']);
|
||||
expect(pieFrame(pie([4, 6]), pie([4, 6]), .5).data[1]).toEqual(pie([4, 6]).data[1]);
|
||||
const grown = pieFrame({ ...pie([4, 6]), data: pie([4, 6]).data.map(t => ({ ...t, pull: [0, 0] })) },
|
||||
{ ...pie([4, 6]), data: pie([4, 6]).data.map(t => ({ ...t, pull: [0, 0.12] })) }, .5);
|
||||
expect(grown.data[1]['pull']).toEqual([0, 0.06]);
|
||||
expect(grown.data[1]['text']).toEqual(['4', '6']);
|
||||
});
|
||||
it('la dona interpola en varios react sin ocultar el host ni pasar por carga, y termina en la figura exacta', async () => {
|
||||
const c = controller();
|
||||
|
||||
@@ -27,6 +27,25 @@ function mixColor(from: unknown, to: unknown, t: number): unknown {
|
||||
return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${+v[3].toFixed(3)})`;
|
||||
}
|
||||
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => typeof n === 'number' && Number.isFinite(n));
|
||||
function mixDomain(from: unknown, to: unknown, t: number): { x: number[]; y: number[] } | undefined {
|
||||
const read = (value: unknown) => {
|
||||
if (!value || typeof value !== 'object') return undefined;
|
||||
const x = (value as { x?: unknown }).x, y = (value as { y?: unknown }).y;
|
||||
if (!numbers(x) || !numbers(y) || x.length !== 2 || y.length !== 2) return undefined;
|
||||
return { x, y };
|
||||
};
|
||||
const start = read(from), end = read(to);
|
||||
if (!start || !end) return undefined;
|
||||
if (start.x.every((v, i) => v === end.x[i]) && start.y.every((v, i) => v === end.y[i])) return undefined;
|
||||
const mix = (a: number[], b: number[]) => b.map((v, i) => a[i] + (v - a[i]) * t);
|
||||
return { x: mix(start.x, end.x), y: mix(start.y, end.y) };
|
||||
}
|
||||
function mixPull(from: unknown, to: unknown, length: number, t: number): number[] | undefined {
|
||||
const start = from === undefined ? Array<number>(length).fill(0) : from;
|
||||
const end = to === undefined ? Array<number>(length).fill(0) : to;
|
||||
if (!numbers(start) || !numbers(end) || start.length !== length || end.length !== length || start.every((v, i) => v === end[i])) return undefined;
|
||||
return end.map((v, i) => start[i] + (v - start[i]) * t);
|
||||
}
|
||||
/** Pies cannot use layout.transition: both figures must have the same pies and value shapes. */
|
||||
export function piesInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean {
|
||||
return to.data.length > 0 && from.data.length === to.data.length && to.data.every((trace, i) => {
|
||||
@@ -46,12 +65,16 @@ export function pieFrame(from: PlotlyFigure, to: PlotlyFigure, t: number): Plotl
|
||||
const marker = trace['marker'] as Record<string, unknown> | undefined;
|
||||
const oldColors = oldMarker?.['colors'], colors = marker?.['colors'];
|
||||
const sameValues = a.every((v, j) => v === b[j]);
|
||||
const clear = (list: unknown) => Array.isArray(list) && list.some(c => typeof c === 'string' && /,\s*0\)$/.test(c));
|
||||
const mixColors = !!marker && Array.isArray(colors) && Array.isArray(oldColors) && oldColors.length === colors.length
|
||||
&& colors.some((c, j) => c !== oldColors[j]);
|
||||
if (sameValues && !mixColors && !moving) return trace;
|
||||
&& !clear(colors) && !clear(oldColors) && colors.some((c, j) => c !== oldColors[j]);
|
||||
const pull = mixPull(from.data[i]['pull'], trace['pull'], b.length, t);
|
||||
const domain = mixDomain(from.data[i]['domain'], trace['domain'], t);
|
||||
if (sameValues && !mixColors && !moving && !pull && !domain) return trace;
|
||||
// Geometry is illustrative until the exact target render. Hide all clinical
|
||||
// readouts (including the centre) and never attach counts to moving slices.
|
||||
return { ...trace, ...(sameValues ? {} : { values: b.map((v, j) => a[j] + (v - a[j]) * t) }),
|
||||
...(pull ? { pull } : {}), ...(domain ? { domain } : {}),
|
||||
...(moving ? { text: b.map(() => ''), textinfo: 'none', texttemplate: '',
|
||||
hoverinfo: 'skip', hovertemplate: null, hovertext: [], customdata: [] } : {}),
|
||||
...(mixColors ? { marker: { ...marker, colors: (colors as unknown[]).map((c, j) => mixColor((oldColors as unknown[])[j], c, t)) } } : {}) };
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
--color-surface: #ffffff;
|
||||
--color-border: #e3e7df;
|
||||
--color-step: #f0f3e8;
|
||||
/* Action controls (home buttons, sign in, sign out): the theme's teal border
|
||||
and the tint it takes under the pointer. */
|
||||
--color-action: #5f9ea0;
|
||||
--color-action-hover: #f1f6f6;
|
||||
--font-body: 'Roboto', sans-serif;
|
||||
--font-heading: 'Rajdhani', 'Roboto Condensed', 'Arial Narrow', sans-serif;
|
||||
--site-header-height: 72px;
|
||||
|
||||
Reference in New Issue
Block a user