Compare commits
56 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c0bdf6184 | |||
| 70aa739f97 | |||
| 394f2c626b | |||
| 644803cf21 | |||
| 8e9a40dec4 | |||
| 1bdec1b838 | |||
| 220d5b9d26 | |||
| fbfd97ec31 | |||
| 18692acc88 | |||
| 6c84dab730 | |||
| 12ce93f58c | |||
| dcaf1a8832 | |||
| 04d529392e | |||
| 6f3e7e22f9 | |||
| 12a0398903 | |||
| 03e51c07cc | |||
| e6be341ad9 | |||
| 85ec11ab0f | |||
| db9ab0d1a7 | |||
| af70d6f378 | |||
| 1940f4fa47 | |||
| ec406d5d2d | |||
| 7b82427713 | |||
| ec642df834 | |||
| 540506bde0 | |||
| 14fd765122 | |||
| 9639423a32 | |||
| 1fe88dfb45 | |||
| a30dbbb102 | |||
| 9cc67c0ef2 | |||
| 1eda9eea29 | |||
| 2cf3a5a40d | |||
| 30946823c4 | |||
| d946228319 | |||
| 8cb3c97b80 | |||
| 1fc23bd0bd | |||
| 11337679dc | |||
| 4685a91a7c | |||
| 69afcc7fdb | |||
| 9fcc65d84f | |||
| c4faa7d9f6 | |||
| 98d0614d80 | |||
| 35e1bc33d3 | |||
| f96fe97ed6 | |||
| fe9442237b | |||
| 61cdf5b72e | |||
| 37c4eacf84 | |||
| 41be0c343f | |||
| ecf2778f1a | |||
| 9c012e9bb4 | |||
| 91832cc6ff | |||
| ea91b31b17 | |||
| ae5e4c5db5 | |||
| b1c4b78f32 | |||
| a66205b725 | |||
| 3605d23fc0 |
+4
-3
@@ -1,3 +1,4 @@
|
||||
node_modules
|
||||
dist
|
||||
.angular
|
||||
node_modules/
|
||||
dist/
|
||||
.angular/
|
||||
.git/
|
||||
|
||||
@@ -42,3 +42,9 @@ __screenshots__/
|
||||
# System files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Temporary UX reports and one-off static checks
|
||||
/UX-*-informe.md
|
||||
/scripts/ux06b-resources.test.mjs
|
||||
/scripts/ux06c-presentation.test.mjs
|
||||
/scripts/ux06d-presentation.test.mjs
|
||||
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
|
||||
"recommendations": ["angular.ng-template"]
|
||||
}
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "ng serve",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: start",
|
||||
"url": "http://localhost:4200/"
|
||||
},
|
||||
{
|
||||
"name": "ng test",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: test",
|
||||
"url": "http://localhost:9876/debug.html"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+42
@@ -0,0 +1,42 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "start",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"owner": "typescript",
|
||||
"pattern": "$tsc",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": {
|
||||
"regexp": "Changes detected"
|
||||
},
|
||||
"endsPattern": {
|
||||
"regexp": "bundle generation (complete|failed)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "test",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"owner": "typescript",
|
||||
"pattern": "$tsc",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": {
|
||||
"regexp": "Changes detected"
|
||||
},
|
||||
"endsPattern": {
|
||||
"regexp": "bundle generation (complete|failed)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+9
-9
@@ -1,10 +1,10 @@
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npx ng build
|
||||
FROM node:22-slim
|
||||
|
||||
FROM nginx:1.29-alpine
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/dist/webapp/browser /usr/share/nginx/html
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 4200
|
||||
CMD ["npx", "ng", "serve", "--host", "0.0.0.0", "--port", "4200"]
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# WebApp
|
||||
|
||||
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 22.1.8.
|
||||
|
||||
## Development server
|
||||
|
||||
To start a local development server, run:
|
||||
|
||||
```bash
|
||||
ng serve
|
||||
```
|
||||
|
||||
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
|
||||
|
||||
## Code scaffolding
|
||||
|
||||
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
|
||||
|
||||
```bash
|
||||
ng generate component component-name
|
||||
```
|
||||
|
||||
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
|
||||
|
||||
```bash
|
||||
ng generate --help
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To build the project run:
|
||||
|
||||
```bash
|
||||
ng build
|
||||
```
|
||||
|
||||
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
|
||||
|
||||
## Running unit tests
|
||||
|
||||
To execute unit tests with the [Vitest](https://vitest.dev/) test runner, use the following command:
|
||||
|
||||
```bash
|
||||
ng test
|
||||
```
|
||||
|
||||
## Running end-to-end tests
|
||||
|
||||
For end-to-end (e2e) testing, run:
|
||||
|
||||
```bash
|
||||
ng e2e
|
||||
```
|
||||
|
||||
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
|
||||
+9
-5
@@ -2,11 +2,12 @@
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"cli": {
|
||||
"packageManager": "npm"
|
||||
"packageManager": "npm",
|
||||
"analytics": false
|
||||
},
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
"webapp": {
|
||||
"WebApp": {
|
||||
"projectType": "application",
|
||||
"schematics": {
|
||||
"@schematics/angular:component": {
|
||||
@@ -29,7 +30,9 @@
|
||||
"input": "public"
|
||||
}
|
||||
],
|
||||
"styles": ["src/styles.scss"]
|
||||
"styles": [
|
||||
"src/styles.scss"
|
||||
]
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
@@ -57,12 +60,13 @@
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"options": { "proxyConfig": "proxy.conf.json" },
|
||||
"configurations": {
|
||||
"production": {
|
||||
"buildTarget": "webapp:build:production"
|
||||
"buildTarget": "WebApp:build:production"
|
||||
},
|
||||
"development": {
|
||||
"buildTarget": "webapp:build:development"
|
||||
"buildTarget": "WebApp:build:development"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Bitácora de textos de pantalla
|
||||
|
||||
Textos que la WebApp escribe a mano en lugar de tomarlos del kit (`indicadores_kit`), por qué
|
||||
y qué hay que mantener al día. Lo más reciente, arriba.
|
||||
|
||||
## 2026-10-25 · «Valores publicados»
|
||||
|
||||
- Las tablas desplegables decían «Valores publicados y celdas suprimidas» o «… y cajas no
|
||||
disponibles», que confundía. Ahora dicen «Valores publicados».
|
||||
- La tabla de contingencia de citología y biopsia (Tasa de confirmación histopatológica) estaba
|
||||
siempre a la vista; ahora va plegada bajo «Valores publicados», como las demás.
|
||||
- En el kit (IND1 0.3.2), la ficha de «Pacientes con citología anómala» ya no cita
|
||||
`kpi_catalog.yaml` en sus referencias: era un archivo interno de trabajo. Las referencias de
|
||||
las demás fichas de cáncer cervicouterino citan las guías europeas y se quedan.
|
||||
|
||||
## Pendientes (2026-10-25)
|
||||
|
||||
- **Método estadístico en la ficha técnica.** Pospuesto: escrito en cada TOML implica subir la
|
||||
versión de muchos indicadores.
|
||||
- **Más campos en la ficha de cáncer cervicouterino**, armados con lo que `/metadatos` ya manda y
|
||||
la ficha no muestra: cada grupo con sus categorías («LIEAG o más: LIEAG (CIN 2 y 3), Carcinoma
|
||||
in situ, Carcinoma invasor»), filtros y estratificadores, qué población es el numerador o el
|
||||
denominador, y quitar «Código». Pospuesto por el volumen de texto a revisar.
|
||||
- **«Calidad de espécimen satisfactoria».** Los textos lo dirán así, pero la consulta
|
||||
(`ultima_valida` del kit) acepta toda citología con resultado cuya calidad no sea
|
||||
insatisfactoria, incluidas las que no tienen calidad registrada. Se cambiará la consulta para
|
||||
exigir «satisfactoria». En el hospital el campo es obligatorio, así que los números no deberían
|
||||
cambiar; en el simulador sí, porque genera un 5 % sin calidad (`proporcion_sin_calidad`).
|
||||
- **Tiempo de tamizaje a diagnóstico: «benigno».** La descripción y la definición dicen «(normal,
|
||||
benigno, lesión o cáncer)», pero la lista de diagnósticos (`cacu.diagnostico.cie`) no tiene un
|
||||
grupo benigno: examen y pesquisa normales, VPH, hallazgo anormal en citología, displasia,
|
||||
carcinoma in situ y cáncer. Las poblaciones ya dicen «normal, de VPH, de lesión o de cáncer».
|
||||
Falta decidir si «benigno» se cambia por «VPH».
|
||||
- **Valores escritos en el texto.** Las poblaciones de los indicadores de cáncer cervicouterino
|
||||
dicen el valor de sus parámetros (180 días, ASC-H, LIEAG o carcinoma in situ…) en lugar de su
|
||||
nombre. Si un parámetro cambia, hay que cambiar el texto; lo avisa el comentario de la versión
|
||||
en cada TOML.
|
||||
- **IND1 no aplica la fecha de corte ni la calidad del espécimen.** Cuenta cualquier resultado
|
||||
anómalo de una citología del periodo, aunque se haya reportado después del corte o la muestra
|
||||
sea insatisfactoria. EU7 y Confirmación histopatológica sí aplican las dos reglas. Alinearlo
|
||||
cambia los números: va con el cambio de la consulta de «calidad satisfactoria».
|
||||
- **La nota de la ficha de los tiempos** («La caja va del primer al tercer cuartil y la línea es
|
||||
la mediana…») sirve bajo la figura, pero también aparece como «Nota» en la ficha técnica, donde
|
||||
no hay caja. Sin decidir.
|
||||
|
||||
## 2026-10-25 · «Sin dato» de la dona de resultados citológicos
|
||||
|
||||
- La nota bajo la dona decía «pacientes sin resultado válido en el periodo»; ahora dice
|
||||
«pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de
|
||||
corte», que es lo que cuenta la consulta (`indicador-eu7-escenario.ts`). Sin total: «Total de
|
||||
la dona no disponible.» (antes «Total con resultado no disponible.»).
|
||||
- Dona vacía: «Sin pacientes con resultado disponible para la dona.»
|
||||
|
||||
## 2026-10-25 · «CaCu» es un nombre interno
|
||||
|
||||
- En pantalla, «CaCu» pasa a «cáncer cervicouterino» (`domainLabels` de `indicadores-page.ts` y
|
||||
`domainNames` de `indicadores-definitions.ts`). Con mayúscula donde abre el texto: la línea
|
||||
«Cáncer cervicouterino, investigación» (`domainTitles`). TEA y CaMa no cambian de nombre.
|
||||
- El botón del encabezado para cambiar de proyecto (`app.ts`) sigue diciendo «CaCu»: es
|
||||
provisional (usuario). Solo es la etiqueta: la dirección sigue siendo `/indicadores/cacu`.
|
||||
- La línea del encabezado ya no dice «Dominio»: «<proyecto>, investigación».
|
||||
- «Dashboard de indicadores» pasa a «Indicadores» y el subtítulo a «Explora los indicadores de
|
||||
<proyecto>.» (antes: «…de indicadores <proyecto> generadas por el servicio de reportes»).
|
||||
- «Datos y definiciones» ya no dice «Dominio: <proyecto>.»: repetía el título.
|
||||
- Siguen igual «Cambiar dominio» y su lectura en voz alta.
|
||||
|
||||
## 2026-10-25 · Tarjetas de indicadores de oportunidad de CaCu
|
||||
|
||||
- Las tarjetas de CaCu ya no muestran las notas del kit (`notas` de `/datos`, que son el pie de
|
||||
las figuras: repetían la definición completa y, en los tiempos, hablaban de la caja). Dicen
|
||||
solo su línea, escrita en `indicadores-kpi.ts`. TEA y CaMa no cambian
|
||||
(`indicador-kpi-panel.ts`).
|
||||
- «Pacientes evaluadas»: «Pacientes con citología tomada en el periodo.» El número no cambia:
|
||||
incluye a las pacientes cuyo espécimen fue insatisfactorio (en la dona van en «Sin dato»).
|
||||
- «Tiempo de tamizaje a diagnóstico»: «*n* citologías; primer cuartil: *x* días; tercer
|
||||
cuartil: *y* días.» Sin «Q1» ni «Q3»: el público es médico.
|
||||
- «Datos y definiciones» de CaCu dice, bajo el dominio, que «Pacientes evaluadas» incluye las
|
||||
citologías con espécimen insatisfactorio.
|
||||
|
||||
Si cambia la definición de `cacu_eu7` o de `cacu_dias_toma_diagnostico` en el kit, revisar
|
||||
estos textos.
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"$schema": "node_modules/ng-openapi-gen/ng-openapi-gen-schema.json",
|
||||
"input": "openapi.json",
|
||||
"output": "src/app/api",
|
||||
"ignoreUnusedModels": false
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
server {
|
||||
listen 80;
|
||||
root /usr/share/nginx/html;
|
||||
location /api/ {
|
||||
proxy_pass http://api:8000/;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
-1689
File diff suppressed because it is too large
Load Diff
Generated
+2712
-2089
File diff suppressed because it is too large
Load Diff
+17
-19
@@ -1,37 +1,35 @@
|
||||
{
|
||||
"name": "webapp",
|
||||
"name": "web-app",
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve --proxy-config proxy.conf.json",
|
||||
"start": "ng serve",
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test",
|
||||
"api": "ng-openapi-gen -c ng-openapi-gen.json"
|
||||
"test": "ng test"
|
||||
},
|
||||
"private": true,
|
||||
"packageManager": "npm@11.20.0",
|
||||
"packageManager": "npm@11.17.0",
|
||||
"dependencies": {
|
||||
"@angular/cdk": "^22.3.0",
|
||||
"@angular/common": "^22.3.0",
|
||||
"@angular/compiler": "^22.3.0",
|
||||
"@angular/core": "^22.3.0",
|
||||
"@angular/forms": "^22.3.0",
|
||||
"@angular/material": "^22.3.0",
|
||||
"@angular/platform-browser": "^22.3.0",
|
||||
"@angular/router": "^22.3.0",
|
||||
"@angular/cdk": "^22.1.7",
|
||||
"@angular/common": "^22.1.0",
|
||||
"@angular/compiler": "^22.1.0",
|
||||
"@angular/core": "^22.1.0",
|
||||
"@angular/forms": "^22.1.0",
|
||||
"@angular/material": "^22.1.7",
|
||||
"@angular/platform-browser": "^22.1.0",
|
||||
"@angular/router": "^22.1.0",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^22.3.0",
|
||||
"@angular/cli": "^22.3.0",
|
||||
"@angular/compiler-cli": "^22.3.0",
|
||||
"jsdom": "^31.0.0",
|
||||
"ng-openapi-gen": "^1.1.0",
|
||||
"@angular/build": "^22.1.8",
|
||||
"@angular/cli": "^22.1.8",
|
||||
"@angular/compiler-cli": "^22.1.0",
|
||||
"jsdom": "^28.0.0",
|
||||
"prettier": "^3.8.1",
|
||||
"typescript": "~6.0.2",
|
||||
"vitest": "^5.0.0"
|
||||
"vitest": "^4.0.8"
|
||||
}
|
||||
}
|
||||
|
||||
+6
-1
@@ -1 +1,6 @@
|
||||
{ "/api": { "target": "http://127.0.0.1:5711", "pathRewrite": { "^/api": "" } } }
|
||||
{
|
||||
"/tea/**": { "target": "http://127.0.0.1:5000", "secure": false },
|
||||
"/cacu/**": { "target": "http://127.0.0.1:5000", "secure": false },
|
||||
"/cama/**": { "target": "http://127.0.0.1:5000", "secure": false },
|
||||
"/health": { "target": "http://127.0.0.1:5000", "secure": false }
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -1,27 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
/**
|
||||
* Provides the ApiConfiguration configuration object with a given root URL.
|
||||
*/
|
||||
export function provideApiConfiguration(rootUrl: string) {
|
||||
var config = new ApiConfiguration();
|
||||
config.rootUrl = rootUrl;
|
||||
return {
|
||||
provide: ApiConfiguration,
|
||||
useValue: config
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Global configuration
|
||||
*/
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class ApiConfiguration {
|
||||
rootUrl: string = '';
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable, firstValueFrom } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { ApiConfiguration } from './api-configuration';
|
||||
import { StrictHttpResponse } from './strict-http-response';
|
||||
|
||||
export type ApiFnOptional<P, R> = (http: HttpClient, rootUrl: string, params?: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>;
|
||||
export type ApiFnRequired<P, R> = (http: HttpClient, rootUrl: string, params: P, context?: HttpContext) => Observable<StrictHttpResponse<R>>;
|
||||
|
||||
/**
|
||||
* Helper service to call API functions directly
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class Api {
|
||||
constructor(
|
||||
private config: ApiConfiguration,
|
||||
private http: HttpClient
|
||||
) {
|
||||
}
|
||||
|
||||
private _rootUrl?: string;
|
||||
|
||||
/**
|
||||
* Returns the root url for API operations. If not set directly here,
|
||||
* will fallback to `ApiConfiguration.rootUrl`.
|
||||
*/
|
||||
get rootUrl(): string {
|
||||
return this._rootUrl || this.config.rootUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the root URL for API operations
|
||||
*/
|
||||
set rootUrl(rootUrl: string) {
|
||||
this._rootUrl = rootUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes an API call, returning the response body only
|
||||
*/
|
||||
invoke<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<R>;
|
||||
invoke<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<R>;
|
||||
async invoke<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<R> {
|
||||
const resp = this.invoke$Response(fn, params, context);
|
||||
return (await resp).body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes an API call, returning the entire response
|
||||
*/
|
||||
invoke$Response<P, R>(fn: ApiFnRequired<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>>;
|
||||
invoke$Response<P, R>(fn: ApiFnOptional<P, R>, params?: P, context?: HttpContext): Promise<StrictHttpResponse<R>>;
|
||||
invoke$Response<P, R>(fn: ApiFnRequired<P, R> | ApiFnOptional<P, R>, params: P, context?: HttpContext): Promise<StrictHttpResponse<R>> {
|
||||
const obs = fn(this.http, this.rootUrl, params, context)
|
||||
.pipe(
|
||||
filter(r => r instanceof HttpResponse),
|
||||
map(r => r as StrictHttpResponse<R>));
|
||||
return firstValueFrom(obs);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface NodeRows$Params {
|
||||
pipeline_id: string;
|
||||
node_id: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export function nodeRows(http: HttpClient, rootUrl: string, params: NodeRows$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>> {
|
||||
const rb = new RequestBuilder(rootUrl, nodeRows.PATH, 'get');
|
||||
if (params) {
|
||||
rb.path('pipeline_id', params.pipeline_id, {});
|
||||
rb.path('node_id', params.node_id, {});
|
||||
rb.query('limit', params.limit, {});
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
nodeRows.PATH = '/ingest/pipelines/{pipeline_id}/nodes/{node_id}/rows';
|
||||
@@ -1,34 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { SavedPipeline } from '../../models/saved-pipeline';
|
||||
|
||||
export interface Pipeline$Params {
|
||||
pipeline_id: string;
|
||||
version?: (number | null);
|
||||
}
|
||||
|
||||
export function pipeline(http: HttpClient, rootUrl: string, params: Pipeline$Params, context?: HttpContext): Observable<StrictHttpResponse<SavedPipeline>> {
|
||||
const rb = new RequestBuilder(rootUrl, pipeline.PATH, 'get');
|
||||
if (params) {
|
||||
rb.path('pipeline_id', params.pipeline_id, {});
|
||||
rb.query('version', params.version, {});
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<SavedPipeline>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
pipeline.PATH = '/ingest/pipelines/{pipeline_id}';
|
||||
@@ -1,33 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Pipelines$Params {
|
||||
}
|
||||
|
||||
export function pipelines(http: HttpClient, rootUrl: string, params?: Pipelines$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>> {
|
||||
const rb = new RequestBuilder(rootUrl, pipelines.PATH, 'get');
|
||||
if (params) {
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
pipelines.PATH = '/ingest/pipelines';
|
||||
@@ -1,38 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { Pipeline } from '../../models/pipeline';
|
||||
|
||||
export interface SavePipeline$Params {
|
||||
pipeline_id: string;
|
||||
body: Pipeline
|
||||
}
|
||||
|
||||
export function savePipeline(http: HttpClient, rootUrl: string, params: SavePipeline$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: number;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, savePipeline.PATH, 'put');
|
||||
if (params) {
|
||||
rb.path('pipeline_id', params.pipeline_id, {});
|
||||
rb.body(params.body, 'application/json');
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: number;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
savePipeline.PATH = '/ingest/pipelines/{pipeline_id}';
|
||||
@@ -1,33 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Schema$Params {
|
||||
}
|
||||
|
||||
export function schema(http: HttpClient, rootUrl: string, params?: Schema$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: any;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, schema.PATH, 'get');
|
||||
if (params) {
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: any;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
schema.PATH = '/ingest/schema';
|
||||
@@ -1,38 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { Source } from '../../models/source';
|
||||
|
||||
export interface SourcePreview$Params {
|
||||
limit?: number;
|
||||
body: Source
|
||||
}
|
||||
|
||||
export function sourcePreview(http: HttpClient, rootUrl: string, params: SourcePreview$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>> {
|
||||
const rb = new RequestBuilder(rootUrl, sourcePreview.PATH, 'post');
|
||||
if (params) {
|
||||
rb.query('limit', params.limit, {});
|
||||
rb.body(params.body, 'application/json');
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
sourcePreview.PATH = '/ingest/sources/preview';
|
||||
@@ -1,32 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { SourceRef } from '../../models/source-ref';
|
||||
|
||||
export interface SourceResources$Params {
|
||||
body: SourceRef
|
||||
}
|
||||
|
||||
export function sourceResources(http: HttpClient, rootUrl: string, params: SourceResources$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<string>>> {
|
||||
const rb = new RequestBuilder(rootUrl, sourceResources.PATH, 'post');
|
||||
if (params) {
|
||||
rb.body(params.body, 'application/json');
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<string>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
sourceResources.PATH = '/ingest/sources/resources';
|
||||
@@ -1,38 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { RunRequest } from '../../models/run-request';
|
||||
|
||||
export interface StartRun$Params {
|
||||
pipeline_id: string;
|
||||
body: RunRequest
|
||||
}
|
||||
|
||||
export function startRun(http: HttpClient, rootUrl: string, params: StartRun$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, startRun.PATH, 'post');
|
||||
if (params) {
|
||||
rb.path('pipeline_id', params.pipeline_id, {});
|
||||
rb.body(params.body, 'application/json');
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
startRun.PATH = '/ingest/pipelines/{pipeline_id}/runs';
|
||||
@@ -1,36 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { BodyUpload } from '../../models/body-upload';
|
||||
|
||||
export interface Upload$Params {
|
||||
body: BodyUpload
|
||||
}
|
||||
|
||||
export function upload(http: HttpClient, rootUrl: string, params: Upload$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, upload.PATH, 'post');
|
||||
if (params) {
|
||||
rb.body(params.body, 'multipart/form-data');
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
upload.PATH = '/ingest/uploads';
|
||||
@@ -1,30 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { Domain } from '../../models/domain';
|
||||
|
||||
export interface Domains$Params {
|
||||
}
|
||||
|
||||
export function domains(http: HttpClient, rootUrl: string, params?: Domains$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Domain>>> {
|
||||
const rb = new RequestBuilder(rootUrl, domains.PATH, 'get');
|
||||
if (params) {
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<Domain>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
domains.PATH = '/domains';
|
||||
@@ -1,33 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Health$Params {
|
||||
}
|
||||
|
||||
export function health(http: HttpClient, rootUrl: string, params?: Health$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, health.PATH, 'get');
|
||||
if (params) {
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
health.PATH = '/health';
|
||||
@@ -1,35 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Conflicts$Params {
|
||||
entity: 'identity' | 'death' | 'clinical_note' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy';
|
||||
}
|
||||
|
||||
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>> {
|
||||
const rb = new RequestBuilder(rootUrl, conflicts.PATH, 'get');
|
||||
if (params) {
|
||||
rb.query('entity', params.entity, {});
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
conflicts.PATH = '/review/conflicts';
|
||||
@@ -1,36 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { Correction } from '../../models/correction';
|
||||
|
||||
export interface Correct$Params {
|
||||
body: Correction
|
||||
}
|
||||
|
||||
export function correct(http: HttpClient, rootUrl: string, params: Correct$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, correct.PATH, 'post');
|
||||
if (params) {
|
||||
rb.body(params.body, 'application/json');
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
correct.PATH = '/review/corrections';
|
||||
@@ -1,36 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { PersonDecision } from '../../models/person-decision';
|
||||
|
||||
export interface DecidePersons$Params {
|
||||
body: PersonDecision
|
||||
}
|
||||
|
||||
export function decidePersons(http: HttpClient, rootUrl: string, params: DecidePersons$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, decidePersons.PATH, 'post');
|
||||
if (params) {
|
||||
rb.body(params.body, 'application/json');
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
decidePersons.PATH = '/review/persons';
|
||||
@@ -1,35 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Held$Params {
|
||||
entity: 'identity' | 'death' | 'clinical_note' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy';
|
||||
}
|
||||
|
||||
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>> {
|
||||
const rb = new RequestBuilder(rootUrl, held.PATH, 'get');
|
||||
if (params) {
|
||||
rb.query('entity', params.entity, {});
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<{
|
||||
[key: string]: any;
|
||||
}>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
held.PATH = '/review/held';
|
||||
@@ -1,41 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Persons$Params {
|
||||
pipeline: string;
|
||||
node: string;
|
||||
}
|
||||
|
||||
export function persons(http: HttpClient, rootUrl: string, params: Persons$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: Array<{
|
||||
[key: string]: any;
|
||||
}>;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, persons.PATH, 'get');
|
||||
if (params) {
|
||||
rb.query('pipeline', params.pipeline, {});
|
||||
rb.query('node', params.node, {});
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: Array<{
|
||||
[key: string]: any;
|
||||
}>;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
persons.PATH = '/review/persons';
|
||||
@@ -1,36 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { Rejection } from '../../models/rejection';
|
||||
|
||||
export interface Reject$Params {
|
||||
body: Rejection
|
||||
}
|
||||
|
||||
export function reject(http: HttpClient, rootUrl: string, params: Reject$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, reject.PATH, 'post');
|
||||
if (params) {
|
||||
rb.body(params.body, 'application/json');
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
reject.PATH = '/review/rejections';
|
||||
@@ -1,35 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { filter, map } from 'rxjs/operators';
|
||||
import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface RunStatus$Params {
|
||||
run_id: string;
|
||||
}
|
||||
|
||||
export function runStatus(http: HttpClient, rootUrl: string, params: RunStatus$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, runStatus.PATH, 'get');
|
||||
if (params) {
|
||||
rb.path('run_id', params.run_id, {});
|
||||
}
|
||||
|
||||
return http.request(
|
||||
rb.build({ responseType: 'json', accept: 'application/json', context })
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
runStatus.PATH = '/runs/{run_id}';
|
||||
@@ -1,39 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
|
||||
export { domains as domains } from './fn/operations/domains';
|
||||
export type { Health$Params as Health$Params } from './fn/operations/health';
|
||||
export { health as health } from './fn/operations/health';
|
||||
export type { Pipelines$Params as Pipelines$Params } from './fn/ingest/pipelines';
|
||||
export { pipelines as pipelines } from './fn/ingest/pipelines';
|
||||
export type { Pipeline$Params as Pipeline$Params } from './fn/ingest/pipeline';
|
||||
export { pipeline as pipeline } from './fn/ingest/pipeline';
|
||||
export type { SavePipeline$Params as SavePipeline$Params } from './fn/ingest/save-pipeline';
|
||||
export { savePipeline as savePipeline } from './fn/ingest/save-pipeline';
|
||||
export type { NodeRows$Params as NodeRows$Params } from './fn/ingest/node-rows';
|
||||
export { nodeRows as nodeRows } from './fn/ingest/node-rows';
|
||||
export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
|
||||
export { startRun as startRun } from './fn/ingest/start-run';
|
||||
export type { Schema$Params as Schema$Params } from './fn/ingest/schema';
|
||||
export { schema as schema } from './fn/ingest/schema';
|
||||
export type { SourcePreview$Params as SourcePreview$Params } from './fn/ingest/source-preview';
|
||||
export { sourcePreview as sourcePreview } from './fn/ingest/source-preview';
|
||||
export type { SourceResources$Params as SourceResources$Params } from './fn/ingest/source-resources';
|
||||
export { sourceResources as sourceResources } from './fn/ingest/source-resources';
|
||||
export type { Upload$Params as Upload$Params } from './fn/ingest/upload';
|
||||
export { upload as upload } from './fn/ingest/upload';
|
||||
export type { Conflicts$Params as Conflicts$Params } from './fn/review/conflicts';
|
||||
export { conflicts as conflicts } from './fn/review/conflicts';
|
||||
export type { Correct$Params as Correct$Params } from './fn/review/correct';
|
||||
export { correct as correct } from './fn/review/correct';
|
||||
export type { Held$Params as Held$Params } from './fn/review/held';
|
||||
export { held as held } from './fn/review/held';
|
||||
export type { Persons$Params as Persons$Params } from './fn/review/persons';
|
||||
export { persons as persons } from './fn/review/persons';
|
||||
export type { DecidePersons$Params as DecidePersons$Params } from './fn/review/decide-persons';
|
||||
export { decidePersons as decidePersons } from './fn/review/decide-persons';
|
||||
export type { Reject$Params as Reject$Params } from './fn/review/reject';
|
||||
export { reject as reject } from './fn/review/reject';
|
||||
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
|
||||
export { runStatus as runStatus } from './fn/runs/run-status';
|
||||
@@ -1,23 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export type { BodyUpload } from './models/body-upload';
|
||||
export type { Condition } from './models/condition';
|
||||
export type { Correction } from './models/correction';
|
||||
export type { Domain } from './models/domain';
|
||||
export type { Extract } from './models/extract';
|
||||
export type { HttpValidationError } from './models/http-validation-error';
|
||||
export type { Join } from './models/join';
|
||||
export type { Link } from './models/link';
|
||||
export type { Map } from './models/map';
|
||||
export type { PersonDecision } from './models/person-decision';
|
||||
export type { Pipeline } from './models/pipeline';
|
||||
export type { Read } from './models/read';
|
||||
export type { Rejection } from './models/rejection';
|
||||
export type { Route } from './models/route';
|
||||
export type { RunRequest } from './models/run-request';
|
||||
export type { SavedPipeline } from './models/saved-pipeline';
|
||||
export type { Source } from './models/source';
|
||||
export type { SourceRef } from './models/source-ref';
|
||||
export type { Target } from './models/target';
|
||||
export type { ValidationError } from './models/validation-error';
|
||||
@@ -1,6 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface BodyUpload {
|
||||
file: string;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Condition {
|
||||
column: string;
|
||||
op: 'equals' | 'contains' | 'matches' | 'present';
|
||||
value?: string;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Correction {
|
||||
field: 'record_number' | 'full_name' | 'curp' | 'nss' | 'birth_date' | 'sex' | 'postal_code';
|
||||
record: string;
|
||||
value: string;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Domain } from './domain';
|
||||
|
||||
/**
|
||||
* Each possible value of `Domain`
|
||||
*/
|
||||
export const DOMAIN: Domain[] = [
|
||||
'cacu',
|
||||
'cama',
|
||||
'tea'
|
||||
];
|
||||
@@ -1,5 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export type Domain = 'cacu' | 'cama' | 'tea';
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
|
||||
/**
|
||||
* Platform fields read from text, each kept with the text it was read from.
|
||||
*
|
||||
* `auto` asks the LLM when one is configured and answering, else applies `patterns`;
|
||||
* with neither, the row is held. Patterns are regexes with one group, per field (the
|
||||
* LLM can propose them from sample documents); their values go through `values` and
|
||||
* `formats` as in `map`.
|
||||
*/
|
||||
export interface Extract {
|
||||
column: string;
|
||||
entity: 'identity' | 'death' | 'clinical_note' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy';
|
||||
formats?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
hints?: string;
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'extract';
|
||||
label?: string;
|
||||
method?: 'auto' | 'llm' | 'patterns';
|
||||
patterns?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
values?: {
|
||||
[key: string]: {
|
||||
[key: string]: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { ValidationError } from '../models/validation-error';
|
||||
export interface HttpValidationError {
|
||||
detail?: Array<ValidationError>;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
|
||||
/**
|
||||
* Two inputs side by side where their columns match.
|
||||
*/
|
||||
export interface Join {
|
||||
how?: 'inner' | 'left';
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'join';
|
||||
label?: string;
|
||||
on: Array<[string, string]>;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
|
||||
/**
|
||||
* Identity rows from every input, grouped into persons (Splink).
|
||||
*
|
||||
* Two records are the same person when any rule holds (Splink's SQL rule syntax, `l.`
|
||||
* and `r.` for the two records); persons are the connected groups. A person whose
|
||||
* records disagree on birth date or sex is held for review as a whole. Pairs Splink
|
||||
* scores above `review` that ended up apart are queued as possible matches.
|
||||
*/
|
||||
export interface Link {
|
||||
fields?: Array<string>;
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'link';
|
||||
label?: string;
|
||||
review?: number;
|
||||
rules?: Array<string>;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
|
||||
/**
|
||||
* Columns to platform fields, with the site's codes and date formats.
|
||||
*/
|
||||
export interface Map {
|
||||
fields: {
|
||||
[key: string]: string;
|
||||
};
|
||||
formats?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'map';
|
||||
label?: string;
|
||||
values?: {
|
||||
[key: string]: {
|
||||
[key: string]: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface PersonDecision {
|
||||
candidate: string;
|
||||
person: string;
|
||||
same: boolean;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Extract } from '../models/extract';
|
||||
import { Join } from '../models/join';
|
||||
import { Link } from '../models/link';
|
||||
import { Map } from '../models/map';
|
||||
import { Read } from '../models/read';
|
||||
import { Route } from '../models/route';
|
||||
import { Source } from '../models/source';
|
||||
import { Target } from '../models/target';
|
||||
export interface Pipeline {
|
||||
nodes: Array<(Source | Read | Route | Map | Extract | Join | Link | Target)>;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
|
||||
/**
|
||||
* Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF).
|
||||
*/
|
||||
export interface Read {
|
||||
column: string;
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'read';
|
||||
label?: string;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Rejection {
|
||||
entity: 'identity' | 'death' | 'clinical_note' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy';
|
||||
reason: string;
|
||||
record: string;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Condition } from '../models/condition';
|
||||
|
||||
/**
|
||||
* Only the rows where every condition holds (e.g. reports titled "Citología").
|
||||
*/
|
||||
export interface Route {
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'route';
|
||||
label?: string;
|
||||
when: Array<Condition>;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface RunRequest {
|
||||
version?: (number | null);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { Pipeline } from '../models/pipeline';
|
||||
export interface SavedPipeline {
|
||||
pipeline: Pipeline;
|
||||
version: number;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface SourceRef {
|
||||
args?: {
|
||||
[key: string]: any;
|
||||
};
|
||||
source: string;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
|
||||
/**
|
||||
* One table, file set or API resource, copied as it is (dlt). Merged on the source's
|
||||
* own primary key or `primary_key`; replaced whole when it has none.
|
||||
*/
|
||||
export interface Source {
|
||||
args?: {
|
||||
[key: string]: any;
|
||||
};
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'source';
|
||||
label?: string;
|
||||
primary_key?: Array<string>;
|
||||
resource?: (string | null);
|
||||
source: string;
|
||||
then?: (string | null);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
|
||||
/**
|
||||
* Rows of platform fields into one platform entity, each row given its person by the
|
||||
* one `link` node among the inputs. Rule breaks are held for review.
|
||||
*/
|
||||
export interface Target {
|
||||
entity: 'identity' | 'death' | 'clinical_note' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy';
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'target';
|
||||
label?: string;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface ValidationError {
|
||||
ctx?: {
|
||||
};
|
||||
input?: any;
|
||||
loc: Array<(string | number)>;
|
||||
msg: string;
|
||||
type: string;
|
||||
}
|
||||
@@ -1,369 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpRequest, HttpParameterCodec, HttpParams, HttpHeaders, HttpContext } from '@angular/common/http';
|
||||
|
||||
/**
|
||||
* Custom parameter codec to correctly handle the plus sign in parameter
|
||||
* values. See https://github.com/angular/angular/issues/18261
|
||||
*/
|
||||
class ParameterCodec implements HttpParameterCodec {
|
||||
encodeKey(key: string): string {
|
||||
return encodeURIComponent(key);
|
||||
}
|
||||
|
||||
encodeValue(value: string): string {
|
||||
return encodeURIComponent(value);
|
||||
}
|
||||
|
||||
decodeKey(key: string): string {
|
||||
return decodeURIComponent(key);
|
||||
}
|
||||
|
||||
decodeValue(value: string): string {
|
||||
return decodeURIComponent(value);
|
||||
}
|
||||
}
|
||||
const ParameterCodecInstance = new ParameterCodec();
|
||||
|
||||
/**
|
||||
* Defines the options for appending a parameter
|
||||
*/
|
||||
interface ParameterOptions {
|
||||
style?: string;
|
||||
explode?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base class for a parameter
|
||||
*/
|
||||
abstract class Parameter {
|
||||
constructor(public name: string, public value: any, public options: ParameterOptions, defaultStyle: string, defaultExplode: boolean) {
|
||||
this.options = options || {};
|
||||
if (this.options.style === null || this.options.style === undefined) {
|
||||
this.options.style = defaultStyle;
|
||||
}
|
||||
if (this.options.explode === null || this.options.explode === undefined) {
|
||||
this.options.explode = defaultExplode;
|
||||
}
|
||||
}
|
||||
|
||||
serializeValue(value: any, separator = ','): string {
|
||||
if (value === null || value === undefined) {
|
||||
return '';
|
||||
} else if (value instanceof Array) {
|
||||
return value.map(v => this.serializeValue(v).split(separator).join(encodeURIComponent(separator))).join(separator);
|
||||
} else if (typeof value === 'object') {
|
||||
const array: string[] = [];
|
||||
for (const key of Object.keys(value)) {
|
||||
let propVal = value[key];
|
||||
if (propVal !== null && propVal !== undefined) {
|
||||
propVal = this.serializeValue(propVal).split(separator).join(encodeURIComponent(separator));
|
||||
if (this.options.explode) {
|
||||
array.push(`${key}=${propVal}`);
|
||||
} else {
|
||||
array.push(key);
|
||||
array.push(propVal);
|
||||
}
|
||||
}
|
||||
}
|
||||
return array.join(separator);
|
||||
} else {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A parameter in the operation path
|
||||
*/
|
||||
class PathParameter extends Parameter {
|
||||
constructor(name: string, value: any, options: ParameterOptions) {
|
||||
super(name, value, options, 'simple', false);
|
||||
}
|
||||
|
||||
append(path: string): string {
|
||||
let value = this.value;
|
||||
if (value === null || value === undefined) {
|
||||
value = '';
|
||||
}
|
||||
let prefix = this.options.style === 'label' ? '.' : '';
|
||||
let separator = this.options.explode ? prefix === '' ? ',' : prefix : ',';
|
||||
let alreadySerialized = false;
|
||||
if (this.options.style === 'matrix') {
|
||||
// The parameter name is just used as prefix, except in some cases...
|
||||
prefix = `;${this.name}=`;
|
||||
if (this.options.explode && typeof value === 'object') {
|
||||
prefix = ';';
|
||||
if (value instanceof Array) {
|
||||
// For arrays we have to repeat the name for each element
|
||||
value = value.map(v => `${this.name}=${this.serializeValue(v, ';')}`);
|
||||
value = value.join(';');
|
||||
alreadySerialized = true;
|
||||
} else {
|
||||
// For objects we have to put each the key / value pairs
|
||||
value = this.serializeValue(value, ';');
|
||||
alreadySerialized = true
|
||||
}
|
||||
}
|
||||
}
|
||||
value = prefix + (alreadySerialized ? value : this.serializeValue(value, separator));
|
||||
// Replace both the plain variable and the corresponding variant taking in the prefix and explode into account
|
||||
path = path.replace(`{${this.name}}`, value);
|
||||
path = path.replace(`{${prefix}${this.name}${this.options.explode ? '*' : ''}}`, value);
|
||||
return path;
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
serializeValue(value: any, separator = ','): string {
|
||||
var result = typeof value === 'string' ? encodeURIComponent(value) : super.serializeValue(value, separator);
|
||||
result = result.replace(/%3D/g, '=');
|
||||
result = result.replace(/%3B/g, ';');
|
||||
result = result.replace(/%2C/g, ',');
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A parameter in the query
|
||||
*/
|
||||
class QueryParameter extends Parameter {
|
||||
constructor(name: string, value: any, options: ParameterOptions) {
|
||||
super(name, value, options, 'form', true);
|
||||
}
|
||||
|
||||
append(params: HttpParams): HttpParams {
|
||||
if (this.value instanceof Array) {
|
||||
// Array serialization
|
||||
if (this.options.explode) {
|
||||
for (const v of this.value) {
|
||||
params = params.append(this.name, this.serializeValue(v));
|
||||
}
|
||||
} else {
|
||||
const separator = this.options.style === 'spaceDelimited'
|
||||
? ' ' : this.options.style === 'pipeDelimited'
|
||||
? '|' : ',';
|
||||
return params.append(this.name, this.serializeValue(this.value, separator));
|
||||
}
|
||||
} else if (this.value !== null && typeof this.value === 'object') {
|
||||
// Object serialization
|
||||
if (this.options.style === 'deepObject') {
|
||||
// Append a parameter for each key, in the form `name[key]`
|
||||
for (const key of Object.keys(this.value)) {
|
||||
const propVal = this.value[key];
|
||||
if (propVal !== null && propVal !== undefined) {
|
||||
params = params.append(`${this.name}[${key}]`, this.serializeValue(propVal));
|
||||
}
|
||||
}
|
||||
} else if (this.options.explode) {
|
||||
// Append a parameter for each key without using the parameter name
|
||||
for (const key of Object.keys(this.value)) {
|
||||
const propVal = this.value[key];
|
||||
if (propVal !== null && propVal !== undefined) {
|
||||
params = params.append(key, this.serializeValue(propVal));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Append a single parameter whose values are a comma-separated list of key,value,key,value...
|
||||
const array: any[] = [];
|
||||
for (const key of Object.keys(this.value)) {
|
||||
const propVal = this.value[key];
|
||||
if (propVal !== null && propVal !== undefined) {
|
||||
array.push(key);
|
||||
array.push(propVal);
|
||||
}
|
||||
}
|
||||
params = params.append(this.name, this.serializeValue(array));
|
||||
}
|
||||
} else if (this.value !== null && this.value !== undefined) {
|
||||
// Plain value
|
||||
params = params.append(this.name, this.serializeValue(this.value));
|
||||
}
|
||||
return params;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A parameter in the HTTP request header
|
||||
*/
|
||||
class HeaderParameter extends Parameter {
|
||||
constructor(name: string, value: any, options: ParameterOptions) {
|
||||
super(name, value, options, 'simple', false);
|
||||
}
|
||||
|
||||
append(headers: HttpHeaders): HttpHeaders {
|
||||
if (this.value !== null && this.value !== undefined) {
|
||||
if (this.value instanceof Array) {
|
||||
for (const v of this.value) {
|
||||
headers = headers.append(this.name, this.serializeValue(v));
|
||||
}
|
||||
} else {
|
||||
headers = headers.append(this.name, this.serializeValue(this.value));
|
||||
}
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to build http requests from parameters
|
||||
*/
|
||||
export class RequestBuilder {
|
||||
|
||||
private _path = new Map<string, PathParameter>();
|
||||
private _query = new Map<string, QueryParameter>();
|
||||
private _header = new Map<string, HeaderParameter>();
|
||||
_bodyContent: any | null;
|
||||
_bodyContentType?: string;
|
||||
|
||||
constructor(
|
||||
public rootUrl: string,
|
||||
public operationPath: string,
|
||||
public method: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a path parameter
|
||||
*/
|
||||
path(name: string, value: any, options?: ParameterOptions): void {
|
||||
this._path.set(name, new PathParameter(name, value, options || {}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a query parameter
|
||||
*/
|
||||
query(name: string, value: any, options?: ParameterOptions): void {
|
||||
this._query.set(name, new QueryParameter(name, value, options || {}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a header parameter
|
||||
*/
|
||||
header(name: string, value: any, options?: ParameterOptions): void {
|
||||
this._header.set(name, new HeaderParameter(name, value, options || {}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the body content, along with the content type
|
||||
*/
|
||||
body(value: any, contentType = 'application/json'): void {
|
||||
if (value instanceof Blob) {
|
||||
this._bodyContentType = value.type;
|
||||
} else {
|
||||
this._bodyContentType = contentType;
|
||||
}
|
||||
if (this._bodyContentType === 'application/x-www-form-urlencoded' && value !== null && typeof value === 'object') {
|
||||
// Handle URL-encoded data
|
||||
const pairs: Array<[string, string]> = [];
|
||||
for (const key of Object.keys(value)) {
|
||||
let val = value[key];
|
||||
if (!(val instanceof Array)) {
|
||||
val = [val];
|
||||
}
|
||||
for (const v of val) {
|
||||
const formValue = this.formDataValue(v);
|
||||
if (formValue !== null) {
|
||||
pairs.push([key, formValue]);
|
||||
}
|
||||
}
|
||||
}
|
||||
this._bodyContent = pairs.map(p => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`).join('&');
|
||||
} else if (this._bodyContentType === 'multipart/form-data') {
|
||||
// Handle multipart form data
|
||||
const formData = new FormData();
|
||||
if (value !== null && value !== undefined) {
|
||||
for (const key of Object.keys(value)) {
|
||||
const val = value[key];
|
||||
if (val instanceof Array) {
|
||||
for (const v of val) {
|
||||
const toAppend = this.formDataValue(v);
|
||||
if (toAppend !== null) {
|
||||
formData.append(key, toAppend);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const toAppend = this.formDataValue(val);
|
||||
if (toAppend !== null) {
|
||||
formData.set(key, toAppend);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this._bodyContent = formData;
|
||||
} else {
|
||||
// The body is the plain content
|
||||
this._bodyContent = value;
|
||||
}
|
||||
}
|
||||
|
||||
private formDataValue(value: any): any {
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof Blob) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
return new Blob([JSON.stringify(value)], {type: 'application/json'})
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the request with the current set parameters
|
||||
*/
|
||||
build<T = any>(options?: {
|
||||
/** Which content types to accept */
|
||||
accept?: string;
|
||||
|
||||
/** The expected response type */
|
||||
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';
|
||||
|
||||
/** Whether to report progress on uploads / downloads */
|
||||
reportProgress?: boolean;
|
||||
|
||||
/** Allow passing HttpContext for HttpClient */
|
||||
context?: HttpContext;
|
||||
}): HttpRequest<T> {
|
||||
|
||||
options = options || {};
|
||||
|
||||
// Path parameters
|
||||
let path = this.operationPath;
|
||||
for (const pathParam of this._path.values()) {
|
||||
path = pathParam.append(path);
|
||||
}
|
||||
const url = this.rootUrl + path;
|
||||
|
||||
// Query parameters
|
||||
let httpParams = new HttpParams({
|
||||
encoder: ParameterCodecInstance
|
||||
});
|
||||
for (const queryParam of this._query.values()) {
|
||||
httpParams = queryParam.append(httpParams);
|
||||
}
|
||||
|
||||
// Header parameters
|
||||
let httpHeaders = new HttpHeaders();
|
||||
if (options.accept) {
|
||||
httpHeaders = httpHeaders.append('Accept', options.accept);
|
||||
}
|
||||
for (const headerParam of this._header.values()) {
|
||||
httpHeaders = headerParam.append(httpHeaders);
|
||||
}
|
||||
|
||||
// Request content headers
|
||||
if (this._bodyContentType && !(this._bodyContent instanceof FormData)) {
|
||||
httpHeaders = httpHeaders.set('Content-Type', this._bodyContentType);
|
||||
}
|
||||
|
||||
// Perform the request
|
||||
return new HttpRequest<T>(this.method.toUpperCase(), url, this._bodyContent, {
|
||||
params: httpParams,
|
||||
headers: httpHeaders,
|
||||
responseType: options.responseType,
|
||||
reportProgress: options.reportProgress,
|
||||
context: options.context
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
import { HttpResponse } from '@angular/common/http';
|
||||
|
||||
/**
|
||||
* Constrains the http response to not have the body defined as `T | null`, but `T` only.
|
||||
*/
|
||||
export type StrictHttpResponse<T> = HttpResponse<T> & {
|
||||
readonly body: T;
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideApiConfiguration } from './api/api-configuration';
|
||||
import { routes } from './app.routes';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(),
|
||||
provideApiConfiguration('/api'),
|
||||
],
|
||||
provideHttpClient()
|
||||
]
|
||||
};
|
||||
|
||||
+28
-16
@@ -1,19 +1,31 @@
|
||||
<mat-toolbar class="bar">
|
||||
<span class="brand">ISSSTELEON</span>
|
||||
<mat-button-toggle-group
|
||||
aria-label="Dominio"
|
||||
[value]="domain()"
|
||||
(change)="domain.set($event.value)"
|
||||
>
|
||||
@for (d of domains.value() ?? []; track d) {
|
||||
<mat-button-toggle [value]="d">{{ labels[d] }}</mat-button-toggle>
|
||||
<a class="skip-link" href="#contenido-principal">Saltar al contenido principal</a>
|
||||
<header class="institutional-header">
|
||||
<div class="header-content">
|
||||
<img class="institutional-logo" src="images/LogoISSSTELEON.png" alt="ISSSTELEON"
|
||||
width="1125" height="358" />
|
||||
<span class="platform-title">{{ title }}</span>
|
||||
@if (activeDomain(); as domain) {
|
||||
<button class="domain-selector" mat-button [matMenuTriggerFor]="domainMenu"
|
||||
[attr.aria-label]="'Dominio actual: ' + domainLabels[domain] + '. Cambiar dominio'">
|
||||
{{ domainLabels[domain] }} <span aria-hidden="true">▾</span>
|
||||
</button>
|
||||
<mat-menu #domainMenu="matMenu" aria-label="Cambiar dominio de indicadores">
|
||||
@for (option of otherDomains(); track option) {
|
||||
<a mat-menu-item [routerLink]="['/indicadores', option]">{{ domainLabels[option] }}</a>
|
||||
}
|
||||
</mat-menu>
|
||||
}
|
||||
</mat-button-toggle-group>
|
||||
<span class="spacer"></span>
|
||||
<span class="status" [class.down]="health.error()">
|
||||
API {{ health.value()?.['status'] ?? (health.error() ? 'sin conexión' : '…') }}
|
||||
</span>
|
||||
</mat-toolbar>
|
||||
<main>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main #mainContent id="contenido-principal" tabindex="-1">
|
||||
<router-outlet />
|
||||
</main>
|
||||
|
||||
@if (showBackToTop()) {
|
||||
<button class="back-to-top" type="button" aria-label="Volver al inicio" (click)="backToTop()">
|
||||
<svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M12 19V5m-7 7 7-7 7 7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
</button>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { routes } from './app.routes';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Router, provideRouter } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadoresPage } from './features/indicadores/indicadores-page';
|
||||
it('permite acceso directo a /indicadores sin guard ni autenticación', async () => {
|
||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
|
||||
const harness = await RouterTestingHarness.create();
|
||||
await harness.navigateByUrl('/indicadores', IndicadoresPage);
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
|
||||
expect(harness.routeNativeElement?.textContent).toContain('Indicadores');
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
http.verify();
|
||||
});
|
||||
|
||||
for (const dominio of ['tea', 'cacu', 'cama']) {
|
||||
it(`navega directamente al dominio ${dominio} y conserva la ruta compartida diferida`, async () => {
|
||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
|
||||
const harness = await RouterTestingHarness.create();
|
||||
const page = await harness.navigateByUrl(`/indicadores/${dominio}`, IndicadoresPage);
|
||||
expect(page.dominio).toBe(dominio);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne(`/${dominio}/indicadores`).flush([]);
|
||||
expect(harness.routeNativeElement?.querySelector('nav')).toBeNull();
|
||||
http.verify();
|
||||
});
|
||||
}
|
||||
it('cancela catálogos pendientes durante navegación rápida entre dominios', async () => {
|
||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
|
||||
const harness = await RouterTestingHarness.create();
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||
const tea = http.expectOne('/tea/indicadores');
|
||||
await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage);
|
||||
const cacu = http.expectOne('/cacu/indicadores');
|
||||
const page = await harness.navigateByUrl('/indicadores/cama', IndicadoresPage);
|
||||
expect(tea.cancelled).toBe(true);
|
||||
expect(cacu.cancelled).toBe(true);
|
||||
expect(() => tea.flush([])).toThrow();
|
||||
http.expectOne('/cama/indicadores').flush([]);
|
||||
expect(page.dominio).toBe('cama');
|
||||
expect(page.catalog()).toEqual([]);
|
||||
http.verify();
|
||||
});
|
||||
@@ -1,3 +1,8 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
export const routes: Routes = [];
|
||||
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
|
||||
export const routes: Routes = [
|
||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, data: { dominio }, loadComponent: loadIndicadores })),
|
||||
];
|
||||
|
||||
+118
-12
@@ -1,19 +1,125 @@
|
||||
.bar {
|
||||
gap: 16px;
|
||||
:host {
|
||||
display: block;
|
||||
min-height: 100%;
|
||||
}
|
||||
.brand {
|
||||
font-weight: 500;
|
||||
|
||||
.institutional-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
background: var(--issste-surface);
|
||||
border-bottom: 3px solid var(--issste-logo-lime);
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
|
||||
.header-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--issste-space-4);
|
||||
box-sizing: border-box;
|
||||
min-height: 69px;
|
||||
max-width: 1488px;
|
||||
margin-inline: auto;
|
||||
padding-inline: var(--issste-page-gutter);
|
||||
}
|
||||
.status {
|
||||
font-size: 14px;
|
||||
opacity: 0.8;
|
||||
|
||||
.institutional-logo {
|
||||
display: block;
|
||||
flex: 0 0 auto;
|
||||
width: 200px;
|
||||
height: auto;
|
||||
}
|
||||
.status.down {
|
||||
color: var(--mat-sys-error);
|
||||
|
||||
.platform-title {
|
||||
color: var(--issste-text);
|
||||
font-family: var(--issste-font-heading);
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.15;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.domain-selector {
|
||||
flex: 0 0 auto;
|
||||
margin-inline-start: auto;
|
||||
background-color: var(--issste-accent);
|
||||
color: var(--issste-text);
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
|
||||
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.domain-selector:disabled { background-color: var(--issste-accent); color: var(--issste-text-secondary); }
|
||||
|
||||
main {
|
||||
padding: 16px;
|
||||
padding: var(--issste-space-4) var(--issste-page-gutter) 5.5rem;
|
||||
scroll-margin-top: var(--issste-header-clearance);
|
||||
}
|
||||
|
||||
.skip-link {
|
||||
position: fixed;
|
||||
top: var(--issste-space-2);
|
||||
left: var(--issste-page-gutter);
|
||||
z-index: 101;
|
||||
transform: translateY(-200%);
|
||||
padding: var(--issste-space-2) var(--issste-space-3);
|
||||
color: var(--issste-surface);
|
||||
background: var(--issste-text);
|
||||
border-radius: var(--issste-radius);
|
||||
}
|
||||
|
||||
.skip-link:focus {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
@media (max-width: 550px) {
|
||||
.header-content {
|
||||
gap: var(--issste-space-2);
|
||||
min-height: 64px;
|
||||
}
|
||||
|
||||
.institutional-logo {
|
||||
width: 145px;
|
||||
}
|
||||
|
||||
.platform-title {
|
||||
font-size: 1.125rem;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 359px) {
|
||||
.header-content {
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
padding-block: var(--issste-space-2);
|
||||
gap: var(--issste-space-1);
|
||||
}
|
||||
|
||||
.platform-title {
|
||||
font-size: 1rem;
|
||||
}
|
||||
.header-content { gap: .25rem; }
|
||||
.institutional-logo { width: 112px; }
|
||||
.domain-selector { padding-inline: .5rem; }
|
||||
}
|
||||
|
||||
.back-to-top {
|
||||
position: fixed;
|
||||
right: max(var(--issste-page-gutter), env(safe-area-inset-right));
|
||||
bottom: max(var(--issste-space-4), env(safe-area-inset-bottom));
|
||||
z-index: 90;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
padding: 0;
|
||||
border: 1px solid var(--issste-text);
|
||||
border-radius: 50%;
|
||||
background: var(--issste-text);
|
||||
color: var(--issste-surface);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.back-to-top:hover { background: var(--issste-text-secondary); }
|
||||
.back-to-top:focus-visible { outline: 3px solid var(--issste-text); outline-offset: 4px; }
|
||||
|
||||
+142
-6
@@ -1,14 +1,150 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { App } from './app';
|
||||
import { routes } from './app.routes';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
describe('App', () => {
|
||||
it('creates the shell', async () => {
|
||||
describe('App — UX-06B', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
providers: [provideHttpClient(), provideHttpClientTesting()],
|
||||
providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
|
||||
}).compileComponents();
|
||||
expect(TestBed.createComponent(App).componentInstance).toBeTruthy();
|
||||
});
|
||||
|
||||
function render() {
|
||||
const fixture = TestBed.createComponent(App);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
it('should create the app', () => {
|
||||
expect(render().componentInstance).toBeTruthy();
|
||||
});
|
||||
|
||||
it('renders one institutional header and the platform identification', () => {
|
||||
const element = render().nativeElement as HTMLElement;
|
||||
expect(element.querySelectorAll('header')).toHaveLength(1);
|
||||
expect(element.querySelector('header')?.textContent).toContain('Plataforma de Indicadores');
|
||||
});
|
||||
|
||||
it('uses the authorized static logo with alternative text and intrinsic proportions', () => {
|
||||
const logo = (render().nativeElement as HTMLElement).querySelector('header img');
|
||||
expect(logo?.getAttribute('src')).toBe('images/LogoISSSTELEON.png');
|
||||
expect(logo?.getAttribute('alt')).toBe('ISSSTELEON');
|
||||
expect(logo?.getAttribute('width')).toBe('1125');
|
||||
expect(logo?.getAttribute('height')).toBe('358');
|
||||
});
|
||||
|
||||
it('keeps the routed content inside a main landmark and a keyboard skip target', () => {
|
||||
const element = render().nativeElement as HTMLElement;
|
||||
const main = element.querySelector('main#contenido-principal');
|
||||
expect(main?.querySelector('router-outlet')).toBeTruthy();
|
||||
expect(main?.getAttribute('tabindex')).toBe('-1');
|
||||
expect(element.querySelector('a.skip-link')?.getAttribute('href')).toBe('#contenido-principal');
|
||||
});
|
||||
|
||||
it('does not duplicate domain navigation or introduce shell HTTP requests', () => {
|
||||
const fixture = render();
|
||||
fixture.detectChanges();
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
expect(element.querySelector('nav')).toBeNull();
|
||||
expect(element.querySelectorAll('[routerLink]')).toHaveLength(0);
|
||||
TestBed.inject(HttpTestingController).expectNone(() => true);
|
||||
TestBed.inject(HttpTestingController).verify();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['tea', 'TEA', 'CaCu', 'CaMa'],
|
||||
['cacu', 'CaCu', 'TEA', 'CaMa'],
|
||||
['cama', 'CaMa', 'TEA', 'CaCu'],
|
||||
] as const)('announces %s as the active domain and offers the other domains in the shell', async (domain, active, ...others) => {
|
||||
const fixture = render();
|
||||
await TestBed.inject(Router).navigateByUrl(`/indicadores/${domain}`);
|
||||
fixture.detectChanges();
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
const catalog = http.expectOne({ method: 'GET', url: `/${domain}/indicadores` });
|
||||
catalog.flush([]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const selector = element.querySelector<HTMLButtonElement>('.domain-selector')!;
|
||||
expect(selector.textContent).toContain(active);
|
||||
expect(selector.getAttribute('aria-label')).toBe(`Dominio actual: ${active}. Cambiar dominio`);
|
||||
selector.click();
|
||||
fixture.detectChanges();
|
||||
const menuItems = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]'));
|
||||
expect(menuItems.map(item => item.textContent?.trim())).toEqual(others);
|
||||
expect(element.querySelector('nav')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
fixture.destroy();
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
describe('App — UX-06D volver al inicio', () => {
|
||||
let scrollY: number;
|
||||
beforeEach(() => {
|
||||
scrollY = 0;
|
||||
vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => scrollY);
|
||||
TestBed.configureTestingModule({ imports: [App], providers: [provideRouter([])] });
|
||||
});
|
||||
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
function render() {
|
||||
const fixture = TestBed.createComponent(App);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
function scroll(fixture: ReturnType<typeof render>, position: number) {
|
||||
scrollY = position;
|
||||
window.dispatchEvent(new Event('scroll'));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
it('oculta al inicio y en el umbral, muestra después y vuelve a ocultar al subir', () => {
|
||||
const fixture = render();
|
||||
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
|
||||
scroll(fixture, 400);
|
||||
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
|
||||
scroll(fixture, 401);
|
||||
expect(fixture.nativeElement.querySelector('.back-to-top')).not.toBeNull();
|
||||
scroll(fixture, 0);
|
||||
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
|
||||
});
|
||||
it('reconoce una posición restaurada al montar el shell', () => {
|
||||
scrollY = 900;
|
||||
expect(render().nativeElement.querySelector('.back-to-top')).not.toBeNull();
|
||||
});
|
||||
it.each([false, true])('activa un botón nativo y respeta movimiento reducido=%s', reduced => {
|
||||
const matchMedia = vi.fn().mockReturnValue({ matches: reduced } as MediaQueryList);
|
||||
vi.stubGlobal('matchMedia', matchMedia);
|
||||
const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
|
||||
const fixture = render();
|
||||
scroll(fixture, 900);
|
||||
const button = fixture.nativeElement.querySelector('.back-to-top') as HTMLButtonElement;
|
||||
const main = fixture.nativeElement.querySelector('main') as HTMLElement;
|
||||
const focus = vi.spyOn(main, 'focus');
|
||||
expect(button.type).toBe('button');
|
||||
expect(button.tabIndex).toBe(0);
|
||||
expect(button.getAttribute('aria-label')).toBe('Volver al inicio');
|
||||
expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
|
||||
button.click();
|
||||
expect(matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)');
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 0, behavior: reduced ? 'instant' : 'smooth' });
|
||||
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
|
||||
// Native Enter/Space activation is checked in Chrome, not emulated by jsdom.
|
||||
});
|
||||
it('registra un listener pasivo y elimina exactamente el mismo al destruir', () => {
|
||||
const add = vi.spyOn(window, 'addEventListener');
|
||||
const remove = vi.spyOn(window, 'removeEventListener');
|
||||
const fixture = render();
|
||||
const registration = add.mock.calls.find(call => call[0] === 'scroll')!;
|
||||
expect(registration[2]).toEqual({ passive: true });
|
||||
fixture.destroy();
|
||||
expect(remove).toHaveBeenCalledWith('scroll', registration[1]);
|
||||
scrollY = 900;
|
||||
window.dispatchEvent(new Event('scroll'));
|
||||
expect(fixture.componentInstance.showBackToTop()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
+42
-18
@@ -1,24 +1,48 @@
|
||||
import { Component, inject, resource, signal } from '@angular/core';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { Api } from './api/api';
|
||||
import { domains } from './api/fn/operations/domains';
|
||||
import { health } from './api/fn/operations/health';
|
||||
import { Domain } from './api/models/domain';
|
||||
|
||||
const LABELS: Record<Domain, string> = { cacu: 'CaCu', cama: 'CaMa', tea: 'TEA' };
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { Component, computed, ElementRef, inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core';
|
||||
import { NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatMenuModule } from '@angular/material/menu';
|
||||
import { filter } from 'rxjs';
|
||||
|
||||
@Component({
|
||||
imports: [RouterOutlet, RouterLink, MatButtonModule, MatMenuModule],
|
||||
selector: 'app-root',
|
||||
imports: [RouterOutlet, MatToolbarModule, MatButtonToggleModule],
|
||||
templateUrl: './app.html',
|
||||
styleUrl: './app.scss',
|
||||
templateUrl: './app.html',
|
||||
})
|
||||
export class App {
|
||||
private readonly api = inject(Api);
|
||||
protected readonly labels = LABELS;
|
||||
protected readonly domain = signal<Domain>('cacu');
|
||||
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
||||
protected readonly health = resource({ loader: () => this.api.invoke(health) });
|
||||
export class App implements OnInit, OnDestroy {
|
||||
protected readonly title = 'Plataforma de Indicadores';
|
||||
private readonly router = inject(Router);
|
||||
private readonly currentUrl = signal(this.router.url);
|
||||
protected readonly activeDomain = computed(() => {
|
||||
const match = /^\/indicadores\/(tea|cacu|cama)(?:\/|$)/.exec(this.currentUrl());
|
||||
return match?.[1] as 'tea' | 'cacu' | 'cama' | undefined;
|
||||
});
|
||||
protected readonly domainLabels = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' } as const;
|
||||
protected readonly otherDomains = computed(() => (['tea', 'cacu', 'cama'] as const)
|
||||
.filter(domain => domain !== this.activeDomain()));
|
||||
private readonly routeSubscription = this.router.events.pipe(filter(event => event instanceof NavigationEnd))
|
||||
.subscribe(event => this.currentUrl.set(event.urlAfterRedirects));
|
||||
readonly showBackToTop = signal(false);
|
||||
@ViewChild('mainContent') private mainContent?: ElementRef<HTMLElement>;
|
||||
private readonly browserWindow = inject(DOCUMENT).defaultView;
|
||||
private readonly updateScroll = () => this.showBackToTop.set((this.browserWindow?.scrollY ?? 0) > 400);
|
||||
|
||||
ngOnInit() {
|
||||
this.updateScroll();
|
||||
this.browserWindow?.addEventListener('scroll', this.updateScroll, { passive: true });
|
||||
}
|
||||
|
||||
backToTop() {
|
||||
const reducedMotion = this.browserWindow?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
// Keep keyboard focus near the destination when the floating button disappears.
|
||||
this.mainContent?.nativeElement.focus({ preventScroll: true });
|
||||
this.browserWindow?.scrollTo({ top: 0, behavior: reducedMotion ? 'instant' : 'smooth' });
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
this.routeSubscription.unsubscribe();
|
||||
this.browserWindow?.removeEventListener('scroll', this.updateScroll);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
export interface SeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
grupo_edad: string;
|
||||
estatus: SeguimientoStatus;
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
||||
dias_toma_diagnostico: number | null;
|
||||
prioridad: SeguimientoStatus | null;
|
||||
}
|
||||
export interface SeguimientoResponse {
|
||||
simulado: boolean;
|
||||
corte: string;
|
||||
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
||||
filtros: { estatus: string | null };
|
||||
estatus_disponibles: SeguimientoStatus[];
|
||||
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
|
||||
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
||||
items: SeguimientoPaciente[];
|
||||
}
|
||||
export function isoDate(value: unknown): value is string {
|
||||
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000')) return false;
|
||||
const date = new Date(value + 'T00:00:00Z');
|
||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
}
|
||||
export function latestStudy(item: SeguimientoPaciente): string | null {
|
||||
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= 200;
|
||||
}
|
||||
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
// The current authorization covers demonstration records only. Validate this
|
||||
// before passing any item to the component; real-patient activation is separate.
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||
if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||
})) throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as SeguimientoResponse;
|
||||
}
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CacuSeguimientoService {
|
||||
private readonly http = inject(HttpClient);
|
||||
consultar(query: SeguimientoQuery) {
|
||||
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
|
||||
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
||||
if (query.corte) params = params.set('corte', query.corte);
|
||||
if (query.estatus) params = params.set('estatus', query.estatus);
|
||||
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import fixtureData from './fixtures/cacu_seguimiento.json';
|
||||
import { CacuSeguimientoService, seguimientoResponse } from './cacu-seguimiento.service';
|
||||
import { latestStudy } from './cacu-seguimiento.models';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
|
||||
describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers:[provideHttpClient(),provideHttpClientTesting()] });
|
||||
fixture=TestBed.createComponent(IndicadoresTracking); http=TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio','cacu'); fixture.componentRef.setInput('domainLabel','CaCu');
|
||||
});
|
||||
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', () => {
|
||||
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']);
|
||||
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();
|
||||
let req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
||||
req.flush(fixtureData); fixture.detectChanges();
|
||||
fixture.componentInstance.navigate(2); req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
||||
expect(req.request.params.get('page')).toBe('2');
|
||||
req.flush({ ...fixtureData, paginacion: { ...fixtureData.paginacion, page: 2 } });
|
||||
});
|
||||
it('consulta solo al abrir CaCu, presenta ventana, nulos, calidad y genotipo sin leyendas de prototipo ni prioridad clínica', () => {
|
||||
fixture.detectChanges(); http.expectNone(()=>true); respond();
|
||||
const root:HTMLElement=fixture.nativeElement;
|
||||
expect(root.textContent).not.toContain('Datos simulados — uso de demostración');
|
||||
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
|
||||
expect(root.textContent).toContain('Ventana consultada:');
|
||||
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
|
||||
expect(root.textContent).toContain('Insatisfactoria');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
|
||||
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||
expect(root.textContent).not.toMatch(/Ronda|Espera|Motivo de revisión/);
|
||||
expect(root.querySelector('tbody tr td:nth-child(8)')?.textContent).toBe('No disponible');
|
||||
expect(root.querySelector('thead')?.textContent).not.toContain('Acciones');
|
||||
expect(root.querySelectorAll('tbody button.patient-link')).toHaveLength(10);
|
||||
expect(root.querySelector('tbody button.patient-link')?.getAttribute('aria-label')).toContain(fixture.componentInstance.data?.items[0].id_seudonimo);
|
||||
expect(latestStudy(seguimientoResponse(fixtureData).items[5])).toBe('2026-08-15');
|
||||
expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull();
|
||||
});
|
||||
it('acepta calidad nula por paciente y la presenta de forma neutra sin rechazar la página', () => {
|
||||
const items = fixtureData.items.map((item, index) => index === 2
|
||||
? {...item, ultima_citologia:{...item.ultima_citologia!, calidad:null}}
|
||||
: item);
|
||||
expect(seguimientoResponse({...fixtureData, items}).items).toHaveLength(fixtureData.items.length);
|
||||
fixture.componentRef.setInput('active',true); fixture.detectChanges();
|
||||
http.expectOne(r=>r.url==='/cacu/seguimiento').flush({...fixtureData,items});
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges();
|
||||
const rows = fixture.nativeElement.querySelectorAll('tbody tr');
|
||||
expect(rows).toHaveLength(fixtureData.items.length);
|
||||
expect(rows[2].textContent).toContain('Calidad: —');
|
||||
expect(rows[2].textContent).not.toContain('Calidad: null');
|
||||
});
|
||||
it('página y filtros conservan los parámetros aplicados; navegación por pestañas no repite GET', () => {
|
||||
respond(); fixture.componentInstance.draft={corte:'2026-09-30',meses:6,estatus:'VIGILANCIA',page:1,page_size:10}; fixture.componentInstance.apply();
|
||||
let req=http.expectOne(r=>r.url==='/cacu/seguimiento'); expect(req.request.params.get('meses')).toBe('6'); expect(req.request.params.get('estatus')).toBe('VIGILANCIA');
|
||||
req.flush({...fixtureData,ventana:{...fixtureData.ventana,meses:6},filtros:{estatus:'VIGILANCIA'}}); fixture.detectChanges();
|
||||
fixture.componentInstance.draft.meses=12; // Draft edits must not affect server pagination.
|
||||
fixture.componentInstance.navigate(2); req=http.expectOne(r=>r.url==='/cacu/seguimiento');
|
||||
expect(req.request.params.get('page')).toBe('2'); expect(req.request.params.get('meses')).toBe('6'); expect(req.request.params.get('corte')).toBe('2026-09-30');
|
||||
req.flush({...fixtureData,ventana:{...fixtureData.ventana,meses:6},filtros:{estatus:'VIGILANCIA'},paginacion:{...fixtureData.paginacion,page:2}});
|
||||
fixture.componentRef.setInput('active',false); fixture.detectChanges(); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.componentInstance.data?.paginacion.page).toBe(2);
|
||||
});
|
||||
it.each([404,400,0,503])('HTTP %s no introduce registros ficticios; reintento conserva consulta', code => {
|
||||
const req=open(); if(code===0) req.error(new ProgressEvent('error')); else req.flush({error:'private'}, {status:code,statusText:'Failure'});
|
||||
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.componentInstance.status).toBe(code===404?'pending':'error'); fixture.componentInstance.retry();
|
||||
http.expectOne(r=>r.url==='/cacu/seguimiento').flush({...fixtureData,items:[],paginacion:{page:1,page_size:50,total_items:0,total_pages:0}});
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({}, {status:404,statusText:'Absent'}); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay registros');
|
||||
});
|
||||
it('no activa registros reales ni acepta respuestas malformadas', () => {
|
||||
expect(()=>seguimientoResponse({...fixtureData,simulado:false})).toThrow();
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[0],ultimo_vph:{fecha:'bad'}}]})).toThrow();
|
||||
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.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
|
||||
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();
|
||||
http.expectNone(()=>true);
|
||||
});
|
||||
});
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
{
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.2.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "estatus_seguimiento",
|
||||
"valores_estrato": [
|
||||
"VIGILANCIA",
|
||||
"POST_COLPOSCOPIA",
|
||||
"POST_TRATAMIENTO",
|
||||
"INFO_INSUFICIENTE"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"VIGILANCIA": "Vigilancia",
|
||||
"POST_COLPOSCOPIA": "Post colposcopia",
|
||||
"POST_TRATAMIENTO": "Post tratamiento",
|
||||
"INFO_INSUFICIENTE": "Información insuficiente"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 44,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-10-22",
|
||||
"generado_en": "2026-10-22T20:26:40.633043+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "94749f578a4d901edf038bca0427e9975bac72de1a1fdea382f4de1d5eb7402b",
|
||||
"parametros_sha": "091ab456d7f51e865bf31e1fd4201d22a3acf9877f057d0473b4765c20095092",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [
|
||||
"NORMAL",
|
||||
"ASC-US",
|
||||
"LIEBG",
|
||||
"ASC-H",
|
||||
"LIEAG",
|
||||
"CIS"
|
||||
],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"calidad_insatisfactoria": "INSATISFACTORIO",
|
||||
"fecha_corte": "2026-10-22",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"periodo_inicio": "2025-07-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "NORMAL",
|
||||
"n": 1027,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "ASC-US",
|
||||
"n": 145,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "LIEBG",
|
||||
"n": 65,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "ASC-H",
|
||||
"n": 22,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "LIEAG",
|
||||
"n": 36,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "CIS",
|
||||
"n": 9,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 46,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "NORMAL",
|
||||
"n": 117,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "ASC-US",
|
||||
"n": 39,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "LIEBG",
|
||||
"n": 30,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "ASC-H",
|
||||
"n": 5,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "LIEAG",
|
||||
"n": 11,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 6,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "NORMAL",
|
||||
"n": 26,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "ASC-US",
|
||||
"n": 7,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "LIEBG",
|
||||
"n": 7,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "LIEAG",
|
||||
"n": null,
|
||||
"orden": 4,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": null,
|
||||
"orden": 6,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "NORMAL",
|
||||
"n": 192,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "ASC-US",
|
||||
"n": 20,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "LIEBG",
|
||||
"n": 16,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "LIEAG",
|
||||
"n": 9,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 12,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
{
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.2.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "grupo_edad",
|
||||
"valores_estrato": [
|
||||
"<25",
|
||||
"25-34",
|
||||
"35-44",
|
||||
"45-54",
|
||||
"55-64",
|
||||
"65+",
|
||||
"sin_dato"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"<25": "<25",
|
||||
"25-34": "25-34",
|
||||
"35-44": "35-44",
|
||||
"45-54": "45-54",
|
||||
"55-64": "55-64",
|
||||
"65+": "65+",
|
||||
"sin_dato": "Sin dato"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 44,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-10-22",
|
||||
"generado_en": "2026-10-22T20:26:40.633043+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "94749f578a4d901edf038bca0427e9975bac72de1a1fdea382f4de1d5eb7402b",
|
||||
"parametros_sha": "091ab456d7f51e865bf31e1fd4201d22a3acf9877f057d0473b4765c20095092",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [
|
||||
"NORMAL",
|
||||
"ASC-US",
|
||||
"LIEBG",
|
||||
"ASC-H",
|
||||
"LIEAG",
|
||||
"CIS"
|
||||
],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"calidad_insatisfactoria": "INSATISFACTORIO",
|
||||
"fecha_corte": "2026-10-22",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"periodo_inicio": "2025-07-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "NORMAL",
|
||||
"n": 50,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "ASC-US",
|
||||
"n": null,
|
||||
"orden": 1,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "LIEBG",
|
||||
"n": null,
|
||||
"orden": 2,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "LIEAG",
|
||||
"n": null,
|
||||
"orden": 4,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": null,
|
||||
"orden": 6,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "NORMAL",
|
||||
"n": 320,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "ASC-US",
|
||||
"n": 32,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "LIEBG",
|
||||
"n": 21,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "ASC-H",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "LIEAG",
|
||||
"n": 13,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 15,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "NORMAL",
|
||||
"n": 441,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "ASC-US",
|
||||
"n": 25,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "LIEBG",
|
||||
"n": 21,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "ASC-H",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "LIEAG",
|
||||
"n": 9,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 16,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "NORMAL",
|
||||
"n": 365,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "ASC-US",
|
||||
"n": 36,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "LIEBG",
|
||||
"n": 21,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "ASC-H",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "LIEAG",
|
||||
"n": 16,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 23,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "NORMAL",
|
||||
"n": 245,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "ASC-US",
|
||||
"n": 23,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "LIEBG",
|
||||
"n": 10,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "ASC-H",
|
||||
"n": 5,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "LIEAG",
|
||||
"n": 5,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 11,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "NORMAL",
|
||||
"n": 74,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "ASC-US",
|
||||
"n": 6,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "LIEBG",
|
||||
"n": null,
|
||||
"orden": 2,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "LIEAG",
|
||||
"n": null,
|
||||
"orden": 4,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": null,
|
||||
"orden": 6,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "NORMAL",
|
||||
"n": 10,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "ASC-US",
|
||||
"n": null,
|
||||
"orden": 1,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "LIEBG",
|
||||
"n": null,
|
||||
"orden": 2,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "LIEAG",
|
||||
"n": null,
|
||||
"orden": 4,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": null,
|
||||
"orden": 6,
|
||||
"suprimido": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
{
|
||||
"simulado": true,
|
||||
"corte": "2026-09-30",
|
||||
"ventana": {
|
||||
"meses": 3,
|
||||
"desde": "2026-07-01",
|
||||
"hasta": "2026-09-30"
|
||||
},
|
||||
"filtros": {
|
||||
"estatus": null
|
||||
},
|
||||
"estatus_disponibles": [
|
||||
{
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
{
|
||||
"codigo": "POST_COLPOSCOPIA",
|
||||
"etiqueta": "Post colposcopia"
|
||||
},
|
||||
{
|
||||
"codigo": "POST_TRATAMIENTO",
|
||||
"etiqueta": "Post tratamiento"
|
||||
},
|
||||
{
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
}
|
||||
],
|
||||
"reglas": [
|
||||
{
|
||||
"clave": "cacu.seguimiento.marco",
|
||||
"valor": [
|
||||
"estatus"
|
||||
],
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.precedencia",
|
||||
"valor": [
|
||||
"POST_TRATAMIENTO",
|
||||
"POST_COLPOSCOPIA",
|
||||
"INFO_INSUFICIENTE",
|
||||
"VIGILANCIA"
|
||||
],
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.ventana_meses",
|
||||
"valor": 3,
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.fecha_estudio",
|
||||
"valor": "toma",
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.estudios",
|
||||
"valor": [
|
||||
"citologia",
|
||||
"vph"
|
||||
],
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.resultado_mostrado",
|
||||
"valor": "ultimo",
|
||||
"estado": "provisional"
|
||||
}
|
||||
],
|
||||
"paginacion": {
|
||||
"page": 1,
|
||||
"page_size": 10,
|
||||
"total_items": 1284,
|
||||
"total_pages": 129
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id_seudonimo": "P-4BC9B9E8F4",
|
||||
"grupo_edad": "25-34",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": null,
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-09-28",
|
||||
"resultado": "NEGATIVO",
|
||||
"genotipo_16_18": null
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-2C9E494F5D",
|
||||
"grupo_edad": "65+",
|
||||
"estatus": {
|
||||
"codigo": "POST_COLPOSCOPIA",
|
||||
"etiqueta": "Post colposcopia"
|
||||
},
|
||||
"ultima_citologia": null,
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-09-23",
|
||||
"resultado": "POSITIVO",
|
||||
"genotipo_16_18": true
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-E470F3442F",
|
||||
"grupo_edad": "35-44",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-09-18",
|
||||
"bethesda": "NORMAL",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-09-08",
|
||||
"resultado": "NEGATIVO",
|
||||
"genotipo_16_18": null
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-24A2B1D6B5",
|
||||
"grupo_edad": "25-34",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-09-13",
|
||||
"bethesda": "LIEAG",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": null,
|
||||
"dias_toma_diagnostico": 23,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-9E0E15AB5C",
|
||||
"grupo_edad": "25-34",
|
||||
"estatus": {
|
||||
"codigo": "POST_COLPOSCOPIA",
|
||||
"etiqueta": "Post colposcopia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-08-22",
|
||||
"bethesda": "NORMAL",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-07-14",
|
||||
"resultado": "NEGATIVO",
|
||||
"genotipo_16_18": null
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-45A44DFE6F",
|
||||
"grupo_edad": "<25",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-08-04",
|
||||
"bethesda": null,
|
||||
"calidad": "INSATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-08-15",
|
||||
"resultado": "POSITIVO",
|
||||
"genotipo_16_18": false
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-367397F2CE",
|
||||
"grupo_edad": "65+",
|
||||
"estatus": {
|
||||
"codigo": "POST_TRATAMIENTO",
|
||||
"etiqueta": "Post tratamiento"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-08-05",
|
||||
"bethesda": "ASC-H",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": null,
|
||||
"dias_toma_diagnostico": 41,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-2FB7CB6653",
|
||||
"grupo_edad": "45-54",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-07-24",
|
||||
"bethesda": "NORMAL",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": null,
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-517CD5E39B",
|
||||
"grupo_edad": "55-64",
|
||||
"estatus": {
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-07-17",
|
||||
"bethesda": "ASC-US",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": null,
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-E1157546FD",
|
||||
"grupo_edad": "25-34",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-07-01",
|
||||
"bethesda": "NORMAL",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-07-01",
|
||||
"resultado": "INDETERMINADO",
|
||||
"genotipo_16_18": null
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,936 @@
|
||||
{
|
||||
"_nota": "Datos SIMULADOS con la forma exacta de GET /cacu/indicadores/cacu_eu7/datos (contrato C2, kit 054837b). Sin 'reportes' (procedencia). Las tres respuestas son del mismo semestre y suman lo mismo.",
|
||||
"general": {
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "NORMAL",
|
||||
"n": 798,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "ASC-US",
|
||||
"n": 62,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "LIEBG",
|
||||
"n": 46,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "ASC-H",
|
||||
"n": 17,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "LIEAG",
|
||||
"n": 19,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "CIS",
|
||||
"n": 4,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 87,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "estatus_seguimiento",
|
||||
"valores_estrato": [
|
||||
"VIGILANCIA",
|
||||
"POST_COLPOSCOPIA",
|
||||
"POST_TRATAMIENTO",
|
||||
"INFO_INSUFICIENTE"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"VIGILANCIA": "Vigilancia",
|
||||
"POST_COLPOSCOPIA": "Post colposcopia",
|
||||
"POST_TRATAMIENTO": "Post tratamiento",
|
||||
"INFO_INSUFICIENTE": "Información insuficiente"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "NORMAL",
|
||||
"n": 610,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "ASC-US",
|
||||
"n": 38,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "LIEBG",
|
||||
"n": 22,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "ASC-H",
|
||||
"n": 6,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "LIEAG",
|
||||
"n": 5,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "CIS",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 48,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "NORMAL",
|
||||
"n": 92,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "ASC-US",
|
||||
"n": 14,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "LIEBG",
|
||||
"n": 16,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "ASC-H",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "LIEAG",
|
||||
"n": 9,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "CIS",
|
||||
"n": 2,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 11,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "NORMAL",
|
||||
"n": 41,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "ASC-US",
|
||||
"n": 6,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "LIEBG",
|
||||
"n": 5,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "ASC-H",
|
||||
"n": 3,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "LIEAG",
|
||||
"n": 4,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "CIS",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 7,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "NORMAL",
|
||||
"n": 55,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "ASC-US",
|
||||
"n": 4,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "LIEBG",
|
||||
"n": 3,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "ASC-H",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "LIEAG",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "CIS",
|
||||
"n": 0,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 21,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"n": 730,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"n": 151,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"n": 67,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"n": 85,
|
||||
"suprimido": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"grupo_edad": {
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "grupo_edad",
|
||||
"valores_estrato": [
|
||||
"<25",
|
||||
"25-34",
|
||||
"35-44",
|
||||
"45-54",
|
||||
"55-64"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"<25": "<25",
|
||||
"25-34": "25-34",
|
||||
"35-44": "35-44",
|
||||
"45-54": "45-54",
|
||||
"55-64": "55-64"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "NORMAL",
|
||||
"n": 40,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "ASC-US",
|
||||
"n": 5,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "LIEBG",
|
||||
"n": 4,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "ASC-H",
|
||||
"n": 0,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "LIEAG",
|
||||
"n": 0,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "CIS",
|
||||
"n": 0,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 6,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "NORMAL",
|
||||
"n": 190,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "ASC-US",
|
||||
"n": 18,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "LIEBG",
|
||||
"n": 17,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "ASC-H",
|
||||
"n": 4,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "LIEAG",
|
||||
"n": 4,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "CIS",
|
||||
"n": 0,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 22,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "NORMAL",
|
||||
"n": 230,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "ASC-US",
|
||||
"n": 20,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "LIEBG",
|
||||
"n": 14,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "ASC-H",
|
||||
"n": 6,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "LIEAG",
|
||||
"n": 7,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "CIS",
|
||||
"n": 2,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 25,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "NORMAL",
|
||||
"n": 205,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "ASC-US",
|
||||
"n": 12,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "LIEBG",
|
||||
"n": 7,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "ASC-H",
|
||||
"n": 4,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "LIEAG",
|
||||
"n": 5,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "CIS",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 20,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "NORMAL",
|
||||
"n": 133,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "ASC-US",
|
||||
"n": 7,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "LIEBG",
|
||||
"n": 4,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "ASC-H",
|
||||
"n": 3,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "LIEAG",
|
||||
"n": 3,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "CIS",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 14,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"n": 55,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"n": 255,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"n": 304,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"n": 254,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"n": 165,
|
||||
"suprimido": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresMemory, GlobalApplied } from './indicadores-memory';
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorCatalogCard>>;
|
||||
let http: HttpTestingController;
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 };
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); create(['f', 'g']);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
function create(figuras: string[], domain = 'cacu') {
|
||||
fixture = TestBed.createComponent(IndicadorCatalogCard);
|
||||
fixture.componentRef.setInput('dominio', domain);
|
||||
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(); }
|
||||
it.each(['C1', 'C2', 'C3r'])('UX-07A omite IDs y contrato %s y conserva título y contador', contrato => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'K05_eeg_20_minutos', titulo: 'EEG con ≥ 20 min de registro', contrato,
|
||||
figuras: ['fig_c1_grupos', 'fig_c1_puntos'], tipos_periodo: ['semestre'] });
|
||||
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');
|
||||
// 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());
|
||||
expect(copy.textContent).not.toMatch(/K05_eeg_20_minutos|Contrato|fig_c1_/);
|
||||
expect(fixture.componentInstance.indicador.id).toBe('K05_eeg_20_minutos');
|
||||
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', () => {
|
||||
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 [
|
||||
['fig_c2_apiladas', 'Barras apiladas'],
|
||||
['fig_c2_barras', 'Barras'],
|
||||
['fig_c2_donas', 'Donas'],
|
||||
['fig_c9_futura', 'Representación 5'],
|
||||
]) {
|
||||
select().selectionChange.emit({ source: select(), value: 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');
|
||||
expect(pending.request.params.get('periodos')).toBe('2025-S1');
|
||||
pending.flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.selectedFigure).toBe(id);
|
||||
expect(TestBed.inject(IndicadoresMemory).figure('cacu', 'i')).toBe(id);
|
||||
expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`);
|
||||
}
|
||||
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('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',
|
||||
figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] });
|
||||
fixture.detectChanges();
|
||||
const helps = fixture.nativeElement.querySelectorAll('.methodology-toggle') as NodeListOf<HTMLButtonElement>;
|
||||
expect(helps).toHaveLength(2);
|
||||
helps[0].click(); helps[1].click(); fixture.detectChanges();
|
||||
const metadata = http.expectOne('/cacu/indicadores/cacu_eu13/metadatos');
|
||||
http.expectNone('/cacu/indicadores/cacu_eu13/metadatos');
|
||||
metadata.flush({ figuras_detalle: [
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Instrucción para donas.'] },
|
||||
{ figura: 'fig_c2_barras', descripcion: null, como_leer: ['Instrucción para barras.'] },
|
||||
{ figura: 'otra', descripcion: null, como_leer: ['No debe asignarse.'] },
|
||||
] });
|
||||
fixture.detectChanges();
|
||||
const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(e => e.componentInstance as IndicadorFigureCard);
|
||||
expect(cards.map(card => card.interpretation)).toEqual([['Instrucción para donas.'], ['Instrucción para barras.']]);
|
||||
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();
|
||||
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);
|
||||
request('f').flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].componentInstance.result().figure.data[0].y).toEqual([7]); http.expectNone(() => true);
|
||||
});
|
||||
it('restaura memoria por dominio e indicador sólo si sigue publicada y conserva carga diferida', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
|
||||
request('g').flush({ data: [], layout: {} }); fixture.destroy(); create(['f', 'g']);
|
||||
expect(fixture.componentInstance.selectedFigure).toBe('g'); expect(fixture.componentInstance.visible).toBe(false); http.expectNone(() => true);
|
||||
fixture.componentInstance.setVisible(true); fixture.detectChanges(); request('g').flush({ data: [], layout: {} });
|
||||
fixture.destroy(); create(['f', 'g'], 'cama'); expect(fixture.componentInstance.selectedFigure).toBe('f');
|
||||
fixture.destroy(); create(['f']); expect(fixture.componentInstance.selectedFigure).toBe('f');
|
||||
});
|
||||
it('cambio de aplicado conserva elección y consulta sólo su representación; fuera de vista cancela revisión obsoleta', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); request('g').flush({ data: [], layout: {} });
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S2'] } }); fixture.detectChanges();
|
||||
const current = request('g'); expect(current.request.params.get('periodos')).toBe('2025-S2'); http.expectNone(r => r.url.endsWith('/figuras/f'));
|
||||
fixture.componentInstance.setVisible(false); fixture.detectChanges();
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision: 3 }); fixture.detectChanges(); expect(current.cancelled).toBe(true);
|
||||
expect(panels()).toHaveLength(0); http.expectNone(() => true);
|
||||
});
|
||||
it('opciones ajenas al catálogo y selección repetida no consultan', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('bad'); fixture.componentInstance.selectFigure('f'); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.selectedFigure).toBe('f'); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
it('C2 sin magnitudes elimina la copia HTML de la nota y no cambia trazas Plotly', () => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigureCard] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
const fixture = TestBed.createComponent(IndicadorFigureCard);
|
||||
const figure = { data: [{ type: 'pie', values: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } };
|
||||
fixture.componentRef.setInput('state', { status: 'ready', figure, presentationFigure: structuredClone(figure) });
|
||||
fixture.componentRef.setInput('selected', { id: 'i', titulo: 'I', contrato: 'C2', figuras: ['fig_c2_donas'], tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('figuraId', 'fig_c2_donas'); fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('[aria-label="Advertencias y notas del servicio"]')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); expect(fixture.nativeElement.textContent).toContain('Los sectores');
|
||||
expect(figure.data[0].values).toEqual([null, null]); fixture.destroy();
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChanges, OnDestroy, output, untracked, ViewChild } from '@angular/core';
|
||||
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';
|
||||
import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile';
|
||||
import { dualFigures } from './indicadores-dual-figures';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { filterCompatibility } from './indicadores-memory';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
||||
(click)="pinChanged.emit()">
|
||||
<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">
|
||||
<p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p>
|
||||
@if (isEu7) {
|
||||
<div #visibilityRegion class="eu7-region">
|
||||
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (isConfirmacion) {
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-confirmacion-citologia [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (tiempos; as par) {
|
||||
<div #visibilityRegion class="tiempos-region">
|
||||
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
@if (!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">
|
||||
@if (isDual) { <h3>{{ figureDisplayName(figure, indicador.figuras) }}</h3> }
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [metadata]="metadata" [figuraId]="figure" [tema]="tema" [applied]="applied" [independentPeriods]="independentPeriods" [visible]="visible" [visualProfile]="visualProfile" [localSelection]="localSelection" (metadataRequested)="loadMetadata()" (hierarchySelected)="localSelection = $event" />
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else { <p role="status">El indicador no tiene figuras disponibles.</p> }
|
||||
</div>
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
|
||||
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
||||
.graphic-region { flex: 1; min-width: 0; }
|
||||
:host(.dual-card) { grid-column: 1 / -1; }
|
||||
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
|
||||
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
|
||||
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
|
||||
app-indicador-figure-panel { grid-row: 2; }
|
||||
// Nine shared tracks: name, controls, help, title, legend, plot, notes,
|
||||
// full labels and stratified detail. Content determines their height.
|
||||
@supports (grid-template-rows: subgrid) {
|
||||
.graphic-region { grid-auto-rows: auto; grid-template-rows: auto auto auto auto auto minmax(0, 1fr) auto auto auto; }
|
||||
.representation-panel { grid-row: span 9; grid-template-rows: subgrid; }
|
||||
app-indicador-figure-panel { grid-row: 2 / span 8; }
|
||||
.graphic-region:has(app-indicador-figure-card.methodology-expanded) { grid-template-rows: none; align-items: start; }
|
||||
.graphic-region:has(app-indicador-figure-card.methodology-expanded) .representation-panel { grid-row: auto; grid-template-rows: auto auto; }
|
||||
.graphic-region:has(app-indicador-figure-card.methodology-expanded) app-indicador-figure-panel { grid-row: auto; grid-template-rows: auto auto auto; }
|
||||
.graphic-region:has(app-indicador-figure-card.methodology-expanded) app-indicador-figure-card { grid-row: auto; grid-template-rows: auto auto auto auto auto auto; }
|
||||
}
|
||||
@media (min-width: 901px) {
|
||||
.dual-panels { grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: var(--issste-space-4); }
|
||||
}
|
||||
.card-identity { min-width: 0; }
|
||||
h2, p { overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
mat-form-field { width: 100%; margin-top: var(--issste-space-4); }
|
||||
.catalog-metadata { margin: var(--issste-space-4) 0 0; padding-top: var(--issste-space-4);
|
||||
border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
@media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } }
|
||||
`,
|
||||
})
|
||||
export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
localSelection: DonutSelection = {};
|
||||
private selectionContext = '';
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private numericSubscription?: Subscription;
|
||||
private numericKey = '';
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private metadataSubscription?: Subscription;
|
||||
private metadataKey = '';
|
||||
metadata?: IndicadorMetadatos;
|
||||
private activatedKey = '';
|
||||
constructor() {
|
||||
effect(() => {
|
||||
this.snapshots.expanded(); this.snapshots.retries();
|
||||
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
|
||||
});
|
||||
}
|
||||
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; }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(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() {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied);
|
||||
if (key !== this.activatedKey) {
|
||||
this.numericSubscription?.unsubscribe(); this.numericKey = '';
|
||||
if (this.visible) this.activatedKey = key;
|
||||
}
|
||||
if (this.activatedKey !== key || !this.snapshots.expanded()
|
||||
|| !filterCompatibility(this.applied, this.indicador.tipos_periodo).compatible) return;
|
||||
const attempt = JSON.stringify([key, this.snapshots.retries()]);
|
||||
if (this.numericKey === attempt) return;
|
||||
this.numericKey = attempt;
|
||||
this.numericSubscription?.unsubscribe();
|
||||
this.numericSubscription = this.snapshots.read(this.dominio, this.indicador, this.applied).subscribe();
|
||||
}
|
||||
ngOnDestroy() { this.numericSubscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); }
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@Input() pinned = false;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
readonly pinChanged = output<void>();
|
||||
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
||||
readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly memory = inject(IndicadoresMemory);
|
||||
private identity = '';
|
||||
visible = false;
|
||||
titleId = '';
|
||||
contentId = '';
|
||||
panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); }
|
||||
selectedFigure?: string;
|
||||
selectFigure(figure: string) {
|
||||
if (!this.indicador.figuras.includes(figure) || figure === this.selectedFigure) return;
|
||||
this.selectedFigure = this.pair.includes(figure) ? this.pair[0] : figure;
|
||||
this.memory.rememberFigure(this.dominio, this.indicador.id, figure);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnChanges() {
|
||||
const context = JSON.stringify([this.dominio, this.indicador.id, this.indicador.version, this.applied, this.tema]);
|
||||
if (context !== this.selectionContext) { this.localSelection = {}; this.selectionContext = context; }
|
||||
const remembered = this.memory.figure(this.dominio, this.indicador.id);
|
||||
const selected = remembered && this.indicador.figuras.includes(remembered) ? remembered : this.pair[0] ?? this.indicador.figuras[0];
|
||||
this.selectedFigure = this.pair.includes(selected) ? this.pair[0] : selected;
|
||||
const identity = indicatorIdentity(this.dominio, this.indicador.id);
|
||||
if (identity === this.identity) { this.updateNumeric(); return; }
|
||||
this.identity = identity;
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadata = undefined;
|
||||
this.metadataKey = '';
|
||||
const id = identityElementId(identity);
|
||||
this.titleId = id + '-title';
|
||||
this.contentId = id + '-content';
|
||||
this.visible = false;
|
||||
this.updateNumeric();
|
||||
}
|
||||
setVisible(visible: boolean) {
|
||||
if (this.visible === visible) return;
|
||||
this.visible = visible;
|
||||
this.updateNumeric();
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
loadMetadata() {
|
||||
const key = JSON.stringify([this.dominio, this.indicador.id]);
|
||||
if (this.metadataKey === key) return;
|
||||
this.metadataKey = key;
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadataSubscription = this.indicators.metadatos(this.dominio, this.indicador.id)
|
||||
.pipe(catchError(() => of(undefined))).subscribe(value => {
|
||||
if (this.metadataKey !== key) return;
|
||||
if (!value) this.metadataKey = '';
|
||||
this.metadata = value;
|
||||
this.changeDetector.markForCheck();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
|
||||
<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">
|
||||
@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>
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</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 citologías y biopsias" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" aria-label="Periodos de la confirmación histopatológica">
|
||||
<button type="button" aria-label="Periodo anterior de la confirmación" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de la confirmación" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</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 citologías de alto grado 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 base de la confirmación">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Grados del anillo exterior">
|
||||
@for (c of m.grados; 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>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure rates"><h3>Por resultado de la citología, {{ m.periodo }}</h3>
|
||||
@if (ratesFigure) {
|
||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación, tasas por citología, ' + 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.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@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" aria-label="Tabla de contingencia de citología y biopsia" tabindex="0">
|
||||
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Citología</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
|
||||
<tbody>@for (fila of m.filas; track fila.id) {
|
||||
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (g of m.grados; track g.id) { <td>{{ cellText(fila.celdas[g.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }</tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,37 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.confirmacion { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
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); }
|
||||
.selection-status { font-weight: 600; }
|
||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||
.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);
|
||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
||||
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
|
||||
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||
.periods span { text-align: center; }
|
||||
.periods button { min-width: 44px; font-size: 1.5rem; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
.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; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
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); } }
|
||||
@@ -0,0 +1,140 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { 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 { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
|
||||
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
||||
Celda, tasas } from './indicadores-confirmacion-citologia';
|
||||
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-confirmacion-citologia',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-confirmacion-citologia.html',
|
||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||
})
|
||||
export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@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 = '';
|
||||
selection?: SeleccionConfirmacion;
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: ModeloConfirmacion;
|
||||
donutFigure?: PlotlyFigure;
|
||||
ratesFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: ModeloConfirmacion[] = [];
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
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; }
|
||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||
readonly estadoTasa = estadoTasa;
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_CITOLOGIA })
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() {
|
||||
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
||||
this.donutFigure = undefined; this.ratesFigure = undefined;
|
||||
}
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== ID_CONFIRMACION || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
||||
{ estrato: ESTRATO_CITOLOGIA }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloConfirmacion(datos, p));
|
||||
// The most recent period first, as the prototype; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof ConfirmacionIncompatible ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof ConfirmacionIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex];
|
||||
this.selection = this.model ? seleccionBase(this.model) : undefined;
|
||||
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
||||
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model || !this.selection) return;
|
||||
this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema);
|
||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
|
||||
<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">
|
||||
@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>
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</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 resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" aria-label="Periodos de dona y barras EU7">
|
||||
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
|
||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">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.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
|
||||
@if (m.total !== null && m.total > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
|
||||
<p>{{ sinDatoNote }}</p>
|
||||
</section>
|
||||
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
|
||||
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
|
||||
@if (m.escenarios.length && barsFigure) {
|
||||
<app-plotly-chart [figure]="barsFigure" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@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" aria-label="Tabla de valores EU7" tabindex="0">
|
||||
<table><caption>Datos generales, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
|
||||
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
<table><caption>Escenarios clínicos, {{ m.periodo }}, porcentajes sin «Sin dato»</caption>
|
||||
<thead><tr><th scope="col">Escenario</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
|
||||
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,33 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.eu7 { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
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); }
|
||||
.selection-status { font-weight: 600; }
|
||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||
.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);
|
||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
||||
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
|
||||
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||
.periods span { text-align: center; }
|
||||
.periods button { min-width: 44px; font-size: 1.5rem; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } }
|
||||
.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; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
@@ -0,0 +1,183 @@
|
||||
import { Component, input, output } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import fixtureData from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub {
|
||||
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>();
|
||||
plotClick = output<unknown>();
|
||||
}
|
||||
describe('EU7 integración Angular y caché compartida', () => {
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||
const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0',
|
||||
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'],
|
||||
filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus de seguimiento', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] };
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorEu7Escenario>>;
|
||||
let http: HttpTestingController;
|
||||
let data: typeof fixtureData;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorEu7Escenario, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData);
|
||||
f = TestBed.createComponent(IndicadorEu7Escenario);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); vi.useRealTimers(); });
|
||||
function requests() {
|
||||
const general = http.expectOne(r => r.url.endsWith('/datos') && !r.params.has('estrato'));
|
||||
const escenarios = http.expectOne(r => r.url.endsWith('/datos') && r.params.get('estrato') === 'estatus_seguimiento');
|
||||
expect(general.request.params.get('periodos')).toBe(escenarios.request.params.get('periodos'));
|
||||
return { general, escenarios };
|
||||
}
|
||||
function flush() { const r = requests(); r.general.flush(data.general); r.escenarios.flush(data.estatus_seguimiento); f.detectChanges(); }
|
||||
it('carga diferida; dos GET compartidos con el KPI y ningún GET por clic, tema o navegación de selección', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
flush(); expect(f.componentInstance.model!.total).toBe(946);
|
||||
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
|
||||
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
|
||||
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
|
||||
const general = data.general; const original = structuredClone(applied);
|
||||
const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>).find(b => b.textContent!.includes('Anormal'))!;
|
||||
anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL');
|
||||
const chart = f.debugElement.queryAll(By.directive(ChartStub))[0].componentInstance as ChartStub;
|
||||
chart.plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 4 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection.categoria).toBe('LIEAG');
|
||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG');
|
||||
f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({});
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839');
|
||||
expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe();
|
||||
});
|
||||
it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => {
|
||||
const periods: [string, string] = ['2025-S1', '2025-S2'];
|
||||
for (const d of [data.general, data.estatus_seguimiento]) {
|
||||
d.periodos = periods; d.filas = [...d.filas.map(r => ({ ...r, periodo: '2025-S1', n: r.n * 2 })), ...d.filas] as typeof d.filas;
|
||||
d.totales_estrato = [...d.totales_estrato.map(t => ({ ...t, periodo: '2025-S1', n: t.n * 2 })), ...d.totales_estrato];
|
||||
}
|
||||
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
|
||||
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
|
||||
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
|
||||
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
|
||||
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
|
||||
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
|
||||
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
|
||||
});
|
||||
it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => {
|
||||
f.detectChanges(); const r = requests(); r.general.flush(data.general);
|
||||
r.escenarios.flush({}, { status: 500, statusText: 'Internal Server Error' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
f.componentInstance.retry(); http.expectNone(r => r.url.endsWith('/datos') && !r.params.has('estrato'));
|
||||
http.expectOne(r => r.params.get('estrato') === 'estatus_seguimiento').flush(data.estatus_seguimiento); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('timeout cancela transportes y permite recuperación', async () => {
|
||||
vi.useFakeTimers(); f.detectChanges(); const r = requests();
|
||||
await vi.advanceTimersByTimeAsync(40001); f.detectChanges();
|
||||
expect(r.general.cancelled && r.escenarios.cancelled).toBe(true);
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.textContent).toContain('tardó demasiado');
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('error de red permite reintento sin figuras engañosas', () => {
|
||||
f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges();
|
||||
expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error');
|
||||
expect(f.componentInstance.donutFigure).toBeUndefined();
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => {
|
||||
f.detectChanges(); const old = requests();
|
||||
f.componentRef.setInput('visible', false); f.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S1'] } });
|
||||
f.detectChanges(); expect(old.general.cancelled && old.escenarios.cancelled).toBe(true);
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
for (const d of [data.general, data.estatus_seguimiento]) { d.periodos = ['2025-S1']; d.filas.forEach(r => r.periodo = '2025-S1'); d.totales_estrato.forEach(t => t.periodo = '2025-S1'); }
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); flush(); expect(f.componentInstance.model!.periodo).toBe('2025-S1');
|
||||
});
|
||||
it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => {
|
||||
data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => {
|
||||
data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = [];
|
||||
f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay pacientes publicados');
|
||||
});
|
||||
it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => {
|
||||
Object.assign(data.general.filas[0], { n: 987654, suprimido: 1 });
|
||||
Object.assign(data.estatus_seguimiento.filas[0], { n: 987654, suprimido: 1 });
|
||||
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
|
||||
expect(f.nativeElement.textContent).not.toContain('987654');
|
||||
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0);
|
||||
});
|
||||
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => {
|
||||
f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges();
|
||||
const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure;
|
||||
f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges();
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
|
||||
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true);
|
||||
});
|
||||
it('«Cómo leer» muestra solo la descripción y el como_leer publicados de dona y barras, sin la ficha', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||
const toggle = f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
toggle.click(); f.detectChanges();
|
||||
expect(requested).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('Metadatos publicados pendientes');
|
||||
f.componentRef.setInput('metadata', {
|
||||
descripcion: 'Descripción del indicador',
|
||||
ficha: { pregunta: '¿Pregunta?', definicion: 'Definición', unidad: 'pacientes', nota: 'Nota de ficha' },
|
||||
referencias: [{ tipo: 'cita', etiqueta: 'Referencia', ref: null }],
|
||||
figuras_detalle: [
|
||||
{ figura: 'fig_c2_barras', descripcion: 'Barras por escenario.', como_leer: ['Lee las barras así.', ' '] },
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona así.'] },
|
||||
{ figura: 'fig_c2_apiladas', descripcion: 'Otra figura', como_leer: ['No va.'] },
|
||||
],
|
||||
}); f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
const guides = [...help.querySelectorAll('.reading-guide')] as HTMLElement[];
|
||||
expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Dona de dos anillos', 'Barras por escenario clínico']);
|
||||
expect([...guides[0].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona así.']);
|
||||
expect(guides[1].querySelector('p')!.textContent).toBe('Barras por escenario.');
|
||||
expect([...guides[1].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las barras así.']);
|
||||
for (const absent of ['Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior'])
|
||||
expect(help.textContent).not.toContain(absent);
|
||||
expect(help.querySelector('details')).toBeNull();
|
||||
f.componentRef.setInput('metadata', { figuras_detalle: [] }); f.detectChanges();
|
||||
expect(help.textContent).toContain('no publica instrucciones de lectura');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const card = TestBed.createComponent(IndicadorCatalogCard);
|
||||
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador);
|
||||
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(1);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
||||
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['tea', 'M23_pacientes_evaluados'], ['cama', 'cama_birads_456_paciente'], ['tea', 'cacu_eu7']]) {
|
||||
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(0);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(2);
|
||||
}
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
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 { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { percentText } from './indicadores-format';
|
||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-eu7-escenario',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-eu7-escenario.html',
|
||||
styleUrl: './indicador-eu7-escenario.scss',
|
||||
})
|
||||
export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@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 = '';
|
||||
selection: Seleccion = {};
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: Modelo;
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: Modelo[] = [];
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
|
||||
get sinDatoNote() {
|
||||
const m = this.model;
|
||||
if (!m) return '';
|
||||
if (m.vacio) return 'No hay registros publicados en este periodo.';
|
||||
const n = m.sinDato.n;
|
||||
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
||||
: m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.`
|
||||
: `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
|
||||
}
|
||||
get generalCells() {
|
||||
const m = this.model;
|
||||
return !m || m.vacio ? [] : [...m.categorias.map(c => ({ etiqueta: c.etiqueta, celda: m.celdas[c.id] })),
|
||||
{ etiqueta: m.sinDatoEtiqueta, celda: m.sinDato }];
|
||||
}
|
||||
get scenarioCells() {
|
||||
const m = this.model;
|
||||
return !m ? [] : m.escenarios.flatMap(s => [...m.categorias.map(c => ({ escenario: s.etiqueta, categoria: c.etiqueta,
|
||||
celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })),
|
||||
{ escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]);
|
||||
}
|
||||
// "Cómo leer" shows only what the kit publishes for the two figures of this view.
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return EU7_FIGURES.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
percentText(value: number | null) { return percentText(value); }
|
||||
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.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras, this.indicador.filtros]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.pages = []; this.periods = []; this.model = undefined;
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
// Visibility and metadata changes must not restart Plotly rendering.
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
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) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version),
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([general, escenarios]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modelo(general, escenarios, p));
|
||||
this.periodIndex = 0; this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof Eu7Incompatible ? error.message
|
||||
: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit'
|
||||
&& this.applied.selection.periodos.length > 1 ? ' La respuesta corresponde al conjunto de periodos solicitado.' : '');
|
||||
this.status.set(error instanceof Eu7Incompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex]; this.selection = {};
|
||||
this.draw(); this.status.set(this.model ? this.model.vacio ? 'empty' : 'ready' : 'empty');
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || this.status() !== 'ready') return;
|
||||
this.selection = clic(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model) return;
|
||||
this.donutFigure = dona(this.model, this.selection, this.tema);
|
||||
this.barsFigure = barras(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected) {
|
||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
|
||||
[attr.aria-expanded]="methodologyExpanded()" [attr.aria-controls]="methodologyId"
|
||||
(click)="toggleMethodology()">
|
||||
<mat-icon aria-hidden="true">help_outline</mat-icon>
|
||||
Cómo leer
|
||||
</button>
|
||||
<div class="methodology-detail" [id]="methodologyId" [hidden]="!methodologyExpanded()">
|
||||
<ul>
|
||||
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
|
||||
</ul>
|
||||
<p class="period-note">{{ periodInterpretation }}</p>
|
||||
@if (state.status === 'ready' && state.footnotes?.length) {
|
||||
<h3 class="footnotes-title">Notas de la figura</h3>
|
||||
<section class="methodological-footnotes" aria-label="Notas de la figura">
|
||||
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
<div class="figure-heading">
|
||||
@if (state.status === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
|
||||
<div class="figure-skeleton"><p class="state" role="status">Cargando figura…</p><div class="skeleton" aria-hidden="true"></div></div>
|
||||
} @else if (state.status === 'deferred') {
|
||||
<div class="figure-skeleton"><p class="state" role="status">{{ state.message }}</p><div class="skeleton" aria-hidden="true"></div></div>
|
||||
} @else if (state.status === 'incompatible') {
|
||||
<div class="state incompatible" role="status"><p>Filtro general incompatible con esta figura.</p><p>{{ state.message }}</p></div>
|
||||
} @else if (state.status === 'error') {
|
||||
<div class="state" role="alert"><p>{{ state.message }}</p>
|
||||
<button mat-stroked-button (click)="retry.emit()">Reintentar solicitud</button></div>
|
||||
} @else if (state.figure; as figure) {
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
</div>
|
||||
@if (chartFigure) {
|
||||
<div class="figure-legend">
|
||||
@if (state.status === 'ready' && state.hierarchy; as hierarchy) {
|
||||
<div #donutNavigation class="donut-navigation" tabindex="-1" aria-label="Explorar grupos de la dona">
|
||||
<p class="donut-status" role="status">{{ activeParent ? 'Categorías de ' + activeParent + '. Anillo exterior: porcentajes dentro de este grupo. Anillo interior: todos los grupos.' : 'Selecciona un segmento para ver sus categorías. También puedes explorar los grupos con Tab y Enter o Espacio.' }}</p>
|
||||
<div class="donut-toolbar">
|
||||
<span class="donut-context">{{ activeParent ? 'Categorías' : 'Grupos' }}</span>
|
||||
@if (activeParent) {
|
||||
<button mat-icon-button type="button" class="donut-restore" matTooltip="Restaurar vista"
|
||||
aria-label="Restaurar vista de la gráfica" (click)="returnToParents($event)">
|
||||
<svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M3 10a9 9 0 1 1 2.6 8.4M3 4v6h6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<div class="donut-legend" aria-label="Leyenda de la dona">
|
||||
<div #donutKeyboard class="donut-keyboard" role="group" aria-label="Explorar grupos con teclado">
|
||||
@for (parent of hierarchy.parents; track parent) {
|
||||
<button type="button" [attr.aria-pressed]="activeParent === parent" (click)="expandParent(parent)">
|
||||
<span class="legend-swatch" [style.background]="legendColor(parent, true)" aria-hidden="true"></span>{{ parent }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<div class="donut-children-region" [class.expanded]="!!activeParent"
|
||||
[attr.aria-hidden]="activeParent ? null : 'true'" [attr.inert]="activeParent ? null : ''">
|
||||
<div class="donut-children-content">
|
||||
<h3 class="donut-children-title">Categorías</h3>
|
||||
<div class="donut-children" role="group" [attr.aria-label]="'Categorías de ' + activeParent">
|
||||
@for (child of visibleChildren; track child.label) {
|
||||
<button type="button" [attr.aria-pressed]="activeCategory === child.label" (click)="selectCategory(child.label)">
|
||||
<span class="legend-swatch" [style.background]="legendColor(child.label, false)" aria-hidden="true"></span>{{ child.label }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@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">
|
||||
<span class="legend-swatch" [style.background]="entry.color ?? 'currentColor'" aria-hidden="true"></span>{{ entry.label }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</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)" />
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
@if (cutoffDate; as cutoff) { <p class="figure-cutoff">Fecha de corte: {{ cutoff }}</p> }
|
||||
</div>
|
||||
<div class="figure-labels" [hidden]="state.status !== 'ready'">
|
||||
@if (state.categoryLabels?.length) {
|
||||
<details class="category-labels">
|
||||
<summary>Nombres completos de las categorías</summary>
|
||||
<ul>
|
||||
@for (label of state.categoryLabels; track $index) {
|
||||
<li><span>{{ label.abbreviated }}</span>: {{ label.original }}</li>
|
||||
}
|
||||
</ul>
|
||||
</details>
|
||||
}
|
||||
</div>
|
||||
</mat-card>
|
||||
@@ -0,0 +1,115 @@
|
||||
:host { display: grid; min-width: 0; }
|
||||
.interpretation {
|
||||
margin: 0;
|
||||
padding: 0 1rem .75rem;
|
||||
color: var(--issste-text);
|
||||
font-family: var(--issste-font-body);
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.methodology-detail {
|
||||
margin-top: var(--issste-space-3);
|
||||
padding: var(--issste-space-4);
|
||||
border-left: 3px solid var(--issste-accent);
|
||||
}
|
||||
.interpretation ul { margin: 0; padding-left: 1.25rem; }
|
||||
.interpretation li + li { margin-top: .25rem; }
|
||||
.period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); }
|
||||
.methodology-toggle { margin-top: .75rem; min-height: 44px; max-width: 100%; height: auto; white-space: normal;
|
||||
--mat-button-outlined-label-text-color: var(--issste-text); --mat-button-outlined-outline-color: var(--issste-border); }
|
||||
.methodology-detail p { margin: 0; }
|
||||
.methodology-detail p + p { margin-top: var(--issste-space-2); }
|
||||
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
|
||||
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
||||
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
|
||||
.interpretation { grid-row: 1; }
|
||||
.figure-legend { grid-row: 3; min-width: 0; }
|
||||
.plot-slot { grid-row: 4; min-width: 0; align-content: start; }
|
||||
.plot-slot[hidden] { display: none; }
|
||||
.figure-footer { grid-row: 5; min-width: 0; align-content: end; }
|
||||
.figure-labels { grid-row: 6; min-width: 0; }
|
||||
@supports (grid-template-rows: subgrid) {
|
||||
:host, .figure-card { grid-template-rows: subgrid; }
|
||||
.figure-card { grid-row: span 6; }
|
||||
}
|
||||
:host(.methodology-expanded), :host(.methodology-expanded) .figure-card { grid-template-rows: auto auto auto auto auto auto; }
|
||||
: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; }
|
||||
.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); } }
|
||||
|
||||
.notes { padding: 1rem; overflow-wrap: anywhere; }
|
||||
.notes h2 { font-size: 1rem; }
|
||||
.notes p { line-height: 1.5; }
|
||||
.footnotes-title { margin: var(--issste-space-4) 0 var(--issste-space-2); font-size: .9375rem; font-family: var(--issste-font-heading); }
|
||||
.figure-cutoff { margin: 0; padding: .5rem 1rem .75rem; font-size: .8125rem; color: var(--issste-text-secondary); }
|
||||
.dark .figure-cutoff { color: var(--mat-sys-outline); }
|
||||
.methodological-footnotes {
|
||||
padding: 0;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
font: var(--mat-sys-body-small);
|
||||
font-family: var(--issste-font-body);
|
||||
font-size: .875rem;
|
||||
color: var(--issste-text-secondary);
|
||||
line-height: 1.5;
|
||||
}
|
||||
.dark .methodological-footnotes { color: var(--mat-sys-outline); }
|
||||
.methodological-footnotes p { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.methodological-footnotes p + p { margin-top: .75rem; }
|
||||
.category-labels { padding: 0 1rem 1rem; overflow-wrap: anywhere; font: var(--mat-sys-body-small); line-height: 1.5; }
|
||||
.category-labels summary { cursor: pointer; min-height: 44px; align-content: center; }
|
||||
.category-labels summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.category-labels ul { margin: .25rem 0 0; padding-left: 1.25rem; }
|
||||
.category-labels li + li { margin-top: .5rem; }
|
||||
|
||||
.figure-skeleton { min-height: 12rem; display: flex; flex-direction: column; }
|
||||
.skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; }
|
||||
.donut-navigation {
|
||||
position: relative;
|
||||
color: var(--issste-text);
|
||||
}
|
||||
.dark .donut-navigation { color: #eef1f7; }
|
||||
.donut-status {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
}
|
||||
.donut-legend { padding: 0 .75rem; box-sizing: border-box; }
|
||||
.donut-keyboard, .donut-children { display: flex; flex-wrap: wrap; align-content: start; gap: .25rem .75rem; }
|
||||
.donut-children-region {
|
||||
display: grid; grid-template-rows: 0fr; opacity: 0; transform: translateY(-.25rem);
|
||||
transition: grid-template-rows 225ms ease, opacity 180ms ease, transform 225ms ease;
|
||||
}
|
||||
.donut-children-region.expanded { grid-template-rows: 1fr; opacity: 1; transform: translateY(0); }
|
||||
.donut-children-content { min-height: 0; overflow: hidden; }
|
||||
.donut-children-title { margin: .5rem 0 0; padding-top: .5rem; border-top: 1px solid var(--issste-border);
|
||||
font: var(--mat-sys-body-small); font-weight: 600; }
|
||||
.donut-children { padding-top: .25rem; }
|
||||
.donut-legend button { display: flex; align-items: center; gap: .5rem; max-width: 100%; min-height: 44px;
|
||||
padding: .25rem .5rem; border: 1px solid transparent; border-radius: 4px; background: transparent; color: inherit;
|
||||
font: inherit; font-size: .875rem; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.donut-legend button[aria-pressed=true] { border-color: currentColor; font-weight: 600; }
|
||||
.legend-swatch { width: .75rem; height: .75rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 2px; }
|
||||
.donut-toolbar {
|
||||
height: 48px; box-sizing: border-box;
|
||||
display: flex; align-items: center; justify-content: space-between; gap: .5rem; padding: 0 .75rem;
|
||||
}
|
||||
.donut-context { min-width: 0; overflow-wrap: anywhere; font: var(--mat-sys-body-small); }
|
||||
.donut-restore { flex-shrink: 0; color: inherit; }
|
||||
.donut-legend button:focus-visible, .donut-restore:focus-visible {
|
||||
outline: 2px solid currentColor; outline-offset: 3px;
|
||||
}
|
||||
.donut-static-legend {
|
||||
display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: .25rem .9rem;
|
||||
padding: .5rem .75rem .25rem; color: var(--issste-text); box-sizing: border-box;
|
||||
}
|
||||
.dark .donut-static-legend { color: #eef1f7; }
|
||||
.donut-static-legend__item { display: flex; align-items: center; gap: .5rem; min-height: 32px; max-width: 100%;
|
||||
font: var(--mat-sys-body-small); overflow-wrap: anywhere; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { vi } from 'vitest';
|
||||
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { presentationFigure } from './indicadores.presentation';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
import { donutHierarchy, donutLegend } from './indicadores-donut-drilldown';
|
||||
|
||||
describe('IndicadorFigureCard', () => {
|
||||
const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] };
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigureCard>>;
|
||||
let react: ReturnType<typeof vi.fn>;
|
||||
let purge: ReturnType<typeof vi.fn>;
|
||||
let disconnect: ReturnType<typeof vi.fn>;
|
||||
let observe: ReturnType<typeof vi.fn>;
|
||||
beforeEach(() => {
|
||||
react = vi.fn().mockResolvedValue(undefined);
|
||||
purge = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
observe = vi.fn();
|
||||
vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; });
|
||||
TestBed.configureTestingModule({
|
||||
imports: [IndicadorFigureCard],
|
||||
providers: [{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({
|
||||
react, purge, Plots: { resize: vi.fn().mockResolvedValue(undefined) },
|
||||
addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined),
|
||||
}) }],
|
||||
});
|
||||
fixture = TestBed.createComponent(IndicadorFigureCard);
|
||||
fixture.componentRef.setInput('selected', selected);
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c1_puntos');
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('state', { status: 'idle' });
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); vi.unstubAllGlobals(); });
|
||||
function state(value: FigureState) { fixture.componentRef.setInput('state', value); fixture.detectChanges(); }
|
||||
async function settle() {
|
||||
await fixture.whenStable();
|
||||
for (let i = 0; i < 12; i++) await Promise.resolve();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function ready(original: PlotlyFigure) {
|
||||
const copy = presentationFigure(original, { indicador: selected.id, figura: 'fig_c1_puntos', tema: 'claro' });
|
||||
state({ status: 'ready', figure: original, presentationFigure: copy });
|
||||
return copy;
|
||||
}
|
||||
it.each(['bar', 'box', 'scatter'])('%s conserva el dimensionamiento intrínseco de Plotly', async type => {
|
||||
const automatic: PlotlyFigure = { data: [{ type, x: ['A'], y: [2] }], layout: { autosize: true } };
|
||||
ready(automatic); await settle();
|
||||
const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
|
||||
expect(chart.style.getPropertyValue('--plot-height')).toBe('');
|
||||
expect(automatic.layout['height']).toBeUndefined();
|
||||
const tall = { ...automatic, layout: { ...automatic.layout, height: 830 } };
|
||||
ready(tall); await settle();
|
||||
expect(chart.style.getPropertyValue('--plot-height')).toBe('');
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart);
|
||||
expect(tall.layout.height).toBe(830);
|
||||
});
|
||||
it('la leyenda de exploración precede al lienzo y conserva su host y altura al expandir', async () => {
|
||||
const { figure, data } = donutFixture();
|
||||
state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data)! }); await settle();
|
||||
const plot = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
|
||||
const slot = plot.closest('.plot-slot')!;
|
||||
const legendElement = fixture.nativeElement.querySelector('.figure-legend') as HTMLElement;
|
||||
expect(legendElement.compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
fixture.componentInstance.expandParent('G2'); await settle();
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(plot);
|
||||
expect(plot.style.getPropertyValue('--plot-height')).toBe('440px');
|
||||
expect(fixture.nativeElement.querySelector('.figure-card .interpretation')).toBeTruthy();
|
||||
});
|
||||
it('C2 expande por Plotly y teclado, vuelve con foco y conserva host; reinicia al cambiar resultado', async () => {
|
||||
const { figure, data } = donutFixture();
|
||||
const hierarchy = donutHierarchy(figure, data)!;
|
||||
state({ status: 'ready', figure, presentationFigure: figure, hierarchy }); await settle();
|
||||
const host = fixture.nativeElement.querySelector('.plot');
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(chart.figure.data).toHaveLength(1);
|
||||
expect(fixture.nativeElement.querySelector('.donut-restore')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Volver a grupos');
|
||||
expect(fixture.nativeElement.querySelectorAll('.donut-navigation > button')).toHaveLength(0);
|
||||
const categories = fixture.nativeElement.querySelector('.donut-children-region') as HTMLElement;
|
||||
expect(categories.classList.contains('expanded')).toBe(false);
|
||||
expect(categories.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(categories.hasAttribute('inert')).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('.donut-children-title').textContent).toBe('Categorías');
|
||||
chart.plotClick.emit({ points: [{ curveNumber: 0, label: 'G2' }] }); await settle();
|
||||
expect(fixture.componentInstance.activeParent).toBe('G2');
|
||||
expect(categories.classList.contains('expanded')).toBe(true);
|
||||
expect(categories.hasAttribute('inert')).toBe(false);
|
||||
expect(categories.getAttribute('aria-hidden')).toBeNull();
|
||||
expect(chart.figure.data[0]['labels']).toEqual(['B', 'C']);
|
||||
chart.plotClick.emit({ points: [{ curveNumber: 1, label: 'G1' }] }); await settle();
|
||||
expect(fixture.componentInstance.activeParent).toBe('G1');
|
||||
expect(chart.figure.data[0]['labels']).toEqual(['A']);
|
||||
chart.plotClick.emit({ points: [{ curveNumber: 0, label: 'G2' }] }); await settle();
|
||||
expect(fixture.componentInstance.activeParent).toBe('G1');
|
||||
chart.plotClick.emit({ points: [{ curveNumber: 1, label: 'G2' }] }); await settle();
|
||||
state({ status: 'ready', figure, presentationFigure: structuredClone(figure), hierarchy }); await settle();
|
||||
expect(fixture.componentInstance.activeParent).toBe('G2');
|
||||
const back = fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement;
|
||||
expect(back.getAttribute('aria-label')).toBe('Restaurar vista de la gráfica');
|
||||
expect(back.querySelector('svg')).not.toBeNull();
|
||||
back.focus(); back.click(); await settle();
|
||||
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.donut-keyboard button'));
|
||||
expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.donut-restore')).toBeNull();
|
||||
const group = fixture.nativeElement.querySelectorAll('.donut-keyboard button')[1] as HTMLButtonElement;
|
||||
group.click(); await settle(); expect(group.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(fixture.nativeElement.querySelector('.plot')).toBe(host); expect(purge).not.toHaveBeenCalled();
|
||||
state({ status: 'loading' }); expect(fixture.componentInstance.activeParent).toBeUndefined();
|
||||
expect(fixture.nativeElement.querySelector('.donut-navigation')).toBeNull();
|
||||
state({ status: 'ready', figure: structuredClone(figure), presentationFigure: figure, hierarchy }); await settle();
|
||||
expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.plot')).toBe(host);
|
||||
});
|
||||
it('homologa la dona simple con leyenda HTML superior sin alterar categorías ni valores', async () => {
|
||||
const { figure } = donutFixture();
|
||||
figure.data.pop();
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_donas');
|
||||
const copy = presentationFigure(figure, { indicador: selected.id, figura: 'fig_c2_donas', tema: 'claro' });
|
||||
const legend = donutLegend(copy)!;
|
||||
state({ status: 'ready', figure, presentationFigure: copy, donutLegend: legend }); await settle();
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(fixture.nativeElement.querySelectorAll('.donut-static-legend__item')).toHaveLength(3);
|
||||
expect(fixture.nativeElement.querySelector('.donut-static-legend').textContent).toContain('A');
|
||||
expect(chart.figure.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
|
||||
expect(chart.figure.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||
expect(chart.figure.data[0]['labels']).toEqual(figure.data[0]['labels']);
|
||||
expect(chart.figure.data[0]['values']).toEqual(figure.data[0]['values']);
|
||||
const heading = fixture.nativeElement.querySelector('.figure-heading') as HTMLElement;
|
||||
const legendElement = fixture.nativeElement.querySelector('.figure-legend') as HTMLElement;
|
||||
const slot = fixture.nativeElement.querySelector('.plot-slot') as HTMLElement;
|
||||
const notes = fixture.nativeElement.querySelector('.figure-footer') as HTMLElement;
|
||||
expect(heading.compareDocumentPosition(legendElement) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(legendElement.compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(slot.compareDocumentPosition(notes) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
it.each(['dominio', 'figuraId', 'selected'])('reinicia expansión cuando cambia identidad %s aunque reciba la misma referencia de figura', input => {
|
||||
const { figure, data } = donutFixture();
|
||||
state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data) });
|
||||
fixture.componentInstance.expandParent('G2');
|
||||
fixture.componentRef.setInput(input, input === 'dominio' ? 'cama' : input === 'figuraId' ? 'otra_dona' : { ...selected, id: 'nuevo' });
|
||||
fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined();
|
||||
expect(fixture.componentInstance.chartFigure?.data).toHaveLength(1);
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'])('presenta notas %s como texto seguro dentro de «Cómo leer» y deja visible la fecha de corte', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} };
|
||||
const notes = ['Nota de la ficha\nFuente: A & B · Fecha de corte: 2025-08-01\nLeyenda', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
|
||||
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes,
|
||||
minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] });
|
||||
const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement;
|
||||
expect(section.getAttribute('aria-label')).toBe('Notas de la figura');
|
||||
expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes);
|
||||
expect(section.querySelector('img, script, a')).toBeNull();
|
||||
const detail = section.closest('.methodology-detail') as HTMLElement;
|
||||
expect(detail).not.toBeNull(); expect(detail.hidden).toBe(true);
|
||||
expect(section.previousElementSibling?.textContent).toBe('Notas de la figura');
|
||||
// Interpretation lines come first; the notes are paragraphs, never list items.
|
||||
expect(detail.querySelector('ul')!.compareDocumentPosition(section) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(section.querySelector('li')).toBeNull();
|
||||
expect(section.closest('.plot-viewport, app-plotly-chart, details, .figure-footer')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.figure-footer').textContent.trim()).toBe('Fecha de corte: 2025-08-01');
|
||||
expect(fixture.nativeElement.querySelector('.figure-labels .category-labels')).toBeTruthy();
|
||||
for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) {
|
||||
state({ status });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
|
||||
}
|
||||
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota nueva');
|
||||
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
|
||||
});
|
||||
it('UX-07D conserva el ancho desplazable durante carga y lo revierte sin recrear el host', async () => {
|
||||
const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} };
|
||||
state({ status: 'ready', figure: original, presentationFigure: original, minimumPlotWidth: 598 }); await settle();
|
||||
const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
|
||||
const host = chart.querySelector('.plot');
|
||||
expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px');
|
||||
expect(chart.querySelector('.plot-viewport')!.getAttribute('tabindex')).toBe('0');
|
||||
state({ status: 'loading' }); await settle();
|
||||
expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px');
|
||||
state({ status: 'ready', figure: original, presentationFigure: original }); await settle();
|
||||
expect(chart.style.getPropertyValue('--plot-min-width')).toBe('');
|
||||
expect(chart.querySelector('.plot')).toBe(host); expect(original.data[0]['y']).toEqual([0, null, 20]);
|
||||
});
|
||||
it('UX-07C ofrece nombres completos en un details nativo sin rerenderizar Plotly ni ocultar notas', async () => {
|
||||
const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} };
|
||||
const copy = presentationFigure(original, { indicador: 'i1', figura: 'fig_c1_puntos', tema: 'claro' });
|
||||
state({ status: 'ready', figure: original, presentationFigure: copy,
|
||||
categoryLabels: [{ axis: 'x', abbreviated: 'Fármaco…', original: 'Fármaco de riesgo para el neurodesarrollo' }],
|
||||
footnotes: ['Nota metodológica siempre visible'] }); await settle();
|
||||
const details = fixture.nativeElement.querySelector('details') as HTMLDetailsElement;
|
||||
const summary = details.querySelector('summary')!;
|
||||
expect(summary.textContent).toContain('Nombres completos'); expect(details.open).toBe(false);
|
||||
expect(details.querySelector('li')!.textContent).toContain('Fármaco de riesgo para el neurodesarrollo');
|
||||
const plot = fixture.nativeElement.querySelector('.plot'), calls = react.mock.calls.length;
|
||||
summary.focus(); summary.click(); fixture.detectChanges(); await settle();
|
||||
expect(details.open).toBe(true); expect(document.activeElement).toBe(summary);
|
||||
expect(react).toHaveBeenCalledTimes(calls); expect(fixture.nativeElement.querySelector('.plot')).toBe(plot);
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes').closest('details')).toBeNull();
|
||||
state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('.category-labels')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.plot').closest('[hidden]')).not.toBeNull();
|
||||
});
|
||||
it('muestra carga, error y emite reintento sin coordinar HTTP', () => {
|
||||
state({ status: 'loading' });
|
||||
expect(fixture.nativeElement.querySelector('mat-card').getAttribute('aria-busy')).toBe('true');
|
||||
expect(fixture.nativeElement.textContent).toContain('Cargando figura');
|
||||
const retry = vi.fn();
|
||||
fixture.componentInstance.retry.subscribe(retry);
|
||||
state({ status: 'error', message: 'La figura o los reportes no están disponibles para esta selección.' });
|
||||
expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('reportes no están disponibles');
|
||||
fixture.nativeElement.querySelector('.state button').click();
|
||||
expect(retry).toHaveBeenCalledTimes(1);
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart))).toBeNull();
|
||||
});
|
||||
it('presenta selección incompleta y un indicador sin figuras', () => {
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.nativeElement.textContent).toContain('Completa una selección válida');
|
||||
fixture.componentRef.setInput('selected', { ...selected, figuras: [] });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('El indicador no tiene figuras disponibles');
|
||||
});
|
||||
it('presenta título del JSON, nombre amigable y conserva datos incluso si Plotly los muta', async () => {
|
||||
const original: PlotlyFigure = {
|
||||
data: [{ type: 'scatter', y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], x: { dtype: 'i1', bdata: 'AAE=' } }],
|
||||
layout: { title: { text: 'Título publicado', font: { size: 20 } }, annotations: [{ text: 'Nota de supresión' }] },
|
||||
config: { staticPlot: false }, frames: [], extra: { preserved: true },
|
||||
};
|
||||
const snapshot = JSON.stringify(original);
|
||||
react.mockImplementation(async (_host, data, layout) => {
|
||||
data[0].y[0] = 0;
|
||||
layout.annotations[0].text = 'Cambio interno de Plotly';
|
||||
});
|
||||
const copy = ready(original);
|
||||
await settle();
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Título publicado');
|
||||
expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe('Figura: Puntos');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('fig_c1_puntos');
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.figure).toBe(copy);
|
||||
expect(JSON.stringify(original)).toBe(snapshot);
|
||||
expect(copy.data).toEqual(original.data);
|
||||
expect(copy.layout['annotations']).toEqual(original.layout['annotations']);
|
||||
});
|
||||
it('distingue resultado sin puntos del error y mantiene valores binarios indeterminados', async () => {
|
||||
ready({ data: [{ y: [null] }], layout: {} });
|
||||
await settle();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart))).not.toBeNull();
|
||||
ready({ data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' } }], layout: {} });
|
||||
await settle();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('No hay valores visibles');
|
||||
});
|
||||
it('UX-07B representa pies como texto seguro, sin duplicación ni notas genéricas', async () => {
|
||||
const figure = { data: [{ y: [42] }], layout: {} };
|
||||
const note = 'Primera línea\n<img src=x onerror=alert(1)>\nAviso completo';
|
||||
state({ status: 'ready', figure, presentationFigure: figure, footnotes: [note] }); await settle();
|
||||
const notes = fixture.nativeElement.querySelector('.methodological-footnotes');
|
||||
expect(notes.textContent).toBe(note); expect(notes.querySelector('img')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelectorAll('.methodological-footnotes p')).toHaveLength(1);
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.showNotes).toBe(false);
|
||||
state({ status: 'loading' });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
state({ status: 'ready', figure, presentationFigure: figure, footnotes: [] }); await settle();
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
});
|
||||
it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
state({ status: 'loading' });
|
||||
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %');
|
||||
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('suprimidos no representan tasas observadas de 0 %');
|
||||
});
|
||||
it('conserva el error y reintento de renderizado dentro de PlotlyChart', async () => {
|
||||
react.mockRejectedValueOnce(new Error('render'));
|
||||
ready({ data: [{ y: [42] }], layout: {} });
|
||||
await settle();
|
||||
expect(fixture.nativeElement.textContent).toContain('No se pudo representar la figura');
|
||||
const retry = vi.fn();
|
||||
fixture.componentInstance.retry.subscribe(retry);
|
||||
fixture.nativeElement.querySelector('app-plotly-chart button').click();
|
||||
await settle();
|
||||
expect(react).toHaveBeenCalledTimes(2);
|
||||
expect(retry).not.toHaveBeenCalled();
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('D.2 mantiene Plotly oculto entre resultados y purga al destruir la card', async () => {
|
||||
ready({ data: [{ y: [42] }], layout: {} }); await settle();
|
||||
const firstHost = fixture.nativeElement.querySelector('.plot');
|
||||
expect(observe).toHaveBeenCalledWith(firstHost);
|
||||
state({ status: 'loading' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
|
||||
state({ status: 'incompatible', message: 'Intervalo de tiempo no publicado' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Intervalo de tiempo no publicado');
|
||||
ready({ data: [{ y: [50] }], layout: {} }); await settle();
|
||||
expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost);
|
||||
expect(firstHost.closest('[hidden]')).toBeNull();
|
||||
fixture.destroy();
|
||||
expect(purge).toHaveBeenCalledWith(firstHost); expect(purge).toHaveBeenCalledTimes(1);
|
||||
expect(disconnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('UX-06E.P0.2 inicia cerrado y despliega toda la explicación con estado accesible', () => {
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
state({ status: 'idle' });
|
||||
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
|
||||
expect(section.textContent).toContain('Cómo leer');
|
||||
expect(section.querySelector('h2')).toBeNull();
|
||||
expect(section.classList.contains('expanded')).toBe(false);
|
||||
expect(section.querySelector('.methodology-detail ul')).not.toBeNull();
|
||||
expect(section.querySelector('ul')?.closest('[hidden]')).not.toBeNull();
|
||||
expect(section.querySelectorAll('button')).toHaveLength(1);
|
||||
expect(section.querySelectorAll('[hidden]')).toHaveLength(1);
|
||||
const button = section.querySelector('button')!;
|
||||
const detail = section.querySelector('[id]') as HTMLElement;
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(false);
|
||||
expect(button.getAttribute('aria-controls')).toBe(detail.id);
|
||||
expect(detail.hidden).toBe(true);
|
||||
expect(button.tagName).toBe('BUTTON');
|
||||
expect(button.nextElementSibling?.classList.contains('methodology-detail')).toBe(true);
|
||||
button.focus();
|
||||
expect(document.activeElement).toBe(button);
|
||||
expect(detail.textContent).toContain('SIN_DATO');
|
||||
expect(detail.textContent).toContain('suprimidos no representan porcentajes observados de 0 %');
|
||||
expect(detail.textContent).toContain('no permite determinar la disponibilidad');
|
||||
expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation);
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(true);
|
||||
state({ status: 'loading' });
|
||||
expect(detail.hidden).toBe(false);
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(detail.hidden).toBe(true);
|
||||
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(false);
|
||||
expect(section.querySelector('.methodology-detail[hidden]')).toBe(detail);
|
||||
});
|
||||
it('UX-06E.P0.2 muestra el contenido de la figura seleccionada al cambiarla', () => {
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
state({ status: 'idle' });
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('conteos por categoría');
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas');
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('La caja representa Q1');
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'))
|
||||
.toBe(fixture.nativeElement.querySelector('.methodology-detail').id);
|
||||
});
|
||||
it('usa instrucciones exactas en orden y conserva caracteres especiales como texto', () => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_donas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_donas', descripcion: 'No repetir', como_leer: [
|
||||
'Primera línea <img src=x onerror=alert(1)>', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final',
|
||||
] }] });
|
||||
state({ status: 'idle' });
|
||||
const lines = fixture.nativeElement.querySelectorAll('.methodology-detail li');
|
||||
expect([...lines].map((line: Element) => line.textContent)).toEqual([
|
||||
'Primera línea <img src=x onerror=alert(1)>', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final',
|
||||
]);
|
||||
expect(fixture.nativeElement.querySelector('img')).toBeNull();
|
||||
expect(fixture.componentInstance.interpretation).toEqual([...lines].map((line: Element) => line.textContent));
|
||||
});
|
||||
it.each([
|
||||
['sin coincidencia', [{ figura: 'otra_figura', descripcion: null, como_leer: ['No corresponde.'] }]],
|
||||
['vacías', [{ figura: 'fig_c2_apiladas', descripcion: 'Sin instrucciones específicas.', como_leer: [] }]],
|
||||
['nulas', [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: null }]],
|
||||
])('mantiene fallback local con figuras_detalle %s', (_label, details) => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: details });
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.componentInstance.interpretation).toContain('Las categorías corresponden a la distribución de cada grupo y periodo.');
|
||||
expect(fixture.componentInstance.interpretation).toContain('SIN_DATO, cuando aparece, es una categoría legítima de la representación.');
|
||||
});
|
||||
it('preserva íntegramente, sin filtrado semántico, instrucciones sobre supresión y categorías pequeñas', () => {
|
||||
const instructions = ['Se ocultan categorías individuales pequeñas.', 'La supresión se determina por grupo.', 'Conclusión.'];
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: instructions }] });
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.componentInstance.interpretation).toEqual(instructions);
|
||||
expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((line: Element) => line.textContent)).toEqual(instructions);
|
||||
});
|
||||
it.each([
|
||||
['fig_c2_barras', 'Barras'],
|
||||
['fig_c2_donas', 'Donas'],
|
||||
])('UX-07D.1 identifica %s con el nombre %s en la tarjeta de figura', (id, label) => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', figuras: [id] });
|
||||
fixture.componentRef.setInput('figuraId', id);
|
||||
ready({ data: [], layout: {} });
|
||||
expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`);
|
||||
});
|
||||
it.each(['fig_c3r_cajas', 'desconocida'])('UX-06E.P0.2 mantiene íntegra la interpretación %s dentro de la ayuda', figura => {
|
||||
fixture.componentRef.setInput('figuraId', figura);
|
||||
if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' });
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull();
|
||||
expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((li: any) => li.textContent))
|
||||
.toEqual(fixture.componentInstance.interpretation);
|
||||
});
|
||||
it.each(['cacu', 'cama'])('UX-06E.P0.2 conserva advertencias C2 de %s en ayuda cerrada', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
state({ status: 'loading' });
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull();
|
||||
const detail = fixture.nativeElement.querySelector('[hidden]') as HTMLElement;
|
||||
expect(detail.hidden).toBe(true);
|
||||
expect(detail.textContent).toContain('Las barras muestran conteos por categoría; los porcentajes publicados pueden aparecer como etiquetas. Consulta la unidad y el denominador de cada representación.');
|
||||
expect(detail.textContent).toContain('SIN_DATO');
|
||||
expect(detail.textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %');
|
||||
});
|
||||
it('UX-06E.P0.2 quita el panel redundante y preserva todas las anotaciones en Plotly', async () => {
|
||||
const figure: PlotlyFigure = { data: [{ y: [null, 0] }], layout: { annotations: [
|
||||
{ text: 'Denominador pequeño<br>Intervalos no disponibles' },
|
||||
{ text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' },
|
||||
{ text: 'Supresión: consulta las notas completas' },
|
||||
] }, frames: [] };
|
||||
const snapshot = JSON.stringify(figure);
|
||||
ready(figure); await settle();
|
||||
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(chart.figure.layout['annotations']).toEqual(figure.layout['annotations']);
|
||||
expect(chart.notes).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text));
|
||||
expect(JSON.stringify(figure)).toBe(snapshot);
|
||||
expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0');
|
||||
});
|
||||
it.each(['claro', 'oscuro'] as const)('UX-06E.P0.2 conserva el tema %s sin duplicar anotaciones en HTML', async tema => {
|
||||
fixture.componentRef.setInput('tema', tema);
|
||||
const annotation = 'Advertencia metodológica única de la figura.';
|
||||
const original: PlotlyFigure = { data: [{ y: [1] }], layout: { annotations: [{ text: annotation }] } };
|
||||
ready(original); await settle();
|
||||
const card = fixture.nativeElement.querySelector('.figure-card');
|
||||
expect(card.classList.contains('dark')).toBe(tema === 'oscuro');
|
||||
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain(annotation);
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(chart.notes).toEqual([annotation]);
|
||||
expect(JSON.stringify(original)).toContain(annotation);
|
||||
});
|
||||
it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
state({ status: 'idle' });
|
||||
const first = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls');
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a' });
|
||||
fixture.componentRef.setInput('figuraId', 'b--fig_c2_apiladas');
|
||||
fixture.detectChanges();
|
||||
const second = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls');
|
||||
expect(first).not.toBe(second);
|
||||
expect(fixture.nativeElement.querySelector('[id]').id).toBe(second);
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'])('UX-06E.B1 conserva C1 de %s íntegro con condiciones críticas visibles', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
state({ status: 'idle' });
|
||||
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
|
||||
const button = section.querySelector('button')!;
|
||||
const detail = section.querySelector('[hidden]') as HTMLElement;
|
||||
expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button');
|
||||
// jsdom does not perform native Enter/Space activation; leave both keys
|
||||
// available to the browser and validate activation in Chrome.
|
||||
for (const key of ['Enter', ' ']) {
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
expect(button.textContent).toContain('Cómo leer');
|
||||
expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba, ' + dominio + ', fig_c1_puntos');
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true);
|
||||
const warnings = detail.querySelector('ul')!;
|
||||
expect(warnings.closest('[hidden]')).not.toBeNull();
|
||||
expect(warnings.textContent).toContain('100 % no implica certeza poblacional');
|
||||
expect(warnings.textContent).toContain('suprimidos no representan tasas observadas de 0 %');
|
||||
if (dominio === 'tea') {
|
||||
expect(warnings.textContent).toContain('Wilson al 95 %');
|
||||
expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan');
|
||||
expect(warnings.textContent).toContain('tamaño de muestra pequeño');
|
||||
} else expect(warnings.textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %');
|
||||
expect([...warnings.querySelectorAll('li')].map(p => p.textContent))
|
||||
.toEqual(fixture.componentInstance.interpretation);
|
||||
button.focus(); button.click(); fixture.detectChanges();
|
||||
expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(false);
|
||||
expect(button.getAttribute('aria-expanded')).toBe('true');
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(true);
|
||||
});
|
||||
it('UX-06E.P0.2 mantiene la oración mixta C3r y sus límites en ayuda cerrada', () => {
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); state({ status: 'idle' });
|
||||
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
|
||||
expect(section.querySelector('[hidden]')).not.toBeNull();
|
||||
expect(section.querySelector('button')).not.toBeNull();
|
||||
expect([...section.querySelectorAll('.methodology-detail li')].map(p => p.textContent)).toEqual([
|
||||
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
|
||||
'Los límites de dibujo no representan necesariamente extremos observados.',
|
||||
'Pueden mostrarse etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
|
||||
'Los puntos suprimidos no representan tasas observadas de 0 %.',
|
||||
]);
|
||||
});
|
||||
it('UX-06E.P0.2 al alternar ayuda conserva Plotly, JSON y observadores sin react ni purge', async () => {
|
||||
const original: PlotlyFigure = { data: [{ y: [42, null] }], layout: { annotations: [{ text: 'Advertencia íntegra del servicio' }] } };
|
||||
const copy = ready(original); await settle();
|
||||
const snapshot = JSON.stringify(original), copySnapshot = JSON.stringify(copy);
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance;
|
||||
const host = fixture.nativeElement.querySelector('.plot');
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle');
|
||||
const calls = react.mock.calls.length, observers = observe.mock.calls.length;
|
||||
for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); await settle(); }
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart);
|
||||
expect(fixture.nativeElement.querySelector('.plot')).toBe(host);
|
||||
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
|
||||
expect(react).toHaveBeenCalledTimes(calls); expect(observe).toHaveBeenCalledTimes(observers);
|
||||
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
|
||||
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { Component, ElementRef, Input, OnChanges, output, signal, SimpleChanges, viewChild } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { Dominio, hasNoVisibleValues, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { figureTitle } from './indicadores.presentation';
|
||||
import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { CategoryLabel } from './indicadores-axis-labels';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
export interface FigureState {
|
||||
status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible';
|
||||
figure?: PlotlyFigure;
|
||||
presentationFigure?: PlotlyFigure;
|
||||
footnotes?: readonly string[];
|
||||
categoryLabels?: readonly CategoryLabel[];
|
||||
minimumPlotWidth?: number;
|
||||
donutLegend?: readonly DonutLegendEntry[];
|
||||
plotWidth?: number;
|
||||
plotHeight?: number;
|
||||
message?: string;
|
||||
hierarchy?: DonutHierarchy;
|
||||
source?: 'datos' | 'figuras';
|
||||
fallbackReason?: string;
|
||||
emptyMessage?: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-card',
|
||||
standalone: true,
|
||||
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
|
||||
templateUrl: './indicador-figure-card.html',
|
||||
styleUrl: './indicador-figure-card.scss',
|
||||
})
|
||||
export class IndicadorFigureCard implements OnChanges {
|
||||
private readonly donutNavigation = viewChild<ElementRef<HTMLElement>>('donutNavigation');
|
||||
private readonly donutKeyboard = viewChild<ElementRef<HTMLElement>>('donutKeyboard');
|
||||
private currentState!: FigureState;
|
||||
// Keep the mounted host's last presentation only. The template hides it whenever
|
||||
// it is not the current result; this is neither applied state nor a results cache.
|
||||
chartFigure?: PlotlyFigure;
|
||||
chartMinimumWidth?: number;
|
||||
activeParent?: string;
|
||||
activeCategory?: string;
|
||||
readonly hierarchySelected = output<DonutSelection>();
|
||||
selectCategory(category: string) {
|
||||
if (!this.state.hierarchy?.children.some(c => c.parent === this.activeParent && c.label === category)) return;
|
||||
this.activeCategory = this.activeCategory === category ? undefined : category;
|
||||
this.hierarchySelected.emit({ parent: this.activeParent, category: this.activeCategory });
|
||||
}
|
||||
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 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; }
|
||||
this.currentState = value;
|
||||
if (value.status === 'ready') {
|
||||
this.updateDonut();
|
||||
this.chartMinimumWidth = value.minimumPlotWidth;
|
||||
}
|
||||
}
|
||||
get state() { return this.currentState; }
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (changes['dominio'] || changes['figuraId']
|
||||
|| (changes['selected'] && changes['selected'].previousValue?.id !== this.selected?.id)) {
|
||||
this.activeParent = undefined;
|
||||
if (this.state.status === 'ready') this.updateDonut();
|
||||
}
|
||||
}
|
||||
private updateDonut() {
|
||||
const { presentationFigure, hierarchy } = this.state;
|
||||
// Empty pages retain the series' plot height as well. This is a derived
|
||||
// layout copy; the original figure and its annotations remain available.
|
||||
const source = presentationFigure && this.state.plotHeight
|
||||
? { ...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;
|
||||
}
|
||||
expandParent(parent: string) {
|
||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||
|| !this.state.hierarchy.children.some(c => c.parent === parent && c.value > 0)) return;
|
||||
this.activeParent = parent;
|
||||
this.activeCategory = undefined;
|
||||
this.updateDonut();
|
||||
this.hierarchySelected.emit({ parent });
|
||||
}
|
||||
returnToParents(event?: MouseEvent) {
|
||||
if (!this.activeParent) return;
|
||||
this.activeParent = undefined; this.activeCategory = undefined; this.updateDonut();
|
||||
this.hierarchySelected.emit({});
|
||||
// The restore button disappears. Transfer keyboard focus to the first
|
||||
// persistent alternative; pointer users return to the graphic region.
|
||||
if (event) {
|
||||
const target = event.detail === 0 ? this.donutKeyboard()?.nativeElement.querySelector('button')
|
||||
: this.donutNavigation()?.nativeElement;
|
||||
target?.focus();
|
||||
}
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
||||
const point = event.points[0];
|
||||
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);
|
||||
}
|
||||
@Input() selected?: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
readonly retry = output<void>();
|
||||
readonly plotWidthChanged = output<number>();
|
||||
reportPlotWidth(width: unknown) {
|
||||
if (typeof width === 'number') this.plotWidthChanged.emit(width);
|
||||
}
|
||||
readonly methodologyExpanded = signal(false);
|
||||
readonly metadataRequested = output<void>();
|
||||
toggleMethodology() {
|
||||
const open = !this.methodologyExpanded();
|
||||
this.methodologyExpanded.set(open);
|
||||
if (open && !this.metadata) this.metadataRequested.emit();
|
||||
}
|
||||
get methodologyId(): string {
|
||||
return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology';
|
||||
}
|
||||
|
||||
// Editorial classification of complete local sentences by known family.
|
||||
// Keep mixed C3r/Wilson sentences and all backend content visible.
|
||||
private get contract(): string | undefined {
|
||||
return this.figuraId.startsWith('fig_c1') ? 'C1'
|
||||
: this.figuraId.startsWith('fig_c2') ? 'C2'
|
||||
: this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato;
|
||||
}
|
||||
readonly hasNoVisibleValues = hasNoVisibleValues;
|
||||
readonly figureTitle = figureTitle;
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
get interpretation(): readonly string[] {
|
||||
return figureInterpretation(this.metadata, this.figuraId, this.contract, this.dominio,
|
||||
this.state.figure?.data.some(trace => trace['type'] === 'pie'));
|
||||
}
|
||||
// The figure's notes live in "Cómo leer"; the cut-off date stays under the plot
|
||||
// because it is the only temporal reference of the data on the card.
|
||||
get cutoffDate(): string | undefined {
|
||||
if (this.state.status !== 'ready') return undefined;
|
||||
for (const note of this.state.footnotes ?? []) {
|
||||
const match = /Fecha de corte: (\d{4}-\d{2}-\d{2})/.exec(note);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { applyGlobal, GlobalFilterState, IndicadoresMemory } from './indicadores-memory';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { Component } from '@angular/core';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const catalog = [
|
||||
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] },
|
||||
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] },
|
||||
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] },
|
||||
];
|
||||
describe('IndicadorFigurePanel', () => {
|
||||
let page: IndicadorFigurePanel;
|
||||
let state: GlobalFilterState;
|
||||
let editor: IndicadorPeriodFilters;
|
||||
let http: HttpTestingController;
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel, IndicadorPeriodFilters], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1');
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
editor = new IndicadorPeriodFilters(); editor.state = state; editor.types = ['semestre'];
|
||||
page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function filters() {
|
||||
fixture.detectChanges();
|
||||
return editor;
|
||||
}
|
||||
function apply() { if (applyGlobal(state, ['semestre'])) { fixture.componentRef.setInput('applied', state.applied); fixture.detectChanges(); } }
|
||||
function load() { fixture.detectChanges(); }
|
||||
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
|
||||
function candidate() {
|
||||
// An unknown representation retains the legacy server-first hierarchy path.
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: 'C2', figuras: ['future_donut', 'f2'] });
|
||||
fixture.componentRef.setInput('figuraId', 'future_donut');
|
||||
load();
|
||||
const sample = donutFixture(); figure().flush(sample.figure);
|
||||
return sample;
|
||||
}
|
||||
it('C2 carga metadatos una vez; explorar, volver y adaptar ancho no consulta HTTP', () => {
|
||||
const sample = candidate();
|
||||
const data = http.expectOne(r => r.url === '/tea/indicadores/i1/datos' && r.params.get('periodos') === '2025-S2');
|
||||
data.flush(sample.data); fixture.detectChanges();
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard;
|
||||
expect(page.result().hierarchy?.parents).toEqual(['G1', 'G2']);
|
||||
card.expandParent('G2'); expect(card.chartFigure?.data[0]['labels']).toEqual(['B','C']);
|
||||
page.updatePlotWidth(400); fixture.detectChanges(); expect(card.activeParent).toBe('G2');
|
||||
card.returnToParents(); http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('figuraId', 'f2'); fixture.detectChanges();
|
||||
expect(card.activeParent).toBeUndefined(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
expect(page.result().hierarchy).toBeUndefined(); http.expectNone(() => true);
|
||||
});
|
||||
it('descubre una representación futura de un anillo sin IDs codificados y restaura desde la UI sin HTTP', () => {
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], id: 'future_item', contrato: 'C2', figuras: ['future_donut'] });
|
||||
fixture.componentRef.setInput('figuraId', 'future_donut'); load();
|
||||
const sample = donutFixture(); sample.figure.data.pop(); sample.data.id = 'future_item';
|
||||
figure().flush(sample.figure); http.expectOne(r => r.url.endsWith('/future_item/datos')).flush(sample.data);
|
||||
fixture.detectChanges();
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard;
|
||||
expect(card.state.hierarchy?.parents).toEqual(['G1','G2']);
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub));
|
||||
chart.triggerEventHandler('plotClick', { points: [{ curveNumber: 0, label: 'G2' }] }); fixture.detectChanges();
|
||||
expect(card.activeParent).toBe('G2');
|
||||
chart.triggerEventHandler('plotClick', { points: [{ curveNumber: 1, label: 'G1' }] }); fixture.detectChanges();
|
||||
expect(card.activeParent).toBe('G1');
|
||||
(fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges();
|
||||
expect(card.activeParent).toBeUndefined(); http.expectNone(() => true);
|
||||
expect(page.result().figure).toEqual(sample.figure);
|
||||
});
|
||||
it.each(['http', 'suppression', 'mismatch'])('C2 conserva la figura publicada cuando %s impide la jerarquía', reason => {
|
||||
const sample = candidate(), request = http.expectOne(r => r.url.endsWith('/datos'));
|
||||
if (reason === 'http') request.flush({}, { status: 503, statusText: 'Unavailable' });
|
||||
else { if (reason === 'suppression') sample.data.filas[0]['suprimido'] = 1;
|
||||
else sample.data.filas[0]['n'] = 999; request.flush(sample.data); }
|
||||
fixture.detectChanges(); expect(page.result().status).toBe('ready');
|
||||
expect(page.result().hierarchy).toBeUndefined(); expect(page.result().figure).toEqual(sample.figure);
|
||||
});
|
||||
it('C2 cancela metadatos pendientes al cambiar tema y no presenta resultados obsoletos', () => {
|
||||
candidate(); const old = http.expectOne(r => r.url.endsWith('/datos'));
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true); expect(page.result().status).toBe('loading');
|
||||
figure().flush({ data: [], layout: {} }); expect(page.result().hierarchy).toBeUndefined();
|
||||
});
|
||||
|
||||
it('UX-07D.2 conserva notas al cambiar perfil/ancho y elimina resultados obsoletos durante carga', () => {
|
||||
fixture.componentRef.setInput('dominio', 'cama');
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], figuras: ['fig_c2_barras'], contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_barras');
|
||||
const request = () => http.expectOne(req => req.url.includes('/cama/indicadores/') && req.url.includes('/figuras/'));
|
||||
const response = (text: string): PlotlyFigure => ({ data: [{ type: 'bar', x: ['A'], y: [0] }],
|
||||
layout: { annotations: [{ text, xref: 'paper', yref: 'paper', x: 0, y: -0.22,
|
||||
xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 } }] } });
|
||||
load(); http.expectOne(r => r.url.endsWith('/datos')).flush({ id: 'i1', contrato: 'C2', tipo_periodo: 'semestre', periodos: [], filas: [] });
|
||||
request().flush(response('Nota vigente')); fixture.detectChanges();
|
||||
for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE]) {
|
||||
fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges();
|
||||
for (const width of [230, 320, 768, 1440]) page.updatePlotWidth(width);
|
||||
expect(page.result().footnotes).toEqual(['Nota vigente']); http.expectNone(() => true);
|
||||
}
|
||||
page.requestFigure(); const old = request(); fixture.detectChanges();
|
||||
expect(page.result().footnotes).toBeUndefined();
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true);
|
||||
const current = request(); current.flush(response('Nota del periodo actual')); fixture.detectChanges();
|
||||
expect(page.result().footnotes).toEqual(['Nota del periodo actual']);
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota del periodo actual');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('UX-07C alterna etiquetas desde el original sin HTTP, conserva el host y restaura hover/categorías', () => {
|
||||
const label = 'Fármaco de riesgo para el neurodesarrollo';
|
||||
const received: PlotlyFigure = { data: [{ type: 'bar', x: [label], y: [0], customdata: [null],
|
||||
hovertemplate: '%{x}<br>%{y:.1f}%<extra></extra>' }], layout: { xaxis: { type: 'category' } } };
|
||||
load(); figure().flush(received); fixture.detectChanges();
|
||||
const before = structuredClone(received), host = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
expect(page.result().categoryLabels?.[0].original).toBe(label);
|
||||
expect(fixture.nativeElement.querySelector('.category-labels')).not.toBeNull();
|
||||
page.updatePlotWidth(1400); fixture.detectChanges();
|
||||
expect(page.result().categoryLabels).toEqual([]);
|
||||
const unchanged = page.result();
|
||||
for (const width of [1400.7, 1399, 1350, 0, NaN]) page.updatePlotWidth(width);
|
||||
expect(page.result()).toBe(unchanged);
|
||||
page.updatePlotWidth(320); fixture.detectChanges();
|
||||
expect(page.result().categoryLabels).toHaveLength(1);
|
||||
http.expectNone(() => true);
|
||||
for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) {
|
||||
fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
expect(page.result().figure).toEqual(before);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(host);
|
||||
if (profile === BASE_VISUAL_PROFILE) {
|
||||
expect(page.result().presentationFigure?.data).toEqual(before.data);
|
||||
expect(page.result().categoryLabels).toEqual([]);
|
||||
} else expect(page.result().categoryLabels).toHaveLength(1);
|
||||
}
|
||||
expect(received).toEqual(before);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['C1', ['proporción observada', 'Wilson al 95 %', 'tamaño de muestra pequeño', '100 % no implica certeza poblacional']],
|
||||
['C2', ['conteos por categoría', 'distribución de cada grupo y periodo', 'SIN_DATO']],
|
||||
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
|
||||
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
|
||||
['toString', ['No hay una explicación específica']],
|
||||
])('explica el contrato %s y la distinción entre reporte y valores representables', (contract, expected) => {
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: contract, figuras: ['f1'] }); load();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
fixture.detectChanges();
|
||||
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
|
||||
for (const text of expected) expect(help).toContain(text);
|
||||
if (contract === 'C3r') {
|
||||
expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados');
|
||||
expect(help).not.toMatch(/serving|corrección|fase independiente/i);
|
||||
}
|
||||
expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables');
|
||||
});
|
||||
it('oculta sólo visualmente el encabezado y conserva identidad, lectura y títulos sin HTTP adicional', () => {
|
||||
load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
const id = page.titleId;
|
||||
const heading = fixture.nativeElement.querySelector('h3') as HTMLElement;
|
||||
const section = fixture.nativeElement.querySelector('section') as HTMLElement;
|
||||
expect(heading.id).toBe(id); expect(id).not.toBe('');
|
||||
expect(section.getAttribute('aria-labelledby')).toBe(id);
|
||||
expect(section.firstElementChild).toBe(heading);
|
||||
expect(heading.textContent).toBe('tea, i1, Uno, f1');
|
||||
expect(heading.hasAttribute('aria-hidden')).toBe(false); expect(heading.hidden).toBe(false);
|
||||
const style = getComputedStyle(heading);
|
||||
expect(style.display).not.toBe('none'); expect(style.visibility).not.toBe('hidden');
|
||||
expect(style.position).toBe('absolute'); expect(style.width).toBe('1px'); expect(style.height).toBe('1px');
|
||||
expect(style.clipPath).toBe('inset(50%)'); expect(style.overflow).toBe('hidden');
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
expect(fixture.nativeElement.querySelector('app-indicador-period-filters')).toBeNull();
|
||||
const result = page.result(), savedState = state;
|
||||
fixture.detectChanges();
|
||||
expect(page.titleId).toBe(id); expect(state).toBe(savedState); expect(page.result()).toBe(result);
|
||||
expect(fixture.nativeElement.querySelector('h3')).toBe(heading);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => {
|
||||
load();
|
||||
const received: PlotlyFigure = {
|
||||
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
|
||||
layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true },
|
||||
config: { staticPlot: false }, frames: [], extra: { preserved: true },
|
||||
};
|
||||
const original = JSON.stringify(received);
|
||||
figure().flush(received); fixture.detectChanges();
|
||||
expect(JSON.stringify(received)).toBe(original);
|
||||
expect(page.result().figure).toEqual(received);
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
|
||||
expect(chart.figure).toBe(page.result().presentationFigure);
|
||||
expect(chart.figure).not.toBe(page.result().figure);
|
||||
expect(chart.figure?.data).toEqual(received.data);
|
||||
expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } });
|
||||
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', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
expect(state?.applied?.selection.mode).toBe('todos');
|
||||
apply();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,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: {} });
|
||||
});
|
||||
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 };
|
||||
figure().flush(received); fixture.detectChanges();
|
||||
const base = structuredClone(page.result().presentationFigure);
|
||||
const original = page.result().figure;
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
const applied = page.applied;
|
||||
fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges();
|
||||
expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc');
|
||||
expect(page.result().figure).toBe(original); expect(page.applied).toBe(applied);
|
||||
expect(page.result().presentationFigure?.data).toEqual(received.data);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart);
|
||||
http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges();
|
||||
expect(page.result().presentationFigure).toEqual(base);
|
||||
expect(page.result().figure).toEqual(received); http.expectNone(() => true);
|
||||
});
|
||||
it('UX-07B cambiar perfil durante carga no cancela ni inicia solicitudes', () => {
|
||||
load(); const pending = figure();
|
||||
fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges();
|
||||
expect(pending.cancelled).toBe(false); http.expectNone(() => true);
|
||||
pending.flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('cancela figuras al cambiar tema rápidamente', () => {
|
||||
load();
|
||||
const old = figure();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
const dark = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(dark.request.params.get('tema')).toBe('oscuro');
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges();
|
||||
expect(dark.cancelled).toBe(true);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it.each([
|
||||
[400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'],
|
||||
])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => {
|
||||
load();
|
||||
figure().flush('<html>error privado</html>', { status: status as number, statusText: 'Error' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().message).toContain(message);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('error privado');
|
||||
fixture.nativeElement.querySelector('app-indicador-figure-card .state button').click();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
expect(page.result().status).toBe('ready');
|
||||
});
|
||||
it('distingue conexión fallida y cancela HTTP al destruirse', () => {
|
||||
load(); figure().error(new ProgressEvent('error'));
|
||||
expect(page.result().message).toContain('conectar');
|
||||
page.requestFigure();
|
||||
const pending = figure();
|
||||
fixture.destroy();
|
||||
expect(pending.cancelled).toBe(true);
|
||||
});
|
||||
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');
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
expect(editor.hasPending).toBe(true);
|
||||
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 }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
apply();
|
||||
const req = figure();
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
req.flush('private', { status: 404, statusText: 'Not Found' });
|
||||
expect(page.result().status).toBe('error');
|
||||
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();
|
||||
const retry = figure();
|
||||
expect(retry.request.params.get('periodos')).toBe(periodos.join(','));
|
||||
retry.flush({ data: [{ y: [null] }], layout: {} });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
});
|
||||
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();
|
||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
const themed = figure();
|
||||
expect(themed.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(themed.request.params.get('tema')).toBe('oscuro');
|
||||
themed.flush('error', { status: 500, statusText: 'Server Error' });
|
||||
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']);
|
||||
});
|
||||
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();
|
||||
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');
|
||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||
});
|
||||
|
||||
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();
|
||||
fixture.detectChanges();
|
||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle');
|
||||
for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); }
|
||||
http.expectNone(() => true);
|
||||
expect(page.result()).toBe(result); expect(state).toBe(filterState);
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
expect(filters()).toBe(control);
|
||||
expect(fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance).toBe(card);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart);
|
||||
fixture.destroy();
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,382 @@
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal, output } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { DimensionEstrato, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { figurePresentation } from './indicadores.presentation';
|
||||
import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile';
|
||||
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
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 { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section class="figure-panel" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
<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')) {
|
||||
<span class="selection-status" [class.selection-active]="!!generalSelectionContext" tabindex="0" role="status"
|
||||
[attr.aria-label]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'"
|
||||
[matTooltip]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'">
|
||||
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
|
||||
</span>
|
||||
}
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
||||
<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">
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
|
||||
(click)="changeDimension('')">Distribución general</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension !== ''" [class.active]="dimension !== ''"
|
||||
[disabled]="!singlePeriod" (click)="chooseStratified()">Distribución estratificada</button>
|
||||
</div>
|
||||
@if (dimension && capabilities.length > 1) {
|
||||
<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>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||
}
|
||||
@if (result().status === 'ready' && donutPages.length > 1) {
|
||||
<nav class="donut-periods" aria-label="Periodos de la dona">
|
||||
<button type="button" aria-label="Periodo anterior de la dona" [disabled]="donutPeriodIndex <= 0" (click)="changeDonutPeriod(-1)">‹</button>
|
||||
<span role="status" aria-live="polite">{{ activeDonutPeriod }}, {{ donutPeriodIndex + 1 }} de {{ donutPages.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
</header>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
<div class="stratified-detail">
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
|
||||
</tbody></table></div>
|
||||
</details>
|
||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: grid; min-width: 0; }
|
||||
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
|
||||
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
|
||||
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
|
||||
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
|
||||
.selection-active { color: var(--issste-text); font-weight: 600; }
|
||||
.selection-status:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.stratified-detail { min-width: 0; overflow-wrap: anywhere; }
|
||||
@supports (grid-template-rows: subgrid) {
|
||||
:host, .figure-panel { grid-template-rows: subgrid; }
|
||||
.figure-panel { grid-row: span 8; }
|
||||
.panel-controls { grid-row: 1; }
|
||||
app-indicador-figure-card { grid-row: 2 / span 6; }
|
||||
.stratified-detail { grid-row: 8; }
|
||||
}
|
||||
:host:has(app-indicador-figure-card.methodology-expanded),
|
||||
.figure-panel:has(app-indicador-figure-card.methodology-expanded) { grid-template-rows: auto auto auto; }
|
||||
.figure-panel:has(app-indicador-figure-card.methodology-expanded) { grid-row: auto; }
|
||||
.distribution-control { margin: var(--issste-space-3) 0; padding: 0; border: 0; min-width: 0; }
|
||||
.distribution-control legend { padding: 0; font-weight: 600; }
|
||||
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
|
||||
.distribution-dimensions { margin-top: .75rem; }
|
||||
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
|
||||
border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text);
|
||||
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.distribution-toggle button:focus-visible, .distribution-dimensions button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.distribution-note { margin: .5rem 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.cells { overflow: auto; max-height: 24rem; } th, td { text-align: start; padding: .5rem; }
|
||||
.donut-periods { display: flex; align-items: center; justify-content: center; gap: .75rem; min-height: 48px; }
|
||||
.donut-periods span { text-align: center; overflow-wrap: anywhere; }
|
||||
.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; }
|
||||
.visually-hidden {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@Input() visible = true;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
@Input() localSelection: DonutSelection = {};
|
||||
readonly hierarchySelected = output<DonutSelection>();
|
||||
readonly metadataRequested = output<void>();
|
||||
donutPages: { period: string; state: FigureState }[] = [];
|
||||
activeDonutPeriod?: string;
|
||||
private donutIdentity = '';
|
||||
get donutPeriodIndex() { return this.donutPages.findIndex(p => p.period === this.activeDonutPeriod); }
|
||||
changeDonutPeriod(step: number) {
|
||||
if (this.result().status !== 'ready' || ![-1, 1].includes(step)) return;
|
||||
const page = this.donutPages[this.donutPeriodIndex + step];
|
||||
if (!page) return;
|
||||
this.activeDonutPeriod = page.period;
|
||||
// Selection belongs to one page. Reset dependent category/stratum state
|
||||
// even when the same labels exist in the following period.
|
||||
this.hierarchySelected.emit({});
|
||||
this.result.set(this.refreshDonutPage(page.state));
|
||||
}
|
||||
selectHierarchy(selection: DonutSelection) {
|
||||
this.hierarchySelected.emit(selection.parent || selection.category
|
||||
? { ...selection, period: this.activeDonutPeriod ?? this.readySelection?.periodos?.[0] } : {});
|
||||
}
|
||||
private refreshDonutPage(state: FigureState): FigureState {
|
||||
const presentation = this.present(state.figure!, this.readySelection!, state.hierarchy);
|
||||
return { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
|
||||
}
|
||||
private activateDonutPages(pages: { period: string; state: FigureState }[]): FigureState {
|
||||
const plotHeight = pages.some(p => p.state.hierarchy) ? 440 : undefined;
|
||||
this.donutPages = pages.map(p => ({ ...p, state: { ...p.state, plotHeight } }));
|
||||
this.activeDonutPeriod = pages.some(p => p.period === this.activeDonutPeriod) ? this.activeDonutPeriod : pages[0]?.period;
|
||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||
}
|
||||
dimension: DimensionEstrato | '' = '';
|
||||
cells: StratifiedCell[] = [];
|
||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||
private stratifiedData?: IndicadorDatos;
|
||||
private generalData?: IndicadorDatos;
|
||||
private generalState?: FigureState;
|
||||
generalSelectionContext?: string;
|
||||
get capabilities() { return stratifiedCapabilities(this.indicador); }
|
||||
get singlePeriod() { return this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1; }
|
||||
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();
|
||||
}
|
||||
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.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 }),
|
||||
source: 'datos', footnotes: data.notas,
|
||||
emptyMessage: this.cells.length ? 'No hay magnitudes disponibles. Consulta las celdas suprimidas y sin información en la tabla de valores.' : 'No hay categorías publicadas para esta selección.' };
|
||||
}
|
||||
private presentGeneral(state: FigureState, selection: FigureSelection): FigureState {
|
||||
const selected = this.generalData && state.figure
|
||||
? c2GeneralSelection(state.figure, this.generalData, selection, this.localSelection) : undefined;
|
||||
this.generalSelectionContext = selected?.context;
|
||||
const presentation = this.present(selected?.figure ?? state.figure!, selection);
|
||||
// Keep the complete original figure in state. Width/profile changes and
|
||||
// restoration always derive afresh, including published percentage arrays.
|
||||
return { ...state, ...presentation, figure: state.figure,
|
||||
footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
|
||||
}
|
||||
private readySelection?: FigureSelection;
|
||||
private plotWidth?: number;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>();
|
||||
private generation = 0;
|
||||
private currentKey = '';
|
||||
titleId = '';
|
||||
distributionAvailabilityId = '';
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin selección aplicada'; }
|
||||
constructor() {
|
||||
this.figureRequests.pipe(switchMap(request => request
|
||||
? defer(() => this.loadFigure(request.selection)).pipe(
|
||||
catchError(error => of({
|
||||
status: 'error',
|
||||
message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404
|
||||
&& (request.selection.periodos?.length ?? 0) > 1
|
||||
? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''),
|
||||
} as FigureState)),
|
||||
startWith({ status: 'loading' } as FigureState),
|
||||
map(state => ({ state, selection: request.selection, revision: request.revision, generation: request.generation })))
|
||||
: of({ state: { status: 'idle' } as FigureState, selection: undefined, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(({ state, selection, revision, generation }) => {
|
||||
if (generation === this.generation && revision === this.applied?.revision) {
|
||||
if (state.status === 'ready') {
|
||||
this.readySelection = selection;
|
||||
if (!this.dimension && this.indicador.contrato === 'C2'
|
||||
&& selection?.figura === 'fig_c2_barras' && this.indicador.figuras.includes('fig_c2_donas')) {
|
||||
this.generalState = state;
|
||||
state = this.presentGeneral(state, selection);
|
||||
}
|
||||
if (!this.donutPages.length) this.activeDonutPeriod = selection?.periodos?.length === 1
|
||||
? selection.periodos[0] : state.figure && donutPeriod(state.figure);
|
||||
}
|
||||
this.result.set(state);
|
||||
}
|
||||
});
|
||||
}
|
||||
private loadFigure(selection: FigureSelection) {
|
||||
if (this.dimension && selection.periodos?.length === 1 && this.capabilities.includes(this.dimension)) {
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo!, selection.periodos, this.indicador.version, { estrato: this.dimension }).pipe(map(data => {
|
||||
if (data.periodos.length !== 1 || data.periodos[0] !== selection.periodos![0]) throw new Error('Periodo estratificado inválido');
|
||||
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
||||
}));
|
||||
}
|
||||
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.
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(
|
||||
switchMap(data => {
|
||||
if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.');
|
||||
if (selection.figura === 'fig_c2_barras') this.generalData = data;
|
||||
const periods = selection.periodos ?? data.periodos;
|
||||
if (selection.figura === 'fig_c2_donas' && periods.length > 1) {
|
||||
const pages = periods.map(period => ({ period, adapted: c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }) }));
|
||||
if (pages.every(p => p.adapted.status === 'supported')) {
|
||||
return of(this.activateDonutPages(pages.map(({ period, adapted }) => {
|
||||
if (adapted.status !== 'supported') throw new Error('Periodo no soportado');
|
||||
return { period, state: { ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage } };
|
||||
})));
|
||||
}
|
||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||
}
|
||||
const adapted = c2Figure(data, selection);
|
||||
return adapted.status === 'supported'
|
||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||
: this.publishedFigure(selection, adapted.reason, data);
|
||||
}));
|
||||
}
|
||||
return this.publishedFigure(selection);
|
||||
}
|
||||
private publishedFigure(selection: FigureSelection, fallbackReason?: string, data?: IndicadorDatos) {
|
||||
return defer(() => this.service.figura(selection)).pipe(
|
||||
switchMap(figure => {
|
||||
const pages = donutPeriodFigures(figure, selection, data?.periodos);
|
||||
if (pages) return of(this.activateDonutPages(pages.map(({ period, figure: page }) => ({ period,
|
||||
state: { ...this.present(page, selection, data && donutHierarchy(page, periodDatos(data, period))),
|
||||
source: 'figuras' as const, fallbackReason,
|
||||
emptyMessage: !page.data.length ? 'No hay valores representables publicados para el periodo ' + period + '. Consulta las notas de la figura.' : undefined } }))));
|
||||
const period = this.indicador.contrato === 'C2'
|
||||
? donutPeriod(figure) : undefined;
|
||||
const present = (hierarchy?: DonutHierarchy) => ({ ...this.present(figure, selection, hierarchy), source: 'figuras' as const, fallbackReason });
|
||||
// A fallback has already read /datos; don't request a different subset.
|
||||
return !fallbackReason && period && selection.tipoPeriodo
|
||||
? this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, [period], this.indicador.version).pipe(
|
||||
map(data => present(donutHierarchy(figure, data))),
|
||||
// The optional hierarchy must never prevent the published figure.
|
||||
catchError(() => of(present())))
|
||||
: of(present());
|
||||
}));
|
||||
}
|
||||
private present(figure: NonNullable<FigureState['figure']>, selection: FigureSelection, hierarchy?: DonutHierarchy): FigureState {
|
||||
const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth);
|
||||
return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes,
|
||||
categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth, hierarchy,
|
||||
donutLegend: selection.figura === 'fig_c2_donas' && !hierarchy ? donutLegend(presentation.figure) : undefined,
|
||||
plotWidth: selection.figura === 'fig_c2_donas' && this.indicador.contrato === 'C2' && this.plotWidth !== undefined
|
||||
? (this.plotWidth < 480 ? 320 : 480) : undefined };
|
||||
}
|
||||
updatePlotWidth(width: number) {
|
||||
if (!Number.isFinite(width) || width <= 0 || Math.floor(width) === this.plotWidth) return;
|
||||
this.plotWidth = Math.floor(width);
|
||||
if (this.dimension) return;
|
||||
const state = this.result();
|
||||
const responsiveC2Donut = this.indicador.contrato === 'C2' && this.figuraId === 'fig_c2_donas';
|
||||
if ((this.visualProfile.axisLabels?.enabled || responsiveC2Donut)
|
||||
&& state.status === 'ready' && state.figure && this.readySelection) {
|
||||
const presentation = this.generalState ? this.presentGeneral(this.generalState, this.readySelection)
|
||||
: this.present(state.figure, this.readySelection, state.hierarchy);
|
||||
const next = { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
|
||||
// A width change within the same label budget must not hide/repaint an
|
||||
// equivalent graph (for example when only the scrollbar gutter changes).
|
||||
if (JSON.stringify([next.presentationFigure, next.categoryLabels, next.minimumPlotWidth, next.plotWidth])
|
||||
!== JSON.stringify([state.presentationFigure, state.categoryLabels, state.minimumPlotWidth, state.plotWidth])) this.result.set(next);
|
||||
}
|
||||
}
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
|
||||
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';
|
||||
this.distributionAvailabilityId = this.titleId + '-distribution-availability';
|
||||
const key = this.requestKey();
|
||||
if (key === this.currentKey) {
|
||||
if (changes['localSelection'] && 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.' }); }
|
||||
} else if (changes['localSelection'] && this.generalState && this.readySelection && this.result().status === 'ready') {
|
||||
this.result.set(this.presentGeneral(this.generalState, this.readySelection));
|
||||
}
|
||||
const state = this.result();
|
||||
if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) {
|
||||
const next = this.generalState ? this.presentGeneral(this.generalState, this.readySelection)
|
||||
: this.present(state.figure, this.readySelection, state.hierarchy);
|
||||
this.result.set({ ...state, ...next, footnotes: state.source === 'datos' ? state.footnotes : next.footnotes });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.visible) this.requestFigure();
|
||||
else {
|
||||
// Cancel stale work immediately but retain the panel and its Plotly host.
|
||||
const message = this.generation === 0
|
||||
? 'Figura pendiente: se cargará al acercarse a esta región.'
|
||||
: 'Actualización pendiente: se consultará al volver a esta región.';
|
||||
this.generation++;
|
||||
this.figureRequests.next(null);
|
||||
this.currentKey = '';
|
||||
this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined;
|
||||
this.result.set({ status: 'deferred', message });
|
||||
}
|
||||
}
|
||||
private requestKey() {
|
||||
return JSON.stringify([figureIdentity(this.dominio, this.indicador.id, this.figuraId),
|
||||
this.indicador.version, this.tema, this.applied?.revision, this.applied && selectionKey(this.applied),
|
||||
this.indicador.tipos_periodo, this.indicador.figuras.includes(this.figuraId), this.dimension]);
|
||||
}
|
||||
requestFigure() {
|
||||
if (!this.visible) return;
|
||||
this.currentKey = this.requestKey();
|
||||
this.stratifiedData = undefined; this.cells = [];
|
||||
this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined;
|
||||
this.donutPages = [];
|
||||
const applied = this.applied;
|
||||
const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo);
|
||||
this.generation++;
|
||||
if (!this.indicador.figuras.includes(this.figuraId) || !compatibility.compatible) {
|
||||
this.figureRequests.next(null);
|
||||
this.result.set({ status: 'incompatible', message: !compatibility.compatible
|
||||
? compatibility.reason : 'Esta figura ya no está publicada en el catálogo.' });
|
||||
return;
|
||||
}
|
||||
this.figureRequests.next({ revision: applied.revision, generation: this.generation, selection: {
|
||||
dominio: this.dominio, indicador: this.indicador.id, figura: this.figuraId,
|
||||
tipoPeriodo: applied.tipo, tema: this.tema,
|
||||
periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined,
|
||||
} });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
|
||||
describe('UX-06E.D.1 KPI presentacional', () => {
|
||||
it('presenta título y definición pendiente sin valores, unidades, fechas ni controles', () => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
fixture.componentRef.setInput('title', 'Indicador destacado 1'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('h3').textContent).toBe('Indicador destacado 1');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Pendiente de definición');
|
||||
expect(fixture.nativeElement.querySelector('.value')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelectorAll('p')).toHaveLength(1);
|
||||
expect(fixture.nativeElement.querySelector('button, input, app-plotly-chart')).toBeNull();
|
||||
fixture.destroy();
|
||||
});
|
||||
it.each([null, undefined])('omite el valor opcional %s sin convertirlo a cero', value => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
fixture.componentRef.setInput('title', 'Presentación'); fixture.componentRef.setInput('value', value);
|
||||
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.value')).toBeNull(); fixture.destroy();
|
||||
});
|
||||
it('admite contenido opcional suministrado por su consumidor sin servicios ni formatos impuestos', () => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
for (const [name, value] of Object.entries({ title: 'Título de prueba', value: 'Valor de prueba', unit: 'Unidad de prueba',
|
||||
temporalReference: 'Referencia de prueba', state: 'Estado de prueba', additionalInfo: 'Información de prueba' })) {
|
||||
fixture.componentRef.setInput(name, value);
|
||||
}
|
||||
fixture.detectChanges();
|
||||
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('.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');
|
||||
fixture.destroy();
|
||||
});
|
||||
it('separa valor y unidad y reúne descripción y notas útiles en una sola línea', () => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
fixture.componentRef.setInput('title', 'Días de la toma al resultado');
|
||||
fixture.componentRef.setInput('value', 7.5);
|
||||
fixture.componentRef.setInput('unit', 'días (mediana)');
|
||||
fixture.componentRef.setInput('additionalInfo', '98 mastografías; Q1 a Q3: 3 a 11 días.');
|
||||
fixture.componentRef.setInput('notes', ['La referencia de 60 días es provisional.', 'La referencia de 60 días es provisional.']);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.value').firstChild.textContent.trim()).toBe('7.5');
|
||||
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('días (mediana)');
|
||||
expect(getComputedStyle(fixture.nativeElement.querySelector('.value span')).marginInlineStart).toBe('0.3em');
|
||||
expect(fixture.nativeElement.querySelectorAll('.additional-info')).toHaveLength(1);
|
||||
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('98 mastografías; Q1 a Q3: 3 a 11 días. La referencia de 60 días es provisional.');
|
||||
fixture.destroy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-kpi-card',
|
||||
imports: [MatCardModule, MatProgressBarModule],
|
||||
template: `
|
||||
<mat-card [attr.aria-busy]="loading">
|
||||
<h3>{{ title }}</h3>
|
||||
@if (loading) { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + title" /> }
|
||||
@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">{{ state }}</p>
|
||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
mat-card { box-sizing: border-box; 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; }
|
||||
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; }
|
||||
h3, p { overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.value { font: var(--mat-sys-headline-medium); }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiCard {
|
||||
@Input({ required: true }) title!: string;
|
||||
@Input() value?: string | number | null;
|
||||
@Input() unit?: string;
|
||||
@Input() temporalReference?: string;
|
||||
@Input() loading = false;
|
||||
@Input() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
@Input() additionalInfo?: string;
|
||||
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(' ');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
|
||||
describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorKpiPanel>>;
|
||||
let http: HttpTestingController;
|
||||
const definition = KPI_BY_DOMAIN.cacu[0];
|
||||
const periods = ['2025-S2', '2025-S1', '2024-S2'];
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorKpiPanel], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadorKpiPanel);
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
const availability = emptyAvailability('ready');
|
||||
availability.byIndicator[definition.id] = [periods[2], '2026-01', periods[0], periods[1]].map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' }));
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('definition', definition);
|
||||
fixture.componentRef.setInput('indicador', { id: definition.id, contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: [], titulo: definition.title });
|
||||
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 });
|
||||
fixture.componentRef.setInput('initialPresentation', true);
|
||||
fixture.componentRef.setInput('availability', availability);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function request(period: string) {
|
||||
return http.expectOne(r => r.url.endsWith('/datos') && r.params.get('periodos') === period);
|
||||
}
|
||||
function data(period: string, kind: 'visible' | 'suppressed' | 'incomplete' | 'null' = 'visible', value = 5) {
|
||||
return { id: definition.id, contrato: 'C2', tipo_periodo: 'semestre', periodos: [period],
|
||||
categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} },
|
||||
filas: [{ periodo: period, grupo: 'TOTAL', categoria: 'A', n: kind === 'null' ? null : value, suprimido: kind === 'suppressed' ? 1 : 0 }] };
|
||||
}
|
||||
it('consulta secuencialmente por intervalo de tiempo, detiene al visible y explica supresión posterior', () => {
|
||||
const latest = request(periods[0]); http.expectNone(() => true);
|
||||
expect(fixture.componentInstance.result().loading).toBe(true);
|
||||
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.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('recorre varios suprimidos sin consultar todos los periodos a la vez', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed'));
|
||||
const second = request(periods[1]); http.expectNone(() => true);
|
||||
second.flush(data(periods[1], 'suppressed'));
|
||||
request(periods[2]).flush(data(periods[2]));
|
||||
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible, 2024-S2');
|
||||
expect(fixture.componentInstance.result().info).toContain('datos ocultos por tamaño');
|
||||
});
|
||||
it('agotado el inventario conserva el estado del último reporte', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed'));
|
||||
request(periods[1]).flush(data(periods[1], 'incomplete'));
|
||||
request(periods[2]).flush(data(periods[2], 'null'));
|
||||
expect(fixture.componentInstance.result().state).toBe('Dato oculto por tamaño');
|
||||
expect(fixture.componentInstance.result().value).toBeUndefined();
|
||||
expect(fixture.componentInstance.temporalReference).toBe(periods[0]);
|
||||
});
|
||||
it('acepta cero legítimo del último periodo y termina sin retroceder', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'visible', 0));
|
||||
expect(fixture.componentInstance.result().value).toBe(0);
|
||||
expect(fixture.componentInstance.temporalReference).toBe(periods[0]);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it.each(['incomplete', 'null', 'missing'] as const)('no muestra %s ni afirma supresión si encuentra un anterior', kind => {
|
||||
const latest = request(periods[0]);
|
||||
if (kind === 'missing') latest.flush('', { status: 404, statusText: 'Not Found' });
|
||||
else latest.flush(data(periods[0], kind));
|
||||
expect(fixture.componentInstance.result().value).toBeUndefined();
|
||||
request(periods[1]).flush(data(periods[1]));
|
||||
expect(fixture.componentInstance.result().value).toBe(5);
|
||||
expect(fixture.componentInstance.result().info).not.toContain('datos ocultos por tamaño');
|
||||
});
|
||||
it('un error HTTP detiene, se comunica y reintenta sin repetir datos resueltos', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed'));
|
||||
request(periods[1]).flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().state).toBe('Error de consulta');
|
||||
expect(fixture.componentInstance.result().value).toBeUndefined();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('datos ocultos por tamaño');
|
||||
http.expectNone(() => true);
|
||||
(fixture.nativeElement.querySelector('button') as HTMLButtonElement).click();
|
||||
request(periods[1]).flush(data(periods[1]));
|
||||
expect(fixture.componentInstance.result().value).toBe(5); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicar Todos durante la búsqueda cancela el pasado y recupera solo el último reporte', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed'));
|
||||
const old = request(periods[1]);
|
||||
fixture.componentRef.setInput('initialPresentation', false); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(fixture.componentInstance.result().state).toBe('Dato oculto por tamaño');
|
||||
expect(fixture.componentInstance.temporalReference).toBe(periods[0]); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicar explícito cancela el recorrido e impide sobrescritura antigua', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed')); const old = request(periods[1]);
|
||||
fixture.componentRef.setInput('initialPresentation', false);
|
||||
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: [periods[2]] }, revision: 1 }); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true); request(periods[2]).flush(data(periods[2], 'visible', 0));
|
||||
expect(fixture.componentInstance.result().value).toBe(0); expect(fixture.componentInstance.temporalReference).toBe(periods[2]);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('comparte el límite cuatro entre periodos y datos; cancela trabajos en cola', () => {
|
||||
const latest = request(periods[0]);
|
||||
const service = TestBed.inject(IndicadoresPeriodos);
|
||||
const subscriptions = ['a', 'b', 'c', 'd', 'e'].map(id => service.periodos('cacu', id).subscribe());
|
||||
const inventory = http.match(r => r.url.endsWith('/periodos'));
|
||||
expect(inventory).toHaveLength(3);
|
||||
subscriptions[4].unsubscribe();
|
||||
latest.flush(data(periods[0], 'suppressed'));
|
||||
const fourth = http.expectOne('/cacu/indicadores/d/periodos');
|
||||
http.expectNone(() => true);
|
||||
inventory[0].flush({ id: 'a', periodos: [] });
|
||||
request(periods[1]).flush(data(periods[1]));
|
||||
inventory.slice(1).forEach((r, i) => r.flush({ id: ['b', 'c'][i], periodos: [] }));
|
||||
fourth.flush({ id: 'd', periodos: [] }); http.expectNone('/cacu/indicadores/e/periodos');
|
||||
subscriptions.forEach(subscription => subscription.unsubscribe());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,237 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorDatos, Dominio } from './indicadores.models';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
describe('KPI integración con autoridad global', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
// KPI scope only: graphic cards stay outside the viewport, so coordinated views
|
||||
// (such as the CaCu paired times) do not add their own /datos requests.
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
||||
function load(domain: Dominio, missing = false, periods = ['2025-S1'], initial = domain === 'tea') {
|
||||
// Ordinary consumer tests begin after initialization; dedicated P0 suites
|
||||
// exercise the real shared search for all three domains.
|
||||
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 })) });
|
||||
fixture.detectChanges();
|
||||
}
|
||||
// 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.
|
||||
function originalRequests() {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
|
||||
const period = r.request.params.get('periodos')!;
|
||||
r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
|
||||
}
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function requests() { return originalRequests(); }
|
||||
function response(index: number, domain: Dominio = 'cacu', period = '2025-S1'): IndicadorDatos {
|
||||
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
|
||||
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
|
||||
}
|
||||
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
|
||||
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
}
|
||||
it('TEA sin catálogo no muestra destacados ni consulta datos', () => {
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull();
|
||||
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', () => {
|
||||
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']);
|
||||
initial[0].flush(response(0, 'tea')); fixture.detectChanges();
|
||||
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()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||
});
|
||||
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);
|
||||
for (const r of req) { expect(r.request.params.has('tipoPeriodo')).toBe(false); expect(r.request.params.has('tema')).toBe(false); }
|
||||
req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta']);
|
||||
panels()[1].retry(); requests()[0].flush(response(1)); fixture.detectChanges();
|
||||
expect(panels()[1].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
});
|
||||
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);
|
||||
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);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(2);
|
||||
next.forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
apply(['2025-S2']); http.expectNone(() => true);
|
||||
});
|
||||
it('selección múltiple cancela, no consulta ni suma meses para un semestre', () => {
|
||||
load('cacu'); const pending = requests(); apply(['2025-01', '2025-02'], 'mes');
|
||||
expect(pending.every(r => r.cancelled)).toBe(true); expect(panels().every(p => p.result().state === 'Selección no consolidable')).toBe(true); http.expectNone(() => true);
|
||||
apply(['2025-01'], 'mes'); requests().forEach((r,i) => { expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush(response(i, 'cacu', '2025-01')); });
|
||||
});
|
||||
it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => {
|
||||
load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
||||
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); const cama = requests(); expect(cama.every(r => r.request.url.startsWith('/cama/'))).toBe(true); cama.forEach((r,i) => r.flush(response(i, 'cama')));
|
||||
load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
|
||||
});
|
||||
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
|
||||
load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.slice(1).map(d => d.id));
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(4);
|
||||
const req = requests(); expect(req).toHaveLength(1); req.forEach((r,i) => r.flush(response(i+1)));
|
||||
});
|
||||
it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => {
|
||||
load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges();
|
||||
const page = fixture.componentInstance, before = panels(), state = page.filters!;
|
||||
state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
||||
const snapshot = structuredClone(state), definitions = page.kpisByDomain.cacu;
|
||||
try {
|
||||
page.kpisByDomain.cacu = definitions.slice(0, count); page.catalog.set([...page.catalog()]); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(count); panels().forEach((panel, i) => expect(panel).toBe(before[i]));
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7].slice(0, count));
|
||||
expect(page.filters).toBe(state); expect(state).toEqual(snapshot);
|
||||
const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null;
|
||||
if (count) {
|
||||
expect(grid!.children).toHaveLength(count + 3);
|
||||
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 3));
|
||||
} else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges();
|
||||
const added = requests(); expect(added).toHaveLength(0);
|
||||
added.forEach((r, i) => r.flush(response(count + i)));
|
||||
expect(panels()).toHaveLength(2); expect(state).toEqual(snapshot);
|
||||
} finally { page.kpisByDomain.cacu = definitions; }
|
||||
});
|
||||
it('retirar un ID del catálogo conserva los otros KPI y los filtros', () => {
|
||||
load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges();
|
||||
const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters);
|
||||
page.catalog.set(page.catalog().slice(1)); fixture.detectChanges();
|
||||
expect(panels()).toEqual(before.slice(1)); expect(page.filters).toEqual(filters);
|
||||
expect(panels()).toHaveLength(1); http.expectNone(() => true);
|
||||
});
|
||||
it('CaCu no presenta KPI disponibles durante carga/error y reintenta sin confirmar vacío', () => {
|
||||
const page = fixture.componentInstance; page.changeDominio('cacu'); fixture.detectChanges();
|
||||
expect(page.catalogLoading()).toBe(true); expect(panels()).toHaveLength(0);
|
||||
expect(fixture.nativeElement.textContent).toContain('Cargando catálogo');
|
||||
http.expectOne('/cacu/indicadores').flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(page.catalogError()).toBeTruthy(); expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); expect(panels()).toHaveLength(0);
|
||||
expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles');
|
||||
page.retryCatalog(); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges();
|
||||
expect(page.catalogError()).toBe(''); expect(page.catalogLoading()).toBe(false);
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); expect(panels()).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it.each(['suprimido', 'nulo', 'sin filas'] as const)('KPI publicado con resultado %s conserva tarjeta y definición', scenario => {
|
||||
load('cacu'); const before = panels();
|
||||
const data = response(1);
|
||||
if (scenario === 'suprimido') data.filas[0]['suprimido'] = 1;
|
||||
if (scenario === 'nulo') data.filas[0]['mediana'] = null;
|
||||
if (scenario === 'sin filas') { data.filas = []; data.periodos = []; }
|
||||
requests().forEach((r, i) => r.flush(i === 1 ? data : response(i))); fixture.detectChanges();
|
||||
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(5);
|
||||
expect(panels()[1].result().state).toBe(scenario === 'suprimido' ? 'Dato oculto por tamaño' : scenario === 'nulo' ? 'Sin valor disponible' : 'Sin filas utilizables');
|
||||
expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true);
|
||||
});
|
||||
it('KPI publicado sin periodos con reporte mantiene sus tres tarjetas sin consultar datos', () => {
|
||||
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();
|
||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain);
|
||||
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
|
||||
req.forEach((r, i) => r.flush({ ...response(i, 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 : 3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', '%', 'días (mediana)']);
|
||||
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', 'Disponible', '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.textContent).not.toContain('Definición provisional');
|
||||
// CaCu cards say only their own line; the kit notes are the figure footer.
|
||||
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(domain !== 'cacu');
|
||||
}
|
||||
});
|
||||
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1'], true);
|
||||
const latest = requests(); expect(latest).toHaveLength(1);
|
||||
const hidden = response(0, 'cacu', '2025-S2'); hidden.filas[0]['suprimido'] = 1; latest[0].flush(hidden);
|
||||
requests()[0].flush(response(0)); fixture.detectChanges();
|
||||
requests().forEach((r, i) => r.flush(response(i + 1))); fixture.detectChanges();
|
||||
expect(panels().every(p => p.temporalReference === '2025-S1')).toBe(true);
|
||||
const page = fixture.componentInstance; page.filters!.editors.semestre!.draft = { mode: 'todos' };
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
requests().forEach((r, i) => { const data = response(i + 1, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); fixture.detectChanges();
|
||||
expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.temporalReference === '2025-S2')).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges();
|
||||
requests().forEach((r, i) => r.flush(response(i + 1, domain))); fixture.detectChanges();
|
||||
expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false);
|
||||
}
|
||||
load('cacu', false, ['2025-S1'], true);
|
||||
expect(fixture.componentInstance.initialPeriodBlocked).toBe(false);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]); http.expectNone(() => true);
|
||||
});
|
||||
it('salir durante el recorrido cancela periodos antiguos y volver reutiliza últimos resueltos', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1'], true);
|
||||
const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data);
|
||||
const old = requests(); expect(old).toHaveLength(1);
|
||||
load('cama'); expect(old.every(r => r.cancelled)).toBe(true);
|
||||
requests().forEach((r, i) => r.flush(response(i, 'cama')));
|
||||
load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1);
|
||||
resumed[0].flush(response(0)); fixture.detectChanges();
|
||||
requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); });
|
||||
expect(panels().every(p => p.temporalReference === '2025-S1')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicado explícito y luego Todos nunca buscan periodos anteriores', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1']); const outgoing = requests();
|
||||
apply(['2025-S1']); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||
requests().forEach((r, i) => { const data = response(i); data.filas[0]['suprimido'] = 1; r.flush(data); });
|
||||
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true);
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'todos' };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
const latest = requests(); expect(latest).toHaveLength(2);
|
||||
latest.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S2'); const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); });
|
||||
expect(panels().every(p => p.temporalReference === '2025-S2')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { Dominio, Indicador } from './indicadores.models';
|
||||
import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } from './indicadores-memory';
|
||||
import { IndicadoresKpiQueries } from './indicadores-kpi-queries';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi';
|
||||
import { PeriodAvailability, sortedPeriods } from './indicadores-periodos';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
|
||||
interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; version?: string; }
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-kpi-panel',
|
||||
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 === 'cacu' ? [] : result().notes ?? []" />
|
||||
@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; }',
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) definition!: KpiDefinition;
|
||||
@Input() indicador?: Indicador;
|
||||
@Input() applied?: GlobalApplied;
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() initialPresentation = false;
|
||||
private readonly queries = inject(IndicadoresKpiQueries);
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly requests = new Subject<void>();
|
||||
private key = '';
|
||||
readonly usedPeriod = signal<string | undefined>(undefined);
|
||||
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
||||
get temporalReference() {
|
||||
if (this.result().earlier) return 'Último dato visible, ' + this.usedPeriod();
|
||||
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
||||
}
|
||||
retry() { this.requests.next(); }
|
||||
constructor() {
|
||||
this.requests.pipe(switchMap((): Observable<KpiDisplay> => {
|
||||
const applied = this.applied, definition = this.definition, domain = this.dominio;
|
||||
this.usedPeriod.set(undefined);
|
||||
if (!applied) return of({ state: 'Esperando filtro aplicado' });
|
||||
if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) {
|
||||
return of({ state: 'Selección no consolidable', info: 'Elige un único periodo aplicado para consultar esta mediana.' });
|
||||
}
|
||||
if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
|
||||
const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]);
|
||||
if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' });
|
||||
if (applied.selection.mode === 'explicit' && applied.selection.periodos.length !== 1) return of({ state: 'Selección no consolidable', info: 'Elige un único periodo; no hay una regla aprobada para consolidarlos.' });
|
||||
let periods: string[];
|
||||
if (applied.selection.mode === 'todos') {
|
||||
if (!this.indicador) return of({ state: 'Sin reportes disponibles' });
|
||||
const availability = this.availability;
|
||||
if (!availability || availability.status === 'loading') return of({ state: 'Consultando periodos…', loading: true });
|
||||
if (availability.errors[definition.id]) return of({ state: 'Error de disponibilidad', info: 'Reintenta la consulta de periodos disponibles en los filtros generales.' });
|
||||
const available = availability.byIndicator[definition.id];
|
||||
if (!available) return of({ state: 'Error de disponibilidad' });
|
||||
periods = sortedPeriods(available.filter(p => p.tipo === applied.tipo).map(p => p.periodo));
|
||||
if (!periods.length) return of({ state: 'Sin reportes disponibles' });
|
||||
if (!this.initialPresentation) periods = periods.slice(0, 1);
|
||||
} else periods = applied.selection.periodos;
|
||||
// One request per KPI at a time: the three configured panels start only after
|
||||
// the existing availability queue (concurrency four) has finished.
|
||||
const search = (index: number, latest?: KpiDisplay, allSuppressed = true): Observable<KpiDisplay> => {
|
||||
const period = periods[index];
|
||||
const resolved: GlobalApplied = { ...applied, selection: { mode: 'explicit', periodos: [period] } };
|
||||
return this.queries.datos(domain, definition.id, applied.tipo, period, this.indicador?.version).pipe(
|
||||
map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas, period,
|
||||
version: typeof data['version'] === 'string' ? data['version'] : undefined } as KpiDisplay)),
|
||||
catchError(error => of<KpiDisplay>({ period,
|
||||
state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta',
|
||||
info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })),
|
||||
switchMap(result => {
|
||||
// Network/contract transport failures stay visible and can be retried.
|
||||
if (result.state === 'Error de consulta') return of(result);
|
||||
if (result.state === 'Disponible' && result.value !== undefined) return of({ ...result, earlier: index > 0,
|
||||
info: [result.info, index > 0 && allSuppressed ? 'Existen reportes posteriores con datos ocultos por tamaño.' : ''].filter(Boolean).join(' ') });
|
||||
const first = latest ?? result;
|
||||
return index + 1 < periods.length
|
||||
? search(index + 1, first, allSuppressed && result.state === 'Dato oculto por tamaño') : of(first);
|
||||
}));
|
||||
};
|
||||
return search(0).pipe(startWith({ state: this.initialPresentation && applied.selection.mode === 'todos'
|
||||
? 'Buscando último dato visible…' : 'Cargando…', loading: true }));
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(result => {
|
||||
this.usedPeriod.set(result.period);
|
||||
this.result.set(result);
|
||||
if (this.applied) this.snapshots.publishKpi(this.dominio, this.indicador ?? this.definition, this.applied,
|
||||
{ ...result, period: this.temporalReference, unit: this.definition.unit }, result.version);
|
||||
});
|
||||
}
|
||||
ngOnChanges() {
|
||||
const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.initialPresentation, this.applied?.revision, this.applied && selectionKey(this.applied),
|
||||
this.applied?.selection.mode === 'todos' ? [this.availability?.status, this.availability?.byIndicator[this.definition.id], this.availability?.errors[this.definition.id]] : undefined]);
|
||||
if (key === this.key) return;
|
||||
this.key = key;
|
||||
this.requests.next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
:host { display: block; min-width: 0; overflow-wrap: anywhere; }
|
||||
section + section { margin-top: var(--issste-space-4); }
|
||||
h4 { margin: 0 0 var(--issste-space-2); font-size: 1rem; }
|
||||
.metadata-copy { max-width: 75ch; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
ul { padding-inline-start: 1.5rem; }
|
||||
li + li { margin-top: var(--issste-space-2); }
|
||||
.table-scroll { max-width: 100%; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; max-width: 75rem; }
|
||||
th, td { text-align: left; vertical-align: top; padding: var(--issste-space-2); border-bottom: 1px solid var(--issste-border); }
|
||||
thead th, tbody th { color: var(--issste-text-secondary); font-weight: 600; }
|
||||
.ficha-table th { width: 10rem; }
|
||||
@media (max-width: 36rem) {
|
||||
.ficha-table th { width: 6rem; }
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadorMetadata } from './indicador-metadata';
|
||||
|
||||
function render(data: unknown) {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const fixture = TestBed.createComponent(IndicadorMetadata);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('indicador', 'future');
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores/future/metadatos').flush(data as Record<string, unknown>);
|
||||
fixture.detectChanges();
|
||||
return { fixture, http, text: fixture.nativeElement.textContent as string };
|
||||
}
|
||||
|
||||
describe('Metadatos metodológicos opcionales', () => {
|
||||
it('muestra descripción sin ficha y trata etiquetas recibidas como texto', () => {
|
||||
const { fixture, http, text } = render({ titulo: 'Título del catálogo', descripcion: 'Guía <img src=x onerror=alert(1)>\nSegunda línea', ficha: null });
|
||||
expect(text).toContain('Guía <img src=x onerror=alert(1)>');
|
||||
expect(fixture.nativeElement.querySelector('img')).toBeNull();
|
||||
expect(text).toContain('Segunda línea');
|
||||
expect(text).not.toContain('Ficha técnica');
|
||||
expect(text).not.toContain('Título del catálogo');
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('muestra todos los campos no vacíos de la ficha', () => {
|
||||
const { fixture, http, text } = render({
|
||||
descripcion: 'Información general.',
|
||||
ficha: { codigo: 'IND-01', para: 'Personas atendidas', unidad: 'Porcentaje', pregunta: '¿Qué proporción?', definicion: 'Casos que cumplen el criterio.', nota: 'Dato sujeto a revisión.' },
|
||||
});
|
||||
for (const content of ['Descripción', 'Información general.', 'Ficha técnica', 'Código', 'IND-01', 'Para quién', 'Personas atendidas', 'Unidad', 'Porcentaje', 'Pregunta', '¿Qué proporción?', 'Definición', 'Casos que cumplen el criterio.', 'Nota', 'Dato sujeto a revisión.']) expect(text).toContain(content);
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('presenta la ficha en una tabla y no muestra las reglas (parametros) aunque vengan', () => {
|
||||
const { fixture, http, text } = render({
|
||||
ficha: { codigo: 'EU-T', definicion: 'Días de la toma al diagnóstico.' },
|
||||
parametros: [{ clave: 'cacu.horizontes.toma_diagnostico_dias', valor: 180, estado: 'provisional', fuente: 'Arbitrario.' }],
|
||||
});
|
||||
const ficha = fixture.nativeElement.querySelector('table.ficha-table') as HTMLTableElement;
|
||||
expect([...ficha.querySelectorAll('th[scope=row]')].map(th => th.textContent)).toEqual(['Código', 'Definición']);
|
||||
expect(fixture.nativeElement.querySelectorAll('table')).toHaveLength(1);
|
||||
for (const absent of ['Reglas', 'cacu.horizontes', 'Provisional', 'Arbitrario']) expect(text).not.toContain(absent);
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('con solo parametros anuncia que no hay información ampliada', () => {
|
||||
const { fixture, http, text } = render({ parametros: [{ clave: 'comun.umbral_supresion', valor: 5, estado: 'provisional' }] });
|
||||
expect(text).toContain('no está disponible'); expect(text).not.toContain('comun.umbral_supresion');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('muestra sólo los campos utilizables de una ficha parcial', () => {
|
||||
const { fixture, http, text } = render({ ficha: { codigo: 'IND-02', para: ' ', unidad: null, definicion: 'Definición breve', nota: '' } });
|
||||
expect(text).toContain('Código'); expect(text).toContain('IND-02');
|
||||
expect(text).toContain('Definición breve'); expect(text).not.toContain('Para');
|
||||
expect(text).not.toContain('Unidad'); expect(text).not.toContain('Pregunta'); expect(text).not.toContain('Nota');
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('acepta nota nula y conserva el resto de la ficha', () => {
|
||||
const { fixture, http, text } = render({ ficha: { unidad: 'Tasa', nota: null } });
|
||||
expect(text).toContain('Unidad'); expect(text).toContain('Tasa');
|
||||
expect(text).not.toContain('Nota'); expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('muestra estado vacío con descripción y ficha ausentes o nulas', () => {
|
||||
const { fixture, http, text } = render({ descripcion: null, ficha: null, referencias: null, poblaciones: null });
|
||||
expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.');
|
||||
expect(text).not.toContain('Ficha técnica'); expect(text).not.toContain('Descripción');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('mantiene referencias y poblaciones de payloads anteriores junto con la descripción', () => {
|
||||
const { fixture, http, text } = render({
|
||||
descripcion: 'Descripción publicada.',
|
||||
referencias: [{ tipo: 'citation', etiqueta: 'Guía publicada <em>edición 2</em>', ref: 'Indicador 7' }],
|
||||
poblaciones: [{ grupo: 'TOTAL', codigo: 'initial-population', descripcion: 'Pacientes con estudio publicado.' }],
|
||||
categorias: { NORMAL: { etiqueta: 'Normal' } },
|
||||
});
|
||||
expect(text).toContain('Descripción publicada.');
|
||||
expect(text).toContain('Guía publicada <em>edición 2</em>, Indicador 7');
|
||||
expect(text).toContain('Pacientes con estudio publicado.');
|
||||
expect(fixture.nativeElement.querySelector('em')).toBeNull();
|
||||
expect(text).not.toMatch(/initial-population|citation|TOTAL|no está disponible/);
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('conserva compatibilidad con el payload anterior que sólo trae categorías', () => {
|
||||
const { fixture, http, text } = render({ categorias: { NORMAL: { etiqueta: 'Normal' } } });
|
||||
expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.');
|
||||
expect(text).not.toContain('Normal');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('no anuncia ausencia cuando hay ficha utilizable aunque sus demás campos estén vacíos', () => {
|
||||
const { fixture, http, text } = render({ ficha: { codigo: ' IND-03 ' } });
|
||||
expect(text).toContain('IND-03'); expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { ChangeDetectorRef, Component, DestroyRef, inject, Input, OnChanges } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, of, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, IndicadorMetadatos } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-metadata',
|
||||
styleUrl: './indicador-metadata.scss',
|
||||
template: `
|
||||
@if (loading) { <p role="status">Cargando información metodológica…</p> }
|
||||
@if (description; as text) {
|
||||
<section aria-labelledby="metadata-description-title">
|
||||
<h4 id="metadata-description-title">Descripción</h4>
|
||||
<p class="metadata-copy">{{ text }}</p>
|
||||
</section>
|
||||
}
|
||||
@if (fichaFields.length) {
|
||||
<section aria-labelledby="metadata-ficha-title">
|
||||
<h4 id="metadata-ficha-title">Ficha técnica</h4>
|
||||
<div class="table-scroll">
|
||||
<table class="ficha-table">
|
||||
<tbody>@for (field of fichaFields; track field.key) {
|
||||
<tr><th scope="row">{{ field.label }}</th><td class="metadata-copy">{{ field.value }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
@if (references.length) {
|
||||
<section aria-labelledby="metadata-references-title">
|
||||
<h4 id="metadata-references-title">Referencias</h4>
|
||||
<ul>@for (ref of references; track $index) { <li>{{ ref.etiqueta }}@if (hasText(ref.ref)) {, {{ ref.ref }} }</li> }</ul>
|
||||
</section>
|
||||
}
|
||||
@if (populations.length) {
|
||||
<section aria-labelledby="metadata-populations-title">
|
||||
<h4 id="metadata-populations-title">Poblaciones del estudio</h4>
|
||||
<ul>@for (population of populations; track $index) { <li>{{ population.descripcion }}</li> }</ul>
|
||||
</section>
|
||||
}
|
||||
@if (!loading && !hasUsableMetadata) { <p>La información metodológica ampliada no está disponible para este indicador.</p> }
|
||||
`,
|
||||
})
|
||||
export class IndicadorMetadata implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: string;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly requests = new Subject<void>();
|
||||
metadata?: IndicadorMetadatos;
|
||||
loading = false;
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly fichaLabels = [
|
||||
['codigo', 'Código'], ['para', 'Para quién'], ['unidad', 'Unidad'],
|
||||
['pregunta', 'Pregunta'], ['definicion', 'Definición'], ['nota', 'Nota'],
|
||||
] as const;
|
||||
hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; }
|
||||
get description() { return this.hasText(this.metadata?.descripcion) ? this.metadata!.descripcion!.trim() : undefined; }
|
||||
get fichaFields() {
|
||||
const ficha = this.metadata?.ficha;
|
||||
return ficha ? this.fichaLabels.flatMap(([key, label]) => this.hasText(ficha[key]) ? [{ key, label, value: ficha[key]!.trim() }] : []) : [];
|
||||
}
|
||||
get references() { return (this.metadata?.referencias ?? []).filter(ref => this.hasText(ref.etiqueta)); }
|
||||
get populations() { return (this.metadata?.poblaciones ?? []).filter(population => this.hasText(population.descripcion)); }
|
||||
get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.references.length || this.populations.length); }
|
||||
constructor() {
|
||||
this.requests.pipe(switchMap(() => this.service.metadatos(this.dominio, this.indicador).pipe(catchError(() => of(undefined)))), takeUntilDestroyed(inject(DestroyRef))).subscribe(value => { this.metadata = value; this.loading = false; this.changeDetector.markForCheck(); });
|
||||
}
|
||||
ngOnChanges() { this.metadata = undefined; this.loading = true; this.requests.next(); }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<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> }
|
||||
<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>
|
||||
@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> }
|
||||
@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') {
|
||||
<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>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>{{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-label>
|
||||
<mat-select [(ngModel)]="unit">
|
||||
@for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { <mat-option [value]="value">{{ value }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button type="button" mat-stroked-button (click)="add()">Agregar periodo</button>
|
||||
</div>
|
||||
<div class="remove" aria-label="Eliminar periodos agregados">
|
||||
@for (period of entry.added; track period) {
|
||||
<button type="button" mat-button (click)="remove(period)" [attr.aria-label]="'Eliminar periodo ' + period">Eliminar {{ period }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@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 (!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>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
</section>
|
||||
@@ -0,0 +1,19 @@
|
||||
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
|
||||
section { min-width: 0; }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
|
||||
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; }
|
||||
p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; }
|
||||
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.5; }
|
||||
.filter-help, .applied-summary { color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
.draft-summary { font-weight: 500; }
|
||||
.pending { border-left: 3px solid var(--issste-text); padding-left: var(--issste-space-3); }
|
||||
.error { color: var(--mat-sys-error); }
|
||||
.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); }
|
||||
@media (max-width: 550px) {
|
||||
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; }
|
||||
.period-builder button { margin-top: 0; }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user