Compare commits
127 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e1a8127c22 | |||
| 6de193f44e | |||
| 0059427179 | |||
| 8192f92be9 | |||
| 1fef7812b4 | |||
| 6465165e34 | |||
| a26df55214 | |||
| 72e5f9bf93 | |||
| 08f1d812ac | |||
| ce207a72a5 | |||
| 5094880622 | |||
| 093ceffa36 | |||
| 6a7c1d0cbd | |||
| fb5a4ed5cc | |||
| e8ce7a487b | |||
| a3a552ad0e | |||
| fb54cfb188 | |||
| 7adceb86bf | |||
| 4e9b25bd8f | |||
| a7b5f4c50b | |||
| 4d159ae0d0 | |||
| 4fba4fa861 | |||
| db4d743413 | |||
| d6c52c8536 | |||
| 1969ffdb5f | |||
| 699d4b13e1 | |||
| c5cbaaab13 | |||
| cc802cbb57 | |||
| e7a6398168 | |||
| 62027f2216 | |||
| 88dc7537c2 | |||
| 0cb9395cd6 | |||
| e74e3d8fd4 | |||
| 0fc80bd29a | |||
| dae8bc517e | |||
| 68e2930e65 | |||
| bb957ec6a4 | |||
| 02e28e624b | |||
| 08161db1c4 | |||
| fa029d69b8 | |||
| 67ae7f482f | |||
| 304c563845 | |||
| efe4404c4e | |||
| 7d180417d8 | |||
| 00f773dd75 | |||
| 3bb1c8dd84 | |||
| ef4f606648 | |||
| 54b3e50ca5 | |||
| 680cc0adc6 | |||
| b53322ed72 | |||
| c32d2b6012 | |||
| 7aa3d2c6e6 | |||
| c2c6d9ef47 | |||
| d4d3ea3837 | |||
| 3385df4ba3 | |||
| 96b1cabb5a | |||
| 366591f247 | |||
| 241631b884 | |||
| 6c063344a3 | |||
| 2f5b1ce1f2 | |||
| 56b3ac6b0c | |||
| f6603ae76e | |||
| 21ae95b5ed | |||
| ce2e86c045 | |||
| 0f8eb0ec94 | |||
| 2f6d419453 | |||
| f34f9e1607 | |||
| c7dd134fce | |||
| 03cc9c9800 | |||
| 04795a09cc | |||
| de3d247d0d | |||
| ee87bcb8d0 | |||
| aaeea7a7b0 | |||
| 7f17681409 | |||
| d72c18756f | |||
| baf5edca42 | |||
| fefa28ae7a | |||
| a217ddae38 | |||
| 97fcb37761 | |||
| 58ff3870be | |||
| 439a039ff4 | |||
| 049a9ca43c | |||
| f128f2e13a | |||
| 20b8c80aaf | |||
| 8e85c91f15 | |||
| 1ac8d5c258 | |||
| 23cd89e882 | |||
| 47a0ab5f1b | |||
| dc37c54938 | |||
| 2834fac85c | |||
| be77c50b45 | |||
| 40d8c8655e | |||
| 4ffd3797b6 | |||
| b42428b068 | |||
| d9009a2e1e | |||
| bb2f49be37 | |||
| b68af3a48a | |||
| 7eb144e8fe | |||
| c509cb7f87 | |||
| 5807f218b1 | |||
| 4d67b019a6 | |||
| 934a793da3 | |||
| e6abf44bef | |||
| 0ee53fd286 | |||
| 62cdb252ca | |||
| 8f2906fe6f | |||
| e8628508d8 | |||
| 53edec8692 | |||
| a1ea31039e | |||
| ef631e2c0b | |||
| 27dc7a0166 | |||
| e6353f9f4c | |||
| 3bb9c2121d | |||
| 737c6f9f14 | |||
| 8e543cbcc6 | |||
| ea7aad5067 | |||
| 09b52e6b0a | |||
| 078db53ae4 | |||
| 957f4cd024 | |||
| 1ce8d98663 | |||
| 1771cb7ec6 | |||
| b74f188b15 | |||
| 5196f20e47 | |||
| 5d4cd6f654 | |||
| a05717f92d | |||
| 123232592f | |||
| 2cbb994667 |
@@ -62,6 +62,17 @@
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
},
|
||||
"simulado": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true,
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/app/app.config.ts",
|
||||
"with": "src/app/app.config.simulado.ts"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "production"
|
||||
@@ -77,6 +88,10 @@
|
||||
},
|
||||
"development": {
|
||||
"buildTarget": "WebApp:build:development"
|
||||
},
|
||||
"simulado": {
|
||||
"buildTarget": "WebApp:build:simulado",
|
||||
"proxyConfig": "simulado/proxy.simulado.json"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 717 B |
@@ -0,0 +1,38 @@
|
||||
# Modo simulado (solo nuestra copia local, rama `ulises/tea-seguimiento`)
|
||||
|
||||
Para ver y modificar la página de seguimiento de TEA sin la plataforma completa ni su preproceso.
|
||||
Todo es **inventado**. No forma parte de la WebApp que se entrega.
|
||||
|
||||
| Archivo | Qué es |
|
||||
|---|---|
|
||||
| `datos_tea.json` | 120 niños inventados: lista, ficha y la relación con el ADOS-2 (modelo de OR de E27). Se genera; no se versiona |
|
||||
| `servidor.py` | Servidor de prueba (Python, sin instalar nada) en `localhost:5051` |
|
||||
| `proxy.simulado.json` | Las rutas de la API, al servidor de prueba |
|
||||
| `../src/app/app.config.simulado.ts` | Igual que `app.config.ts`, pero el seguimiento de TEA lee el contrato JSON (`/tea/seguimiento`) |
|
||||
|
||||
## Cómo se usa
|
||||
|
||||
1. Generar los datos (una vez, o cuando cambie el modelo), desde `biomarcadores-tea/`:
|
||||
```
|
||||
python experimentos/E27_modelo_or/simulado_plataforma.py
|
||||
```
|
||||
2. Levantar el servidor de prueba, desde `webapp-tea/`:
|
||||
```
|
||||
python simulado/servidor.py
|
||||
```
|
||||
3. En otra terminal, la página, desde `webapp-tea/`:
|
||||
```
|
||||
npx ng serve --configuration simulado --port 4300
|
||||
```
|
||||
4. Abrir `http://localhost:4300/indicadores/tea`, entrar a **Seguimiento** y abrir un paciente.
|
||||
|
||||
## El panel nuevo: «Relación con el ADOS-2»
|
||||
|
||||
En la ficha del paciente (`tea-paciente-resumen.*`) muestra, por cada asociación clara de la cohorte (q < 0.05):
|
||||
- la zona del EEG y el z del paciente, marcada si está alterada (|z| ≥ 2);
|
||||
- el aspecto del ADOS-2 (reactivo o dominio);
|
||||
- el OR de la cohorte con su intervalo y su q;
|
||||
- la probabilidad que el modelo da a este paciente (con su edad y módulo) frente a la de un niño con z = 0;
|
||||
- lo que muestra su ADOS-2.
|
||||
|
||||
El campo `relacion_ados2` es opcional: sin él (la plataforma real hoy), el panel no aparece.
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"/api": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/imports": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/data": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/health": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/cacu": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/cama": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/tea": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/governance": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
},
|
||||
"/reportes": {
|
||||
"target": "http://localhost:5051",
|
||||
"secure": false,
|
||||
"changeOrigin": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
servidor.py — Servidor de prueba con datos SIMULADOS para ver la página de TEA sin la plataforma completa.
|
||||
|
||||
Solo para nuestra copia local (rama ulises/tea-seguimiento): no forma parte de la WebApp que se entrega.
|
||||
Responde lo que pide la sección de seguimiento de TEA en su contrato JSON:
|
||||
- `/tea/seguimiento`: la lista, con filtros y páginas;
|
||||
- `/tea/seguimiento/<id>`: la ficha, incluido el campo nuevo `relacion_ados2`.
|
||||
|
||||
A lo demás de `/tea/...` contesta vacío, para que la página cargue.
|
||||
|
||||
Los datos los escribe `biomarcadores-tea/experimentos/E27_modelo_or/simulado_plataforma.py` en `datos_tea.json`.
|
||||
|
||||
python simulado/servidor.py # http://localhost:5051
|
||||
npx ng serve --configuration simulado --port 4300
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from datetime import date, timedelta
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, unquote, urlparse
|
||||
|
||||
PUERTO = 5051
|
||||
DATOS = json.loads((Path(__file__).with_name("datos_tea.json")).read_text(encoding="utf-8"))
|
||||
VACIO_FHIR = {"resourceType": "Bundle", "type": "searchset", "total": 0, "entry": []}
|
||||
|
||||
|
||||
def _num(q, k):
|
||||
v = q.get(k, [None])[0]
|
||||
try:
|
||||
return float(v) if v is not None else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def lista(q: dict) -> dict:
|
||||
meses = int(q.get("meses", ["12"])[0]) if q.get("meses", ["12"])[0] in ("1", "3", "6", "12") else 12
|
||||
corte = q.get("corte", [date.today().isoformat()])[0]
|
||||
page = max(1, int(q.get("page", ["1"])[0]))
|
||||
size = min(200, max(1, int(q.get("page_size", ["25"])[0])))
|
||||
filtro = q.get("alteraciones_eeg", [None])[0]
|
||||
ps = DATOS["pacientes"]
|
||||
if filtro in ("normal", "anormal"):
|
||||
ps = [p for p in ps if p["alteraciones_eeg"] == filtro]
|
||||
elif filtro == "sin_eeg_valido":
|
||||
ps = [p for p in ps if p["ultimo_eeg"] is None]
|
||||
if q.get("grupo_edad"):
|
||||
ps = [p for p in ps if p["grupo_edad"].startswith(q["grupo_edad"][0].replace("_", "-"))]
|
||||
for campo, lo, hi in (("mchat", "mchat_min", "mchat_max"), ("css_ados2", "css_min", "css_max")):
|
||||
a, b = _num(q, lo), _num(q, hi)
|
||||
if a is not None:
|
||||
ps = [p for p in ps if p[campo] is not None and a <= p[campo] <= (b if b is not None else 99)]
|
||||
if q.get("estado_caso"):
|
||||
ps = [p for p in ps if p["estado_caso"] == q["estado_caso"][0]]
|
||||
if q.get("alteracion"):
|
||||
ps = [p for p in ps if q["alteracion"][0] in p["alteraciones"]]
|
||||
total = len(ps)
|
||||
por_alt = [{"codigo": t["codigo"], "etiqueta": t["etiqueta"], "n": sum(t["codigo"] in p["alteraciones"] for p in ps)}
|
||||
for t in DATOS["tipos_alteracion"]]
|
||||
hasta = date.fromisoformat(corte)
|
||||
return {
|
||||
"simulado": True, "corte": corte,
|
||||
"ventana": {"meses": meses, "desde": (hasta - timedelta(days=30 * meses)).isoformat(), "hasta": corte},
|
||||
"filtros": {"alteraciones_eeg": filtro},
|
||||
"paginacion": {"page": page, "page_size": size, "total_items": total, "total_pages": max(1, math.ceil(total / size))},
|
||||
"items": ps[(page - 1) * size: page * size],
|
||||
"tipos_alteracion": DATOS["tipos_alteracion"],
|
||||
"resumen_eeg": {"validadas": True, "con_eeg_valido": total,
|
||||
"normales": sum(p["alteraciones_eeg"] == "normal" for p in ps),
|
||||
"anormales": sum(p["alteraciones_eeg"] == "anormal" for p in ps), "sin_eeg": 0,
|
||||
"por_alteracion": por_alt},
|
||||
}
|
||||
|
||||
|
||||
class Manejador(BaseHTTPRequestHandler):
|
||||
def _json(self, cuerpo, codigo=200):
|
||||
datos = json.dumps(cuerpo, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(codigo)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(datos)))
|
||||
self.end_headers()
|
||||
self.wfile.write(datos)
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
u = urlparse(self.path)
|
||||
ruta, q = u.path.rstrip("/"), parse_qs(u.query)
|
||||
if ruta == "/tea/seguimiento":
|
||||
return self._json(lista(q))
|
||||
if ruta.startswith("/tea/seguimiento/"):
|
||||
d = DATOS["detalles"].get(unquote(ruta.rsplit("/", 1)[1]))
|
||||
return self._json(d) if d else self._json({"error": "no encontrado"}, 404)
|
||||
if "/fhir/" in ruta:
|
||||
return self._json(VACIO_FHIR)
|
||||
if ruta.endswith("/indicadores"):
|
||||
return self._json([])
|
||||
if ruta == "/health":
|
||||
return self._json({"status": "ok", "simulado": True})
|
||||
return self._json({"error": "sin datos simulados para esta ruta"}, 404)
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
sys.stderr.write(" " + fmt % args + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"Servidor simulado en http://localhost:{PUERTO} ({len(DATOS['pacientes'])} niños inventados)")
|
||||
ThreadingHTTPServer(("127.0.0.1", PUERTO), Manejador).serve_forever()
|
||||
@@ -37,10 +37,11 @@ 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) => {
|
||||
it.each([['tea', 'Trastorno del espectro autista'], ['cacu', 'Cáncer cervicouterino'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
|
||||
await ir('/indicadores/' + dominio);
|
||||
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
|
||||
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
|
||||
@@ -59,7 +60,7 @@ describe('Encabezado del marco', () => {
|
||||
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
|
||||
await ir('/indicadores/cama');
|
||||
const items = await abrirMenu();
|
||||
expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']);
|
||||
expect(items.map(a => a.textContent?.trim())).toEqual(['Trastorno del espectro autista', 'Cáncer cervicouterino']);
|
||||
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
|
||||
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
|
||||
});
|
||||
@@ -68,7 +69,7 @@ describe('Encabezado del marco', () => {
|
||||
const items = await abrirMenu();
|
||||
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(router.url).toBe('/indicadores/cacu');
|
||||
expect(selector()!.textContent).toContain('CaCu');
|
||||
expect(selector()!.textContent).toContain('Cáncer cervicouterino');
|
||||
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
|
||||
const ubicacion = TestBed.inject(Location);
|
||||
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
|
||||
@@ -79,7 +80,8 @@ describe('Encabezado del marco', () => {
|
||||
await ir(url);
|
||||
expect(selector()).toBeNull();
|
||||
expect(root().querySelector('.platform-title')).toBeNull();
|
||||
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
|
||||
expect(root().querySelector('.site-header__section')).toBeNull();
|
||||
expect(root().querySelector('.site-header__nav')?.textContent).not.toContain('Análisis de información');
|
||||
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
|
||||
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { routes } from './app.routes';
|
||||
import { IndicadoresService } from './features/indicadores/indicadores.service';
|
||||
import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos';
|
||||
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
|
||||
|
||||
// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento
|
||||
// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`).
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
||||
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
||||
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
|
||||
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
|
||||
]
|
||||
};
|
||||
@@ -2,11 +2,23 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/
|
||||
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 { TeaSeguimientoService } from './features/indicadores/tea-seguimiento.service';
|
||||
import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir';
|
||||
import { FhirTeaSeguimientoService } from './features/indicadores/tea-seguimiento-fhir';
|
||||
|
||||
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`).
|
||||
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
|
||||
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
|
||||
{ provide: TeaSeguimientoService, useClass: FhirTeaSeguimientoService },
|
||||
]
|
||||
};
|
||||
|
||||
+41
-23
@@ -1,33 +1,51 @@
|
||||
<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">
|
||||
@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
-25
@@ -1,37 +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: '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: '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: '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' },
|
||||
// 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: '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: '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: '' },
|
||||
];
|
||||
|
||||
+69
-19
@@ -41,14 +41,6 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.site-header__section {
|
||||
text-decoration: none;
|
||||
color: var(--color-text);
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
@@ -89,11 +81,6 @@
|
||||
width: clamp(132px, 42vw, 170px);
|
||||
}
|
||||
|
||||
.site-header__section {
|
||||
font-size: 13px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.site-footer__content {
|
||||
min-height: 76px;
|
||||
padding: 0 20px;
|
||||
@@ -117,12 +104,75 @@
|
||||
|
||||
.domain-selector--espera {
|
||||
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
|
||||
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||
max-width: 100%; background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; line-height: 1.2;
|
||||
min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||
}
|
||||
|
||||
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
||||
@media (max-width: 599px) {
|
||||
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
||||
.app-shell--indicadores .brand { margin-inline-end: auto; }
|
||||
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
|
||||
/* 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;
|
||||
}
|
||||
|
||||
// Full domain names need their own track. On a wide header they sit beside the title;
|
||||
// below 900px the name takes a row of its own so the logo and the exit stay together.
|
||||
.app-shell--indicadores .site-header__content {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto auto;
|
||||
grid-template-areas: "brand title domain salir";
|
||||
align-items: center;
|
||||
column-gap: 16px;
|
||||
row-gap: 8px;
|
||||
padding-block: 8px;
|
||||
}
|
||||
.app-shell--indicadores .brand { grid-area: brand; }
|
||||
.app-shell--indicadores .platform-title { grid-area: title; margin: 0; overflow-wrap: normal; }
|
||||
.app-shell--indicadores .domain-selector,
|
||||
.app-shell--indicadores .domain-selector--espera { grid-area: domain; justify-self: end; }
|
||||
.app-shell--indicadores .site-header__salir { grid-area: salir; margin-inline-start: 0; }
|
||||
@media (max-width: 900px) {
|
||||
.app-shell--indicadores .site-header__content {
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
grid-template-areas:
|
||||
"brand salir"
|
||||
"domain domain"
|
||||
"title title";
|
||||
}
|
||||
.app-shell--indicadores .domain-selector,
|
||||
.app-shell--indicadores .domain-selector--espera { justify-self: start; white-space: normal; }
|
||||
.app-shell--indicadores .platform-title { font-size: 1.125rem; }
|
||||
}
|
||||
|
||||
+105
-25
@@ -1,46 +1,126 @@
|
||||
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('home shows only the brand name as eyebrow and names the risk models action', async () => {
|
||||
// Fails if the eyebrow regains the section text or the action goes back to «Indicadores».
|
||||
const page = await render('/');
|
||||
expect(page.querySelector('.home__eyebrow')?.textContent?.trim()).toBe('ISSSTELEON');
|
||||
const acciones = Array.from(page.querySelectorAll('.home__action')).map(a => a.textContent?.replace(/\s+/g, ' ').trim());
|
||||
expect(acciones.some(t => t?.endsWith('Modelos predictivos de riesgo'))).toBe(true);
|
||||
expect(acciones.some(t => t?.endsWith('Indicadores'))).toBe(false);
|
||||
});
|
||||
|
||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||
const page = await render('/conectar');
|
||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||
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('Cáncer cervicouterino');
|
||||
});
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+25
-3
@@ -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,13 +33,32 @@ 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' };
|
||||
protected readonly domainLabels: Record<Dominio, string> = {
|
||||
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
|
||||
};
|
||||
private readonly url = toSignal(this.router.events.pipe(
|
||||
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
|
||||
/** On an indicators page the header names its domain and switches to the others. */
|
||||
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 : '/';
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,8 @@ export interface PreviewResponse {
|
||||
/** Sub-tables the source offers (Excel sheets...), with the options to read each. */
|
||||
tables?: { name: string; options: Record<string, unknown>; kind: string }[];
|
||||
source_metadata?: Record<string, unknown>;
|
||||
/** Columns whose sampled cells hold files (PDF, images) that can be read as documents. */
|
||||
document_columns?: string[];
|
||||
}
|
||||
|
||||
export interface FileOptions {
|
||||
@@ -134,6 +136,56 @@ export interface ImportSourcePayload extends SourceLocator {
|
||||
label?: string;
|
||||
column_mapping: Record<string, string>;
|
||||
defaults?: Record<string, unknown>;
|
||||
derived?: Record<string, DerivationRule>;
|
||||
documents?: DocumentColumnsConfig;
|
||||
/** Also store, on the patient, captions the documents print that the project's catalog already knows. */
|
||||
catalog_fallback?: boolean;
|
||||
}
|
||||
|
||||
// Derived fields and document columns
|
||||
|
||||
export type DerivationParamKind = 'column' | 'columns' | 'text' | 'integer' | 'mapping' | 'boolean';
|
||||
|
||||
export interface DerivationParam {
|
||||
name: string;
|
||||
kind: DerivationParamKind;
|
||||
label: string;
|
||||
required: boolean;
|
||||
default: unknown;
|
||||
}
|
||||
|
||||
/** One operation a derived field may use, as `/imports/derivations` lists it. */
|
||||
export interface DerivationSpec {
|
||||
op: string;
|
||||
label: string;
|
||||
description: string;
|
||||
params: DerivationParam[];
|
||||
}
|
||||
|
||||
export interface DerivationCatalog {
|
||||
derivations: DerivationSpec[];
|
||||
cases: string[];
|
||||
}
|
||||
|
||||
/** `{op, ...params, case?}`: how one target field is computed from source columns. */
|
||||
export type DerivationRule = { op: string; case?: string } & Record<string, unknown>;
|
||||
|
||||
/** A grouping or naming given as a column, a list of columns or a rule. */
|
||||
export type ColumnRule = string | string[] | DerivationRule;
|
||||
|
||||
/** Which columns of a source hold documents, and how their records are formed. */
|
||||
export interface DocumentColumnsConfig {
|
||||
columns: string[];
|
||||
group_by?: ColumnRule;
|
||||
name_by?: ColumnRule;
|
||||
file_field?: string;
|
||||
segmentation?: string;
|
||||
pages_per_record?: number;
|
||||
ocr_mode?: OcrMode;
|
||||
key_pattern?: string;
|
||||
include_pattern?: string;
|
||||
exclude_pattern?: string;
|
||||
overrides?: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
// Clinical documents
|
||||
@@ -145,13 +197,19 @@ export interface DocumentSettings {
|
||||
pages_per_record: number;
|
||||
ocr_mode: OcrMode;
|
||||
key_pattern: string;
|
||||
/** Only documents whose text matches (regular expression, case and accents ignored). */
|
||||
include_pattern?: string;
|
||||
/** Documents whose text matches are left out. */
|
||||
exclude_pattern?: string;
|
||||
}
|
||||
|
||||
export interface ExtractedField {
|
||||
value: unknown;
|
||||
confidence: number;
|
||||
/** etiqueta | patron | texto_libre | manual */
|
||||
/** etiqueta | patron | texto_libre | medicion | columna_fuente | manual */
|
||||
method: string;
|
||||
/** What the report says about the mention: afirmado, negado, incierto, hipotetico, historico, presuntivo. */
|
||||
assertion?: string | null;
|
||||
raw?: string;
|
||||
document?: string;
|
||||
page_number?: number;
|
||||
@@ -175,6 +233,10 @@ export interface ExtractedRecord {
|
||||
conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[];
|
||||
sources: { document: string; page_numbers: number[] }[];
|
||||
images: DocumentImage[];
|
||||
/** `false` when the pages only name another kind of study than the target's; `null` when they name none. */
|
||||
on_topic?: boolean | null;
|
||||
/** Per field, the other values the extractors proposed, best first. */
|
||||
alternatives?: Record<string, ExtractedField[]>;
|
||||
}
|
||||
|
||||
export interface DocumentFieldSpec {
|
||||
@@ -188,6 +250,8 @@ export interface DocumentExtraction extends PreviewResponse {
|
||||
key_field: string | null;
|
||||
fields: DocumentFieldSpec[];
|
||||
records: ExtractedRecord[];
|
||||
/** The extraction code's version and its ranker's, as stored with each row. */
|
||||
nlp_version?: string;
|
||||
}
|
||||
|
||||
export interface RowError {
|
||||
|
||||
@@ -1,12 +1,41 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types';
|
||||
import { Observable, shareReplay } from 'rxjs';
|
||||
import {
|
||||
BatchResult,
|
||||
ConflictStrategy,
|
||||
DerivationCatalog,
|
||||
ImportSourcePayload,
|
||||
PreviewResponse,
|
||||
Row,
|
||||
ValidationResult,
|
||||
} from './api.types';
|
||||
|
||||
/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */
|
||||
/**
|
||||
* POST /imports/validate (one source, writes nothing), POST /imports/commit
|
||||
* (a batch, one transaction), the rows a source would write
|
||||
* (POST /imports/mapped-preview), the columns documents add to a source
|
||||
* (POST /imports/sources/document/columns) and the operations derived
|
||||
* fields may use (GET /imports/derivations, fetched once).
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ImportsApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
private catalog?: Observable<DerivationCatalog>;
|
||||
|
||||
derivations(): Observable<DerivationCatalog> {
|
||||
this.catalog ??= this.http.get<DerivationCatalog>('/imports/derivations').pipe(shareReplay(1));
|
||||
return this.catalog;
|
||||
}
|
||||
|
||||
/** A source with document columns: its own columns plus every field and caption its documents print. */
|
||||
documentColumns(source: ImportSourcePayload): Observable<PreviewResponse> {
|
||||
return this.http.post<PreviewResponse>('/imports/sources/document/columns', { source });
|
||||
}
|
||||
|
||||
mappedPreview(source: ImportSourcePayload, limit = 20): Observable<{ rows: Row[] }> {
|
||||
return this.http.post<{ rows: Row[] }>('/imports/mapped-preview', { source, limit });
|
||||
}
|
||||
|
||||
validate(source: ImportSourcePayload): Observable<ValidationResult> {
|
||||
return this.http.post<ValidationResult>('/imports/validate', { source });
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -85,6 +85,31 @@
|
||||
</mat-form-field>
|
||||
</form>
|
||||
} @else {
|
||||
@if (savedConnections().length) {
|
||||
<div class="saved-connections">
|
||||
<span class="saved-connections__label">Conexiones guardadas</span>
|
||||
<div class="saved-connections__list">
|
||||
@for (saved of savedConnections(); track saved.id) {
|
||||
<div class="saved-connection">
|
||||
<button type="button" class="saved-connection__pick" matRipple (click)="applySaved(saved)">
|
||||
<mat-icon aria-hidden="true">storage</mat-icon>
|
||||
<span>{{ saved.label }}</span>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
class="saved-connection__forget"
|
||||
(click)="forgetSaved(saved, $event)"
|
||||
aria-label="Eliminar esta conexión guardada"
|
||||
matTooltip="Eliminar"
|
||||
>
|
||||
<mat-icon aria-hidden="true">close</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<form [formGroup]="serverForm" class="db-form" (ngSubmit)="connectDatabase()">
|
||||
<mat-form-field appearance="outline" class="db-form__host">
|
||||
<mat-label>Servidor</mat-label>
|
||||
@@ -108,6 +133,9 @@
|
||||
<input matInput type="password" formControlName="password" autocomplete="new-password" />
|
||||
</mat-form-field>
|
||||
</form>
|
||||
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
|
||||
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
|
||||
</mat-checkbox>
|
||||
}
|
||||
|
||||
@if (testing()) {
|
||||
|
||||
@@ -80,6 +80,62 @@
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
}
|
||||
|
||||
.saved-connections {
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.saved-connections__label {
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
display: block;
|
||||
font: var(--mat-sys-label-small);
|
||||
margin-bottom: var(--space-1);
|
||||
}
|
||||
|
||||
.saved-connections__list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.saved-connection {
|
||||
align-items: center;
|
||||
background: var(--mat-sys-surface-variant);
|
||||
border-radius: var(--mat-sys-corner-full);
|
||||
display: flex;
|
||||
gap: var(--space-1);
|
||||
padding-right: var(--space-1);
|
||||
}
|
||||
|
||||
.saved-connection__pick {
|
||||
align-items: center;
|
||||
background: none;
|
||||
border: 0;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
font: var(--mat-sys-body-small);
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-1) 0 var(--space-1) var(--space-3);
|
||||
|
||||
mat-icon {
|
||||
font-size: 18px;
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.saved-connection__forget {
|
||||
--mdc-icon-button-state-layer-size: 28px;
|
||||
height: 28px;
|
||||
width: 28px;
|
||||
|
||||
mat-icon {
|
||||
font-size: 16px;
|
||||
height: 16px;
|
||||
width: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.db-form {
|
||||
display: grid;
|
||||
gap: 0 var(--space-4);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Component, computed, inject, signal } from '@angular/core';
|
||||
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
@@ -17,6 +18,7 @@ import { SourceGateway } from '../../api/source-gateway';
|
||||
import { connectionsFor } from '../../domain/connection-registry';
|
||||
import { GALLERY_CATEGORIES, GalleryCategory, GalleryEntry, galleryEntries } from '../../domain/connector-catalog';
|
||||
import { DataConnection } from '../../domain/data-source';
|
||||
import { SavedSqlConnection, listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from '../../domain/saved-sql-connections';
|
||||
import { SqlConnection } from '../../domain/sql-source';
|
||||
import { describeSqlServer, describeSqlUrl } from '../../domain/sql-url';
|
||||
import { FileDropzone } from '../file-dropzone/file-dropzone';
|
||||
@@ -33,6 +35,7 @@ type View = 'catalog' | 'files' | 'database';
|
||||
imports: [
|
||||
FileDropzone,
|
||||
MatButtonModule,
|
||||
MatCheckboxModule,
|
||||
MatDialogModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
@@ -95,6 +98,7 @@ export class ConnectorGalleryDialog {
|
||||
readonly urlForm = this.formBuilder.nonNullable.group({ url: ['', Validators.required] });
|
||||
readonly testing = signal(false);
|
||||
readonly testResult = signal<{ ok: boolean; message: string } | null>(null);
|
||||
readonly remember = signal(false);
|
||||
|
||||
readonly engine = computed(() => this.entry()?.engine ?? null);
|
||||
readonly serverEngine = computed(() => {
|
||||
@@ -102,10 +106,29 @@ export class ConnectorGalleryDialog {
|
||||
return engine && engine !== 'url' ? engine : null;
|
||||
});
|
||||
|
||||
private readonly savedConnectionsAll = signal(listSavedSqlConnections());
|
||||
/** Only the ones for the engine currently picked, so a saved SQL Server entry never fills a MySQL form. */
|
||||
readonly savedConnections = computed(() => {
|
||||
const engineId = this.serverEngine()?.id;
|
||||
return engineId ? this.savedConnectionsAll().filter((saved) => saved.engine === engineId) : [];
|
||||
});
|
||||
|
||||
applySaved(saved: SavedSqlConnection): void {
|
||||
this.serverForm.patchValue({ host: saved.host, port: saved.port, database: saved.database, user: saved.user });
|
||||
this.testResult.set(null);
|
||||
}
|
||||
|
||||
forgetSaved(saved: SavedSqlConnection, event: Event): void {
|
||||
event.stopPropagation();
|
||||
removeSqlConnection(saved.id);
|
||||
this.savedConnectionsAll.set(listSavedSqlConnections());
|
||||
}
|
||||
|
||||
pick(entry: GalleryEntry): void {
|
||||
if (!entry.available) return;
|
||||
this.entry.set(entry);
|
||||
this.testResult.set(null);
|
||||
this.remember.set(false);
|
||||
this.view.set(entry.engine ? 'database' : 'files');
|
||||
}
|
||||
|
||||
@@ -143,6 +166,10 @@ export class ConnectorGalleryDialog {
|
||||
connectDatabase(): void {
|
||||
const ref = this.connectionRef();
|
||||
if (!ref) return;
|
||||
if (this.remember() && 'server' in ref) {
|
||||
const { password: _password, ...shape } = ref.server;
|
||||
saveSqlConnection({ label: this.connectionLabel(), ...shape });
|
||||
}
|
||||
this.dialogRef.close([new SqlConnection(ref, this.connectionLabel(), this.serverEngine()?.default_schema ?? undefined)]);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,15 @@
|
||||
/>
|
||||
<mat-hint>Expresión regular; ayuda a encontrar el expediente sin etiqueta.</mat-hint>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Solo documentos que digan</mat-label>
|
||||
<input matInput [ngModel]="settings().include_pattern ?? ''" (ngModelChange)="updateSettings({ include_pattern: $event })" />
|
||||
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Omitir documentos que digan</mat-label>
|
||||
<input matInput [ngModel]="settings().exclude_pattern ?? ''" (ngModelChange)="updateSettings({ exclude_pattern: $event })" />
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>OCR</mat-label>
|
||||
<mat-select [value]="settings().ocr_mode" (valueChange)="updateSettings({ ocr_mode: $event })">
|
||||
@@ -89,6 +98,12 @@
|
||||
Confianza mínima {{ record.confidence | percent }}
|
||||
</span>
|
||||
</header>
|
||||
@if (record.on_topic === false) {
|
||||
<p class="record__off-topic" role="status">
|
||||
<mat-icon aria-hidden="true">report</mat-icon>
|
||||
Sus páginas mencionan otro tipo de estudio y no el de este destino; sus valores quedan vacíos para que los revise.
|
||||
</p>
|
||||
}
|
||||
|
||||
<table class="fields" aria-label="Campos extraídos">
|
||||
<thead>
|
||||
@@ -115,6 +130,21 @@
|
||||
(change)="setValue(record, field.name, $any($event.target).value)"
|
||||
[attr.aria-label]="'Valor de ' + field.name"
|
||||
/>
|
||||
@if (alternatives(record, field.name).length && !isOverridden(record, field.name)) {
|
||||
<span class="fields__alternatives">
|
||||
También:
|
||||
@for (alternative of alternatives(record, field.name); track $index) {
|
||||
<button
|
||||
type="button"
|
||||
class="fields__alternative"
|
||||
(click)="pick(record, field.name, alternative)"
|
||||
[matTooltip]="(methodLabels[alternative.method] ?? alternative.method) + ' · ' + (alternative.confidence | percent) + (alternative.line ? ' · “' + alternative.line + '”' : '')"
|
||||
>
|
||||
{{ alternative.value }}
|
||||
</button>
|
||||
}
|
||||
</span>
|
||||
}
|
||||
@if (conflict) {
|
||||
<span class="fields__conflict" [matTooltip]="'Otro documento dice: ' + conflict.discarded.value + ' (' + conflict.discarded.document + ' p. ' + conflict.discarded.page_number + ')'">
|
||||
<mat-icon aria-hidden="true">compare_arrows</mat-icon>difiere
|
||||
@@ -132,6 +162,9 @@
|
||||
[attr.aria-label]="'Confianza ' + (found.confidence | percent)"
|
||||
></mat-progress-bar>
|
||||
<span class="method">{{ methodLabels[found.method] ?? found.method }} · {{ found.confidence | percent }}</span>
|
||||
@if (found.assertion && assertionLabels[found.assertion]) {
|
||||
<span class="method method--assertion">{{ assertionLabels[found.assertion] }}</span>
|
||||
}
|
||||
}
|
||||
</td>
|
||||
<td class="fields__evidence">
|
||||
|
||||
@@ -133,6 +133,47 @@
|
||||
background: color-mix(in srgb, var(--mat-sys-primary) 8%, transparent);
|
||||
}
|
||||
|
||||
.fields__alternatives {
|
||||
align-items: center;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
font: var(--mat-sys-label-small);
|
||||
gap: 4px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.fields__alternative {
|
||||
background: var(--mat-sys-surface-container-high);
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
color: var(--mat-sys-on-surface);
|
||||
cursor: pointer;
|
||||
font: var(--mat-sys-label-small);
|
||||
padding: 1px 8px;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
background: var(--mat-sys-secondary-container);
|
||||
}
|
||||
}
|
||||
|
||||
.method--assertion {
|
||||
color: var(--mat-sys-tertiary);
|
||||
display: block;
|
||||
}
|
||||
|
||||
.record__off-topic {
|
||||
align-items: center;
|
||||
background: var(--mat-sys-error-container);
|
||||
color: var(--mat-sys-on-error-container);
|
||||
display: flex;
|
||||
font: var(--mat-sys-body-small);
|
||||
gap: var(--space-2);
|
||||
margin: 0 0 var(--space-2);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.fields__conflict {
|
||||
align-items: center;
|
||||
color: var(--mat-sys-error);
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
|
||||
import { SourceGateway } from '../../api/source-gateway';
|
||||
import { DocumentExtraction, ExtractedRecord } from '../../api/api.types';
|
||||
import { DocumentReviewDialog } from './document-review-dialog';
|
||||
|
||||
/**
|
||||
* The review of extracted documents: the other readings the extractors proposed can be picked as a correction, a
|
||||
* record whose pages name another kind of study asks for review, and a qualified mention shows how it was qualified.
|
||||
* The table is a stub holding one extraction already made, so no request is sent; the gateway is never called.
|
||||
*/
|
||||
describe('DocumentReviewDialog', () => {
|
||||
const record: ExtractedRecord = {
|
||||
index: 0,
|
||||
key: 'K-1',
|
||||
confidence: 0.9,
|
||||
fields: { bx_cin_grado: { value: 'LIEAG', confidence: 0.9, method: 'texto_libre', assertion: 'presuntivo' } },
|
||||
missing: [],
|
||||
conflicts: [],
|
||||
sources: [{ document: 'a.pdf', page_numbers: [1] }],
|
||||
images: [],
|
||||
on_topic: true,
|
||||
alternatives: { bx_cin_grado: [{ value: 'LIEBG', confidence: 0.7, method: 'etiqueta', line: 'Diagnóstico: NIC I' }] },
|
||||
};
|
||||
|
||||
function open(records: ExtractedRecord[]) {
|
||||
const extraction = { key_field: 'pac_id_hospital', fields: [{ name: 'bx_cin_grado', kind: 'choice', required: false, labels: [] }], records } as unknown as DocumentExtraction;
|
||||
const table = {
|
||||
settings: () => ({}),
|
||||
overrides: () => ({}),
|
||||
extractions: signal({ biopsia: extraction }),
|
||||
configure: vi.fn(),
|
||||
};
|
||||
TestBed.configureTestingModule({
|
||||
imports: [DocumentReviewDialog],
|
||||
providers: [
|
||||
{ provide: MAT_DIALOG_DATA, useValue: { table, target: { key: 'biopsia', domain: 'cacu', table: 'biopsia_cervical' }, segmentations: [] } },
|
||||
{ provide: MatDialogRef, useValue: { close: vi.fn() } },
|
||||
{ provide: SourceGateway, useValue: {} },
|
||||
],
|
||||
});
|
||||
const fixture = TestBed.createComponent(DocumentReviewDialog);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
it('picks another reading as the correction', () => {
|
||||
// Fails if the alternatives stop being offered or picking one stops recording it as an override.
|
||||
const fixture = open([record]);
|
||||
const dialog = fixture.componentInstance;
|
||||
const [alternative] = dialog.alternatives(record, 'bx_cin_grado');
|
||||
dialog.pick(record, 'bx_cin_grado', alternative);
|
||||
expect(dialog.value(record, 'bx_cin_grado')).toBe('LIEBG');
|
||||
expect(dialog.isOverridden(record, 'bx_cin_grado')).toBe(true);
|
||||
});
|
||||
|
||||
it('shows how a mention was qualified and asks to review off-topic records', () => {
|
||||
// Fails if the assertion label or the off-topic warning disappear from the page.
|
||||
const fixture = open([record, { ...record, index: 1, on_topic: false }]);
|
||||
expect(fixture.nativeElement.textContent).toContain('Presuntivo');
|
||||
expect(fixture.componentInstance.needsReview()).toBe(1);
|
||||
fixture.componentInstance.select(1);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('otro tipo de estudio');
|
||||
});
|
||||
});
|
||||
@@ -33,9 +33,19 @@ const METHOD_LABELS: Record<string, string> = {
|
||||
etiqueta: 'Etiqueta',
|
||||
patron: 'Patrón',
|
||||
texto_libre: 'Texto libre',
|
||||
medicion: 'Medición',
|
||||
columna_fuente: 'Columna',
|
||||
manual: 'Manual',
|
||||
};
|
||||
|
||||
/** How a value's mention is qualified, for the ones a reviewer should notice. */
|
||||
const ASSERTION_LABELS: Record<string, string> = {
|
||||
incierto: 'Incierto',
|
||||
hipotetico: 'Hipotético',
|
||||
historico: 'Antecedente',
|
||||
presuntivo: 'Presuntivo',
|
||||
};
|
||||
|
||||
const REVIEW_BELOW = 0.8;
|
||||
|
||||
/**
|
||||
@@ -73,6 +83,7 @@ export class DocumentReviewDialog {
|
||||
readonly target = this.data.target;
|
||||
readonly segmentations = this.data.segmentations;
|
||||
readonly methodLabels = METHOD_LABELS;
|
||||
readonly assertionLabels = ASSERTION_LABELS;
|
||||
readonly reviewBelow = REVIEW_BELOW;
|
||||
|
||||
readonly settings = signal<DocumentSettings>({ ...this.table.settings() });
|
||||
@@ -133,7 +144,18 @@ export class DocumentReviewDialog {
|
||||
}
|
||||
|
||||
recordNeedsReview(record: ExtractedRecord): boolean {
|
||||
return record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW;
|
||||
return (
|
||||
record.missing.length > 0 || record.conflicts.length > 0 || record.confidence < REVIEW_BELOW || record.on_topic === false
|
||||
);
|
||||
}
|
||||
|
||||
alternatives(record: ExtractedRecord, field: string): ExtractedField[] {
|
||||
return record.alternatives?.[field] ?? [];
|
||||
}
|
||||
|
||||
/** Takes another reading the extractors proposed; the correction teaches the ranker once imported. */
|
||||
pick(record: ExtractedRecord, field: string, alternative: ExtractedField): void {
|
||||
this.setValue(record, field, alternative.value === null || alternative.value === undefined ? '' : String(alternative.value));
|
||||
}
|
||||
|
||||
extracted(record: ExtractedRecord, field: string): ExtractedField | null {
|
||||
|
||||
@@ -55,6 +55,15 @@
|
||||
</ng-template>
|
||||
<div class="editor__panel"><app-column-mapper [flow]="f"></app-column-mapper></div>
|
||||
</mat-tab>
|
||||
<mat-tab>
|
||||
<ng-template mat-tab-label>
|
||||
<mat-icon aria-hidden="true">functions</mat-icon>Reglas
|
||||
@if (f.documents() || (f.derived() | keyvalue).length) {
|
||||
<span class="tab-count">{{ (f.derived() | keyvalue).length + (f.documents() ? 1 : 0) }}</span>
|
||||
}
|
||||
</ng-template>
|
||||
<div class="editor__panel"><app-mapping-rules [flow]="f"></app-mapping-rules></div>
|
||||
</mat-tab>
|
||||
<mat-tab>
|
||||
<ng-template mat-tab-label><mat-icon aria-hidden="true">table_view</mat-icon>Datos</ng-template>
|
||||
<div class="editor__panel"><app-data-grid [flow]="f"></app-data-grid></div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { DecimalPipe, KeyValuePipe } from '@angular/common';
|
||||
import { Component, computed, inject, input, signal } from '@angular/core';
|
||||
import { MatBadgeModule } from '@angular/material/badge';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
@@ -13,12 +13,13 @@ import { ConnectWorkspaceStore } from '../../state/connect-workspace.store';
|
||||
import { ColumnMapper } from '../column-mapper/column-mapper';
|
||||
import { DataGrid } from '../data-grid/data-grid';
|
||||
import { DocumentReviewData, DocumentReviewDialog } from '../document-review-dialog/document-review-dialog';
|
||||
import { MappingRules } from '../mapping-rules/mapping-rules';
|
||||
import { FlowStatusChip } from '../shared/flow-status';
|
||||
import { ValidationReport } from '../validation-report/validation-report';
|
||||
|
||||
const VALIDATION_TAB = 2;
|
||||
const VALIDATION_TAB = 3;
|
||||
|
||||
/** Everything about the selected flow: its mapping, its data, its validation. */
|
||||
/** Everything about the selected flow: its mapping, its rules, its data, its validation. */
|
||||
@Component({
|
||||
selector: 'app-flow-editor',
|
||||
imports: [
|
||||
@@ -26,6 +27,8 @@ const VALIDATION_TAB = 2;
|
||||
DataGrid,
|
||||
DecimalPipe,
|
||||
FlowStatusChip,
|
||||
KeyValuePipe,
|
||||
MappingRules,
|
||||
MatBadgeModule,
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
@let f = flow();
|
||||
@let docs = documentForm();
|
||||
<div class="rules">
|
||||
<section class="rules__section" aria-labelledby="documents-title">
|
||||
<header class="rules__header">
|
||||
<h3 id="documents-title"><mat-icon aria-hidden="true">document_scanner</mat-icon>Documentos dentro de columnas</h3>
|
||||
@if (f.documents()) {
|
||||
<span class="rules__badge">Leyendo {{ f.documents()!.columns.length }} columna(s)</span>
|
||||
}
|
||||
</header>
|
||||
<p class="rules__hint">
|
||||
Si alguna columna guarda archivos (PDF o imágenes, como binario, hexadecimal o base64), se leen y todo lo que
|
||||
imprimen (campos conocidos y cualquier otra etiqueta) aparece como columnas nuevas que puede asignar o usar en reglas.
|
||||
Los valores que vienen de columnas de la fuente se respetan por encima de lo que diga el documento.
|
||||
@if (f.documentColumns().length) {
|
||||
Columnas con archivos detectadas: <strong>{{ f.documentColumns().join(', ') }}</strong>.
|
||||
}
|
||||
</p>
|
||||
<div class="rules__grid">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Columnas con documentos</mat-label>
|
||||
<mat-select multiple [ngModel]="docs.columns" (ngModelChange)="patchDocuments({ columns: $event })">
|
||||
@for (name of columnNames(); track name) {
|
||||
<mat-option [value]="name">{{ name }}@if (f.documentColumns().includes(name)) { (archivo) }</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Agrupar registros por</mat-label>
|
||||
<mat-select [ngModel]="docs.group_by" (ngModelChange)="patchDocuments({ group_by: $event })">
|
||||
<mat-option value="">Por el identificador del paciente</mat-option>
|
||||
@for (name of columnNames(); track name) {
|
||||
<mat-option [value]="name">{{ name }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>Las filas con el mismo valor forman un solo registro (p. ej. un número de estudio).</mat-hint>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Guardar el documento en</mat-label>
|
||||
<mat-select [ngModel]="docs.file_field" (ngModelChange)="patchDocuments({ file_field: $event })">
|
||||
<mat-option value="">No guardar</mat-option>
|
||||
@for (field of fileFields(); track field.name) {
|
||||
<mat-option [value]="field.name">{{ field.name }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>OCR</mat-label>
|
||||
<mat-select [ngModel]="docs.ocr_mode" (ngModelChange)="patchDocuments({ ocr_mode: $event })">
|
||||
<mat-option value="auto">Solo páginas escaneadas</mat-option>
|
||||
<mat-option value="always">Todas las páginas</mat-option>
|
||||
<mat-option value="never">Nunca (solo texto del PDF)</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Solo documentos que digan</mat-label>
|
||||
<input matInput [ngModel]="docs.include_pattern" (ngModelChange)="patchDocuments({ include_pattern: $event })" />
|
||||
<mat-hint>Expresión regular; sin distinguir mayúsculas ni acentos.</mat-hint>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Omitir documentos que digan</mat-label>
|
||||
<input matInput [ngModel]="docs.exclude_pattern" (ngModelChange)="patchDocuments({ exclude_pattern: $event })" />
|
||||
</mat-form-field>
|
||||
</div>
|
||||
<mat-checkbox [checked]="f.catalogFallback()" (change)="f.setCatalogFallback($event.checked)">
|
||||
Guardar también, en el expediente de cada paciente, las etiquetas de los documentos que el catálogo del proyecto ya
|
||||
conoce
|
||||
</mat-checkbox>
|
||||
<p class="rules__hint">
|
||||
Las etiquetas que nadie usa no se guardan: aparecen, solo con su nombre y cuántos registros las traen, en la
|
||||
Bitácora de cargas.
|
||||
</p>
|
||||
<div class="rules__actions">
|
||||
<button mat-flat-button type="button" [disabled]="documentsBusy()" (click)="applyDocuments()">
|
||||
<mat-icon aria-hidden="true">play_arrow</mat-icon>Leer documentos
|
||||
</button>
|
||||
@if (f.documents()) {
|
||||
<button mat-button type="button" (click)="clearDocuments()">Dejar de leerlos</button>
|
||||
}
|
||||
</div>
|
||||
@if (documentsBusy()) {
|
||||
<mat-progress-bar mode="indeterminate" />
|
||||
}
|
||||
@if (documentsError(); as error) {
|
||||
<p class="rules__error" role="alert">{{ error }}</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="rules__section" aria-labelledby="derived-title">
|
||||
<header class="rules__header">
|
||||
<h3 id="derived-title"><mat-icon aria-hidden="true">functions</mat-icon>Campos calculados</h3>
|
||||
</header>
|
||||
<p class="rules__hint">
|
||||
Para cuando las columnas no coinciden una a una con los campos: unir nombre y apellidos, separar un nombre completo,
|
||||
tomar la primera columna con valor, extraer un dato de un texto o traducir códigos. Funciona igual con columnas de la
|
||||
fuente y con lo leído de los documentos.
|
||||
</p>
|
||||
|
||||
@for (item of rules(); track item.field) {
|
||||
<div class="rule">
|
||||
<mat-icon aria-hidden="true">arrow_forward</mat-icon>
|
||||
<strong>{{ item.field }}</strong>
|
||||
<span class="rule__summary">{{ item.summary }}</span>
|
||||
<button mat-icon-button type="button" [attr.aria-label]="'Quitar regla de ' + item.field" (click)="removeRule(item.field)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="rules__grid">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Campo</mat-label>
|
||||
<mat-select [ngModel]="ruleField()" (ngModelChange)="ruleField.set($event)">
|
||||
@for (field of f.target.fields; track field.name) {
|
||||
<mat-option [value]="field.name">{{ field.name }}@if (field.required) { * }</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Cómo calcularlo</mat-label>
|
||||
<mat-select [ngModel]="ruleOp()" (ngModelChange)="chooseOp($event)">
|
||||
@for (spec of catalog()?.derivations ?? []; track spec.op) {
|
||||
<mat-option [value]="spec.op" [matTooltip]="spec.description">{{ spec.label }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (selectedSpec(); as spec) {
|
||||
<mat-hint>{{ spec.description }}</mat-hint>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
@for (param of selectedSpec()?.params ?? []; track param.name) {
|
||||
@switch (param.kind) {
|
||||
@case ('column') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>{{ param.label }}</mat-label>
|
||||
<mat-select [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
|
||||
@for (name of columnNames(); track name) {
|
||||
<mat-option [value]="name">{{ name }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@case ('columns') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>{{ param.label }} (en orden)</mat-label>
|
||||
<mat-select multiple [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">
|
||||
@for (name of columnNames(); track name) {
|
||||
<mat-option [value]="name">{{ name }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@case ('integer') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>{{ param.label }}</mat-label>
|
||||
<input matInput type="number" [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
|
||||
</mat-form-field>
|
||||
}
|
||||
@case ('boolean') {
|
||||
<mat-checkbox [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)">{{ param.label }}</mat-checkbox>
|
||||
}
|
||||
@case ('mapping') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="rules__wide">
|
||||
<mat-label>{{ param.label }}</mat-label>
|
||||
<textarea matInput rows="3" placeholder="M = Masculino" [ngModel]="mappingText(param.name)" (ngModelChange)="setMappingText(param.name, $event)"></textarea>
|
||||
<mat-hint>Una equivalencia por línea: valor = nuevo valor.</mat-hint>
|
||||
</mat-form-field>
|
||||
}
|
||||
@default {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>{{ param.label }}</mat-label>
|
||||
<input matInput [ngModel]="ruleParams()[param.name]" (ngModelChange)="setParam(param.name, $event)" />
|
||||
</mat-form-field>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@if (selectedSpec()) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Mayúsculas</mat-label>
|
||||
<mat-select [ngModel]="ruleCase()" (ngModelChange)="ruleCase.set($event)">
|
||||
<mat-option value="">Sin cambio</mat-option>
|
||||
<mat-option value="upper">MAYÚSCULAS</mat-option>
|
||||
<mat-option value="lower">minúsculas</mat-option>
|
||||
<mat-option value="title">Tipo Título</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
</div>
|
||||
<div class="rules__actions">
|
||||
<button mat-stroked-button type="button" [disabled]="!ruleField() || !selectedSpec()" (click)="addRule()">
|
||||
<mat-icon aria-hidden="true">add</mat-icon>Agregar regla
|
||||
</button>
|
||||
</div>
|
||||
@if (ruleError(); as error) {
|
||||
<p class="rules__error" role="alert">{{ error }}</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="rules__section" aria-labelledby="result-title">
|
||||
<header class="rules__header">
|
||||
<h3 id="result-title"><mat-icon aria-hidden="true">preview</mat-icon>Resultado</h3>
|
||||
<button mat-stroked-button type="button" [disabled]="previewBusy()" (click)="preview()">
|
||||
<mat-icon aria-hidden="true">visibility</mat-icon>Ver cómo quedarían las filas
|
||||
</button>
|
||||
</header>
|
||||
@if (previewBusy()) {
|
||||
<mat-progress-bar mode="indeterminate" />
|
||||
}
|
||||
@if (previewError(); as error) {
|
||||
<p class="rules__error" role="alert">{{ error }}</p>
|
||||
}
|
||||
@if (previewRows(); as rows) {
|
||||
<div class="rules__table-wrap">
|
||||
<table class="rules__table">
|
||||
<thead>
|
||||
<tr>
|
||||
@for (column of previewColumns(); track column) {
|
||||
<th scope="col">{{ column }}</th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (row of rows; track $index) {
|
||||
<tr>
|
||||
@for (column of previewColumns(); track column) {
|
||||
<td>{{ cell(row[column]) }}</td>
|
||||
}
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr><td>La fuente no dio filas.</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
@@ -0,0 +1,113 @@
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.rules {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.rules__section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.rules__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
h3 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
font: var(--mat-sys-title-medium);
|
||||
}
|
||||
}
|
||||
|
||||
.rules__badge {
|
||||
font: var(--mat-sys-label-medium);
|
||||
color: var(--mat-sys-primary);
|
||||
}
|
||||
|
||||
.rules__hint {
|
||||
margin: 0;
|
||||
font: var(--mat-sys-body-small);
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
}
|
||||
|
||||
.rules__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
gap: 12px 16px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.rules__wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.rules__actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.rules__error {
|
||||
margin: 0;
|
||||
color: var(--mat-sys-error);
|
||||
font: var(--mat-sys-body-medium);
|
||||
}
|
||||
|
||||
.rule {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--mat-sys-surface-container);
|
||||
}
|
||||
|
||||
.rule__summary {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
}
|
||||
|
||||
.rules__table-wrap {
|
||||
overflow-x: auto;
|
||||
max-height: 360px;
|
||||
border: 1px solid var(--mat-sys-outline-variant);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.rules__table {
|
||||
border-collapse: collapse;
|
||||
font: var(--mat-sys-body-small);
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--mat-sys-outline-variant);
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
max-width: 240px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--mat-sys-surface-container-high);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { Component, computed, effect, inject, input, signal } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import {
|
||||
DerivationParam,
|
||||
DerivationRule,
|
||||
DerivationSpec,
|
||||
DocumentColumnsConfig,
|
||||
OcrMode,
|
||||
Row,
|
||||
apiErrorMessage,
|
||||
} from '../../api/api.types';
|
||||
import { ImportsApi } from '../../api/imports.api';
|
||||
import { ImportFlow } from '../../domain/import-flow';
|
||||
|
||||
interface DocumentForm {
|
||||
columns: string[];
|
||||
group_by: string;
|
||||
file_field: string;
|
||||
ocr_mode: OcrMode;
|
||||
include_pattern: string;
|
||||
exclude_pattern: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a plain column-to-field mapping can't express, for any kind of
|
||||
* source: columns whose cells hold documents (read for every field and
|
||||
* caption they print, which then become columns of their own), target
|
||||
* fields computed from several columns, and a look at the rows as they
|
||||
* would be written.
|
||||
*
|
||||
* The operations and their parameters come from the server
|
||||
* (`/imports/derivations`), so a new operation needs no change here.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-mapping-rules',
|
||||
imports: [
|
||||
FormsModule,
|
||||
MatButtonModule,
|
||||
MatCheckboxModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatProgressBarModule,
|
||||
MatSelectModule,
|
||||
MatTooltipModule,
|
||||
],
|
||||
templateUrl: './mapping-rules.html',
|
||||
styleUrl: './mapping-rules.scss',
|
||||
})
|
||||
export class MappingRules {
|
||||
readonly flow = input.required<ImportFlow>();
|
||||
private readonly api = inject(ImportsApi);
|
||||
|
||||
readonly catalog = toSignal(this.api.derivations());
|
||||
readonly columnNames = computed(() => this.flow().sourceColumns().map((column) => column.name));
|
||||
readonly fileFields = computed(() => this.flow().target.fields.filter((field) => field.type === 'binary' || field.name.endsWith('_blob')));
|
||||
|
||||
readonly documentForm = signal<DocumentForm>(this.emptyDocumentForm());
|
||||
readonly documentsBusy = signal(false);
|
||||
readonly documentsError = signal<string | null>(null);
|
||||
|
||||
readonly ruleField = signal<string>('');
|
||||
readonly ruleOp = signal<string>('');
|
||||
readonly ruleParams = signal<Record<string, unknown>>({});
|
||||
readonly ruleCase = signal<string>('');
|
||||
readonly ruleError = signal<string | null>(null);
|
||||
|
||||
readonly previewRows = signal<Row[] | null>(null);
|
||||
readonly previewBusy = signal(false);
|
||||
readonly previewError = signal<string | null>(null);
|
||||
|
||||
readonly selectedSpec = computed<DerivationSpec | undefined>(() =>
|
||||
this.catalog()?.derivations.find((spec) => spec.op === this.ruleOp()),
|
||||
);
|
||||
|
||||
readonly rules = computed(() =>
|
||||
Object.entries(this.flow().derived()).map(([field, rule]) => ({ field, rule, summary: this.describe(rule) })),
|
||||
);
|
||||
|
||||
readonly previewColumns = computed(() => {
|
||||
const rows = this.previewRows() ?? [];
|
||||
return [...new Set(rows.flatMap((row) => Object.keys(row)))];
|
||||
});
|
||||
|
||||
constructor() {
|
||||
// The form follows the flow: what it has configured, or the columns the server flagged.
|
||||
effect(() => {
|
||||
const flow = this.flow();
|
||||
const current = flow.documents();
|
||||
this.documentForm.set(current ? this.formFrom(current) : { ...this.emptyDocumentForm(), columns: flow.documentColumns() });
|
||||
});
|
||||
}
|
||||
|
||||
// -- documents -----------------------------------------------------------
|
||||
|
||||
patchDocuments(patch: Partial<DocumentForm>): void {
|
||||
this.documentForm.update((form) => ({ ...form, ...patch }));
|
||||
}
|
||||
|
||||
async applyDocuments(): Promise<void> {
|
||||
const form = this.documentForm();
|
||||
const flow = this.flow();
|
||||
if (!form.columns.length) {
|
||||
this.clearDocuments();
|
||||
return;
|
||||
}
|
||||
flow.setDocuments({
|
||||
columns: form.columns,
|
||||
group_by: form.group_by || undefined,
|
||||
file_field: form.file_field || undefined,
|
||||
ocr_mode: form.ocr_mode,
|
||||
include_pattern: form.include_pattern.trim() || undefined,
|
||||
exclude_pattern: form.exclude_pattern.trim() || undefined,
|
||||
});
|
||||
this.documentsBusy.set(true);
|
||||
this.documentsError.set(null);
|
||||
try {
|
||||
flow.useDocumentPreview(await firstValueFrom(this.api.documentColumns(await flow.toPayload())));
|
||||
} catch (error) {
|
||||
this.documentsError.set(apiErrorMessage(error, 'No se pudieron leer los documentos.'));
|
||||
} finally {
|
||||
this.documentsBusy.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
clearDocuments(): void {
|
||||
this.flow().setDocuments(null);
|
||||
this.documentsError.set(null);
|
||||
}
|
||||
|
||||
// -- derived fields ------------------------------------------------------
|
||||
|
||||
chooseOp(op: string): void {
|
||||
this.ruleOp.set(op);
|
||||
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === op);
|
||||
this.ruleParams.set(Object.fromEntries((spec?.params ?? []).map((param) => [param.name, this.initial(param)])));
|
||||
this.ruleError.set(null);
|
||||
}
|
||||
|
||||
setParam(name: string, value: unknown): void {
|
||||
this.ruleParams.update((params) => ({ ...params, [name]: value }));
|
||||
}
|
||||
|
||||
/** `clave = valor` lines, the text form of a `mapping` parameter. */
|
||||
mappingText(name: string): string {
|
||||
const value = this.ruleParams()[name];
|
||||
return value && typeof value === 'object' ? Object.entries(value).map(([k, v]) => `${k} = ${v}`).join('\n') : '';
|
||||
}
|
||||
|
||||
setMappingText(name: string, text: string): void {
|
||||
const entries = text
|
||||
.split('\n')
|
||||
.map((line) => line.split('='))
|
||||
.filter((parts) => parts.length >= 2 && parts[0].trim())
|
||||
.map(([key, ...rest]) => [key.trim(), rest.join('=').trim()]);
|
||||
this.setParam(name, Object.fromEntries(entries));
|
||||
}
|
||||
|
||||
addRule(): void {
|
||||
const spec = this.selectedSpec();
|
||||
const field = this.ruleField();
|
||||
if (!spec || !field) return;
|
||||
const params = this.ruleParams();
|
||||
const missing = spec.params.filter((param) => param.required && this.blank(params[param.name]));
|
||||
if (missing.length) {
|
||||
this.ruleError.set(`Falta: ${missing.map((param) => param.label).join(', ')}`);
|
||||
return;
|
||||
}
|
||||
const rule: DerivationRule = { op: spec.op };
|
||||
for (const param of spec.params) {
|
||||
const value = params[param.name];
|
||||
if (!this.blank(value)) rule[param.name] = param.kind === 'integer' ? Number(value) : value;
|
||||
}
|
||||
if (this.ruleCase()) rule.case = this.ruleCase();
|
||||
this.flow().setDerived(field, rule);
|
||||
this.ruleField.set('');
|
||||
this.ruleOp.set('');
|
||||
this.ruleParams.set({});
|
||||
this.ruleCase.set('');
|
||||
this.ruleError.set(null);
|
||||
}
|
||||
|
||||
removeRule(field: string): void {
|
||||
this.flow().setDerived(field, null);
|
||||
}
|
||||
|
||||
// -- preview ---------------------------------------------------------------
|
||||
|
||||
async preview(): Promise<void> {
|
||||
this.previewBusy.set(true);
|
||||
this.previewError.set(null);
|
||||
try {
|
||||
const { rows } = await firstValueFrom(this.api.mappedPreview(await this.flow().toPayload(), 10));
|
||||
this.previewRows.set(rows);
|
||||
} catch (error) {
|
||||
this.previewError.set(apiErrorMessage(error, 'No se pudo armar la vista previa.'));
|
||||
} finally {
|
||||
this.previewBusy.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
cell(value: unknown): string {
|
||||
if (value === null || value === undefined) return '';
|
||||
return typeof value === 'object' ? JSON.stringify(value) : String(value);
|
||||
}
|
||||
|
||||
private describe(rule: DerivationRule): string {
|
||||
const spec = this.catalog()?.derivations.find((candidate) => candidate.op === rule.op);
|
||||
const parts = (spec?.params ?? [])
|
||||
.filter((param) => !this.blank(rule[param.name]))
|
||||
.map((param) => `${param.label}: ${this.cell(rule[param.name])}`);
|
||||
return [spec?.label ?? rule.op, ...parts, ...(rule.case ? [`(${rule.case})`] : [])].join(' · ');
|
||||
}
|
||||
|
||||
private initial(param: DerivationParam): unknown {
|
||||
if (param.kind === 'columns') return [];
|
||||
if (param.kind === 'mapping') return {};
|
||||
return param.default ?? (param.kind === 'boolean' ? false : '');
|
||||
}
|
||||
|
||||
private blank(value: unknown): boolean {
|
||||
return (
|
||||
value === null ||
|
||||
value === undefined ||
|
||||
(typeof value === 'string' && !value.trim()) ||
|
||||
(Array.isArray(value) && !value.length) ||
|
||||
(typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length)
|
||||
);
|
||||
}
|
||||
|
||||
private emptyDocumentForm(): DocumentForm {
|
||||
return { columns: [], group_by: '', file_field: '', ocr_mode: 'auto', include_pattern: '', exclude_pattern: '' };
|
||||
}
|
||||
|
||||
private formFrom(config: DocumentColumnsConfig): DocumentForm {
|
||||
return {
|
||||
columns: config.columns,
|
||||
group_by: typeof config.group_by === 'string' ? config.group_by : '',
|
||||
file_field: config.file_field ?? '',
|
||||
ocr_mode: config.ocr_mode ?? 'auto',
|
||||
include_pattern: config.include_pattern ?? '',
|
||||
exclude_pattern: config.exclude_pattern ?? '',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -92,4 +92,40 @@ describe('ImportFlow', () => {
|
||||
expect(flow.autoMap()).toBe(1);
|
||||
expect(flow.mapping.toRecord()).toEqual({ Sexo: 'pac_sexo', Clave: 'pac_id_hospital' });
|
||||
});
|
||||
|
||||
it('counts a derived field as covered, and mapping a column onto it drops the rule', async () => {
|
||||
// Fails if `missingRequired` ignores `derived`, or a field could be fed by a column and a rule at once.
|
||||
const flow = loadedFlow();
|
||||
flow.setDerived('pac_id_hospital', { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' });
|
||||
expect(flow.missingRequired()).toEqual([]);
|
||||
expect((await flow.toPayload()).derived).toEqual({ pac_id_hospital: { op: 'concat', columns: ['Clave', 'Sexo'], separator: '-' } });
|
||||
|
||||
flow.map('Clave', 'pac_id_hospital');
|
||||
expect(flow.derived()).toEqual({});
|
||||
expect((await flow.toPayload()).derived).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sends document columns without blank settings and swaps in their columns until they are dropped', async () => {
|
||||
// Fails if blank document settings reach the payload, or the source's own columns are lost when documents are dropped.
|
||||
const flow = loadedFlow();
|
||||
const own = flow.sourceColumns();
|
||||
flow.setDocuments({ columns: ['Clave'], group_by: '', include_pattern: undefined, ocr_mode: 'auto' });
|
||||
expect((await flow.toPayload()).documents).toEqual({ columns: ['Clave'], ocr_mode: 'auto' });
|
||||
expect(flow.missingRequired()).toEqual([]);
|
||||
|
||||
flow.useDocumentPreview(preview({ columns: [...own, { name: 'Tipo de persona', inferred_type: 'string' }] }));
|
||||
expect(flow.sourceColumns().map((c) => c.name)).toContain('Tipo de persona');
|
||||
|
||||
flow.setDocuments(null);
|
||||
expect(flow.sourceColumns()).toEqual(own);
|
||||
expect((await flow.toPayload()).documents).toBeUndefined();
|
||||
});
|
||||
|
||||
it('asks for the catalog fallback only when chosen', async () => {
|
||||
// Fails if `catalog_fallback` is sent without the user switching it on, or not sent once they do.
|
||||
const flow = loadedFlow();
|
||||
expect((await flow.toPayload()).catalog_fallback).toBeUndefined();
|
||||
flow.setCatalogFallback(true);
|
||||
expect((await flow.toPayload()).catalog_fallback).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,8 @@ import { Signal, computed, signal } from '@angular/core';
|
||||
import { Observable, catchError, finalize, map, of, tap } from 'rxjs';
|
||||
import {
|
||||
CommitSourceResult,
|
||||
DerivationRule,
|
||||
DocumentColumnsConfig,
|
||||
ImportSourcePayload,
|
||||
PreviewResponse,
|
||||
RowError,
|
||||
@@ -47,9 +49,14 @@ export class ImportFlow {
|
||||
readonly mapping = new MappingSet();
|
||||
|
||||
private readonly _preview = signal<PreviewResponse | null>(null);
|
||||
/** The source's own preview, kept while document columns replace it. */
|
||||
private _sourcePreview: PreviewResponse | null = null;
|
||||
private readonly _loading = signal(false);
|
||||
private readonly _error = signal<string | null>(null);
|
||||
private readonly _defaults = signal<Record<string, string>>({});
|
||||
private readonly _derived = signal<Record<string, DerivationRule>>({});
|
||||
private readonly _documents = signal<DocumentColumnsConfig | null>(null);
|
||||
private readonly _catalogFallback = signal(false);
|
||||
private readonly _validation = signal<ValidationResult | null>(null);
|
||||
private readonly _validating = signal(false);
|
||||
private readonly _result = signal<CommitSourceResult | null>(null);
|
||||
@@ -58,6 +65,12 @@ export class ImportFlow {
|
||||
readonly loading: Signal<boolean> = this._loading.asReadonly();
|
||||
readonly error: Signal<string | null> = this._error.asReadonly();
|
||||
readonly defaults: Signal<Record<string, string>> = this._defaults.asReadonly();
|
||||
/** Target fields computed from source columns (`derived`), by field. */
|
||||
readonly derived: Signal<Record<string, DerivationRule>> = this._derived.asReadonly();
|
||||
/** Source columns read as documents, or `null` when none are. */
|
||||
readonly documents: Signal<DocumentColumnsConfig | null> = this._documents.asReadonly();
|
||||
/** Whether captions the catalog knows are stored too (`catalog_fallback`); off unless chosen. */
|
||||
readonly catalogFallback: Signal<boolean> = this._catalogFallback.asReadonly();
|
||||
readonly validation: Signal<ValidationResult | null> = this._validation.asReadonly();
|
||||
readonly validating: Signal<boolean> = this._validating.asReadonly();
|
||||
readonly result: Signal<CommitSourceResult | null> = this._result.asReadonly();
|
||||
@@ -65,18 +78,28 @@ export class ImportFlow {
|
||||
readonly sourceColumns = computed<SourceColumn[]>(() => this._preview()?.columns ?? []);
|
||||
readonly totalRows = computed(() => this._preview()?.total_rows ?? null);
|
||||
|
||||
/** A field is covered when a column feeds it or it has a default value. */
|
||||
/**
|
||||
* A field is covered when a column feeds it, a rule computes it or it has
|
||||
* a default value. With document columns, extraction may fill any field,
|
||||
* so nothing is reported missing before validation says so.
|
||||
*/
|
||||
readonly missingRequired = computed<TargetField[]>(() => {
|
||||
if (this._documents()) return [];
|
||||
const mapped = this.mapping.byField();
|
||||
const defaults = this._defaults();
|
||||
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !defaults[f.name]?.trim());
|
||||
const derived = this._derived();
|
||||
return this.target.fields.filter((f) => f.required && !mapped.has(f.name) && !derived[f.name] && !defaults[f.name]?.trim());
|
||||
});
|
||||
|
||||
/** Columns no mapping, rule or document setting reads. */
|
||||
readonly unmappedColumns = computed(() => {
|
||||
const used = this.mapping.bySource();
|
||||
const used = new Set([...this.mapping.bySource().keys(), ...this._documents()?.columns ?? []]);
|
||||
return this.sourceColumns().filter((column) => !used.has(column.name));
|
||||
});
|
||||
|
||||
/** Columns whose sampled cells hold documents. */
|
||||
readonly documentColumns = computed<string[]>(() => this._preview()?.document_columns ?? []);
|
||||
|
||||
readonly pendingSuggestions = computed(() => this.mapping.items().filter((m) => m.confidence !== undefined).length);
|
||||
|
||||
readonly status = computed<FlowStatus>(() => {
|
||||
@@ -84,7 +107,8 @@ export class ImportFlow {
|
||||
if (this._error() || !this._preview()) return 'error';
|
||||
if (this._result()) return 'loaded';
|
||||
if (this._validating()) return 'validating';
|
||||
if (this.missingRequired().length > 0 || this.mapping.size() + Object.keys(this.activeDefaults()).length === 0) {
|
||||
const assigned = this.mapping.size() + Object.keys(this.activeDefaults()).length + Object.keys(this._derived()).length;
|
||||
if (this.missingRequired().length > 0 || (assigned === 0 && !this._documents())) {
|
||||
return 'incomplete';
|
||||
}
|
||||
const validation = this._validation();
|
||||
@@ -161,6 +185,9 @@ export class ImportFlow {
|
||||
|
||||
map(source: string, field: string): void {
|
||||
this.mapping.assign(source, field);
|
||||
if (this._derived()[field]) {
|
||||
this._derived.update(({ [field]: _, ...rest }) => rest);
|
||||
}
|
||||
this.touch();
|
||||
}
|
||||
|
||||
@@ -188,9 +215,51 @@ export class ImportFlow {
|
||||
clearMapping(): void {
|
||||
this.mapping.clear();
|
||||
this._defaults.set({});
|
||||
this._derived.set({});
|
||||
this._documents.set(null);
|
||||
this.touch();
|
||||
}
|
||||
|
||||
/** Computes `field` with `rule`, replacing any column mapped to it; `null` removes the rule. */
|
||||
setDerived(field: string, rule: DerivationRule | null): void {
|
||||
if (rule) this.mapping.releaseField(field);
|
||||
this._derived.update((derived) => {
|
||||
const next = { ...derived };
|
||||
if (rule) next[field] = rule;
|
||||
else delete next[field];
|
||||
return next;
|
||||
});
|
||||
this.touch();
|
||||
}
|
||||
|
||||
setCatalogFallback(on: boolean): void {
|
||||
this._catalogFallback.set(on);
|
||||
this.touch();
|
||||
}
|
||||
|
||||
/** Reads some of the source's columns as documents; `null` stops reading them. */
|
||||
setDocuments(config: DocumentColumnsConfig | null): void {
|
||||
this._documents.set(config && config.columns.length ? config : null);
|
||||
if (!this._documents()) this.useDocumentPreview(null);
|
||||
this.touch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows, as the source's columns, its own plus every field and caption
|
||||
* its documents print, so they can be mapped and used in rules; `null`
|
||||
* goes back to the source's own columns.
|
||||
*/
|
||||
useDocumentPreview(preview: PreviewResponse | null): void {
|
||||
if (preview) {
|
||||
this._sourcePreview ??= this._preview();
|
||||
this._preview.set({ ...preview, document_columns: this._sourcePreview?.document_columns ?? [] });
|
||||
this.mapping.fillFrom(preview.suggested_mapping);
|
||||
} else if (this._sourcePreview) {
|
||||
this._preview.set(this._sourcePreview);
|
||||
this._sourcePreview = null;
|
||||
}
|
||||
}
|
||||
|
||||
setDefault(field: string, value: string | null): void {
|
||||
this._defaults.update((defaults) => {
|
||||
const next = { ...defaults };
|
||||
@@ -215,6 +284,9 @@ export class ImportFlow {
|
||||
label: this.label,
|
||||
column_mapping: this.mapping.toRecord(),
|
||||
...(Object.keys(defaults).length ? { defaults } : {}),
|
||||
...(Object.keys(this._derived()).length ? { derived: this._derived() } : {}),
|
||||
...(this._documents() ? { documents: withoutBlanks(this._documents()!) } : {}),
|
||||
...(this._catalogFallback() ? { catalog_fallback: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -256,3 +328,9 @@ export class ImportFlow {
|
||||
this._result.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
function withoutBlanks(config: DocumentColumnsConfig): DocumentColumnsConfig {
|
||||
return Object.fromEntries(
|
||||
Object.entries(config).filter(([, value]) => value !== undefined && value !== null && value !== ''),
|
||||
) as unknown as DocumentColumnsConfig;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { listSavedSqlConnections, removeSqlConnection, saveSqlConnection } from './saved-sql-connections';
|
||||
|
||||
describe('saved SQL connections', () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it('never stores a password field', () => {
|
||||
const saved = saveSqlConnection({ label: 'HIS · lector@his.local', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
|
||||
expect(Object.keys(saved)).not.toContain('password');
|
||||
expect(JSON.parse(localStorage.getItem('isssteleon.connect.savedSqlConnections')!)[0]).not.toHaveProperty('password');
|
||||
});
|
||||
|
||||
it('upserts by connection shape instead of growing duplicates', () => {
|
||||
const entry = { label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' };
|
||||
saveSqlConnection(entry);
|
||||
saveSqlConnection({ ...entry, label: 'HIS (renamed)' });
|
||||
const all = listSavedSqlConnections();
|
||||
expect(all.length).toBe(1);
|
||||
expect(all[0].label).toBe('HIS (renamed)');
|
||||
});
|
||||
|
||||
it('keeps connections to different servers separate', () => {
|
||||
saveSqlConnection({ label: 'A', engine: 'mssql', host: 'a.local', port: 1433, database: 'HIS', user: 'lector' });
|
||||
saveSqlConnection({ label: 'B', engine: 'mysql', host: 'b.local', port: 3306, database: 'HIS', user: 'lector' });
|
||||
expect(listSavedSqlConnections().length).toBe(2);
|
||||
});
|
||||
|
||||
it('removes a saved connection by id', () => {
|
||||
const saved = saveSqlConnection({ label: 'HIS', engine: 'mssql', host: 'his.local', port: 1433, database: 'HIS', user: 'lector' });
|
||||
removeSqlConnection(saved.id);
|
||||
expect(listSavedSqlConnections()).toEqual([]);
|
||||
});
|
||||
|
||||
it('caps the list so it cannot grow without bound', () => {
|
||||
for (let i = 0; i < 25; i++) {
|
||||
saveSqlConnection({ label: `db${i}`, engine: 'mssql', host: `host${i}`, port: 1433, database: 'HIS', user: 'lector' });
|
||||
}
|
||||
expect(listSavedSqlConnections().length).toBeLessThanOrEqual(20);
|
||||
});
|
||||
|
||||
it('degrades to an empty list rather than throwing when storage is unreadable', () => {
|
||||
const spy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
|
||||
throw new Error('blocked');
|
||||
});
|
||||
expect(listSavedSqlConnections()).toEqual([]);
|
||||
spy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
const STORAGE_KEY = 'isssteleon.connect.savedSqlConnections';
|
||||
const MAX_SAVED = 20;
|
||||
|
||||
/**
|
||||
* A database connection's shape, remembered across visits so the form
|
||||
* doesn't need retyping. Never the password: credentials travel with every
|
||||
* request and are never stored (see `sql-source.ts`), so reconnecting
|
||||
* through a saved entry still asks for it.
|
||||
*/
|
||||
export interface SavedSqlConnection {
|
||||
id: string;
|
||||
label: string;
|
||||
engine: string;
|
||||
host: string;
|
||||
port: number | null;
|
||||
database: string;
|
||||
user: string;
|
||||
}
|
||||
|
||||
export type SavedSqlConnectionInput = Omit<SavedSqlConnection, 'id'>;
|
||||
|
||||
function connectionId(entry: SavedSqlConnectionInput): string {
|
||||
return [entry.engine, entry.host, entry.port ?? '', entry.database, entry.user].join('|');
|
||||
}
|
||||
|
||||
function readAll(): SavedSqlConnection[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
const parsed = raw ? JSON.parse(raw) : [];
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeAll(entries: SavedSqlConnection[]): void {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));
|
||||
} catch {
|
||||
// Private browsing, a cleared/blocked store, or a full quota: the form
|
||||
// just won't remember anything this time, nothing to surface to the user.
|
||||
}
|
||||
}
|
||||
|
||||
export function listSavedSqlConnections(): SavedSqlConnection[] {
|
||||
return readAll();
|
||||
}
|
||||
|
||||
/** Upserts by connection shape (engine/host/port/database/user), newest first. */
|
||||
export function saveSqlConnection(entry: SavedSqlConnectionInput): SavedSqlConnection {
|
||||
const saved: SavedSqlConnection = { ...entry, id: connectionId(entry) };
|
||||
const rest = readAll().filter((existing) => existing.id !== saved.id);
|
||||
writeAll([saved, ...rest].slice(0, MAX_SAVED));
|
||||
return saved;
|
||||
}
|
||||
|
||||
export function removeSqlConnection(id: string): void {
|
||||
writeAll(readAll().filter((existing) => existing.id !== id));
|
||||
}
|
||||
@@ -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';
|
||||
@@ -11,9 +13,9 @@ import { DataConnection, SourceTable } from '../domain/data-source';
|
||||
import { ImportFlow } from '../domain/import-flow';
|
||||
|
||||
export const DOMAINS: { id: Domain; label: string; description: string }[] = [
|
||||
{ id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' },
|
||||
{ id: 'cacu', label: 'Cáncer cervicouterino', description: 'Cáncer cervicouterino' },
|
||||
{ id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' },
|
||||
{ id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' },
|
||||
{ id: 'tea', label: 'Trastorno del espectro autista', description: 'Trastorno del espectro autista' },
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
:host { display: contents; }
|
||||
.domain-selector {
|
||||
flex: 0 0 auto;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
min-height: 40px;
|
||||
background-color: var(--issste-accent);
|
||||
color: var(--issste-text);
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.domain-selector { white-space: normal; text-align: start; padding-block: 8px; }
|
||||
}
|
||||
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
|
||||
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||
export interface SeguimientoPaciente {
|
||||
|
||||
@@ -16,11 +16,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
||||
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
||||
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
||||
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
|
||||
it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
|
||||
respond();
|
||||
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
|
||||
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
|
||||
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
|
||||
expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
|
||||
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
||||
fixture.componentInstance.apply();
|
||||
@@ -92,14 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
it('tea conserva su estado pendiente sin consultas de pacientes', () => {
|
||||
const dominio = 'tea';
|
||||
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
|
||||
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
|
||||
});
|
||||
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
||||
const service=TestBed.inject(CacuSeguimientoService);
|
||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
|
||||
const EDADES: Readonly<Record<string, string>> = {
|
||||
MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
|
||||
MENOR_40: 'Menores de 40 años', '<40': 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
|
||||
};
|
||||
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
|
||||
const HISTOLOGIA: Readonly<Record<string, string>> = {
|
||||
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
|
||||
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
|
||||
};
|
||||
const ESCENARIOS: Readonly<Record<string, string>> = { POST_TRATAMIENTO: 'Post-tratamiento', EN_OBSERVACION: 'En observación' };
|
||||
|
||||
/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */
|
||||
export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo;
|
||||
/** «50-59» as «50 a 59 años». Any other text is returned as it came. */
|
||||
export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo;
|
||||
export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo;
|
||||
/** The patient's clinical scenario at the cut-off: «Post-tratamiento» or «En observación». */
|
||||
export const etiquetaEscenario = (codigo: string) => ESCENARIOS[codigo] ?? codigo;
|
||||
|
||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
|
||||
const POR_CLAVE: Readonly<Record<string, (codigo: string) => string>> = {
|
||||
birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia, escenario_clinico: etiquetaEscenario,
|
||||
};
|
||||
|
||||
/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */
|
||||
export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// The parts of FHIR R4 the WebApi's `/<domain>/fhir/` endpoints serve, read loosely: every field is optional and the
|
||||
// readers below decide what a missing one means.
|
||||
|
||||
export interface Coding { system?: string; code?: string; display?: string }
|
||||
export interface Concept { coding?: Coding[]; text?: string }
|
||||
export interface Quantity { value?: number; unit?: string }
|
||||
export interface Extension {
|
||||
url: string;
|
||||
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
|
||||
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
|
||||
extension?: Extension[];
|
||||
}
|
||||
export interface Resource {
|
||||
resourceType: string;
|
||||
id?: string;
|
||||
meta?: { tag?: Coding[] };
|
||||
extension?: Extension[];
|
||||
[field: string]: unknown;
|
||||
}
|
||||
export interface Bundle extends Resource {
|
||||
total?: number;
|
||||
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
|
||||
}
|
||||
|
||||
export const CODE_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/';
|
||||
|
||||
export function code(concept: Concept | undefined): string | undefined {
|
||||
return concept?.coding?.[0]?.code;
|
||||
}
|
||||
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).
|
||||
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
|
||||
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).
|
||||
export function extensions(owner: { extension?: Extension[] } | undefined, name: string): Extension[] {
|
||||
return (owner?.extension ?? []).filter(e => e.url === name || e.url.endsWith('/' + name));
|
||||
}
|
||||
export function extension(owner: { extension?: Extension[] } | undefined, name: string): Extension | undefined {
|
||||
return extensions(owner, name)[0];
|
||||
}
|
||||
export function resources(bundle: Bundle | undefined, type?: string): Resource[] {
|
||||
return (bundle?.entry ?? []).map(e => e.resource).filter(r => !type || r.resourceType === type);
|
||||
}
|
||||
export function isSimulated(resource: Resource): boolean {
|
||||
return !!resource.meta?.tag?.some(t => t.code === 'simulado');
|
||||
}
|
||||
// `Patient/P-1` -> `P-1`.
|
||||
export function referenceId(reference: { reference?: string } | undefined): string | undefined {
|
||||
return reference?.reference?.split('/').pop();
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 1,
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3",
|
||||
"date": "2026-11-08T06:47:32.900609+00:00",
|
||||
"period": {
|
||||
"start": "2025-07-01",
|
||||
"end": "2025-12-31"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-evento",
|
||||
"valueDate": "2026-11-08"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T06:47:32.766239+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "TOTAL",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 2
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 100.5,
|
||||
"unit": "d",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
|
||||
"valueDecimal": 70.25
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
|
||||
"valueDecimal": 130.75
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 1,
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/CACU_EU13|0.3.2",
|
||||
"date": "2026-11-08T00:28:51.413089+00:00",
|
||||
"period": {
|
||||
"start": "2025-01-01",
|
||||
"end": "2025-06-30"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:51.351883+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "principal",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 0
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 0.0
|
||||
},
|
||||
"stratifier": [
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "45-54"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 0
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 0.0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 2,
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/CACU_EU7|0.3.3",
|
||||
"date": "2026-11-08T00:28:56.089006+00:00",
|
||||
"period": {
|
||||
"start": "2025-01-01",
|
||||
"end": "2025-06-30"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "TOTAL",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "resultado"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "LIEBG"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"text": "NEGATIVO"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"text": "SIN_DATO"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "45-54"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/CACU_EU7|0.3.3",
|
||||
"date": "2026-11-08T00:28:56.099338+00:00",
|
||||
"period": {
|
||||
"start": "2025-07-01",
|
||||
"end": "2025-12-31"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "TOTAL",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "resultado"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "LIEAG"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"text": "NEGATIVO"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"text": "SIN_DATO"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": [
|
||||
{
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"stratum": [
|
||||
{
|
||||
"value": {
|
||||
"text": "45-54"
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 2,
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/IND1|0.3.2",
|
||||
"date": "2026-11-08T00:28:50.038223+00:00",
|
||||
"period": {
|
||||
"start": "2025-01-01",
|
||||
"end": "2025-06-30"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "principal",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 0.25
|
||||
}
|
||||
}
|
||||
],
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "MeasureReport",
|
||||
"status": "complete",
|
||||
"type": "summary",
|
||||
"measure": "cacu/IND1|0.3.2",
|
||||
"date": "2026-11-08T00:28:50.044435+00:00",
|
||||
"period": {
|
||||
"start": "2025-07-01",
|
||||
"end": "2025-12-31"
|
||||
},
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
|
||||
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
|
||||
}
|
||||
],
|
||||
"group": [
|
||||
{
|
||||
"id": "principal",
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"count": 1
|
||||
}
|
||||
],
|
||||
"measureScore": {
|
||||
"value": 0.25
|
||||
}
|
||||
}
|
||||
],
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "dimensiones": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}], "horizontes_dias": [30, 90, 180, 365], "tipos_periodo": ["mes", "semestre"], "secciones": [{"clave": "resumen", "titulo": "Indicadores de la cohorte", "estado": "disponible", "motivo": null}, {"clave": "distribucion", "titulo": "Distribución de pacientes", "estado": "disponible", "motivo": null}, {"clave": "comparacion", "titulo": "Comparación entre grupos", "estado": "disponible", "motivo": null}, {"clave": "mapa", "titulo": "Mapa entre variables", "estado": "disponible", "motivo": null}, {"clave": "tendencia", "titulo": "Tendencia en el tiempo", "estado": "disponible", "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "medida": "maligno", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "seleccion": {"birads": "BIRADS_4"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "seleccion": {"birads": "BIRADS_4A"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "seleccion": {"birads": "BIRADS_4B"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "seleccion": {"birads": "BIRADS_4C"}}, {"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "seleccion": {"birads": "BIRADS_5"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "seleccion": {"birads": "BIRADS_6"}}], "prueba": {"valida": false, "motivo": "Hacen falta al menos dos grupos con datos publicados.", "nombre": "Chi cuadrada de homogeneidad"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "medida": "invasor", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "<40", "etiqueta": "<40", "seleccion": {"grupo_edad": "<40"}}, {"estado": "disponible", "casos": 5, "total": 12, "valor": 41.67, "ic_bajo": 19.33, "ic_alto": 68.05, "codigo": "40-49", "etiqueta": "40-49", "seleccion": {"grupo_edad": "40-49"}}, {"estado": "disponible", "casos": 6, "total": 13, "valor": 46.15, "ic_bajo": 23.21, "ic_alto": 70.86, "codigo": "50-59", "etiqueta": "50-59", "seleccion": {"grupo_edad": "50-59"}}, {"estado": "disponible", "casos": 8, "total": 17, "valor": 47.06, "ic_bajo": 26.17, "ic_alto": 69.04, "codigo": "60-69", "etiqueta": "60-69", "seleccion": {"grupo_edad": "60-69"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "70+", "etiqueta": "70+", "seleccion": {"grupo_edad": "70+"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "SIN_DATO", "etiqueta": "Sin dato", "seleccion": {"grupo_edad": "SIN_DATO"}}], "prueba": {"valida": true, "estadistico": 0.0889, "gl": 2, "p": 0.9565070599102384, "nombre": "Chi cuadrada de homogeneidad"}}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "biopsia", "total": 61, "items": [{"codigo": "BENIGNO", "etiqueta": "Benigno", "suprimido": false, "n": 21, "porcentaje": 34.43, "ic_bajo": 23.75, "ic_alto": 46.95, "seleccion": {"biopsia": "BENIGNO"}}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_IN_SITU"}}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_INVASOR"}}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"biopsia": "SIN_DATO"}}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"biopsia": "SIN_BIOPSIA"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "total": 61, "items": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "suprimido": false, "n": 33, "porcentaje": 54.1, "ic_bajo": 41.72, "ic_alto": 65.99, "seleccion": {"birads": "BIRADS_4"}}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4A"}}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4B"}}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4C"}}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_5"}}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_6"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "total": 61, "items": [{"codigo": "<40", "etiqueta": "<40", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "<40"}}, {"codigo": "40-49", "etiqueta": "40-49", "suprimido": false, "n": 16, "porcentaje": 26.23, "ic_bajo": 16.84, "ic_alto": 38.44, "seleccion": {"grupo_edad": "40-49"}}, {"codigo": "50-59", "etiqueta": "50-59", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"grupo_edad": "50-59"}}, {"codigo": "60-69", "etiqueta": "60-69", "suprimido": false, "n": 26, "porcentaje": 42.62, "ic_bajo": 31.02, "ic_alto": 55.1, "seleccion": {"grupo_edad": "60-69"}}, {"codigo": "70+", "etiqueta": "70+", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "70+"}}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "SIN_DATO"}}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "escenario": "diagnostico", "corte": "2026-11-16", "umbral_supresion": 5, "unidad": "paciente", "denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6", "grupos": [{"codigo": "BIRADS_4", "n": 33, "suprimido": false}, {"codigo": "BIRADS_4A", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4B", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4C", "n": 0, "suprimido": false}, {"codigo": "BIRADS_5", "n": null, "suprimido": true}, {"codigo": "BIRADS_6", "n": null, "suprimido": true}], "horizonte_dias": 0, "indicadores": []}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
|
||||
@@ -0,0 +1 @@
|
||||
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "horizonte_dias": 90, "indicadores": [{"clave": "cohorte", "titulo": "Pacientes en la cohorte BI-RADS 4 a 6", "descripcion": "Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "unidad": "pacientes", "estado": "disponible", "valor": 61, "ic_bajo": null, "ic_alto": null, "n": 61, "denominador": null, "q1": null, "q3": null, "motivo": null}, {"clave": "con_biopsia", "titulo": "Con biopsia reportada", "descripcion": "Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.", "unidad": "%", "estado": "disponible", "valor": 68.85, "ic_bajo": 56.41, "ic_alto": 79.06, "n": 42, "denominador": 61, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_conocido", "titulo": "Resultado maligno entre las biopsias con resultado", "descripcion": "Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. No es incidencia: el denominador son pacientes ya biopsiadas.", "unidad": "%", "estado": "disponible", "valor": 50.0, "ic_bajo": 35.53, "ic_alto": 64.47, "n": 21, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "invasor_conocido", "titulo": "Carcinoma invasor entre las biopsias con resultado", "descripcion": "Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.", "unidad": "%", "estado": "disponible", "valor": 45.24, "ic_bajo": 31.22, "ic_alto": 60.05, "n": 19, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "biopsia_90d", "titulo": "Biopsia reportada en 90 días", "descripcion": "Pacientes cuya biopsia se reportó dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte.", "unidad": "%", "estado": "disponible", "valor": 75.56, "ic_bajo": 61.33, "ic_alto": 85.76, "n": 34, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_90d", "titulo": "Cáncer confirmado en 90 días", "descripcion": "Pacientes con un reporte de biopsia maligna dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte. No es incidencia acumulada: no hay seguimiento de quien no tuvo biopsia.", "unidad": "%", "estado": "disponible", "valor": 40.0, "ic_bajo": 27.02, "ic_alto": 54.55, "n": 18, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "dias_a_biopsia", "titulo": "Días de la mastografía al reporte de biopsia", "descripcion": "Mediana y cuartiles entre las pacientes con biopsia reportada.", "unidad": "días", "estado": "disponible", "valor": 27.5, "ic_bajo": null, "ic_alto": null, "n": 42, "denominador": null, "q1": 19.25, "q3": 30.75, "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"corte": "2026-11-16", "umbral_supresion": 5, "tipo_periodo": "semestre", "unidad": "reportes", "poblacion": "Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, de todas las pacientes; no la cohorte de Seguimiento", "alcance_biopsias": "Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); una biopsia sin mastografía ligada no se cuenta", "denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": [{"periodo": "2025-S1", "inicio": "2025-01-01", "fin": "2025-06-30", "incompleto": false, "reportes_mastografia": {"total": 96, "por_categoria": {"4_a_6": {"n": 31, "suprimido": false}, "otras": {"n": 65, "suprimido": false}}}, "reportes_biopsia": {"total": 24, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 15, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 16, "total": 24, "valor": 66.67, "ic_bajo": 46.71, "ic_alto": 82.03}}, {"periodo": "2025-S2", "inicio": "2025-07-01", "fin": "2025-12-31", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 37, "suprimido": false}, "otras": {"n": 60, "suprimido": false}}}, "reportes_biopsia": {"total": 25, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 13, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 14, "total": 25, "valor": 56.0, "ic_bajo": 37.07, "ic_alto": 73.33}}, {"periodo": "2026-S1", "inicio": "2026-01-01", "fin": "2026-06-30", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 25, "suprimido": false}, "otras": {"n": 72, "suprimido": false}}}, "reportes_biopsia": {"total": 18, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 11, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 13, "total": 18, "valor": 72.22, "ic_bajo": 49.13, "ic_alto": 87.5}}, {"periodo": "2026-S2", "inicio": "2026-07-01", "fin": "2026-12-31", "incompleto": true, "reportes_mastografia": {"total": 72, "por_categoria": {"4_a_6": {"n": 27, "suprimido": false}, "otras": {"n": 45, "suprimido": false}}}, "reportes_biopsia": {"total": 19, "por_grado": {"BENIGNO": {"n": 9, "suprimido": false}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": null, "suprimido": true}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 10, "total": 19, "valor": 52.63, "ic_bajo": 31.71, "ic_alto": 72.67}}]}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,842 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 8,
|
||||
"link": [
|
||||
{
|
||||
"relation": "self",
|
||||
"url": "http://127.0.0.1:28091/cama/fhir/Measure?_count=50&_offset=0"
|
||||
}
|
||||
],
|
||||
"entry": [
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIOPSIAS",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIOPSIAS",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIOPSIAS",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_biopsias",
|
||||
"title": "Distribución de resultados de biopsia",
|
||||
"status": "active",
|
||||
"description": "Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada paciente. «Sin dato»: el reporte no trae grado.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_biopsias"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "grado"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads",
|
||||
"title": "Distribución de BI-RADS",
|
||||
"status": "active",
|
||||
"description": "Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías. «Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS-CANCER-INVASOR",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
|
||||
"version": "0.1.0",
|
||||
"name": "cama_birads_cancer_invasor",
|
||||
"title": "BI-RADS de los cánceres invasores",
|
||||
"status": "active",
|
||||
"description": "De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico, etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_cancer_invasor"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "grupo_edad"
|
||||
}
|
||||
],
|
||||
"text": "grupo_edad"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "estadio"
|
||||
}
|
||||
],
|
||||
"text": "Estadio clínico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "etapa"
|
||||
}
|
||||
],
|
||||
"text": "Etapa"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "clasificacion"
|
||||
}
|
||||
],
|
||||
"text": "Subtipo molecular"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "tamano"
|
||||
}
|
||||
],
|
||||
"text": "Tamaño tumoral (T)"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads_456_mastografia",
|
||||
"title": "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6",
|
||||
"status": "active",
|
||||
"description": "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_456_mastografia"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-PACIENTE",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-BIRADS456-PACIENTE",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_birads_456_paciente",
|
||||
"title": "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
|
||||
"status": "active",
|
||||
"description": "Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus mastografías.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C2"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "cohort"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_birads_456_paciente"
|
||||
}
|
||||
}
|
||||
],
|
||||
"stratifier": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
|
||||
"code": "birads"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "paciente"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-CONFIRMACION-BIRADS45",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
|
||||
"version": "0.2.0",
|
||||
"name": "cama_confirmacion_birads45",
|
||||
"title": "Tasa de confirmación histopatológica",
|
||||
"status": "active",
|
||||
"description": "De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si la biopsia confirmó cáncer.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C1"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "proportion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "principal"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_denominador"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "denominator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Denominador",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_denominador"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "numerator"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Numerador",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_confirmacion_birads45_numerador"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "episodio"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "increase"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
|
||||
"version": "0.2.2",
|
||||
"name": "cama_dias_toma_diagnostico",
|
||||
"title": "Tiempo de tamizaje a diagnóstico",
|
||||
"status": "active",
|
||||
"description": "Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_dias_toma_diagnostico"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-EU38A",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CAMA-EU38A",
|
||||
"url": "https://isssteleon.org/fhir/Measure/CAMA-EU38A",
|
||||
"version": "0.2.1",
|
||||
"name": "cama_eu38a",
|
||||
"title": "Días de la toma de la mastografía a su resultado",
|
||||
"status": "active",
|
||||
"description": "Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
}
|
||||
],
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cama_eu38a"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 6, "desde": "2026-05-18", "hasta": "2026-11-17"}, "filtros": {"birads": "BIRADS_5", "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "254", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-11", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-09-16"}, {"pac_id": "129", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-22", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-20"}, {"pac_id": "117", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-09"}, {"pac_id": "101", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-03", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-31"}, {"pac_id": "225", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-02", "biopsia": "CARCINOMA_IN_SITU", "biopsia_fecha": "2026-07-31"}, {"pac_id": "287", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-14", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-13"}, {"pac_id": "55", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-09", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-30"}, {"pac_id": "7", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-02", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "260", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-05-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-07"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 3, "desde": "2026-08-18", "hasta": "2026-11-17"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "54", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "255", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-21", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "4", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-10", "biopsia": "BENIGNO", "biopsia_fecha": "2026-11-06"}, {"pac_id": "256", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-08", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "239", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-14", "biopsia": "BENIGNO", "biopsia_fecha": "2026-10-06"}, {"pac_id": "245", "grupo_edad": "40-49", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-09", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "186", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-31", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "282", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-29", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-10"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "31", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}]}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
@@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||
}
|
||||
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
|
||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
||||
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
||||
@@ -38,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
|
||||
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
|
||||
expect(fixture.nativeElement.querySelector('.catalog-metadata')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
|
||||
// The internal panel heading is deliberately visually hidden and retains identity.
|
||||
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
|
||||
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
|
||||
@@ -47,13 +46,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => {
|
||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
|
||||
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
||||
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
|
||||
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
|
||||
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
|
||||
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
|
||||
]);
|
||||
http.expectNone(() => true);
|
||||
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
|
||||
for (const [id, label] of [
|
||||
@@ -62,7 +57,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
['fig_c2_donas', 'Donas'],
|
||||
['fig_c9_futura', 'Representación 5'],
|
||||
]) {
|
||||
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
|
||||
fixture.componentInstance.selectFigure(id); fixture.detectChanges();
|
||||
const pending = request(id);
|
||||
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
||||
expect(pending.request.params.get('tema')).toBe('claro');
|
||||
@@ -74,9 +69,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
|
||||
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
it('no ofrece selector de representación y sólo consulta la figura mostrada', () => {
|
||||
fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull();
|
||||
request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
|
||||
@@ -98,9 +93,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
||||
});
|
||||
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
||||
open(); const first = request('f'); expect(select().disabled).toBe(false);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
|
||||
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
|
||||
open(); const first = request('f'); expect(panels()).toHaveLength(1);
|
||||
fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
|
||||
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
||||
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
||||
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
||||
|
||||
@@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan
|
||||
import { catchError, of, Subscription } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
@@ -29,14 +27,16 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
@if (!conteos) {
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
}
|
||||
@if (!sobrio) {
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
||||
@@ -44,7 +44,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||
</button>
|
||||
}
|
||||
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
|
||||
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="conteos ? null : titleId">
|
||||
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
|
||||
@if (isEu7) {
|
||||
<div #visibilityRegion class="eu7-region">
|
||||
@@ -64,19 +64,9 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
</div>
|
||||
} @else if (conteos; as par) {
|
||||
<div #visibilityRegion class="conteos-region">
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
@if (!sobrio && (!pair.length || otherFigures.length)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Representación gráfica</mat-label>
|
||||
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
|
||||
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
|
||||
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
|
||||
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||
@for (figure of displayFigures; track panelIdentity(figure)) {
|
||||
<div class="representation-panel">
|
||||
@@ -145,8 +135,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
|
||||
});
|
||||
}
|
||||
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
|
||||
get sobrio() { return this.dominio === 'cama'; }
|
||||
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
|
||||
get sobrio() { return true; }
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
@@ -156,7 +146,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
private updateNumeric() {
|
||||
|
||||
@@ -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);
|
||||
@@ -26,6 +35,23 @@ summary { cursor: pointer; padding-block: .75rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
.histo-meta { display: flex; justify-content: flex-end; align-items: flex-start; gap: .75rem; margin: -.85rem -.65rem 0 0; }
|
||||
.view-context { display: flex; flex-direction: column; align-items: flex-end; gap: .1rem; margin: .2rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; }
|
||||
.histo .figure { border-top: 0; }
|
||||
.histo .figure + .figure { border-top: 1px solid var(--issste-border); padding-top: .25rem; }
|
||||
.histo .help { position: relative; display: flex; justify-content: flex-end; padding-bottom: 0; }
|
||||
.histo .help .methodology-toggle { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; font-weight: 800; font-size: 1rem; line-height: 1; background: var(--issste-accent); color: var(--issste-on-accent); }
|
||||
.histo .help .methodology { position: absolute; z-index: 8; top: 100%; right: 0; width: min(34rem, calc(100vw - 2rem)); max-height: 18rem; overflow: auto; background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
|
||||
.histo .legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
|
||||
.histo .tab-bar { display: flex; align-items: flex-end; gap: .5rem; border-bottom: 1px solid var(--issste-border); }
|
||||
.histo .tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
|
||||
.histo .tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
|
||||
.histo .tabs .tab[aria-selected=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
|
||||
.histo .child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
|
||||
.histo .tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
|
||||
.histo .tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); }
|
||||
.histo .tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); }
|
||||
.histo .tab .swatch, .histo .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide + .reading-guide { margin-top: 1rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
@@ -34,4 +60,7 @@ app-plotly-chart { --plot-height: 360px; }
|
||||
.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
|
||||
.rate-states:empty { display: none; }
|
||||
/* Rates on the left, donut on the right (the reverse of EU7). */
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); } }
|
||||
@media (min-width: 1100px) {
|
||||
.figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); }
|
||||
.histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; }
|
||||
}
|
||||
|
||||
@@ -1,21 +1,4 @@
|
||||
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
|
||||
<h3>Dona por categoría</h3>
|
||||
@if (donutGuide; as guide) {
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
|
||||
</section>
|
||||
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
|
||||
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
|
||||
<p>Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
|
||||
@@ -24,6 +7,8 @@
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' && model; as m) {
|
||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
@@ -32,22 +17,43 @@
|
||||
</nav>
|
||||
}
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
<section class="figure">
|
||||
<div class="figure-head">
|
||||
<h3>{{ tituloMastografias }}</h3>
|
||||
<div class="help" (mouseenter)="openHelp('examenes')" (mouseleave)="hideHelp('examenes')" (focusin)="openHelp('examenes')" (focusout)="onHelpFocusOut('examenes', $event)">
|
||||
<button type="button" class="help-icon" aria-label="Cómo leer, mastografías por categoría" [attr.aria-expanded]="helpWhich === 'examenes'"
|
||||
[attr.aria-describedby]="helpWhich === 'examenes' ? 'cama-birads-ayuda-mastografias' : null" (click)="toggleHelp('examenes')"><span aria-hidden="true">!</span></button>
|
||||
@if (helpWhich === 'examenes') {
|
||||
<div class="methodology" id="cama-birads-ayuda-mastografias" role="tooltip">Cada mastografía cuenta en su propia categoría.</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@if (total) {
|
||||
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
||||
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="tituloMastografias" />
|
||||
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
||||
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||
</section>
|
||||
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
|
||||
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
|
||||
<section class="figure">
|
||||
<div class="figure-head">
|
||||
<h3>{{ tituloPacientes }}</h3>
|
||||
<div class="help" (mouseenter)="openHelp('pacientes')" (mouseleave)="hideHelp('pacientes')" (focusin)="openHelp('pacientes')" (focusout)="onHelpFocusOut('pacientes', $event)">
|
||||
<button type="button" class="help-icon" aria-label="Cómo leer, pacientes por categoría" [attr.aria-expanded]="helpWhich === 'pacientes'"
|
||||
[attr.aria-describedby]="helpWhich === 'pacientes' ? 'cama-birads-ayuda-pacientes' : null" (click)="toggleHelp('pacientes')"><span aria-hidden="true">!</span></button>
|
||||
@if (helpWhich === 'pacientes') {
|
||||
<div class="methodology" id="cama-birads-ayuda-pacientes" role="tooltip">La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@if (totalPacientes) {
|
||||
<app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="tituloPacientes" />
|
||||
} @else { <p role="status">{{ !m.pacientesVerificados ? 'Dona de pacientes no disponible hasta verificar la definición publicada.' : totalPacientes === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.pacientes + ' en el periodo.' }}</p> }
|
||||
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
|
||||
</section>
|
||||
</div>
|
||||
<p class="note">Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.</p>
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
|
||||
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más alta) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
|
||||
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
|
||||
@@ -3,17 +3,28 @@
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.figure-head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
|
||||
.figure-head h3 { margin: 0; }
|
||||
.help { display: flex; flex: none; justify-content: flex-end; }
|
||||
.help .methodology { position: absolute; z-index: 8; inset-block-start: calc(100% + .35rem); inset-inline-end: 0;
|
||||
box-sizing: border-box; inline-size: min(34rem, 100%); background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
|
||||
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
||||
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
|
||||
.periods button:disabled { opacity: .5; cursor: default; }
|
||||
// The two figures share the card in equal halves; one above the other on a narrow card.
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.help-icon { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; background: var(--issste-accent); color: var(--issste-on-accent); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
|
||||
.help-icon:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; }
|
||||
.figure + .figure { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-4); padding-top: var(--issste-space-4); }
|
||||
@media (min-width: 1100px) {
|
||||
.figures { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.figure + .figure { border-top: 0; margin-top: 0; padding-top: 0; border-inline-start: 1px solid var(--issste-border); padding-inline-start: var(--issste-space-6); }
|
||||
}
|
||||
app-plotly-chart { --plot-height: 400px; }
|
||||
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
|
||||
.donut-chart { --plot-min-width: 230px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; }
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { TitleCasePipe } from '@angular/common';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
|
||||
import { ConteosIncompatibles, donaConteos, donaPacientes, ModeloConteos, modelosConteos, ParConteos, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-conteos-pareados',
|
||||
@@ -25,38 +25,45 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
periodIndex = 0;
|
||||
pages: ModeloConteos[] = [];
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
patientsFigure?: PlotlyFigure;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
// On a narrow screen the donut's long label gives way to a legend under it.
|
||||
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
|
||||
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
|
||||
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
|
||||
private anchoDona = 390;
|
||||
private anchoPacientes = 390;
|
||||
|
||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
||||
get totalPacientes() { return this.model ? totalPacientes(this.model) : null; }
|
||||
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
|
||||
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
|
||||
helpOpen = false;
|
||||
// "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's
|
||||
// description of its own bars does not apply to them and is not used.
|
||||
get donutGuide() {
|
||||
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
|
||||
helpWhich: 'examenes' | 'pacientes' | null = null;
|
||||
private helpPinned: 'examenes' | 'pacientes' | null = null;
|
||||
toggleHelp(which: 'examenes' | 'pacientes') {
|
||||
if (this.helpPinned === which) { this.helpPinned = null; this.helpWhich = null; return; }
|
||||
this.helpPinned = which;
|
||||
this.openHelp(which);
|
||||
}
|
||||
openHelp(which: 'examenes' | 'pacientes') {
|
||||
this.helpWhich = which;
|
||||
}
|
||||
hideHelp(which: 'examenes' | 'pacientes') {
|
||||
if (this.helpPinned === which) return;
|
||||
if (this.helpWhich === which) this.helpWhich = null;
|
||||
}
|
||||
onHelpFocusOut(which: 'examenes' | 'pacientes', event: FocusEvent) {
|
||||
const next = event.relatedTarget;
|
||||
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
|
||||
if (this.helpPinned === which) this.helpPinned = null;
|
||||
if (this.helpWhich === which) this.helpWhich = null;
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
||||
@@ -68,7 +75,7 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
|
||||
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.patientsFigure = undefined; }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
@@ -108,12 +115,24 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.draw();
|
||||
}
|
||||
ajustarAnchoDona(ancho: number) {
|
||||
if (ancho === this.anchoDona) return;
|
||||
this.anchoDona = ancho;
|
||||
const m = this.model;
|
||||
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
|
||||
}
|
||||
ajustarAnchoPacientes(ancho: number) {
|
||||
if (ancho === this.anchoPacientes) return;
|
||||
this.anchoPacientes = ancho;
|
||||
const m = this.model;
|
||||
if (m) this.patientsFigure = donaPacientes(m, this.par, this.tema, ancho);
|
||||
}
|
||||
private draw() {
|
||||
const m = this.model;
|
||||
if (!m) return;
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false);
|
||||
this.barsFigure = barrasConteos(m, this.par, this.tema);
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
|
||||
this.patientsFigure = donaPacientes(m, this.par, this.tema, this.anchoPacientes);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { percentText } from './indicadores-format';
|
||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
@@ -101,7 +101,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|
||||
|| !(stratifiedCapabilities(this.indicador).includes(ESTRATO) || declaraEstrato(this.indicador, ESTRATO))
|
||||
|| !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
|
||||
@@ -83,7 +83,23 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
|
||||
@if (row.group; as g) {
|
||||
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
|
||||
}
|
||||
@for (c of row.items; track c.id) {
|
||||
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
|
||||
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||
@for (entry of state.donutLegend; track entry.label) {
|
||||
<span class="donut-static-legend__item" role="listitem">
|
||||
@@ -94,7 +110,7 @@
|
||||
}
|
||||
</div>
|
||||
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
:host(.methodology-expanded) .figure-card { grid-row: auto; }
|
||||
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
|
||||
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; }
|
||||
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
|
||||
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
|
||||
|
||||
@@ -113,3 +113,16 @@
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||
}
|
||||
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
|
||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||
.dark .highlight-legend { color: #eef1f7; }
|
||||
.highlight-status { margin: 0; font-weight: 600; }
|
||||
.highlight-back { justify-self: start; }
|
||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 999px; font: inherit; cursor: pointer; }
|
||||
.highlight-legend button:disabled { opacity: .45; cursor: default; }
|
||||
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||
.highlight-legend .highlight-group { font-weight: 600; }
|
||||
|
||||
@@ -12,6 +12,8 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
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 {
|
||||
@@ -22,6 +24,10 @@ export interface FigureState {
|
||||
categoryLabels?: readonly CategoryLabel[];
|
||||
minimumPlotWidth?: number;
|
||||
donutLegend?: readonly DonutLegendEntry[];
|
||||
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
|
||||
ownLayout?: boolean;
|
||||
// Legend buttons that highlight one part of the figure (CaCu style).
|
||||
highlight?: FigureHighlight;
|
||||
plotWidth?: number;
|
||||
plotHeight?: number;
|
||||
message?: string;
|
||||
@@ -57,14 +63,15 @@ 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';
|
||||
}
|
||||
@Input({ required: true }) set state(value: FigureState) {
|
||||
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
|
||||
this.currentState = value;
|
||||
if (value.status === 'ready') {
|
||||
this.updateDonut();
|
||||
@@ -87,7 +94,8 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
||||
this.chartFigure = source && hierarchy
|
||||
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
||||
: source && this.state.donutLegend ? donutSimpleView(source) : source;
|
||||
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
|
||||
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
|
||||
}
|
||||
expandParent(parent: string) {
|
||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||
@@ -109,9 +117,28 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
target?.focus();
|
||||
}
|
||||
}
|
||||
highlightSelection: HighlightSelection = {};
|
||||
readonly highlightRows = highlightRows;
|
||||
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
|
||||
highlight(kind: 'group' | 'item', id: string) {
|
||||
if (!this.state.highlight) return;
|
||||
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
|
||||
this.updateDonut();
|
||||
}
|
||||
highlightBack() {
|
||||
const sel = this.highlightSelection;
|
||||
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
|
||||
this.updateDonut();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
||||
const point = event.points[0];
|
||||
if (this.state.highlight) {
|
||||
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
|
||||
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
|
||||
if (hit) this.highlight(hit.kind, hit.id);
|
||||
return;
|
||||
}
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
|
||||
@@ -215,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
});
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
@@ -228,18 +228,13 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(state?.applied?.selection.mode).toBe('todos');
|
||||
apply();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S2');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
apply();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
manual.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
||||
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
||||
@@ -300,7 +295,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual');
|
||||
const control = filters(); control.select([]);
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
@@ -308,9 +303,9 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
const control = filters(); control.select([]); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
apply();
|
||||
const req = figure();
|
||||
@@ -320,7 +315,6 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
expect(page.result().message).toContain('esta selección');
|
||||
expect(page.result().message).not.toContain('2025');
|
||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
||||
expect(control.selectedPeriods).toEqual(periodos);
|
||||
control.select([]);
|
||||
page.requestFigure();
|
||||
@@ -333,7 +327,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
@@ -344,17 +338,17 @@ describe('IndicadorFigurePanel', () => {
|
||||
page.requestFigure();
|
||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} });
|
||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
});
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); const old = figure();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
apply(); const current = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S2');
|
||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||
@@ -362,7 +356,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
|
||||
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||
|
||||
@@ -13,7 +13,10 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified';
|
||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
@@ -22,8 +25,48 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
selector: 'app-indicador-figure-panel',
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section class="figure-panel" [attr.aria-labelledby]="titleId">
|
||||
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
@if (sidebar) {
|
||||
<aside class="strata-sidebar" aria-label="Estratificación">
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Estratificar por</legend>
|
||||
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
|
||||
(click)="changeDimension('')">Sin estratificar</button>
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
|
||||
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||
}
|
||||
</div>
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
|
||||
@if (dimension && estratos.length > 1) {
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Mostrar</legend>
|
||||
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
|
||||
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
|
||||
@for (e of estratos; track e.valor) {
|
||||
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
|
||||
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
|
||||
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
|
||||
</fieldset>
|
||||
}
|
||||
@if (dimension) {
|
||||
<fieldset class="sidebar-group">
|
||||
<legend>Medida</legend>
|
||||
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
}
|
||||
</aside>
|
||||
}
|
||||
<header class="panel-controls">
|
||||
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
|
||||
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
|
||||
@@ -33,7 +76,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
|
||||
</span>
|
||||
}
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
|
||||
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
||||
<legend>Distribución</legend>
|
||||
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
|
||||
@@ -46,10 +89,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
|
||||
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (dimension) {
|
||||
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||
}
|
||||
@@ -68,8 +117,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
|
||||
</tbody></table></div>
|
||||
</details>
|
||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||
@@ -114,6 +163,30 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
|
||||
.donut-periods button:disabled { opacity: .45; }
|
||||
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
|
||||
shared with the neighbouring panel, so the bars line up with the donut. */
|
||||
:host { container-type: inline-size; }
|
||||
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
|
||||
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
|
||||
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
|
||||
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
|
||||
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
|
||||
.sidebar-list { display: grid; gap: .25rem; }
|
||||
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
|
||||
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
|
||||
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.sidebar-reset { margin-top: .5rem; }
|
||||
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
@container (max-width: 559px) {
|
||||
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
|
||||
.strata-sidebar { position: static; }
|
||||
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
|
||||
}
|
||||
.visually-hidden {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
@@ -162,7 +235,39 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||
}
|
||||
dimension: DimensionEstrato | '' = '';
|
||||
readonly etiquetaDimension = etiquetaDimension;
|
||||
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
|
||||
private medidaElegida?: MedidaEstrato;
|
||||
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
|
||||
changeMedida(medida: MedidaEstrato) {
|
||||
if (medida === this.medida) return;
|
||||
this.medidaElegida = medida;
|
||||
this.representStratified();
|
||||
}
|
||||
cells: StratifiedCell[] = [];
|
||||
/** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */
|
||||
get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; }
|
||||
estratos: StratumOption[] = [];
|
||||
ocultos = new Set<string>();
|
||||
toggleEstrato(valor: string) {
|
||||
const ocultos = new Set(this.ocultos);
|
||||
if (ocultos.has(valor)) ocultos.delete(valor);
|
||||
else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor);
|
||||
else return;
|
||||
this.ocultos = ocultos;
|
||||
this.representStratified();
|
||||
}
|
||||
mostrarTodos() {
|
||||
if (!this.ocultos.size) return;
|
||||
this.ocultos = new Set();
|
||||
this.representStratified();
|
||||
}
|
||||
private representStratified() {
|
||||
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||
try { this.result.set(this.presentStratified(this.stratifiedData)); }
|
||||
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
|
||||
}
|
||||
}
|
||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||
private stratifiedData?: IndicadorDatos;
|
||||
@@ -174,14 +279,18 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
changeDimension(value: DimensionEstrato | '') {
|
||||
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
|
||||
if (this.dimension === value) return;
|
||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
|
||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set();
|
||||
this.requestFigure();
|
||||
}
|
||||
chooseStratified() {
|
||||
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
|
||||
}
|
||||
private presentStratified(data: IndicadorDatos): FigureState {
|
||||
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
|
||||
this.estratos = stratumOptions(data);
|
||||
const publicados = new Set(this.estratos.map(e => e.valor));
|
||||
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos);
|
||||
this.cells = adapted.cells;
|
||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||
@@ -245,6 +354,26 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
||||
}));
|
||||
}
|
||||
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
|
||||
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
|
||||
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
|
||||
const adapted = c1DonutFigure(data, selection);
|
||||
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
|
||||
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
|
||||
}));
|
||||
}
|
||||
if (c1AlterationCapability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(map(data => {
|
||||
const adapted = c1AlterationFigure(data, selection);
|
||||
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||
highlight: adapted.highlight, ownLayout: true, plotHeight: 400,
|
||||
emptyMessage: adapted.total === 0 ? 'Ningún niño tiene su primer EEG de buena calidad en la selección; no hay un porcentaje que representar.' : undefined };
|
||||
}));
|
||||
}
|
||||
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||
// Both panels, KPI and numeric table share the exact same transport key.
|
||||
// Do not catch /datos errors here: a backend failure is a real error state.
|
||||
@@ -265,6 +394,13 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||
}
|
||||
const adapted = c2Figure(data, selection);
|
||||
if (adapted.status === 'supported' && selection.dominio === 'tea') {
|
||||
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
|
||||
if (selection.figura === 'fig_c2_donas') {
|
||||
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
|
||||
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
|
||||
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
|
||||
}
|
||||
return adapted.status === 'supported'
|
||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||
@@ -319,7 +455,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
}
|
||||
}
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) {
|
||||
this.dimension = ''; this.estratos = []; this.ocultos = new Set();
|
||||
}
|
||||
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
||||
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
|
||||
this.titleId = identityElementId(identity) + '-title';
|
||||
|
||||
@@ -1,20 +1,27 @@
|
||||
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
<section class="confirmacion histo" aria-label="Resultado histopatológico por categoría BI-RADS">
|
||||
<div class="histo-meta">
|
||||
<p class="view-context">
|
||||
<span>{{ intervalLabel }}</span>
|
||||
@if (contextPeriod) { <span>Periodo {{ contextPeriod }}</span> }
|
||||
</p>
|
||||
<div class="help" (mouseenter)="showHelp()" (mouseleave)="hideHelp()" (focusin)="showHelp()" (focusout)="onHelpFocusOut($event)">
|
||||
<button type="button" class="methodology-toggle" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" [attr.aria-describedby]="helpOpen ? 'histo-como-leer' : null" (click)="toggleHelp()"><span aria-hidden="true">!</span></button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology" id="histo-como-leer" role="tooltip">
|
||||
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||
@@ -30,19 +37,25 @@
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" 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 class="legend">
|
||||
<div class="tab-bar">
|
||||
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
|
||||
@for (g of m.grupos; track g.id; let gi = $index) {
|
||||
<button type="button" role="tab" class="tab" [id]="'histo-tab-' + g.id" [style.--swatch]="g.color" [attr.aria-selected]="selection?.grupo === g.id" [attr.aria-controls]="'histo-panel-' + g.id" (click)="select('grupos', gi)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</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="child-groups">
|
||||
@for (g of m.grupos; track g.id) {
|
||||
<div class="tab-panel" role="group" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + g.id">
|
||||
@for (c of 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>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -51,13 +64,10 @@
|
||||
@if (ratesFigure) {
|
||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
<ul class="rate-states">
|
||||
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
||||
</ul>
|
||||
</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>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { Celda } from './indicadores-confirmacion-citologia';
|
||||
@@ -43,6 +43,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
donutFigure?: PlotlyFigure;
|
||||
ratesFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private helpPinned = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
@@ -54,7 +55,11 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
private readonly alCambiarAncho = () => this.draw();
|
||||
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get intervalLabel() { return this.applied?.tipo === 'mes' ? 'Intervalo mensual' : 'Intervalo semestral'; }
|
||||
get contextPeriod() {
|
||||
return this.model?.periodo ?? this.periods[this.periodIndex]
|
||||
?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : '');
|
||||
}
|
||||
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
||||
@@ -71,7 +76,23 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
toggleHelp() {
|
||||
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
|
||||
this.helpPinned = true;
|
||||
this.showHelp();
|
||||
}
|
||||
showHelp() {
|
||||
if (this.helpOpen) return;
|
||||
this.helpOpen = true;
|
||||
this.metadataRequested.emit();
|
||||
}
|
||||
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
|
||||
onHelpFocusOut(event: FocusEvent) {
|
||||
const next = event.relatedTarget;
|
||||
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
|
||||
this.helpPinned = false;
|
||||
this.helpOpen = false;
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
||||
|
||||
@@ -27,6 +27,10 @@ import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba');
|
||||
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
|
||||
expect(fixture.nativeElement.textContent).toContain('Referencia de prueba');
|
||||
expect(fixture.nativeElement.querySelector('.period-label')).toBeNull();
|
||||
fixture.componentRef.setInput('temporalReference', '2025-S2'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.period-label').textContent).toBe('Periodo:');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-foot').textContent).toContain('2025-S2');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba');
|
||||
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
|
||||
@@ -12,16 +12,23 @@ import { MatCardModule } from '@angular/material/card';
|
||||
@if (value !== null && value !== undefined) {
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
|
||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||
<div class="kpi-foot">
|
||||
@if (showPeriod && temporalReference) {
|
||||
<p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p>
|
||||
}
|
||||
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
|
||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||
</div>
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
|
||||
:host { display: flex; flex-direction: column; height: 100%; min-width: 0; }
|
||||
mat-card { box-sizing: border-box; display: flex; flex-direction: column; flex: 1 1 auto; height: auto; min-height: 100%; padding: var(--issste-space-6);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
||||
border-radius: var(--issste-radius); box-shadow: none; }
|
||||
.kpi-foot { margin-top: auto; }
|
||||
.period { display: flex; flex-wrap: wrap; align-items: baseline; gap: .35rem; }
|
||||
.period-label { font-weight: 600; }
|
||||
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
||||
h3, p { overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
@@ -30,9 +37,9 @@ import { MatCardModule } from '@angular/material/card';
|
||||
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
// CaMa's cards are as tall as their grid row.
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
|
||||
:host-context(.kpi-section) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section) mat-card { flex: 1 1 auto; height: auto; }
|
||||
:host-context(.kpi-section) .value { font-size: 1.65rem; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiCard {
|
||||
@@ -40,12 +47,18 @@ export class IndicadorKpiCard {
|
||||
@Input() value?: string | number | null;
|
||||
@Input() unit?: string;
|
||||
@Input() temporalReference?: string;
|
||||
// The opportunity strip shares one period, shown by the parent instead of on every card.
|
||||
@Input() showPeriod = true;
|
||||
@Input() loading = false;
|
||||
@Input() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
// A card that shows its value needs no "Disponible" line.
|
||||
@Input() quietWhenAvailable = false;
|
||||
@Input() additionalInfo?: string;
|
||||
get labeledPeriod(): boolean {
|
||||
const text = this.temporalReference?.trim();
|
||||
return !!text && text.split(',').every(part => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(part.trim()));
|
||||
}
|
||||
get informationLine(): string | undefined {
|
||||
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
||||
return [...new Set(lines)].join(' ');
|
||||
|
||||
@@ -39,7 +39,8 @@ describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
latest.flush(data(periods[0], 'suppressed'));
|
||||
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().value).toBe(5);
|
||||
expect(fixture.nativeElement.textContent).toContain('Último dato visible, 2025-S1');
|
||||
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible, 2025-S1');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Último dato visible');
|
||||
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
@@ -27,9 +27,14 @@ describe('KPI integración con autoridad global', () => {
|
||||
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
||||
flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo })));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
// Availability runs four requests at a time; flushing one batch starts the next.
|
||||
function flushPeriodos(periodos: () => unknown[]) {
|
||||
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos')))
|
||||
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() }));
|
||||
}
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
@@ -56,7 +61,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(panels().map(p => p.definition.id)).toEqual([]);
|
||||
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => {
|
||||
it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => {
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
||||
load('tea'); const initial = requests();
|
||||
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
||||
@@ -64,8 +69,10 @@ describe('KPI integración con autoridad global', () => {
|
||||
const req = requests();
|
||||
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
|
||||
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
|
||||
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||
expect(panels()[3].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
|
||||
expect(panels()[4].result().info).toBe('2 de 5 pacientes con diagnóstico confirmado no tienen todavía un EEG de buena calidad.');
|
||||
});
|
||||
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
|
||||
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||
@@ -80,7 +87,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
@@ -164,7 +171,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
||||
flushPeriodos(() => []); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
@@ -176,14 +183,18 @@ describe('KPI integración con autoridad global', () => {
|
||||
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
|
||||
fixture.detectChanges();
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined]);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined]);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
|
||||
expect(cards).toHaveLength(5);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
|
||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
|
||||
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('2025-S1'),
|
||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||
]));
|
||||
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
|
||||
expect(cards.filter(card => card.querySelector('.value')).every(card => card.querySelector('.kpi-state')?.classList.contains('visually-hidden'))).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
|
||||
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
|
||||
|
||||
@@ -19,14 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" />
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="true"
|
||||
[showPeriod]="false" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
|
||||
:host-context(.kpi-section) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section) app-indicador-kpi-card { flex: 1 1 auto; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Component, inject, Input, OnChanges, signal } from '@angular/core';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, PlotlyFigure } from './indicadores.models';
|
||||
import { proportionFigure } from './measure-report';
|
||||
import { MeasureReportService } from './measure-report.service';
|
||||
|
||||
/** A proportion drawn from the WebApi's FHIR `MeasureReport`s: the data comes as the standard, the figure is ours. */
|
||||
@Component({
|
||||
selector: 'app-indicador-measure-report',
|
||||
imports: [MatProgressBarModule, PlotlyChart],
|
||||
template: `
|
||||
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando indicador" /> }
|
||||
@if (status() === 'error') { <p role="alert">No se pudo cargar el indicador.</p> }
|
||||
@if (figure(); as figure) { <app-plotly-chart [figure]="figure" [label]="titulo" /> }
|
||||
`,
|
||||
})
|
||||
export class IndicadorMeasureReport implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: string;
|
||||
@Input({ required: true }) titulo!: string;
|
||||
@Input({ required: true }) periodos!: string[];
|
||||
@Input() estrato?: string;
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
readonly figure = signal<PlotlyFigure | undefined>(undefined);
|
||||
private readonly service = inject(MeasureReportService);
|
||||
|
||||
ngOnChanges() {
|
||||
this.status.set('loading');
|
||||
this.service.series(this.dominio, this.indicador, this.periodos).subscribe({
|
||||
next: series => { this.figure.set(proportionFigure(series, this.titulo, this.estrato)); this.status.set('ready'); },
|
||||
error: () => { this.figure.set(undefined); this.status.set('error'); },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,13 @@
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||
<div class="fields compact">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<div class="interval">
|
||||
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
|
||||
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
</div>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||
@@ -49,47 +51,35 @@
|
||||
</section>
|
||||
} @else {
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||
<div class="fields">
|
||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de tiempo</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
|
||||
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
|
||||
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
|
||||
<mat-option value="todos">Todos con reporte</mat-option>
|
||||
<mat-option value="manual">Elegir periodos</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (entry.draft.mode !== 'todos') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodos seleccionados</mat-label>
|
||||
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||
</mat-form-field>
|
||||
}
|
||||
<div class="interval">
|
||||
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
|
||||
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
</div>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
@if (availability) {
|
||||
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
||||
@else if (availability.status === 'error') {
|
||||
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
||||
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de tiempo.</p> }
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability && entry.draft.mode !== 'todos') {
|
||||
@if (!availability) {
|
||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||
<div class="fields period-builder">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||
@@ -108,7 +98,7 @@
|
||||
}
|
||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||
<p class="draft-summary">Selección en edición: {{ summary }}</p>
|
||||
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
|
||||
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
|
||||
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
||||
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||
|
||||
@@ -2,13 +2,30 @@
|
||||
|
||||
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
|
||||
// CaMa's compact row: tighter fields and buttons, one line of text under it.
|
||||
:host(.compacto) { margin: 0; @include mat.theme((density: -4)); }
|
||||
:host(.compacto) {
|
||||
margin: 0;
|
||||
@include mat.theme((density: -4));
|
||||
// That theme also rewrites the corner scale, which turns this switch into a pill.
|
||||
// The history switch keeps the slight rounding of the indicators pages.
|
||||
--mat-sys-corner-extra-small: 2px;
|
||||
--mat-sys-corner-small: 2px;
|
||||
--mat-sys-corner-medium: 4px;
|
||||
--mat-sys-corner-large: 4px;
|
||||
--mat-sys-corner-extra-large: 6px;
|
||||
--mat-sys-corner-full: 4px;
|
||||
}
|
||||
:host(.compacto) .interval mat-button-toggle-group {
|
||||
--mat-button-toggle-height: 40px;
|
||||
--mat-button-toggle-shape: 6px;
|
||||
}
|
||||
:host(.compacto) p { line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
|
||||
:host(.compacto) .pending { color: var(--issste-text); border-left-color: var(--issste-accent); padding-left: var(--issste-space-2); }
|
||||
:host(.compacto) .apply-button { min-height: 40px; }
|
||||
:host(.compacto) .period-builder button { min-height: 40px; }
|
||||
section { min-width: 0; }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
|
||||
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
|
||||
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
|
||||
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
|
||||
.period-builder mat-form-field { flex: 0 1 10rem; }
|
||||
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
|
||||
@@ -21,7 +38,7 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
|
||||
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
||||
.remove button { min-height: 44px; }
|
||||
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
|
||||
.fields.compact { align-items: center; }
|
||||
.fields.compact { align-items: end; }
|
||||
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
||||
.fields.compact .apply-button { margin-top: 0; }
|
||||
@media (max-width: 550px) {
|
||||
|
||||
@@ -18,6 +18,10 @@ describe('UX-04 control asistido', () => {
|
||||
control = fixture.componentInstance;
|
||||
});
|
||||
afterEach(() => fixture.destroy());
|
||||
function periodSelect() {
|
||||
return fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
|
||||
}
|
||||
it('en modo compacto agregar otro periodo sustituye la selección anterior', () => {
|
||||
fixture.componentRef.setInput('compact', true); fixture.detectChanges();
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
@@ -25,18 +29,15 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
||||
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
|
||||
} },
|
||||
});
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2');
|
||||
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S2');
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
||||
@@ -50,10 +51,11 @@ describe('UX-04 control asistido', () => {
|
||||
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
||||
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
||||
fixture.changeDetectorRef.detach();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const select = periodSelect();
|
||||
expect(select.componentInstance.multiple).toBe(false);
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
const edits = vi.spyOn(control.edited, 'emit');
|
||||
@@ -61,16 +63,16 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
}
|
||||
expect(model.control.value).toEqual([]);
|
||||
expect(model.control.value).toBeNull();
|
||||
expect(writes).not.toHaveBeenCalled();
|
||||
expect(edits).not.toHaveBeenCalled();
|
||||
expect(control.state.applied?.selection.mode).toBe('todos');
|
||||
});
|
||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => {
|
||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
|
||||
control.changeTipo('mes');
|
||||
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const select = periodSelect();
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
@@ -85,7 +87,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('normaliza el año y rechaza agregar duplicados', () => {
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
control.year = '1'; control.unit = 'S1'; control.add();
|
||||
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
||||
control.add();
|
||||
@@ -93,7 +95,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual(['0001-S1']);
|
||||
});
|
||||
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
||||
control.changeMode('manual'); control.year = year; control.unit = unit; control.add();
|
||||
control.select([]); control.year = year; control.unit = unit; control.add();
|
||||
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
||||
@@ -101,21 +103,22 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('conserva borradores independientes sin convertir periodos', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
||||
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
||||
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
||||
});
|
||||
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
control.select(['2025-S2']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
fixture.detectChanges();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
expect(select).toBeTruthy();
|
||||
const select = periodSelect();
|
||||
expect(select.componentInstance.multiple).toBe(false);
|
||||
expect(select.nativeElement.querySelector('button')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
||||
fixture.nativeElement.querySelector('.remove button').click();
|
||||
@@ -126,7 +129,7 @@ describe('UX-04 control asistido', () => {
|
||||
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
||||
const edited = vi.spyOn(control.edited, 'emit');
|
||||
const apply = vi.spyOn(control.apply, 'emit');
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
@@ -135,11 +138,20 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('no ofrece Todos en meses cuando el primero es semestre', () => {
|
||||
control.changeTipo('mes'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty');
|
||||
control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', () => {
|
||||
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
|
||||
expect(fixture.nativeElement.querySelector('.field-label').textContent).toBe('Intervalo de análisis');
|
||||
expect(labels).not.toContain('Modalidad');
|
||||
expect([...fixture.nativeElement.querySelectorAll('mat-button-toggle')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(['Mensual', 'Semestral']);
|
||||
});
|
||||
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
||||
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
||||
options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
|
||||
fixture.detectChanges();
|
||||
control.changeTipo('mes');
|
||||
expect(control.selectedPeriods).toEqual(['2025-12']);
|
||||
control.select(['2025-11']); control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
// A period already chosen for that interval is kept.
|
||||
expect(control.selectedPeriods).toEqual(['2025-11']);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user