Compare commits
131 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c076e1e7a9 | |||
| 710790b98e | |||
| d16804d416 | |||
| 05a55a673e | |||
| e803c38acf | |||
| 6009aea83e | |||
| cda3563184 | |||
| 7a6f87d141 | |||
| 78313adb4a | |||
| 7dc420773f | |||
| 552e2c194f | |||
| 8f01f8693d | |||
| ad8444a788 | |||
| f78db1ae37 | |||
| 0914b8db23 | |||
| 8aa66c6277 | |||
| 1e1999f264 | |||
| e95c175f9b | |||
| ff03a88ea0 | |||
| d761a6fb1a | |||
| 2982d482bf | |||
| 5e16f5454b | |||
| ce3ed34fbf | |||
| d159067efd | |||
| 7b8fd9e01d | |||
| 8a3f68df6b | |||
| bc75c058e1 | |||
| 502fc969f0 | |||
| 612a11fa6f | |||
| 8b7dd6ec19 | |||
| 59ce79d1a2 | |||
| e13e727de3 | |||
| 67cde017fa | |||
| 8c3e41527c | |||
| 3aba7fe329 | |||
| 739bf9613c | |||
| 987bce0d93 | |||
| eaaffa9ebe | |||
| 088d9d4550 | |||
| e5ff3427c7 | |||
| 0bf1f82366 | |||
| edd6e4b640 | |||
| 3674a43587 | |||
| 27bd4d4a65 | |||
| cbae29bc24 | |||
| 35b329e235 | |||
| 7f303d1160 | |||
| e2b307abf5 | |||
| 39974b8533 | |||
| 53edec8692 | |||
| a1ea31039e | |||
| ef631e2c0b | |||
| 27dc7a0166 | |||
| e6353f9f4c | |||
| 3bb9c2121d | |||
| 737c6f9f14 | |||
| 8e543cbcc6 | |||
| ea7aad5067 | |||
| 09b52e6b0a | |||
| 078db53ae4 | |||
| 957f4cd024 | |||
| 1ce8d98663 | |||
| 1771cb7ec6 | |||
| b74f188b15 | |||
| 5196f20e47 | |||
| 5d4cd6f654 | |||
| a05717f92d | |||
| 123232592f | |||
| 2cbb994667 | |||
| f4d2a3e85f | |||
| 8c63ed83ac | |||
| e6e6fb7210 | |||
| 82efba35cb | |||
| 26fe1ccbb3 | |||
| 94c63c460c | |||
| 05a9967906 | |||
| 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 |
+2
-5
@@ -1,10 +1,7 @@
|
||||
# Production image: build the Angular app, serve the static bundle with
|
||||
# nginx, and reverse-proxy the API paths to the `webapi` compose service —
|
||||
# the same routing `proxy.conf.json` gives `ng serve` in development, so the
|
||||
# app's relative `/imports`, `/data`, ... calls work unchanged.
|
||||
# Production image: the Angular build served by nginx, which proxies the API paths to `webapi`.
|
||||
FROM node:22-slim AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npx ng build --configuration production
|
||||
|
||||
@@ -1,59 +1,16 @@
|
||||
# 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:
|
||||
Interfaz de ISSSTELEON en Angular y Angular Material: conexión e importación de
|
||||
datos (`/conectar`), bitácora de cargas (`/bitacora`), gobernanza y tablero de
|
||||
indicadores (`/indicadores`).
|
||||
|
||||
```bash
|
||||
ng serve
|
||||
npm ci
|
||||
npx ng serve # http://localhost:4200
|
||||
npx ng test --watch=false # pruebas unitarias (Vitest)
|
||||
npx ng build # compilación de producción en dist/WebApp
|
||||
```
|
||||
|
||||
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.
|
||||
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
||||
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
||||
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
||||
|
||||
@@ -31,6 +31,14 @@
|
||||
}
|
||||
],
|
||||
"styles": [
|
||||
"node_modules/@fontsource/roboto/300.css",
|
||||
"node_modules/@fontsource/roboto/400.css",
|
||||
"node_modules/@fontsource/roboto/500.css",
|
||||
"node_modules/@fontsource/rajdhani/600.css",
|
||||
"node_modules/@fontsource/rajdhani/700.css",
|
||||
"node_modules/@fontsource/roboto-mono/400.css",
|
||||
"node_modules/@fontsource/roboto-mono/600.css",
|
||||
"node_modules/material-icons/iconfont/filled.css",
|
||||
"src/styles.scss"
|
||||
]
|
||||
},
|
||||
|
||||
+5
-1
@@ -8,7 +8,11 @@ server {
|
||||
# the ~33% base64 overhead.
|
||||
client_max_body_size 270m;
|
||||
|
||||
location ~ ^/(api|imports|data|cacu|cama|tea|governance|health)(/|$) {
|
||||
gzip on;
|
||||
gzip_types text/css application/javascript application/json image/svg+xml;
|
||||
gzip_min_length 1024;
|
||||
|
||||
location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) {
|
||||
proxy_pass http://webapi:5000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
|
||||
Generated
+37
@@ -16,6 +16,10 @@
|
||||
"@angular/material": "^22.1.7",
|
||||
"@angular/platform-browser": "^22.1.0",
|
||||
"@angular/router": "^22.1.0",
|
||||
"@fontsource/rajdhani": "^5.3.0",
|
||||
"@fontsource/roboto": "^5.3.0",
|
||||
"@fontsource/roboto-mono": "^5.3.0",
|
||||
"material-icons": "^1.13.14",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
@@ -1417,6 +1421,33 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/rajdhani": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/rajdhani/-/rajdhani-5.3.0.tgz",
|
||||
"integrity": "sha512-oBJgSIibWJvVBKseme1JczqPLoDHN97LHti4uh0LjfcJqQoVmnQQlRKIpEjTJV559rmVQ6qbVZZwKwk2wkBTtw==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/roboto": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/roboto/-/roboto-5.3.0.tgz",
|
||||
"integrity": "sha512-BapRJOWYP+LZ21zp+wBQjfpPYKRoxc4LspJ/RLuI+HSMBD5u/X4O+ESDrSvEqDSy0rAl7GwBJ+09mdc16cVQ1Q==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/roboto-mono": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/roboto-mono/-/roboto-mono-5.3.0.tgz",
|
||||
"integrity": "sha512-yhwplHMHW9dCk+1pZuERfcJe+K3rosGVZEoK0XktkxRSqQ9qsipSwwiuW2/8Qmtp9lzu3Ixa/ie4BMH3i8CkZQ==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@harperfast/extended-iterable": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@harperfast/extended-iterable/-/extended-iterable-1.0.3.tgz",
|
||||
@@ -5933,6 +5964,12 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/material-icons": {
|
||||
"version": "1.13.14",
|
||||
"resolved": "https://registry.npmjs.org/material-icons/-/material-icons-1.13.14.tgz",
|
||||
"integrity": "sha512-kZOfc7xCC0rAT8Q3DQixYAeT+tBqZnxkseQtp2bxBxz7q5pMAC+wmit7vJn1g/l7wRU+HEPq23gER4iPjGs5Cg==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
|
||||
@@ -19,6 +19,10 @@
|
||||
"@angular/material": "^22.1.7",
|
||||
"@angular/platform-browser": "^22.1.0",
|
||||
"@angular/router": "^22.1.0",
|
||||
"@fontsource/rajdhani": "^5.3.0",
|
||||
"@fontsource/roboto": "^5.3.0",
|
||||
"@fontsource/roboto-mono": "^5.3.0",
|
||||
"material-icons": "^1.13.14",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
|
||||
+2
-1
@@ -6,5 +6,6 @@
|
||||
"/cacu": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
|
||||
"/cama": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
|
||||
"/tea": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
|
||||
"/governance": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }
|
||||
"/governance": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true },
|
||||
"/reportes": { "target": "http://localhost:5050", "secure": false, "changeOrigin": true }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Covers the shell's header: on an indicators page it carries the platform title and the domain selector; on
|
||||
// the institutional routes it keeps the breadcrumb. The pages are stubs: only the header and the router matter.
|
||||
import { Component } from '@angular/core';
|
||||
import { Location } from '@angular/common';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { App } from './app';
|
||||
import { routes } from './app.routes';
|
||||
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
@Component({ template: 'página', selector: 'app-stub' })
|
||||
class Stub {}
|
||||
|
||||
describe('Encabezado del marco', () => {
|
||||
const rutas = [
|
||||
{ path: '', component: Stub },
|
||||
{ path: 'conectar', component: Stub, data: { workspace: true, breadcrumb: 'Conectar datos' } },
|
||||
{ path: 'gobernanza', component: Stub, data: { workspace: true, breadcrumb: 'Gobernanza de modelos' } },
|
||||
...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, component: Stub, data: { workspace: true, breadcrumb: 'Indicadores', dominio } })),
|
||||
];
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<App>>, router: Router;
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({ imports: [App], providers: [provideRouter(rutas), provideHttpClient(), provideHttpClientTesting()] }).compileComponents();
|
||||
fixture = TestBed.createComponent(App); router = TestBed.inject(Router);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); document.querySelectorAll('.cdk-overlay-container').forEach(e => e.replaceChildren()); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
async function ir(url: string) { await router.navigateByUrl(url); await fixture.whenStable(); fixture.detectChanges(); }
|
||||
const selector = () => root().querySelector('.domain-selector') as HTMLButtonElement | null;
|
||||
async function abrirMenu() {
|
||||
selector()!.click(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
return [...document.querySelectorAll('.mat-mdc-menu-panel a[mat-menu-item]')] as HTMLAnchorElement[];
|
||||
}
|
||||
|
||||
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
|
||||
// Fails if the selector would point at a route the application does not have.
|
||||
const paths = routes.map(r => r.path);
|
||||
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
|
||||
});
|
||||
it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
|
||||
await ir('/indicadores/' + dominio);
|
||||
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
|
||||
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
|
||||
expect(root().querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
|
||||
// The breadcrumb is replaced, not duplicated beside the selector.
|
||||
expect(root().querySelector('.site-header__nav')).toBeNull();
|
||||
expect(root().querySelector('.app-shell--indicadores')).not.toBeNull();
|
||||
});
|
||||
it('el selector tiene nombre accesible con el dominio actual y anuncia un menú', async () => {
|
||||
await ir('/indicadores/cama');
|
||||
expect(selector()!.getAttribute('aria-label')).toBe('Dominio actual: Cáncer de mama. Cambiar dominio');
|
||||
expect(selector()!.getAttribute('aria-haspopup')).toBe('menu');
|
||||
expect(selector()!.tagName).toBe('BUTTON');
|
||||
expect(selector()!.tabIndex).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
|
||||
await ir('/indicadores/cama');
|
||||
const items = await abrirMenu();
|
||||
expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']);
|
||||
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
|
||||
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
|
||||
});
|
||||
it('elegir otro dominio navega por el enrutador, actualiza el selector y deja una entrada en el historial', async () => {
|
||||
await ir('/indicadores/cama');
|
||||
const items = await abrirMenu();
|
||||
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(router.url).toBe('/indicadores/cacu');
|
||||
expect(selector()!.textContent).toContain('CaCu');
|
||||
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
|
||||
const ubicacion = TestBed.inject(Location);
|
||||
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
|
||||
expect(ubicacion.path()).toBe('/indicadores/cama');
|
||||
});
|
||||
it.each(['/', '/conectar', '/gobernanza'])('en %s conserva el encabezado institucional sin selector', async url => {
|
||||
// Fails if the indicators header leaks into the institutional routes.
|
||||
await ir(url);
|
||||
expect(selector()).toBeNull();
|
||||
expect(root().querySelector('.platform-title')).toBeNull();
|
||||
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
|
||||
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
|
||||
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
|
||||
});
|
||||
it('una ruta parecida que no es de indicadores no activa el selector', async () => {
|
||||
await router.navigateByUrl('/'); fixture.detectChanges();
|
||||
expect(selector()).toBeNull();
|
||||
});
|
||||
});
|
||||
+16
-6
@@ -1,15 +1,25 @@
|
||||
<div class="app-shell" [class.app-shell--workspace]="workspace()">
|
||||
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
|
||||
<header class="site-header">
|
||||
<div class="site-header__content">
|
||||
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
</a>
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
@if (activeDomain(); as domain) {
|
||||
<span class="platform-title">{{ title }}</span>
|
||||
@defer (on immediate) {
|
||||
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
|
||||
} @placeholder {
|
||||
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
|
||||
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
|
||||
}
|
||||
</nav>
|
||||
} @else {
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
||||
@@ -20,6 +20,12 @@ export const routes: Routes = [
|
||||
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
|
||||
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
|
||||
},
|
||||
{
|
||||
path: 'bitacora',
|
||||
title: 'Bitácora de cargas | ISSSTELEON',
|
||||
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
|
||||
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
|
||||
},
|
||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
...DOMINIOS.map(dominio => ({
|
||||
path: `indicadores/${dominio}`,
|
||||
|
||||
@@ -103,3 +103,26 @@
|
||||
width: 155px;
|
||||
}
|
||||
}
|
||||
|
||||
.platform-title {
|
||||
color: var(--color-text);
|
||||
font-family: var(--issste-font-heading);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.15;
|
||||
margin-inline-start: var(--issste-space-4);
|
||||
margin-inline-end: auto;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.domain-selector--espera {
|
||||
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
|
||||
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||
}
|
||||
|
||||
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
||||
@media (max-width: 599px) {
|
||||
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
||||
.app-shell--indicadores .brand { margin-inline-end: auto; }
|
||||
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
|
||||
}
|
||||
|
||||
@@ -30,6 +30,17 @@ describe('App', () => {
|
||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('an indicators page shows the platform title and a menu named after its domain', async () => {
|
||||
// Fails if the header stops naming the domain or offers the current one among the others.
|
||||
const page = await render('/indicadores/cama');
|
||||
expect(page.querySelector('.platform-title')?.textContent).toContain('Plataforma de Indicadores');
|
||||
expect(page.querySelector('.domain-selector')?.textContent).toContain('Cáncer de mama');
|
||||
(page.querySelector('.domain-selector') as HTMLButtonElement).click();
|
||||
const options = Array.from(document.querySelectorAll('.mat-mdc-menu-panel a')).map(a => a.textContent?.trim());
|
||||
expect(options).toEqual(['TEA', 'CaCu']);
|
||||
expect(page.querySelector('.site-header__crumb')).toBeNull();
|
||||
});
|
||||
|
||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||
const page = await render('/conectar');
|
||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||
|
||||
+12
-1
@@ -2,9 +2,11 @@ import { Component, computed, inject } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||
import { filter, map } from 'rxjs';
|
||||
import { DomainSelector } from './domain-selector';
|
||||
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
@Component({
|
||||
imports: [RouterLink, RouterOutlet],
|
||||
imports: [RouterLink, RouterOutlet, DomainSelector],
|
||||
selector: 'app-root',
|
||||
styleUrl: './app.scss',
|
||||
templateUrl: './app.html',
|
||||
@@ -28,4 +30,13 @@ export class App {
|
||||
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
|
||||
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
|
||||
readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
|
||||
|
||||
protected readonly title = 'Plataforma de Indicadores';
|
||||
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
|
||||
private readonly url = toSignal(this.router.events.pipe(
|
||||
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
|
||||
/** On an indicators page the header names its domain and switches to the others. */
|
||||
protected readonly activeDomain = computed(() =>
|
||||
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
|
||||
protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain()));
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ export interface ImportSourcePayload extends SourceLocator {
|
||||
defaults?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// -- documents -----------------------------------------------------------------
|
||||
// Clinical documents
|
||||
|
||||
export type OcrMode = 'auto' | 'always' | 'never';
|
||||
|
||||
@@ -223,6 +223,9 @@ export interface CommitSourceResult {
|
||||
export interface BatchResult {
|
||||
ok: boolean;
|
||||
results: CommitSourceResult[];
|
||||
/** Id of this attempt in the aggregate import log (`/reportes/importaciones`). */
|
||||
audit_id?: string;
|
||||
indicadores_en_recalculo?: boolean;
|
||||
}
|
||||
|
||||
export interface DataPage {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
/** Base64 of a File's bytes, for JSON endpoints that carry a file. */
|
||||
export async function fileToBase64(file: Blob): Promise<string> {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const chunk = 0x8000;
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i += chunk) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||
}
|
||||
return btoa(binary);
|
||||
export function fileToBase64(file: Blob): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const dataUrl = reader.result as string;
|
||||
resolve(dataUrl.slice(dataUrl.indexOf(',') + 1));
|
||||
};
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
@if (store.connections().length === 0) {
|
||||
<div class="pane__empty">
|
||||
<app-file-dropzone [accept]="store.acceptedExtensions()" [multiple]="true" (filesChange)="onFilesDropped($event)"></app-file-dropzone>
|
||||
<app-file-dropzone [accept]="store.acceptedExtensions()" [keepSelection]="false" (filesChange)="onFilesDropped($event)"></app-file-dropzone>
|
||||
<button mat-stroked-button type="button" class="pane__db-button" (click)="addConnection.emit()">
|
||||
<mat-icon aria-hidden="true">storage</mat-icon>Conectar una base de datos
|
||||
</button>
|
||||
|
||||
@@ -69,7 +69,7 @@
|
||||
}
|
||||
}
|
||||
</p>
|
||||
<app-file-dropzone [accept]="entry()?.connector?.extensions ?? []" [multiple]="true" (filesChange)="files.set($event)"></app-file-dropzone>
|
||||
<app-file-dropzone [accept]="entry()?.connector?.extensions ?? []" (filesChange)="files.set($event)"></app-file-dropzone>
|
||||
}
|
||||
|
||||
@case ('database') {
|
||||
|
||||
@@ -83,10 +83,8 @@ export class ConnectorGalleryDialog {
|
||||
this.categories.filter((c) => c.id === 'all' || this.entries().some((entry) => entry.category === c.id)),
|
||||
);
|
||||
|
||||
// -- files --
|
||||
readonly files = signal<File[]>([]);
|
||||
|
||||
// -- database --
|
||||
readonly serverForm = this.formBuilder.nonNullable.group({
|
||||
host: ['', Validators.required],
|
||||
port: [null as number | null],
|
||||
|
||||
@@ -101,8 +101,6 @@ export class DocumentReviewDialog {
|
||||
});
|
||||
}
|
||||
|
||||
// -- settings ------------------------------------------------------------
|
||||
|
||||
updateSettings(patch: Partial<DocumentSettings>): void {
|
||||
this.settings.update((settings) => ({ ...settings, ...patch }));
|
||||
}
|
||||
@@ -128,8 +126,6 @@ export class DocumentReviewDialog {
|
||||
});
|
||||
}
|
||||
|
||||
// -- records and values ------------------------------------------------------
|
||||
|
||||
select(index: number): void {
|
||||
this.selectedIndex.set(index);
|
||||
this.page.set(null);
|
||||
@@ -171,8 +167,6 @@ export class DocumentReviewDialog {
|
||||
return record.conflicts.find((conflict) => conflict.field === field) ?? null;
|
||||
}
|
||||
|
||||
// -- pages and images ----------------------------------------------------------
|
||||
|
||||
thumbnailKey(image: DocumentImage): string {
|
||||
return `${image.document}|${image.page_number}|${image.bbox.join(',')}`;
|
||||
}
|
||||
@@ -199,8 +193,6 @@ export class DocumentReviewDialog {
|
||||
});
|
||||
}
|
||||
|
||||
// -- close -------------------------------------------------------------------------
|
||||
|
||||
apply(): void {
|
||||
this.table.configure(this.settings(), { [this.target.key]: this.overrides() });
|
||||
this.dialogRef.close(true);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<mat-icon class="dropzone__icon" aria-hidden="true">cloud_upload</mat-icon>
|
||||
<p class="dropzone__title">Arrastra tus archivos aquí</p>
|
||||
<p class="dropzone__formats">{{ formatsLabel }}</p>
|
||||
<input #fileInput class="visually-hidden" type="file" [multiple]="multiple" [attr.accept]="acceptAttribute" aria-label="Seleccionar archivos" (change)="onFileSelection($event)" />
|
||||
<input #fileInput class="visually-hidden" type="file" [multiple]="multiple()" [attr.accept]="acceptAttribute" aria-label="Seleccionar archivos" (change)="onFileSelection($event)" />
|
||||
<button class="upload-action upload-action--outlined select-files-button" mat-stroked-button type="button" (click)="fileInput.click()">
|
||||
<mat-icon aria-hidden="true">upload_file</mat-icon>
|
||||
<span>Seleccionar archivos</span>
|
||||
|
||||
@@ -2,8 +2,10 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { FileDropzone } from './file-dropzone';
|
||||
|
||||
describe('FileDropzone', () => {
|
||||
function createFixture() {
|
||||
function createFixture(keepSelection = true) {
|
||||
const fixture = TestBed.createComponent(FileDropzone);
|
||||
fixture.componentRef.setInput('accept', ['xlsx', 'csv', 'json', 'pdf']);
|
||||
fixture.componentRef.setInput('keepSelection', keepSelection);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
@@ -81,7 +83,27 @@ describe('FileDropzone', () => {
|
||||
expect(emitted.at(-1)).toEqual([]);
|
||||
});
|
||||
|
||||
it('honors a custom accept input, keeping pdf available by default', () => {
|
||||
it('without keepSelection emits only each new batch and lists nothing', () => {
|
||||
const fixture = createFixture(false);
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const component = fixture.componentInstance;
|
||||
const emitted: File[][] = [];
|
||||
component.filesChange.subscribe((files) => emitted.push(files));
|
||||
const drop = (files: File[]) =>
|
||||
component.onDrop({ preventDefault: () => undefined, dataTransfer: { files } } as unknown as DragEvent);
|
||||
|
||||
const first = new File(['a'], 'uno.csv');
|
||||
const second = new File(['b'], 'dos.csv');
|
||||
drop([first]);
|
||||
drop([second]);
|
||||
drop([new File(['x'], 'malo.docx')]);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(emitted).toEqual([[first], [second]]);
|
||||
expect(compiled.querySelectorAll('.file-row')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('honors a custom accept input', () => {
|
||||
const fixture = createFixture();
|
||||
expect(fixture.componentInstance.allowedExtensions.has('pdf')).toBe(true);
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Component, EventEmitter, Input, Output, signal } from '@angular/core';
|
||||
import { Component, input, output, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
/** Drag-and-drop and file-picker area that collects a validated list of files. */
|
||||
/**
|
||||
* Drag-and-drop and file-picker area that validates files by extension and size.
|
||||
* With `keepSelection` it keeps and emits the whole selected list; without it,
|
||||
* it emits only each batch of newly accepted files and keeps nothing.
|
||||
*/
|
||||
@Component({
|
||||
imports: [MatButtonModule, MatIconModule],
|
||||
selector: 'app-file-dropzone',
|
||||
@@ -10,9 +14,10 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
templateUrl: './file-dropzone.html',
|
||||
})
|
||||
export class FileDropzone {
|
||||
@Input() accept: string[] = ['xlsx', 'csv', 'json', 'pdf'];
|
||||
@Input() multiple = true;
|
||||
@Output() readonly filesChange = new EventEmitter<File[]>();
|
||||
readonly accept = input.required<string[]>();
|
||||
readonly multiple = input(true);
|
||||
readonly keepSelection = input(true);
|
||||
readonly filesChange = output<File[]>();
|
||||
|
||||
readonly files = signal<File[]>([]);
|
||||
readonly fileMessages = signal<string[]>([]);
|
||||
@@ -21,15 +26,15 @@ export class FileDropzone {
|
||||
private dragDepth = 0;
|
||||
|
||||
get allowedExtensions(): Set<string> {
|
||||
return new Set(this.accept.map((extension) => extension.toLowerCase()));
|
||||
return new Set(this.accept().map((extension) => extension.toLowerCase()));
|
||||
}
|
||||
|
||||
get acceptAttribute(): string {
|
||||
return this.accept.map((extension) => `.${extension}`).join(',');
|
||||
return this.accept().map((extension) => `.${extension}`).join(',');
|
||||
}
|
||||
|
||||
get formatsLabel(): string {
|
||||
return this.accept.map((extension) => extension.toUpperCase()).join(' · ');
|
||||
return this.accept().map((extension) => extension.toUpperCase()).join(' · ');
|
||||
}
|
||||
|
||||
onFileSelection(event: Event): void {
|
||||
@@ -88,7 +93,8 @@ export class FileDropzone {
|
||||
|
||||
private addFiles(incomingFiles: File[]): void {
|
||||
const messages: string[] = [];
|
||||
const accepted = this.multiple ? [...this.files()] : [];
|
||||
const kept = this.keepSelection() && this.multiple() ? [...this.files()] : [];
|
||||
const accepted = [...kept];
|
||||
|
||||
for (const file of incomingFiles) {
|
||||
const extension = this.extensionOf(file.name);
|
||||
@@ -104,16 +110,20 @@ export class FileDropzone {
|
||||
messages.push(`${file.name} ya se encuentra seleccionado.`);
|
||||
continue;
|
||||
}
|
||||
if (!this.multiple) {
|
||||
if (!this.multiple()) {
|
||||
accepted.length = 0;
|
||||
}
|
||||
accepted.push(file);
|
||||
if (!this.multiple) break;
|
||||
if (!this.multiple()) break;
|
||||
}
|
||||
|
||||
this.files.set(accepted);
|
||||
this.fileMessages.set(messages);
|
||||
this.filesChange.emit(accepted);
|
||||
if (this.keepSelection()) {
|
||||
this.files.set(accepted);
|
||||
this.filesChange.emit(accepted);
|
||||
} else if (accepted.length > kept.length) {
|
||||
this.filesChange.emit(accepted.slice(kept.length));
|
||||
}
|
||||
}
|
||||
|
||||
private extensionOf(fileName: string): string {
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
{{ o.merged | number }} combinadas con registros de otras fuentes@if (o.warnings) {, {{ o.warnings | number }} valor(es) en desacuerdo}.
|
||||
}
|
||||
</p>
|
||||
@if (o.created + o.updated > 0) {
|
||||
<p class="lead">Los indicadores se recalcularán automáticamente. El avance y el resumen de esta carga pueden consultarse en la Bitácora de cargas.</p>
|
||||
}
|
||||
}
|
||||
|
||||
<table mat-table [dataSource]="flows()" class="flows">
|
||||
@@ -49,7 +52,7 @@
|
||||
<ng-container matColumnDef="outcome">
|
||||
<th mat-header-cell *matHeaderCellDef>Resultado</th>
|
||||
<td mat-cell *matCellDef="let flow">
|
||||
@if (resultOf(flow); as result) {
|
||||
@if (flow.result(); as result) {
|
||||
+{{ result.created }} · ↻{{ result.updated }} · ✕{{ result.rejected }}@if (result.merged) { · ⧉{{ result.merged }} }
|
||||
} @else {
|
||||
—
|
||||
|
||||
@@ -37,12 +37,7 @@ export class LoadDialog implements OnInit {
|
||||
/** With merging, rows incomplete on their own may be completed by another source. */
|
||||
readonly canLoad = computed(() => this.totals().valid > 0 || (this.store.mergeDuplicates() && this.totals().rows > 0));
|
||||
|
||||
/**
|
||||
* The flows the next batch would write. Reactive to the merge checkbox
|
||||
* while nothing has loaded yet, so ticking it reveals the flow it
|
||||
* completes; frozen the moment a batch starts, so the results table
|
||||
* keeps listing exactly what was sent.
|
||||
*/
|
||||
/** The flows the next batch writes; frozen once it starts so the results match what was sent. */
|
||||
private readonly _frozenFlows = signal<ImportFlow[] | null>(null);
|
||||
readonly flows = computed(() => this._frozenFlows() ?? this.store.submittableFlows());
|
||||
readonly skipped = computed(() => this.store.flows().filter((flow) => !this.flows().includes(flow) && !flow.canSubmit));
|
||||
@@ -85,7 +80,7 @@ export class LoadDialog implements OnInit {
|
||||
this.store.setOnConflict(strategy);
|
||||
}
|
||||
|
||||
/** Toggling may bring an until-now-skipped flow into `flows()`; preview its rows too. */
|
||||
/** Merging can add flows to the batch; validate them so their rows show up in the preview. */
|
||||
toggleMerge(merge: boolean): void {
|
||||
this.store.setMergeDuplicates(merge);
|
||||
Promise.all(this.flows().filter((flow) => !flow.validation()).map((flow) => this.store.validate(flow)));
|
||||
@@ -99,8 +94,4 @@ export class LoadDialog implements OnInit {
|
||||
explore(): void {
|
||||
this.dialogRef.close('explore');
|
||||
}
|
||||
|
||||
resultOf(flow: ImportFlow) {
|
||||
return flow.result();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@ import { FileConnection } from './file-source';
|
||||
import { PdfConnection } from './pdf-source';
|
||||
|
||||
/** Turns the files chosen for one source kind into workspace connections. */
|
||||
export type ConnectionFactory = (files: File[]) => DataConnection[];
|
||||
type ConnectionFactory = (files: File[]) => DataConnection[];
|
||||
|
||||
// Adding a file source on the client is one `DataConnection` subclass and one entry here.
|
||||
const FACTORIES = new Map<SourceType, ConnectionFactory>([
|
||||
['csv', (files) => files.map((file) => new FileConnection(file, 'csv'))],
|
||||
['excel', (files) => files.map((file) => new FileConnection(file, 'excel'))],
|
||||
@@ -18,11 +19,6 @@ const FACTORIES = new Map<SourceType, ConnectionFactory>([
|
||||
['document', (files) => [new DocumentConnection(files)]],
|
||||
]);
|
||||
|
||||
/** Adding a file source on the client is one `DataConnection` subclass and one call here. */
|
||||
export function registerConnectionFactory(kind: SourceType, factory: ConnectionFactory): void {
|
||||
FACTORIES.set(kind, factory);
|
||||
}
|
||||
|
||||
export function connectionsFor(kind: SourceType, files: File[]): DataConnection[] {
|
||||
const factory = FACTORIES.get(kind);
|
||||
return factory && files.length ? factory(files) : [];
|
||||
|
||||
@@ -134,12 +134,7 @@ export class ImportFlow {
|
||||
return !['loading', 'error', 'incomplete'].includes(this.status());
|
||||
}
|
||||
|
||||
/**
|
||||
* Belongs in the next load: complete and not already written. A loaded
|
||||
* flow stays out of later batches (re-sending it would duplicate rows in
|
||||
* tables without a natural key) until it's edited, since any edit clears
|
||||
* its result.
|
||||
*/
|
||||
/** Complete and not yet written; editing a loaded flow clears its result and makes it pending again. */
|
||||
get pendingLoad(): boolean {
|
||||
return this.canSubmit && this.status() !== 'loaded';
|
||||
}
|
||||
@@ -162,7 +157,7 @@ export class ImportFlow {
|
||||
);
|
||||
}
|
||||
|
||||
// -- mapping edits (every one invalidates the last validation) -----------
|
||||
// Every mapping edit invalidates the last validation.
|
||||
|
||||
map(source: string, field: string): void {
|
||||
this.mapping.assign(source, field);
|
||||
@@ -210,7 +205,6 @@ export class ImportFlow {
|
||||
return Object.fromEntries(Object.entries(this._defaults()).filter(([, value]) => value.trim() !== ''));
|
||||
}
|
||||
|
||||
// -- backend round trips ---------------------------------------------------
|
||||
|
||||
async toPayload(): Promise<ImportSourcePayload> {
|
||||
const locator = await this.table.locator(this.target.key);
|
||||
|
||||
@@ -52,7 +52,6 @@ const SQL_DIALECT_LABELS: Record<string, string> = {
|
||||
mariadb: 'MariaDB',
|
||||
postgresql: 'PostgreSQL',
|
||||
mssql: 'SQL Server',
|
||||
oracle: 'Oracle',
|
||||
sqlite: 'SQLite',
|
||||
};
|
||||
|
||||
|
||||
@@ -75,12 +75,7 @@ export class ConnectWorkspaceStore {
|
||||
/** A batch writes to one domain's database, so the domain can only change while there are no flows. */
|
||||
readonly domainLocked = computed(() => this._flows().length > 0);
|
||||
|
||||
/**
|
||||
* Flows with a known target and a natural key, not still loading/erroring
|
||||
* and not already written — candidates to combine by `mergeDuplicates`,
|
||||
* complete or not (a source missing a required field may still supply
|
||||
* others a sibling source lacks).
|
||||
*/
|
||||
/** Unwritten flows into a keyed target: what `mergeDuplicates` may combine, complete or not. */
|
||||
private readonly mergeCandidateFlows = computed(() =>
|
||||
this._flows().filter((flow) => !!flow.target.conflict_fields && !['loading', 'error', 'loaded'].includes(flow.status())),
|
||||
);
|
||||
@@ -97,13 +92,7 @@ export class ConnectWorkspaceStore {
|
||||
return new Set([...counts].filter(([, count]) => count > 1).map(([key]) => key));
|
||||
});
|
||||
|
||||
/**
|
||||
* Flows the next batch will write. Normally just the complete ones; with
|
||||
* `mergeDuplicates` on, a flow missing a required field joins them too
|
||||
* when another flow targets the same keyed entity — the gap may be
|
||||
* exactly what that other source supplies, so the batch combines them
|
||||
* before validating instead of dropping the incomplete one silently.
|
||||
*/
|
||||
/** Flows the next batch writes: the complete ones, plus incomplete ones another flow may complete when merging. */
|
||||
readonly submittableFlows = computed(() => {
|
||||
const complete = this._flows().filter((flow) => flow.pendingLoad);
|
||||
if (!this._mergeDuplicates()) return complete;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
:host { display: contents; }
|
||||
.domain-selector {
|
||||
flex: 0 0 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; }
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Component, input } from '@angular/core';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatMenuModule } from '@angular/material/menu';
|
||||
import { Dominio } from './features/indicadores/indicadores.models';
|
||||
|
||||
/** The header's domain menu. Loaded deferred: Material's menu and overlay are not needed by the institutional routes. */
|
||||
@Component({
|
||||
selector: 'app-domain-selector',
|
||||
imports: [RouterLink, MatButtonModule, MatMenuModule],
|
||||
template: `
|
||||
<button class="domain-selector" mat-button [matMenuTriggerFor]="domainMenu"
|
||||
[attr.aria-label]="'Dominio actual: ' + labels()[actual()] + '. Cambiar dominio'">
|
||||
{{ labels()[actual()] }} <span aria-hidden="true">▾</span>
|
||||
</button>
|
||||
<mat-menu #domainMenu="matMenu" aria-label="Cambiar dominio de indicadores">
|
||||
@for (option of otros(); track option) {
|
||||
<a mat-menu-item [routerLink]="['/indicadores', option]">{{ labels()[option] }}</a>
|
||||
}
|
||||
</mat-menu>
|
||||
`,
|
||||
styleUrl: './domain-selector.scss',
|
||||
})
|
||||
export class DomainSelector {
|
||||
readonly actual = input.required<Dominio>();
|
||||
readonly otros = input.required<readonly Dominio[]>();
|
||||
readonly labels = input.required<Record<Dominio, string>>();
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number;
|
||||
// Filters a list announces in `filtros_disponibles`, by key.
|
||||
filtros?: Record<string, string>; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
export interface SeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
|
||||
@@ -16,11 +16,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
||||
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
||||
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
||||
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
|
||||
it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
|
||||
respond();
|
||||
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
|
||||
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
|
||||
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
|
||||
expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
|
||||
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
||||
fixture.componentInstance.apply();
|
||||
@@ -39,12 +38,18 @@ describe('Seguimiento CaCu con contrato 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:last-child')?.textContent).toBe('No disponible');
|
||||
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();
|
||||
});
|
||||
@@ -86,13 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
it.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();
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
[
|
||||
{
|
||||
"id": "cama_dias_resultado_diagnostico",
|
||||
"titulo": "Tiempo de resultado a diagnóstico",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C3r",
|
||||
"unidad": "examen",
|
||||
"sentido": "decrease",
|
||||
"tipos_periodo": [
|
||||
"semestre",
|
||||
"mes"
|
||||
],
|
||||
"figuras": [
|
||||
"fig_c3r_caja"
|
||||
],
|
||||
"estratos": [],
|
||||
"filtros": []
|
||||
},
|
||||
{
|
||||
"id": "cama_histopatologia_birads",
|
||||
"titulo": "Histopatología por BI-RADS",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"sentido": null,
|
||||
"tipos_periodo": [
|
||||
"semestre",
|
||||
"mes"
|
||||
],
|
||||
"figuras": [
|
||||
"fig_c2_barras",
|
||||
"fig_c2_donas"
|
||||
],
|
||||
"estratos": [
|
||||
"birads"
|
||||
],
|
||||
"filtros": []
|
||||
},
|
||||
{
|
||||
"id": "cama_tasa_deteccion_histopatologica",
|
||||
"titulo": "Detección histopatológica",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C1",
|
||||
"unidad": "examen",
|
||||
"sentido": null,
|
||||
"tipos_periodo": [
|
||||
"semestre",
|
||||
"mes"
|
||||
],
|
||||
"figuras": [
|
||||
"fig_c1_puntos"
|
||||
],
|
||||
"estratos": [],
|
||||
"filtros": []
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"id": "cama_dias_resultado_diagnostico",
|
||||
"titulo": "Tiempo de resultado a diagnóstico",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C3r",
|
||||
"unidad": "examen",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Días de resultado a diagnóstico"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [
|
||||
"Sin nota hasta el corte no hay observación. Convención provisional."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 71,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2026-11-12",
|
||||
"generado_en": "2026-11-12T17:00:26.219496+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||
"parametros_sha": "5e4badce17afe0141e8296c9edd88ff1ce50a21c8c278d1aad5327069830d251",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"fecha_corte": "2026-11-12",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"n": null,
|
||||
"mediana": null,
|
||||
"q1": null,
|
||||
"q3": null,
|
||||
"n_sin_evento": 0,
|
||||
"n_excluido": 0,
|
||||
"suprimido": 1,
|
||||
"unidad": "dias"
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"id": "cama_dias_resultado_diagnostico",
|
||||
"titulo": "Tiempo de resultado a diagnóstico",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C3r",
|
||||
"unidad": "examen",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Días de resultado a diagnóstico"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [
|
||||
"Sin nota hasta el corte no hay observación. Convención provisional."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 71,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2026-11-12",
|
||||
"generado_en": "2026-11-12T17:00:38.264922+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7",
|
||||
"parametros_sha": "f26ecdc2fcef0aa015f8997b7c1aa2053678cb86ca9cff9b1524efaf000971ad",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"fecha_corte": "2026-11-12",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"n": 4,
|
||||
"mediana": 6.5,
|
||||
"q1": 2.25,
|
||||
"q3": 12.5,
|
||||
"n_sin_evento": 0,
|
||||
"n_excluido": 1,
|
||||
"suprimido": 0,
|
||||
"unidad": "dias"
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
{
|
||||
"id": "cama_histopatologia_birads",
|
||||
"titulo": "Histopatología por BI-RADS",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": "birads",
|
||||
"valores_estrato": [
|
||||
"BIRADS_4",
|
||||
"BIRADS_4A",
|
||||
"BIRADS_4B",
|
||||
"BIRADS_4C",
|
||||
"BIRADS_5",
|
||||
"BIRADS_6"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"BIRADS_4": "BI-RADS 4 sin subtipo",
|
||||
"BIRADS_4A": "BI-RADS 4A",
|
||||
"BIRADS_4B": "BI-RADS 4B",
|
||||
"BIRADS_4C": "BI-RADS 4C",
|
||||
"BIRADS_5": "BI-RADS 5",
|
||||
"BIRADS_6": "BI-RADS 6"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"BENIGNO": {
|
||||
"etiqueta": "Benigno",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_MALIGNO",
|
||||
"gravedad": 1
|
||||
},
|
||||
"RIESGO_B3": {
|
||||
"etiqueta": "Lesión de riesgo (B3)",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_MALIGNO",
|
||||
"gravedad": 2
|
||||
},
|
||||
"IN_SITU": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#D9822B",
|
||||
"grupo": "MALIGNO",
|
||||
"gravedad": 3
|
||||
},
|
||||
"INVASOR": {
|
||||
"etiqueta": "Carcinoma invasor",
|
||||
"color": "#B5482E",
|
||||
"grupo": "MALIGNO",
|
||||
"gravedad": 4
|
||||
},
|
||||
"SIN_BIOPSIA": {
|
||||
"etiqueta": "Sin biopsia reportada",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": null,
|
||||
"gravedad": null
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_MALIGNO": "No maligno",
|
||||
"MALIGNO": "Maligno",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 141,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2025-12-31",
|
||||
"generado_en": "2026-11-12T16:33:37.621606+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [
|
||||
"BENIGNO",
|
||||
"RIESGO_B3",
|
||||
"IN_SITU",
|
||||
"INVASOR"
|
||||
],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"fecha_corte": "2025-12-31",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 2,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 0,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "INVASOR",
|
||||
"n": 2,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "BENIGNO",
|
||||
"n": 1,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 1,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "IN_SITU",
|
||||
"n": 1,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "INVASOR",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4A",
|
||||
"n": 7,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4B",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_4C",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_5",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "BIRADS_6",
|
||||
"n": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
{
|
||||
"id": "cama_histopatologia_birads",
|
||||
"titulo": "Histopatología por BI-RADS",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"BENIGNO": {
|
||||
"etiqueta": "Benigno",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_MALIGNO",
|
||||
"gravedad": 1
|
||||
},
|
||||
"RIESGO_B3": {
|
||||
"etiqueta": "Lesión de riesgo (B3)",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_MALIGNO",
|
||||
"gravedad": 2
|
||||
},
|
||||
"IN_SITU": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#D9822B",
|
||||
"grupo": "MALIGNO",
|
||||
"gravedad": 3
|
||||
},
|
||||
"INVASOR": {
|
||||
"etiqueta": "Carcinoma invasor",
|
||||
"color": "#B5482E",
|
||||
"grupo": "MALIGNO",
|
||||
"gravedad": 4
|
||||
},
|
||||
"SIN_BIOPSIA": {
|
||||
"etiqueta": "Sin biopsia reportada",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": null,
|
||||
"gravedad": null
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_MALIGNO": "No maligno",
|
||||
"MALIGNO": "Maligno",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 141,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2025-12-31",
|
||||
"generado_en": "2026-11-12T16:33:37.621606+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [
|
||||
"BENIGNO",
|
||||
"RIESGO_B3",
|
||||
"IN_SITU",
|
||||
"INVASOR"
|
||||
],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"fecha_corte": "2025-12-31",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "BENIGNO",
|
||||
"n": 7,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "RIESGO_B3",
|
||||
"n": 5,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "IN_SITU",
|
||||
"n": 6,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "INVASOR",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "SIN_BIOPSIA",
|
||||
"n": 6,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 6,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
{
|
||||
"campo_ventana": "mastografia_fecha",
|
||||
"columnas": [
|
||||
{
|
||||
"clave": "id_seudonimo",
|
||||
"etiqueta": "Identificador seudónimo"
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad"
|
||||
},
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento"
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "mastografia_fecha",
|
||||
"etiqueta": "Fecha"
|
||||
}
|
||||
],
|
||||
"etiqueta": "Última mastografía"
|
||||
},
|
||||
{
|
||||
"clave": "biopsia",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "biopsia_fecha",
|
||||
"etiqueta": "Fecha de biopsia"
|
||||
}
|
||||
],
|
||||
"etiqueta": "Resultado histopatológico"
|
||||
},
|
||||
{
|
||||
"clave": "dias_mastografia_diagnostico",
|
||||
"etiqueta": "Días de mastografía a diagnóstico"
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad"
|
||||
}
|
||||
],
|
||||
"corte": "2026-10-20",
|
||||
"filtros": {
|
||||
"birads": null,
|
||||
"estatus": null,
|
||||
"grupo_edad": null,
|
||||
"prioridad": null
|
||||
},
|
||||
"filtros_disponibles": [
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "PENDIENTE_BIOPSIA",
|
||||
"etiqueta": "Pendiente de biopsia"
|
||||
},
|
||||
{
|
||||
"codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"etiqueta": "Biopsia sin resultado"
|
||||
},
|
||||
{
|
||||
"codigo": "CANCER_CONFIRMADO",
|
||||
"etiqueta": "Cáncer confirmado"
|
||||
},
|
||||
{
|
||||
"codigo": "BENIGNO",
|
||||
"etiqueta": "Benigno, regresa a tamizaje"
|
||||
},
|
||||
{
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"etiqueta": "Categoría BI-RADS",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "BIRADS_4A",
|
||||
"etiqueta": "BI-RADS 4A"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4B",
|
||||
"etiqueta": "BI-RADS 4B"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4C",
|
||||
"etiqueta": "BI-RADS 4C"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_5",
|
||||
"etiqueta": "BI-RADS 5"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_6",
|
||||
"etiqueta": "BI-RADS 6"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "40-49",
|
||||
"etiqueta": "40-49"
|
||||
},
|
||||
{
|
||||
"codigo": "50-59",
|
||||
"etiqueta": "50-59"
|
||||
},
|
||||
{
|
||||
"codigo": "60-69",
|
||||
"etiqueta": "60-69"
|
||||
},
|
||||
{
|
||||
"codigo": "70+",
|
||||
"etiqueta": "70+"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "ALTA",
|
||||
"etiqueta": "Alta"
|
||||
},
|
||||
{
|
||||
"codigo": "MEDIA",
|
||||
"etiqueta": "Media"
|
||||
},
|
||||
{
|
||||
"codigo": "BAJA",
|
||||
"etiqueta": "Baja"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"id_seudonimo": "M-0001",
|
||||
"mastografia_fecha": "2026-10-15",
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-10-18",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"id_seudonimo": "M-0002",
|
||||
"mastografia_fecha": "2026-10-15",
|
||||
"prioridad": "Media",
|
||||
"prioridad_codigo": "MEDIA"
|
||||
},
|
||||
{
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-09-10",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"dias_mastografia_diagnostico": 16,
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"id_seudonimo": "M-0003",
|
||||
"mastografia_fecha": "2026-09-01",
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-08-22",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"dias_mastografia_diagnostico": 20,
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"grupo_edad": "70+",
|
||||
"grupo_edad_codigo": "70+",
|
||||
"id_seudonimo": "M-0004",
|
||||
"mastografia_fecha": "2026-08-15",
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"birads": "BI-RADS 6",
|
||||
"birads_codigo": "BIRADS_6",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"id_seudonimo": "M-0005",
|
||||
"mastografia_fecha": "2026-07-21",
|
||||
"prioridad": "Media",
|
||||
"prioridad_codigo": "MEDIA"
|
||||
}
|
||||
],
|
||||
"paginacion": {
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"total_items": 5,
|
||||
"total_pages": 1
|
||||
},
|
||||
"simulado": true,
|
||||
"ventana": {
|
||||
"desde": "2026-07-21",
|
||||
"hasta": "2026-10-20",
|
||||
"meses": 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
{
|
||||
"campo_ventana": "mastografia_fecha",
|
||||
"columnas": [
|
||||
{
|
||||
"clave": "id_seudonimo",
|
||||
"etiqueta": "Identificador seudónimo"
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad"
|
||||
},
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento"
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "mastografia_fecha",
|
||||
"etiqueta": "Fecha"
|
||||
}
|
||||
],
|
||||
"etiqueta": "Última mastografía"
|
||||
},
|
||||
{
|
||||
"clave": "biopsia",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "biopsia_fecha",
|
||||
"etiqueta": "Fecha de biopsia"
|
||||
}
|
||||
],
|
||||
"etiqueta": "Resultado histopatológico"
|
||||
},
|
||||
{
|
||||
"clave": "dias_mastografia_diagnostico",
|
||||
"etiqueta": "Días de mastografía a diagnóstico"
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad"
|
||||
}
|
||||
],
|
||||
"corte": "2026-10-20",
|
||||
"filtros": {
|
||||
"birads": null,
|
||||
"estatus": null,
|
||||
"grupo_edad": null,
|
||||
"prioridad": "ALTA"
|
||||
},
|
||||
"filtros_disponibles": [
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "PENDIENTE_BIOPSIA",
|
||||
"etiqueta": "Pendiente de biopsia"
|
||||
},
|
||||
{
|
||||
"codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"etiqueta": "Biopsia sin resultado"
|
||||
},
|
||||
{
|
||||
"codigo": "CANCER_CONFIRMADO",
|
||||
"etiqueta": "Cáncer confirmado"
|
||||
},
|
||||
{
|
||||
"codigo": "BENIGNO",
|
||||
"etiqueta": "Benigno, regresa a tamizaje"
|
||||
},
|
||||
{
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"etiqueta": "Categoría BI-RADS",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "BIRADS_4A",
|
||||
"etiqueta": "BI-RADS 4A"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4B",
|
||||
"etiqueta": "BI-RADS 4B"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4C",
|
||||
"etiqueta": "BI-RADS 4C"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_5",
|
||||
"etiqueta": "BI-RADS 5"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_6",
|
||||
"etiqueta": "BI-RADS 6"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "40-49",
|
||||
"etiqueta": "40-49"
|
||||
},
|
||||
{
|
||||
"codigo": "50-59",
|
||||
"etiqueta": "50-59"
|
||||
},
|
||||
{
|
||||
"codigo": "60-69",
|
||||
"etiqueta": "60-69"
|
||||
},
|
||||
{
|
||||
"codigo": "70+",
|
||||
"etiqueta": "70+"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "ALTA",
|
||||
"etiqueta": "Alta"
|
||||
},
|
||||
{
|
||||
"codigo": "MEDIA",
|
||||
"etiqueta": "Media"
|
||||
},
|
||||
{
|
||||
"codigo": "BAJA",
|
||||
"etiqueta": "Baja"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [],
|
||||
"paginacion": {
|
||||
"page": 4,
|
||||
"page_size": 1,
|
||||
"total_items": 3,
|
||||
"total_pages": 3
|
||||
},
|
||||
"simulado": true,
|
||||
"ventana": {
|
||||
"desde": "2025-10-21",
|
||||
"hasta": "2026-10-20",
|
||||
"meses": 12
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
{
|
||||
"simulado": true,
|
||||
"corte": "2026-10-20",
|
||||
"ventana": {
|
||||
"meses": 3,
|
||||
"desde": "2026-07-21",
|
||||
"hasta": "2026-10-20"
|
||||
},
|
||||
"campo_ventana": "mastografia_fecha",
|
||||
"filtros": {
|
||||
"estatus": null,
|
||||
"birads": null,
|
||||
"grupo_edad": null,
|
||||
"prioridad": null
|
||||
},
|
||||
"filtros_disponibles": [
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "PENDIENTE_BIOPSIA",
|
||||
"etiqueta": "Pendiente de biopsia"
|
||||
},
|
||||
{
|
||||
"codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"etiqueta": "Biopsia sin resultado"
|
||||
},
|
||||
{
|
||||
"codigo": "CANCER_CONFIRMADO",
|
||||
"etiqueta": "Cáncer confirmado"
|
||||
},
|
||||
{
|
||||
"codigo": "BENIGNO",
|
||||
"etiqueta": "Benigno, regresa a tamizaje"
|
||||
},
|
||||
{
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"etiqueta": "Categoría BI-RADS",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "BIRADS_4A",
|
||||
"etiqueta": "BI-RADS 4A"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4B",
|
||||
"etiqueta": "BI-RADS 4B"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_4C",
|
||||
"etiqueta": "BI-RADS 4C"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_5",
|
||||
"etiqueta": "BI-RADS 5"
|
||||
},
|
||||
{
|
||||
"codigo": "BIRADS_6",
|
||||
"etiqueta": "BI-RADS 6"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "40-49",
|
||||
"etiqueta": "40-49"
|
||||
},
|
||||
{
|
||||
"codigo": "50-59",
|
||||
"etiqueta": "50-59"
|
||||
},
|
||||
{
|
||||
"codigo": "60-69",
|
||||
"etiqueta": "60-69"
|
||||
},
|
||||
{
|
||||
"codigo": "70+",
|
||||
"etiqueta": "70+"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad",
|
||||
"opciones": [
|
||||
{
|
||||
"codigo": "ALTA",
|
||||
"etiqueta": "Alta"
|
||||
},
|
||||
{
|
||||
"codigo": "MEDIA",
|
||||
"etiqueta": "Media"
|
||||
},
|
||||
{
|
||||
"codigo": "BAJA",
|
||||
"etiqueta": "Baja"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"columnas": [
|
||||
{
|
||||
"clave": "id_seudonimo",
|
||||
"etiqueta": "Identificador seudónimo"
|
||||
},
|
||||
{
|
||||
"clave": "grupo_edad",
|
||||
"etiqueta": "Grupo de edad"
|
||||
},
|
||||
{
|
||||
"clave": "estatus",
|
||||
"etiqueta": "Estatus de seguimiento"
|
||||
},
|
||||
{
|
||||
"clave": "birads",
|
||||
"etiqueta": "Última mastografía",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "mastografia_fecha",
|
||||
"etiqueta": "Fecha"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "biopsia",
|
||||
"etiqueta": "Resultado histopatológico",
|
||||
"detalles": [
|
||||
{
|
||||
"clave": "biopsia_fecha",
|
||||
"etiqueta": "Fecha de biopsia"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"clave": "dias_mastografia_diagnostico",
|
||||
"etiqueta": "Días de mastografía a diagnóstico"
|
||||
},
|
||||
{
|
||||
"clave": "prioridad",
|
||||
"etiqueta": "Prioridad"
|
||||
}
|
||||
],
|
||||
"paginacion": {
|
||||
"page": 1,
|
||||
"page_size": 50,
|
||||
"total_items": 27,
|
||||
"total_pages": 1
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id_seudonimo": "M-0081",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-07-25",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0020",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-07-31",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0051",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-08-01",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0022",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 6",
|
||||
"birads_codigo": "BIRADS_6",
|
||||
"mastografia_fecha": "2026-08-03",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0029",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-08-13",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-09-11",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0019",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-08-21",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0064",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-08-22",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0048",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-09-01",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-10-07",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0059",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-09-05",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0050",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-09-06",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0084",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-09-08",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-09-18",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0054",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Pendiente de biopsia",
|
||||
"estatus_codigo": "PENDIENTE_BIOPSIA",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-10-04",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Alta",
|
||||
"prioridad_codigo": "ALTA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0035",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Biopsia sin resultado",
|
||||
"estatus_codigo": "BIOPSIA_SIN_RESULTADO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-08-21",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": "2026-08-31",
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Media",
|
||||
"prioridad_codigo": "MEDIA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0052",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Información insuficiente",
|
||||
"estatus_codigo": "INFO_INSUFICIENTE",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-10-01",
|
||||
"biopsia": null,
|
||||
"biopsia_fecha": null,
|
||||
"dias_mastografia_diagnostico": null,
|
||||
"prioridad": "Media",
|
||||
"prioridad_codigo": "MEDIA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0033",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-07-25",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-09-03",
|
||||
"dias_mastografia_diagnostico": 15,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0040",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-07-25",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-08-16",
|
||||
"dias_mastografia_diagnostico": 71,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0011",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-08-08",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-08-16",
|
||||
"dias_mastografia_diagnostico": 46,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0047",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-08-28",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-09-28",
|
||||
"dias_mastografia_diagnostico": 36,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0038",
|
||||
"grupo_edad": "60-69",
|
||||
"grupo_edad_codigo": "60-69",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-08-29",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-10-08",
|
||||
"dias_mastografia_diagnostico": 42,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0072",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-09-03",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-09-26",
|
||||
"dias_mastografia_diagnostico": 49,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0021",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-09-07",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-09-27",
|
||||
"dias_mastografia_diagnostico": 56,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0039",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4C",
|
||||
"birads_codigo": "BIRADS_4C",
|
||||
"mastografia_fecha": "2026-09-08",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-09-17",
|
||||
"dias_mastografia_diagnostico": 27,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0083",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 5",
|
||||
"birads_codigo": "BIRADS_5",
|
||||
"mastografia_fecha": "2026-09-20",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-09-27",
|
||||
"dias_mastografia_diagnostico": 25,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0062",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4A",
|
||||
"birads_codigo": "BIRADS_4A",
|
||||
"mastografia_fecha": "2026-09-26",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-10-14",
|
||||
"dias_mastografia_diagnostico": 19,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0032",
|
||||
"grupo_edad": "40-49",
|
||||
"grupo_edad_codigo": "40-49",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-10-07",
|
||||
"biopsia": "Benigno",
|
||||
"biopsia_fecha": "2026-10-20",
|
||||
"dias_mastografia_diagnostico": 61,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0077",
|
||||
"grupo_edad": "50-59",
|
||||
"grupo_edad_codigo": "50-59",
|
||||
"estatus": "Benigno, regresa a tamizaje",
|
||||
"estatus_codigo": "BENIGNO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-10-14",
|
||||
"biopsia": "Lesión de riesgo (B3)",
|
||||
"biopsia_fecha": "2026-10-20",
|
||||
"dias_mastografia_diagnostico": 60,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "M-0027",
|
||||
"grupo_edad": "70+",
|
||||
"grupo_edad_codigo": "70+",
|
||||
"estatus": "Cáncer confirmado",
|
||||
"estatus_codigo": "CANCER_CONFIRMADO",
|
||||
"birads": "BI-RADS 4B",
|
||||
"birads_codigo": "BIRADS_4B",
|
||||
"mastografia_fecha": "2026-10-16",
|
||||
"biopsia": "Carcinoma invasor",
|
||||
"biopsia_fecha": "2026-10-20",
|
||||
"dias_mastografia_diagnostico": 36,
|
||||
"prioridad": "Baja",
|
||||
"prioridad_codigo": "BAJA"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"id": "cama_tasa_deteccion_histopatologica",
|
||||
"titulo": "Detección histopatológica",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C1",
|
||||
"unidad": "examen",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"total": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [
|
||||
"Detección histopatológica"
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 127,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2026-11-12",
|
||||
"generado_en": "2026-11-12T17:00:31.282549+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
|
||||
"parametros_sha": "d909bc4a153b244533acde1f26ce8c4cfaaedf0d277239dd9b1ce9e9f65b23a9",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"fecha_corte": "2026-11-12",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "total",
|
||||
"estrato": null,
|
||||
"numerador": null,
|
||||
"denominador": null,
|
||||
"valor": null,
|
||||
"ic_bajo": null,
|
||||
"ic_alto": null,
|
||||
"suprimido": 1,
|
||||
"n_sin_evento": 0,
|
||||
"n_excluido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"id": "cama_tasa_deteccion_histopatologica",
|
||||
"titulo": "Detección histopatológica",
|
||||
"version": "0.1.0",
|
||||
"contrato": "C1",
|
||||
"unidad": "examen",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S1"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"total": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [
|
||||
"Detección histopatológica"
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"report_id": 127,
|
||||
"periodo_inicio": "2025-01-01",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"fecha_corte": "2026-11-12",
|
||||
"generado_en": "2026-11-12T17:00:42.857591+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7",
|
||||
"parametros_sha": "7202a2779ae47c29a7659dd6fdfb77e8895d4d778a772ff13cc2ce93c5a6e871",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"fecha_corte": "2026-11-12",
|
||||
"periodo_fin": "2025-07-01",
|
||||
"periodo_inicio": "2025-01-01"
|
||||
},
|
||||
"umbral_supresion": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S1",
|
||||
"grupo": "total",
|
||||
"estrato": null,
|
||||
"numerador": 0,
|
||||
"denominador": 1,
|
||||
"valor": 0.0,
|
||||
"ic_bajo": 0.0,
|
||||
"ic_alto": 79.3450688208,
|
||||
"suprimido": 0,
|
||||
"n_sin_evento": 1,
|
||||
"n_excluido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
@@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||
}
|
||||
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
|
||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
||||
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
||||
@@ -38,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
|
||||
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
|
||||
// The card doesn't count its figures; the figures themselves show what is published.
|
||||
expect(fixture.nativeElement.textContent).not.toContain('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());
|
||||
@@ -47,13 +46,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => {
|
||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
|
||||
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
||||
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
|
||||
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
|
||||
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
|
||||
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
|
||||
]);
|
||||
http.expectNone(() => true);
|
||||
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
|
||||
for (const [id, label] of [
|
||||
@@ -62,7 +57,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
['fig_c2_donas', 'Donas'],
|
||||
['fig_c9_futura', 'Representación 5'],
|
||||
]) {
|
||||
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
|
||||
fixture.componentInstance.selectFigure(id); fixture.detectChanges();
|
||||
const pending = request(id);
|
||||
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
||||
expect(pending.request.params.get('tema')).toBe('claro');
|
||||
@@ -74,9 +69,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
|
||||
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
it('no ofrece selector de representación y sólo consulta la figura mostrada', () => {
|
||||
fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull();
|
||||
request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
|
||||
@@ -98,9 +93,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
||||
});
|
||||
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
||||
open(); const first = request('f'); expect(select().disabled).toBe(false);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
|
||||
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
|
||||
open(); const first = request('f'); expect(panels()).toHaveLength(1);
|
||||
fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
|
||||
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
||||
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
||||
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
||||
|
||||
@@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan
|
||||
import { catchError, of, Subscription } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
@@ -17,40 +15,56 @@ 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 { vistaConfirmacion } from './indicadores-confirmacion-citologia';
|
||||
import { vistaEscenario } from './indicadores-eu7-escenario';
|
||||
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
||||
import { ID_HISTOPATOLOGIA } from './indicadores-histopatologia-cama';
|
||||
import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
import { parConteos } from './indicadores-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario],
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId">{{ indicador.titulo }}</h2>
|
||||
<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>
|
||||
@if (!sobrio && fijable) {
|
||||
<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 (isHistopatologia) {
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-histopatologia-cama [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 (conteos; as par) {
|
||||
<div #visibilityRegion class="conteos-region">
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</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">
|
||||
@@ -91,14 +105,12 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
}
|
||||
.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; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
||||
.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); } }
|
||||
`,
|
||||
})
|
||||
@@ -119,8 +131,18 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
|
||||
});
|
||||
}
|
||||
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
|
||||
get sobrio() { return this.dominio === 'cama'; }
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isEu7() { return !!vistaEscenario(this.dominio, this.indicador); }
|
||||
// CaMa's histopathology has its own view (isHistopatologia); the confirmation view is CaCu's cytology.
|
||||
get isConfirmacion() { return !this.isHistopatologia && !!vistaConfirmacion(this.dominio, this.indicador); }
|
||||
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
||||
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
@@ -146,6 +168,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@Input() pinned = false;
|
||||
// Pinning reorders a long grid; with a few cards there is nothing to bring forward.
|
||||
@Input() fijable = true;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
readonly pinChanged = output<void>();
|
||||
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<section class="confirmacion" [attr.aria-label]="'Confirmación histopatológica, ' + vista.textos.filas.toLowerCase()">
|
||||
<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" [attr.aria-label]="'Cargando ' + indicador.titulo" /><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">{{ vista.textos.vacio }}</p> }
|
||||
@else {
|
||||
@if (!vista.botones) {
|
||||
<p class="hint">Haz clic en un anillo de la dona para elegir un grupo o un resultado; el centro regresa un paso, hasta el total.</p>
|
||||
}
|
||||
<!-- Without visible buttons they stay for the keyboard, shown while one has the focus. -->
|
||||
<div class="legend" [class.solo-teclado]="!vista.botones" 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>{{ vista.textos.filas }}, {{ m.periodo }}</h3>
|
||||
@if (ratesFigure) {
|
||||
<app-plotly-chart [figure]="ratesFigure" [animated]="!vista.botones" [showNotes]="false" [label]="'Confirmación, tasas ' + vista.textos.filas.toLowerCase() + ', ' + 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" [animated]="!vista.botones" [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 ' + vista.textos.sujetos + ' 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" [attr.aria-label]="'Tabla de contingencia, ' + indicador.titulo" tabindex="0">
|
||||
<table><caption>Tabla de contingencia de {{ vista.textos.sujetos }}, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">{{ vista.textos.encabezado }}</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,41 @@
|
||||
: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; }
|
||||
.hint { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.legend.solo-teclado:not(:focus-within) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
// The donut is the control: its slices and centre answer to the pointer.
|
||||
.donut app-plotly-chart { cursor: pointer; }
|
||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||
border-radius: var(--issste-radius); 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,142 @@
|
||||
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 { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas,
|
||||
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
||||
Celda, Tasa, tasas, vistaConfirmacion } from './indicadores-confirmacion-citologia';
|
||||
|
||||
@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 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.vista.botones ? this.model.base : undefined); }
|
||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||
// CaCu's words when the catalog doesn't name this indicator, so the messages still read.
|
||||
get vista() { return vistaConfirmacion(this.dominio, this.indicador) ?? CONFIRMACION_CACU; }
|
||||
estadoTasa(t: Tasa) { return estadoTasa(t, this.vista.textos.sujetos); }
|
||||
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 ?? [];
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const figuras = [['fig_c2_donas', 'Dona de resultados de biopsia'], ['fig_c2_barras', 'Tasas ' + this.vista.textos.filas.toLowerCase()]] as const;
|
||||
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: this.vista.estrato })
|
||||
+ 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);
|
||||
const vista = vistaConfirmacion(this.dominio, this.indicador);
|
||||
if (!vista || 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: vista.estrato }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods, vista);
|
||||
this.pages = this.periods.map(p => modeloConfirmacion(datos, p, vista));
|
||||
// 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];
|
||||
// With buttons the view opens on the base group; without, on the total, as CaCu's interactive donut.
|
||||
this.selection = this.model ? (this.vista.botones ? 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 = (this.vista.botones ? clicConfirmacion : clicDona)(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 = (this.vista.botones ? donaConfirmacion : donaExpandible)(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,57 @@
|
||||
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
|
||||
<h3>Dona por categoría</h3>
|
||||
@if (donutGuide; as guide) {
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
|
||||
</section>
|
||||
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
|
||||
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
|
||||
<p>Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
|
||||
@case ('empty') { <p role="status">No hay periodos publicados por los dos conteos.</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' && model; as m) {
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ m.periodo }}, {{ periodIndex + 1 }} de {{ pages.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === pages.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
@if (total) {
|
||||
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
||||
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
||||
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||
</section>
|
||||
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
|
||||
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
|
||||
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
|
||||
</section>
|
||||
</div>
|
||||
<p class="note">Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.</p>
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
|
||||
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,22 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.conteos { 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); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
||||
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
|
||||
.periods button:disabled { opacity: .5; cursor: default; }
|
||||
// The two figures share the card in equal halves; one above the other on a narrow card.
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
app-plotly-chart { --plot-height: 400px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -0,0 +1,115 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { TitleCasePipe } from '@angular/common';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-conteos-pareados',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe],
|
||||
templateUrl: './indicador-conteos-pareados.html',
|
||||
styleUrl: './indicador-conteos-pareados.scss',
|
||||
})
|
||||
export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) par!: ParConteos;
|
||||
// The card's indicator (the exams); its partner (the patients) has no card and is requested by id.
|
||||
@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 = '';
|
||||
periodIndex = 0;
|
||||
pages: ModeloConteos[] = [];
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
|
||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
||||
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
|
||||
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
|
||||
helpOpen = false;
|
||||
// "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's
|
||||
// description of its own bars does not apply to them and is not used.
|
||||
get donutGuide() {
|
||||
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
||||
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.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario 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 = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version),
|
||||
this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([examenes, pacientes]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo);
|
||||
// The most recent period first; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.pages.length - 1);
|
||||
this.draw(); this.status.set(this.model ? 'ready' : 'empty');
|
||||
} 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 ConteosIncompatibles ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.draw();
|
||||
}
|
||||
private draw() {
|
||||
const m = this.model;
|
||||
if (!m) return;
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema);
|
||||
this.barsFigure = barrasConteos(m, this.par, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -1,54 +1,38 @@
|
||||
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<section class="eu7" [attr.aria-label]="indicador.titulo + ' por ' + etiquetaEstrato">
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<p>El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.</p>
|
||||
<p>Las barras usan el total con resultado válido de cada escenario, excluyendo «Sin dato». Al seleccionar un grupo o categoría se conserva ese denominador.</p>
|
||||
<p>El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.</p>
|
||||
<p>Selecciona un grupo para expandirlo y una categoría para resaltarla. Repite el clic para liberar la selección. El centro o el botón Volver regresa de categoría a grupo y después a TOTAL. También puedes usar Tab y Enter o Espacio en la leyenda.</p>
|
||||
<p>Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.</p>
|
||||
@if (metadata; as info) {
|
||||
@if (info.descripcion) { <p>{{ info.descripcion }}</p> }
|
||||
@if (info.ficha; as ficha) {
|
||||
@if (ficha.pregunta) { <p>{{ ficha.pregunta }}</p> }
|
||||
@if (ficha.definicion) { <p>{{ ficha.definicion }}</p> }
|
||||
@if (ficha.unidad) { <p>Unidad: {{ ficha.unidad }}</p> }
|
||||
@if (ficha.nota) { <p>{{ ficha.nota }}</p> }
|
||||
}
|
||||
<details><summary>Metadatos publicados de las figuras originales</summary>
|
||||
<p>Estas descripciones corresponden a las figuras publicadas originales. En esta vista coordinada, «Sin dato» queda fuera de la dona y las barras son porcentajes por escenario.</p>
|
||||
@for (detail of info.figuras_detalle; track detail.figura) {
|
||||
@if (detail.figura === 'fig_c2_donas' || detail.figura === 'fig_c2_barras') {
|
||||
<p>{{ detail.descripcion }}</p>
|
||||
@for (line of detail.como_leer; track $index) { <p>{{ line }}</p> }
|
||||
}
|
||||
}
|
||||
@for (reference of info.referencias; track $index) { <p>{{ reference.etiqueta }} {{ reference.ref }}</p> }
|
||||
</details>
|
||||
@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 ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><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 }} / {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
<nav class="periods" [attr.aria-label]="'Periodos de dona y barras, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [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" [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>
|
||||
<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="legend" role="group" [attr.aria-label]="'Explorar grupos y categorías, ' + indicador.titulo">
|
||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selecció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.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
@@ -61,29 +45,29 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Distribución de resultados · {{ m.periodo }}</h3>
|
||||
<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 válido para la dona.' }}</p> }
|
||||
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="indicador.titulo + ', 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>
|
||||
<section class="figure"><h3>{{ selectionLabel }} por {{ etiquetaEstrato }}, {{ m.periodo }}</h3>
|
||||
<p>Porcentaje del total válido de cada {{ etiquetaEstrato }}; excluye «{{ m.sinDatoEtiqueta }}».</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" />
|
||||
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="indicador.titulo + ', barras por ' + etiquetaEstrato + ', ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados y celdas suprimidas</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
|
||||
<table><caption>Datos generales · {{ m.periodo }}</caption>
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||
<table><caption>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>
|
||||
<table><caption>Por {{ etiquetaEstrato }}, {{ m.periodo }}, porcentajes sin «{{ m.sinDatoEtiqueta }}»</caption>
|
||||
<thead><tr><th scope="col">{{ etiquetaEstrato.charAt(0).toUpperCase() + etiquetaEstrato.slice(1) }}</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>
|
||||
|
||||
@@ -8,7 +8,7 @@ p, h3, summary { overflow-wrap: anywhere; }
|
||||
.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; }
|
||||
border-radius: var(--issste-radius); 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; }
|
||||
@@ -27,3 +27,7 @@ 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; }
|
||||
|
||||
@@ -14,7 +14,7 @@ import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub {
|
||||
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>();
|
||||
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>();
|
||||
plotClick = output<unknown>();
|
||||
}
|
||||
describe('EU7 integración Angular y caché compartida', () => {
|
||||
@@ -46,6 +46,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
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);
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
|
||||
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');
|
||||
@@ -70,10 +71,13 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
}
|
||||
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);
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub);
|
||||
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.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
|
||||
expect(charts.map(chart => chart.animated())).toEqual([true, true]);
|
||||
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
|
||||
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
|
||||
});
|
||||
@@ -122,7 +126,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
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);
|
||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores, Distribución de resultados citológicos"]').tabIndex).toBe(0);
|
||||
});
|
||||
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
|
||||
@@ -136,6 +140,36 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
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);
|
||||
|
||||
@@ -4,13 +4,14 @@ 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 { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
|
||||
import { 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';
|
||||
import { barras, Celda, clic, dona, esEu7, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta, vistaEscenario } from './indicadores-eu7-escenario';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-eu7-escenario',
|
||||
@@ -41,16 +42,19 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: Modelo[] = [];
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get vista(): VistaEscenario | undefined { return vistaEscenario(this.dominio, this.indicador); }
|
||||
get etiquetaEstrato() { return this.vista?.etiqueta ?? 'escenario clínico'; }
|
||||
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;
|
||||
if (this.vista && !esEu7(this.vista)) return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
||||
: `Fuera de la dona: ${n} pacientes con «${m.sinDatoEtiqueta}»${m.total === null ? '' : ` de ${m.total + n}`}.`;
|
||||
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
||||
: m.total === null ? `Fuera de la dona: ${n} pacientes sin resultado válido. Total con resultado no disponible.`
|
||||
: `Fuera de la dona: ${n} de ${m.total + n} pacientes sin resultado válido en el periodo.`;
|
||||
: 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;
|
||||
@@ -63,8 +67,19 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
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 ?? [];
|
||||
const figuras = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por ' + this.etiquetaEstrato]] as const;
|
||||
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 }] : [];
|
||||
});
|
||||
}
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
percentText(value: number | null) { return value === null ? 'No disponible' : value.toFixed(1) + ' %'; }
|
||||
percentText(value: number | null) { return percentText(value); }
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
@@ -86,10 +101,11 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
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'
|
||||
const vista = this.vista;
|
||||
if (!vista || 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.';
|
||||
|| !stratifiedCapabilities(this.indicador).includes(vista.estrato) || !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;
|
||||
@@ -97,13 +113,13 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
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 }),
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: vista.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.pages = this.periods.map(p => modelo(general, escenarios, p, vista.estrato));
|
||||
this.periodIndex = 0; this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
@@ -138,7 +154,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
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.barsFigure = barras(this.model, this.selection, this.tema, `% de pacientes de cada ${this.etiquetaEstrato}`);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<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'">
|
||||
<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-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>
|
||||
@@ -13,6 +13,12 @@
|
||||
@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>
|
||||
}
|
||||
@@ -77,7 +83,23 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
|
||||
@if (row.group; as g) {
|
||||
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
|
||||
}
|
||||
@for (c of row.items; track c.id) {
|
||||
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
|
||||
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||
@for (entry of state.donutLegend; track entry.label) {
|
||||
<span class="donut-static-legend__item" role="listitem">
|
||||
@@ -88,15 +110,11 @@
|
||||
}
|
||||
</div>
|
||||
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
@if (state.footnotes?.length) {
|
||||
<section class="methodological-footnotes" aria-label="Notas al pie de la figura">
|
||||
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
|
||||
</section>
|
||||
}
|
||||
@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) {
|
||||
|
||||
@@ -44,8 +44,11 @@
|
||||
.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: .75rem 1rem 1rem;
|
||||
padding: 0;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
@@ -110,3 +113,16 @@
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||
}
|
||||
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
|
||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||
.dark .highlight-legend { color: #eef1f7; }
|
||||
.highlight-status { margin: 0; font-weight: 600; }
|
||||
.highlight-back { justify-self: start; }
|
||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); font: inherit; cursor: pointer; }
|
||||
.highlight-legend button:disabled { opacity: .45; cursor: default; }
|
||||
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||
.highlight-legend .highlight-group { font-weight: 600; }
|
||||
|
||||
@@ -145,25 +145,33 @@ describe('IndicadorFigureCard', () => {
|
||||
fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined();
|
||||
expect(fixture.componentInstance.chartFigure?.data).toHaveLength(1);
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'])('UX-07D.2 presenta notas %s como texto seguro inmediatamente después del gráfico', dominio => {
|
||||
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 = ['Fuente: A & B\nSegunda línea', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
|
||||
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 al pie de la figura');
|
||||
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();
|
||||
expect(section.parentElement?.previousElementSibling?.querySelector('app-plotly-chart')).toBeTruthy();
|
||||
expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull();
|
||||
expect(section.parentElement?.parentElement?.querySelector('.figure-labels .category-labels')).toBeTruthy();
|
||||
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: {} };
|
||||
@@ -284,9 +292,9 @@ describe('IndicadorFigureCard', () => {
|
||||
state({ status: 'loading' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
|
||||
state({ status: 'incompatible', message: 'Granularidad no publicada' });
|
||||
state({ status: 'incompatible', message: 'Intervalo de tiempo no publicado' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Granularidad no publicada');
|
||||
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();
|
||||
@@ -458,7 +466,7 @@ describe('IndicadorFigureCard', () => {
|
||||
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-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')!;
|
||||
|
||||
@@ -10,8 +10,9 @@ 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 { contractInterpretation, figureMetadataInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
export interface FigureState {
|
||||
@@ -22,6 +23,10 @@ export interface FigureState {
|
||||
categoryLabels?: readonly CategoryLabel[];
|
||||
minimumPlotWidth?: number;
|
||||
donutLegend?: readonly DonutLegendEntry[];
|
||||
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
|
||||
ownLayout?: boolean;
|
||||
// Legend buttons that highlight one part of the figure (CaCu style).
|
||||
highlight?: FigureHighlight;
|
||||
plotWidth?: number;
|
||||
plotHeight?: number;
|
||||
message?: string;
|
||||
@@ -64,7 +69,7 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
}
|
||||
@Input({ required: true }) set state(value: FigureState) {
|
||||
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
|
||||
this.currentState = value;
|
||||
if (value.status === 'ready') {
|
||||
this.updateDonut();
|
||||
@@ -87,7 +92,8 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
||||
this.chartFigure = source && hierarchy
|
||||
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
||||
: source && this.state.donutLegend ? donutSimpleView(source) : source;
|
||||
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
|
||||
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
|
||||
}
|
||||
expandParent(parent: string) {
|
||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||
@@ -109,9 +115,28 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
target?.focus();
|
||||
}
|
||||
}
|
||||
highlightSelection: HighlightSelection = {};
|
||||
readonly highlightRows = highlightRows;
|
||||
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
|
||||
highlight(kind: 'group' | 'item', id: string) {
|
||||
if (!this.state.highlight) return;
|
||||
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
|
||||
this.updateDonut();
|
||||
}
|
||||
highlightBack() {
|
||||
const sel = this.highlightSelection;
|
||||
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
|
||||
this.updateDonut();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
||||
const point = event.points[0];
|
||||
if (this.state.highlight) {
|
||||
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
|
||||
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
|
||||
if (hit) this.highlight(hit.kind, hit.id);
|
||||
return;
|
||||
}
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
@@ -143,23 +168,23 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
: this.figuraId.startsWith('fig_c2') ? 'C2'
|
||||
: this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato;
|
||||
}
|
||||
private get complementaryLineCount(): number {
|
||||
return this.contract === 'C1' ? 1
|
||||
: this.contract === 'C2' ? (this.dominio === 'tea' ? 2 : 1) : 0;
|
||||
}
|
||||
get methodologyDetail(): readonly string[] {
|
||||
return this.interpretation.slice(0, this.complementaryLineCount);
|
||||
}
|
||||
get visibleInterpretation(): readonly string[] {
|
||||
return this.interpretation.slice(this.complementaryLineCount);
|
||||
}
|
||||
readonly hasNoVisibleValues = hasNoVisibleValues;
|
||||
readonly figureTitle = figureTitle;
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
get interpretation(): readonly string[] {
|
||||
return figureMetadataInterpretation(this.metadata, this.figuraId)
|
||||
?? contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie'));
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
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.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');
|
||||
@@ -215,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
});
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
@@ -228,18 +228,13 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(state?.applied?.selection.mode).toBe('todos');
|
||||
apply();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S2');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
apply();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
manual.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
||||
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
||||
@@ -300,7 +295,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual');
|
||||
const control = filters(); control.select([]);
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
@@ -308,9 +303,9 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
const control = filters(); control.select([]); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
apply();
|
||||
const req = figure();
|
||||
@@ -320,7 +315,6 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
expect(page.result().message).toContain('esta selección');
|
||||
expect(page.result().message).not.toContain('2025');
|
||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
||||
expect(control.selectedPeriods).toEqual(periodos);
|
||||
control.select([]);
|
||||
page.requestFigure();
|
||||
@@ -333,7 +327,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
@@ -344,17 +338,17 @@ describe('IndicadorFigurePanel', () => {
|
||||
page.requestFigure();
|
||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} });
|
||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
});
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); const old = figure();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
apply(); const current = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S2');
|
||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||
@@ -362,7 +356,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
|
||||
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||
|
||||
@@ -13,7 +13,9 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||
import { etiquetaDimension, MedidaEstrato, 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';
|
||||
@@ -23,7 +25,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
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>
|
||||
<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')) {
|
||||
@@ -46,17 +48,23 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
|
||||
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (dimension) {
|
||||
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||
}
|
||||
@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 }} / {{ donutPages.length }}</span>
|
||||
<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>
|
||||
}
|
||||
@@ -67,9 +75,9 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
@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 y celdas suprimidas</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> }
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
|
||||
</tbody></table></div>
|
||||
</details>
|
||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||
@@ -102,7 +110,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
.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);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); 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; }
|
||||
@@ -162,6 +170,18 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||
}
|
||||
dimension: DimensionEstrato | '' = '';
|
||||
readonly etiquetaDimension = etiquetaDimension;
|
||||
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
|
||||
private medidaElegida?: MedidaEstrato;
|
||||
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
|
||||
changeMedida(medida: MedidaEstrato) {
|
||||
if (medida === this.medida) return;
|
||||
this.medidaElegida = medida;
|
||||
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||
try { this.result.set(this.presentStratified(this.stratifiedData)); }
|
||||
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
|
||||
}
|
||||
}
|
||||
cells: StratifiedCell[] = [];
|
||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||
@@ -181,7 +201,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
}
|
||||
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);
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida);
|
||||
this.cells = adapted.cells;
|
||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||
@@ -245,6 +265,17 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
||||
}));
|
||||
}
|
||||
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
|
||||
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
|
||||
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
|
||||
const adapted = c1DonutFigure(data, selection);
|
||||
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
|
||||
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
|
||||
}));
|
||||
}
|
||||
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||
// Both panels, KPI and numeric table share the exact same transport key.
|
||||
// Do not catch /datos errors here: a backend failure is a real error state.
|
||||
@@ -265,6 +296,13 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||
}
|
||||
const adapted = c2Figure(data, selection);
|
||||
if (adapted.status === 'supported' && selection.dominio === 'tea') {
|
||||
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
|
||||
if (selection.figura === 'fig_c2_donas') {
|
||||
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
|
||||
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
|
||||
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
|
||||
}
|
||||
return adapted.status === 'supported'
|
||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||
@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 histopatología por BI-RADS">
|
||||
<button type="button" aria-label="Periodo anterior de la histopatología" [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 histopatología" [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 pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
|
||||
@if (ratesFigure) {
|
||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
<ul class="rate-states">
|
||||
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
||||
</ul>
|
||||
</section>
|
||||
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
||||
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@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 pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
|
||||
<table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead>
|
||||
<tbody>@for (fila of m.filas; track fila.id) {
|
||||
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (c of m.categorias; track c.id) { <td>{{ cellText(fila.celdas[c.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }<td>{{ cellText(fila.total) }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,149 @@
|
||||
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 { Celda } from './indicadores-confirmacion-citologia';
|
||||
import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA,
|
||||
lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama';
|
||||
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const;
|
||||
|
||||
/**
|
||||
* CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the
|
||||
* result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service
|
||||
* for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-indicador-histopatologia-cama',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-histopatologia-cama.html',
|
||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||
})
|
||||
export class IndicadorHistopatologiaCama 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?: SeleccionHistopatologia;
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: ModeloHistopatologia;
|
||||
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: ModeloHistopatologia[] = [];
|
||||
// The rates figure has a phone-width variant; it is redrawn when the window crosses that width.
|
||||
private readonly estrecho = typeof matchMedia === 'function' ? matchMedia('(max-width: 600px)') : undefined;
|
||||
private readonly alCambiarAncho = () => this.draw();
|
||||
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
|
||||
|
||||
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_BIRADS })
|
||||
+ 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 !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || 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_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosHistopatologia(datos, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloHistopatologia(datos, p));
|
||||
// The most recent period first; 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 HistopatologiaIncompatible ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof HistopatologiaIncompatible || 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 = clicHistopatologia(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 = donaHistopatologia(this.model, this.selection, this.tema);
|
||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Component, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
|
||||
/**
|
||||
* CaMa's histopathological result by BI-RADS category, while the catalog does not publish its indicator
|
||||
* (`cama_histopatologia_birads`). It keeps the card's place and structure, with no figure and no number.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-indicador-histopatologia-pendiente',
|
||||
host: { class: 'dual-card' },
|
||||
imports: [MatButtonModule, MatCardModule],
|
||||
template: `
|
||||
<mat-card>
|
||||
<h2>Resultado histopatológico por categoría BI-RADS</h2>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="ayuda()" (click)="ayuda.set(!ayuda())">Cómo leer</button>
|
||||
@if (ayuda()) {
|
||||
<div class="methodology">
|
||||
<p>Cuando el catálogo publique el indicador, esta tarjeta mostrará, por categoría BI-RADS, el porcentaje de biopsias con resultado maligno y su intervalo de confianza, y la distribución del resultado de la biopsia en una dona que se puede recorrer por grupo y por resultado.</p>
|
||||
</div>
|
||||
}
|
||||
<p class="estado" role="status"><strong>Integración pendiente.</strong> Este indicador aún no está publicado por el catálogo institucional.</p>
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Por categoría BI-RADS</h3><div class="vacio">Sin datos publicados</div></section>
|
||||
<section class="figure"><h3>Resultado de la biopsia</h3><div class="vacio">Sin datos publicados</div></section>
|
||||
</div>
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; grid-column: 1 / -1; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
h3 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.estado { color: var(--issste-text-secondary); }
|
||||
.methodology { margin-top: var(--issste-space-3); padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.methodology p { margin: 0; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); margin-top: var(--issste-space-3); }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
|
||||
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
||||
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorHistopatologiaPendiente {
|
||||
readonly ayuda = signal(false);
|
||||
}
|
||||
@@ -13,21 +13,27 @@ import { MatCardModule } from '@angular/material/card';
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||
<p class="kpi-state" role="status">{{ state }}</p>
|
||||
<!-- A card with its value shows nothing more; «Disponible» stays only for screen readers. -->
|
||||
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ 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);
|
||||
:host { display: flex; flex-direction: column; min-width: 0; }
|
||||
mat-card { box-sizing: border-box; flex: 1 1 auto; 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 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
||||
h3, p { overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.value { font: var(--mat-sys-headline-medium); }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
// CaMa's cards are as tall as their grid row.
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiCard {
|
||||
@@ -38,6 +44,8 @@ export class IndicadorKpiCard {
|
||||
@Input() loading = false;
|
||||
@Input() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
// A card that shows its value needs no "Disponible" line.
|
||||
@Input() quietWhenAvailable = false;
|
||||
@Input() additionalInfo?: string;
|
||||
get informationLine(): string | undefined {
|
||||
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
||||
|
||||
@@ -33,13 +33,13 @@ describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
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 granularidad, detiene al visible y explica supresión posterior', () => {
|
||||
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('Último dato visible, 2025-S1');
|
||||
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -48,7 +48,7 @@ describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
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.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', () => {
|
||||
|
||||
@@ -5,7 +5,9 @@ import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, CAMA_OPORTUNIDAD_KPIS, KPI_BY_DOMAIN as KPI_BASE } from './indicadores-kpi';
|
||||
// CaMa's cards are its opportunity strip: the catalog here publishes all four, so none is pending.
|
||||
const KPI_BY_DOMAIN = { ...KPI_BASE, cama: CAMA_OPORTUNIDAD_KPIS };
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorDatos, Dominio } from './indicadores.models';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
@@ -13,26 +15,57 @@ 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(); });
|
||||
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 })) });
|
||||
flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo })));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); }
|
||||
function requests() { return http.match(r => r.url.endsWith('/datos')); }
|
||||
// Availability runs four requests at a time; flushing one batch starts the next.
|
||||
function flushPeriodos(periodos: () => unknown[]) {
|
||||
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos')))
|
||||
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() }));
|
||||
}
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
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 }] };
|
||||
}
|
||||
// Answers every card by its URL until none is waiting: a domain with more cards than the concurrent
|
||||
// requests gets them in batches.
|
||||
function flushAll(domain: Dominio, extra: Partial<IndicadorDatos> = {}) {
|
||||
for (let reqs = requests(); reqs.length; reqs = requests()) {
|
||||
// A flushed answer can cancel its siblings (a new anchor period); those are not answered.
|
||||
for (const r of reqs.filter(r => !r.cancelled)) {
|
||||
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.includes('/' + d.id + '/'));
|
||||
r.flush({ ...response(index, domain, r.request.params.get('periodos') ?? '2025-S1'), ...extra });
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
}
|
||||
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();
|
||||
@@ -42,7 +75,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(panels().map(p => p.definition.id)).toEqual([]);
|
||||
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => {
|
||||
it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => {
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
||||
load('tea'); const initial = requests();
|
||||
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
||||
@@ -50,8 +83,10 @@ describe('KPI integración con autoridad global', () => {
|
||||
const req = requests();
|
||||
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
|
||||
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
|
||||
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||
expect(panels()[3].result().info).toBe('2 de 5 pacientes con TEA positivo tienen un EEG ligado.');
|
||||
expect(panels()[4].result().info).toBe('2 de 5 pacientes con TEA positivo no tienen ningún EEG ligado.');
|
||||
});
|
||||
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);
|
||||
@@ -66,7 +101,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
@@ -83,13 +118,14 @@ describe('KPI integración con autoridad global', () => {
|
||||
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);
|
||||
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); expect(requests().every(r => r.request.url.startsWith('/cama/'))).toBe(true); flushAll('cama');
|
||||
// CaMa's last cards start after its first batch and are cancelled by the change of domain.
|
||||
load('cacu'); const restored = requests().filter(r => !r.cancelled); 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(2);
|
||||
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 => {
|
||||
@@ -104,8 +140,8 @@ describe('KPI integración con autoridad global', () => {
|
||||
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 + 1);
|
||||
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 1));
|
||||
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();
|
||||
@@ -142,7 +178,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
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(3);
|
||||
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);
|
||||
});
|
||||
@@ -150,26 +186,28 @@ describe('KPI integración con autoridad global', () => {
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
||||
flushPeriodos(() => []); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||
it('las 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)));
|
||||
fixture.detectChanges();
|
||||
flushAll(domain, { notas: ['Nota del pie de la figura.'] });
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', '7', undefined] : ['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', 'días (mediana)', undefined] : ['pacientes', '%', 'días (mediana)']);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']);
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7', '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)', 'días (mediana)']);
|
||||
// «Disponible» stays for screen readers, visually hidden; any other state is the visible message.
|
||||
expect(cards.map(card => card.querySelector('.kpi-state:not(.visually-hidden)')?.textContent.trim())).toEqual(domain === 'cacu' ? [undefined, 'Selección no consolidable', undefined, 'Indicador no disponible', 'Indicador no disponible'] : Array(4).fill(undefined));
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('2025-S1'),
|
||||
expect.stringContaining(`5 ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: 3 a 9 días.`),
|
||||
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 and CaMa cards say only their own line; the kit notes are the figure footer.
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Nota del pie de la figura.');
|
||||
}
|
||||
});
|
||||
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
|
||||
@@ -189,7 +227,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
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();
|
||||
flushAll(domain);
|
||||
expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false);
|
||||
}
|
||||
load('cacu', false, ['2025-S1'], true);
|
||||
@@ -201,7 +239,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
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')));
|
||||
flushAll('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)); });
|
||||
|
||||
@@ -19,11 +19,12 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [notes]="result().notes ?? []" />
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="true" />
|
||||
@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; }',
|
||||
// The card fills the panel, so cards in one grid row are as tall as the row.
|
||||
styles: ':host { display: flex; flex-direction: column; min-width: 0; } app-indicador-kpi-card { flex: 1 1 auto; }',
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@@ -40,7 +41,7 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
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();
|
||||
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(); }
|
||||
@@ -49,6 +50,9 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
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 : '' });
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
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; }
|
||||
.ficha-fields { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 3fr); gap: var(--issste-space-2) var(--issste-space-4); max-width: 75ch; margin: 0; }
|
||||
.ficha-fields > div { display: contents; }
|
||||
dt { color: var(--issste-text-secondary); font-weight: 600; }
|
||||
dd { margin: 0; }
|
||||
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-fields { grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-1); }
|
||||
dd { margin-bottom: var(--issste-space-2); }
|
||||
.ficha-table th { width: 6rem; }
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
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 metodológica');
|
||||
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();
|
||||
@@ -32,11 +32,29 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
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 metodológica', 'Código', 'IND-01', 'Para', '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);
|
||||
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');
|
||||
@@ -56,7 +74,7 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
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 metodológica'); expect(text).not.toContain('Descripción');
|
||||
expect(text).not.toContain('Ficha técnica'); expect(text).not.toContain('Descripción');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
@@ -68,7 +86,7 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
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('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/);
|
||||
|
||||
@@ -17,16 +17,20 @@ import { IndicadoresService } from './indicadores.service';
|
||||
}
|
||||
@if (fichaFields.length) {
|
||||
<section aria-labelledby="metadata-ficha-title">
|
||||
<h4 id="metadata-ficha-title">Ficha metodológica</h4>
|
||||
<dl class="ficha-fields">@for (field of fichaFields; track field.key) {
|
||||
<div><dt>{{ field.label }}</dt><dd class="metadata-copy">{{ field.value }}</dd></div>
|
||||
}</dl>
|
||||
<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>
|
||||
<ul>@for (ref of references; track $index) { <li>{{ ref.etiqueta }}@if (hasText(ref.ref)) {, {{ ref.ref }} }</li> }</ul>
|
||||
</section>
|
||||
}
|
||||
@if (populations.length) {
|
||||
@@ -47,7 +51,7 @@ export class IndicadorMetadata implements OnChanges {
|
||||
loading = false;
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly fichaLabels = [
|
||||
['codigo', 'Código'], ['para', 'Para'], ['unidad', 'Unidad'],
|
||||
['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; }
|
||||
|
||||
@@ -1,45 +1,34 @@
|
||||
@if (compact) {
|
||||
<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">La granularidad del borrador ya no está publicada para este proyecto. Elige una granularidad disponible.</p> }
|
||||
<div class="fields">
|
||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Granularidad</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>
|
||||
}
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||
<div class="fields compact">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||
@if (hasPending) { <span class="pending" role="status">Hay cambios sin aplicar.</span> }
|
||||
</div>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}</p>
|
||||
@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 esta granularidad.</p> }
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability && entry.draft.mode !== 'todos') {
|
||||
@if (!availability) {
|
||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||
<div class="fields period-builder">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||
@@ -57,10 +46,56 @@
|
||||
</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>
|
||||
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
|
||||
</section>
|
||||
} @else {
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||
<div class="fields">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||
@if (hasPending) { <span class="pending" role="status">Hay cambios sin aplicar.</span> }
|
||||
</div>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}</p>
|
||||
@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 análisis.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability) {
|
||||
<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> }
|
||||
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
|
||||
</section>
|
||||
}
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
@use '@angular/material' as mat;
|
||||
|
||||
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
|
||||
// CaMa's compact row: tighter fields and buttons, one line of text under it.
|
||||
:host(.compacto) { margin: 0; @include mat.theme((density: -4)); }
|
||||
:host(.compacto) p { line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
|
||||
:host(.compacto) .pending { color: var(--issste-text); border-left-color: var(--issste-accent); padding-left: var(--issste-space-2); }
|
||||
:host(.compacto) .apply-button { min-height: 40px; }
|
||||
:host(.compacto) .period-builder button { min-height: 40px; }
|
||||
section { min-width: 0; }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
|
||||
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); }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); }
|
||||
mat-form-field { flex: 0 1 14rem; min-width: 0; }
|
||||
.period-builder mat-form-field { flex: 0 1 9rem; }
|
||||
.period-builder button { min-height: 40px; }
|
||||
p { overflow-wrap: anywhere; line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
|
||||
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.4; }
|
||||
.filter-help, .applied-summary { color: var(--issste-text-secondary); }
|
||||
.pending { color: var(--issste-text); font: var(--mat-sys-body-small); border-left: 3px solid var(--issste-accent); padding-left: var(--issste-space-2); }
|
||||
.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); }
|
||||
.fields.compact { align-items: center; }
|
||||
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
||||
.fields.compact .apply-button { margin-top: 0; }
|
||||
@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; }
|
||||
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; }
|
||||
}
|
||||
|
||||
@@ -18,18 +18,19 @@ describe('UX-04 control asistido', () => {
|
||||
control = fixture.componentInstance;
|
||||
});
|
||||
afterEach(() => fixture.destroy());
|
||||
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
||||
function periodSelect() {
|
||||
return fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
|
||||
}
|
||||
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
|
||||
} },
|
||||
});
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2');
|
||||
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S2');
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
||||
@@ -43,10 +44,11 @@ describe('UX-04 control asistido', () => {
|
||||
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
||||
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
||||
fixture.changeDetectorRef.detach();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const select = periodSelect();
|
||||
expect(select.componentInstance.multiple).toBe(false);
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
const edits = vi.spyOn(control.edited, 'emit');
|
||||
@@ -54,16 +56,16 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
}
|
||||
expect(model.control.value).toEqual([]);
|
||||
expect(model.control.value).toBeNull();
|
||||
expect(writes).not.toHaveBeenCalled();
|
||||
expect(edits).not.toHaveBeenCalled();
|
||||
expect(control.state.applied?.selection.mode).toBe('todos');
|
||||
});
|
||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => {
|
||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
|
||||
control.changeTipo('mes');
|
||||
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const select = periodSelect();
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
@@ -78,7 +80,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('normaliza el año y rechaza agregar duplicados', () => {
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
control.year = '1'; control.unit = 'S1'; control.add();
|
||||
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
||||
control.add();
|
||||
@@ -86,7 +88,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual(['0001-S1']);
|
||||
});
|
||||
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
||||
control.changeMode('manual'); control.year = year; control.unit = unit; control.add();
|
||||
control.select([]); control.year = year; control.unit = unit; control.add();
|
||||
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
||||
@@ -94,21 +96,22 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('conserva borradores independientes sin convertir periodos', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
||||
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
||||
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
||||
});
|
||||
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
control.select(['2025-S2']);
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
fixture.detectChanges();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
expect(select).toBeTruthy();
|
||||
const select = periodSelect();
|
||||
expect(select.componentInstance.multiple).toBe(false);
|
||||
expect(select.nativeElement.querySelector('button')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
||||
fixture.nativeElement.querySelector('.remove button').click();
|
||||
@@ -119,7 +122,7 @@ describe('UX-04 control asistido', () => {
|
||||
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
||||
const edited = vi.spyOn(control.edited, 'emit');
|
||||
const apply = vi.spyOn(control.apply, 'emit');
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
@@ -128,11 +131,25 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('no ofrece Todos en meses cuando el primero es semestre', () => {
|
||||
control.changeTipo('mes'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty');
|
||||
control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
|
||||
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
|
||||
expect(labels).toContain('Intervalo de análisis');
|
||||
expect(labels).not.toContain('Modalidad');
|
||||
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||
.find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
|
||||
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
|
||||
expect(options).toEqual(['Semestral', 'Mensual']);
|
||||
select.componentInstance.close();
|
||||
});
|
||||
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
||||
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
||||
options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
|
||||
fixture.detectChanges();
|
||||
control.changeTipo('mes');
|
||||
expect(control.selectedPeriods).toEqual(['2025-12']);
|
||||
control.select(['2025-11']); control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
// A period already chosen for that interval is kept.
|
||||
expect(control.selectedPeriods).toEqual(['2025-11']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './
|
||||
@Component({
|
||||
selector: 'app-indicador-period-filters',
|
||||
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
|
||||
host: { '[class.compacto]': 'compact' },
|
||||
templateUrl: './indicador-period-filters.html',
|
||||
styleUrl: './indicador-period-filters.scss',
|
||||
})
|
||||
@@ -19,6 +20,8 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
@Input({ required: true }) types!: TipoPeriodo[];
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() initialPresentation = false;
|
||||
// One period at a time, with the interval and Aplicar on one row.
|
||||
@Input() compact = false;
|
||||
@Output() retryAvailability = new EventEmitter<void>();
|
||||
@Output() edited = new EventEmitter<void>();
|
||||
@Output() apply = new EventEmitter<void>();
|
||||
@@ -29,7 +32,7 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
ngOnChanges() { this.year = this.unit = this.error = ''; }
|
||||
get entry() { return this.state.editors[this.state.tipo]!; }
|
||||
// NgModel schedules a microtask and markForCheck when its input reference changes.
|
||||
// Keep the empty multiple-select value stable so an unchanged draft can settle.
|
||||
// Keep the empty selection stable so an unchanged draft can settle.
|
||||
private readonly emptyPeriods: string[] = [];
|
||||
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
|
||||
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
|
||||
@@ -42,21 +45,21 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
get hasPending() { return pending(this.state); }
|
||||
get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
|
||||
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
|
||||
// There is no "every period" choice in the editor: a new interval starts on its most recent
|
||||
// period with a report (options are sorted newest first).
|
||||
changeTipo(tipo: TipoPeriodo) {
|
||||
if (!this.types.includes(tipo)) return;
|
||||
this.state.tipo = tipo;
|
||||
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
|
||||
this.year = this.unit = this.error = '';
|
||||
if (this.entry.draft.mode !== 'explicit' && this.availability?.status === 'ready' && this.options.length)
|
||||
this.entry.draft = { mode: 'explicit', periodos: [this.options[0]] };
|
||||
this.edited.emit();
|
||||
}
|
||||
changeMode(mode: 'todos' | 'manual') {
|
||||
if (mode === 'todos' && (this.state.tipo !== 'semestre' || this.state.tipo !== this.types[0])) return;
|
||||
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
|
||||
this.error = '';
|
||||
this.edited.emit();
|
||||
}
|
||||
// Only one period can be chosen: cards and figures never combine periods.
|
||||
select(values: string[]) {
|
||||
const unique = [...new Set(values)];
|
||||
const unique = [...new Set(this.compact ? values.slice(-1) : values)];
|
||||
if (unique.length > 1) return;
|
||||
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
|
||||
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
|
||||
this.edited.emit();
|
||||
@@ -70,13 +73,11 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
return;
|
||||
}
|
||||
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
|
||||
const selected = this.selectedPeriods;
|
||||
this.entry.added.push(period);
|
||||
this.select([...selected, period]);
|
||||
this.select([period]);
|
||||
}
|
||||
remove(period: string) {
|
||||
this.entry.added = this.entry.added.filter(p => p !== period);
|
||||
// Removing an unselected option must not change the Todos mode.
|
||||
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
|
||||
else this.edited.emit();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<section class="tiempos" aria-label="Días desde la toma: resultado y diagnóstico">
|
||||
<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">
|
||||
@for (guide of readingGuide; track guide.clave) {
|
||||
<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>
|
||||
}
|
||||
<p class="caveat">{{ caveat }}</p>
|
||||
@if (metadataPending) { <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 tiempos de resultado y diagnóstico" /><p role="status">Cargando los mismos periodos para los dos tiempos…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (model; as m) {
|
||||
<h3 class="figure-title">Días desde la toma: resultado y diagnóstico</h3>
|
||||
@if (status() === 'empty') { <p role="status">No hay cajas publicadas para estos periodos.</p> }
|
||||
@else if (figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Tiempos por periodo, ' + par.etiquetas.reporte + ' y ' + par.etiquetas.diagnostico" />
|
||||
}
|
||||
@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 tiempos por periodo" tabindex="0">
|
||||
<table><caption>Q1, mediana y Q3 en días por periodo</caption>
|
||||
<thead><tr><th scope="col">Periodo</th>@for (clave of claves; track clave) { <th scope="col">{{ par.etiquetas[clave] }}</th> }</tr></thead>
|
||||
<tbody>@for (periodo of m.periodos; track periodo) {
|
||||
<tr><th scope="row">{{ periodo }}</th>@for (clave of claves; track clave) { <td>{{ cajaTexto(m.cajas[clave][periodo]) }}</td> }</tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,17 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.tiempos { 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); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide + .reading-guide, .caveat { margin-top: 1rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -0,0 +1,131 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { catchError, combineLatest, of, 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 { IndicadoresService } from './indicadores.service';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { cajaTexto, CLAVES, Clave, FIGURA_C3R, figuraTiempos, hayCajas, ModeloTiempos, modeloTiempos, ParTiempos,
|
||||
TiemposIncompatibles } from './indicadores-tiempos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-tiempos-pareados',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-tiempos-pareados.html',
|
||||
styleUrl: './indicador-tiempos-pareados.scss',
|
||||
})
|
||||
export class IndicadorTiemposPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) par!: ParTiempos;
|
||||
// The card's indicator (diagnosis). Its partner (lab result) is hidden from the
|
||||
// catalog and requested directly by id, for data and metadata.
|
||||
@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');
|
||||
readonly claves = CLAVES;
|
||||
readonly cajaTexto = cajaTexto;
|
||||
message = '';
|
||||
model?: ModeloTiempos;
|
||||
figure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
partnerMetadata?: IndicadorMetadatos;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private metadataSubscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
// TODO: mover al kit (como_leer de la vista coordinada de tiempos).
|
||||
get caveat() {
|
||||
return `Las dos cajas no cuentan exactamente a las mismas ${this.par.estudios}: cada indicador tiene su propio horizonte `
|
||||
+ 'y la segunda solo incluye las que llegaron a diagnóstico. La diferencia entre las medianas no es el tiempo del tramo intermedio.';
|
||||
}
|
||||
/** "Cómo leer": only what the kit publishes for each C3r figure, plus the caveat above. */
|
||||
get readingGuide() {
|
||||
const fuentes: Record<Clave, IndicadorMetadatos | undefined> = { reporte: this.partnerMetadata, diagnostico: this.metadata };
|
||||
return CLAVES.flatMap(clave => {
|
||||
const detail = fuentes[clave]?.figuras_detalle?.find(item => item.figura === FIGURA_C3R);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ clave, nombre: this.par.etiquetas[clave], descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
get metadataPending() { return !this.metadata || !this.partnerMetadata; }
|
||||
toggleHelp() {
|
||||
this.helpOpen = !this.helpOpen;
|
||||
if (!this.helpOpen) return;
|
||||
if (!this.metadata) this.metadataRequested.emit();
|
||||
if (!this.partnerMetadata) {
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadataSubscription = this.service.metadatos(this.dominio, this.par.reporte).pipe(catchError(() => of(undefined)))
|
||||
.subscribe(value => { this.partnerMetadata = value; this.changeDetector.markForCheck(); });
|
||||
}
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([
|
||||
this.par.reporte, this.par.diagnostico, this.indicador.contrato, this.indicador.tipos_periodo]);
|
||||
if (changes['dominio'] || changes['par']) { this.partnerMetadata = undefined; this.metadataSubscription?.unsubscribe(); }
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.model = undefined; this.figure = 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();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.model = undefined; this.figure = undefined;
|
||||
if (this.indicador.id !== this.par.diagnostico || this.indicador.contrato !== 'C3r') {
|
||||
this.message = 'El catálogo no publica el indicador de tiempo necesario para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
// The partner shares the diagnosis periodicity; its response is validated by id, contract and period.
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (!compatibility.compatible) { this.message = compatibility.reason; 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.par.reporte, this.applied.tipo, periods),
|
||||
this.snapshots.datos(this.dominio, this.par.diagnostico, this.applied.tipo, periods, this.indicador.version),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([reporte, diagnostico]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.model = modeloTiempos(this.par, { reporte, diagnostico }, this.applied.tipo, periods);
|
||||
this.draw();
|
||||
this.status.set(hayCajas(this.model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.model = undefined; this.figure = undefined;
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof TiemposIncompatibles ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof TiemposIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model) return;
|
||||
this.figure = figuraTiempos(this.model, this.par, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { AnalisisResultados, AnalisisSubgrupos } from './indicadores-analisis.service';
|
||||
|
||||
const DIAS_POR_MES = 30.4375;
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
||||
function transparente(hex: string, alfa: number) {
|
||||
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
|
||||
return m ? `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, ${alfa})` : hex;
|
||||
}
|
||||
|
||||
// What the stage measures: the cumulative incidence of its event, or the survival (alive at t).
|
||||
export const nombreMedida = (medida: 'incidencia' | 'supervivencia') => medida === 'supervivencia' ? 'Supervivencia' : 'Incidencia acumulada';
|
||||
|
||||
/**
|
||||
* The stage's measure per published group (cumulative incidence, or survival in the survival stage): a step line with its 95 % band. The curve ends where the
|
||||
* answer suppressed it (fewer at risk than the threshold); each line carries its group in `meta`, so a click
|
||||
* can only change the filters, never read rows.
|
||||
*/
|
||||
export function curvasFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), meses = r.horizonte_dias / DIAS_POR_MES;
|
||||
const data: Record<string, unknown>[] = [];
|
||||
const supervivencia = r.medida === 'supervivencia';
|
||||
let maximo = 1, minimo = 100;
|
||||
for (const g of r.grupos.filter(x => !x.suprimido)) {
|
||||
const puntos = r.curvas.filter(c => c.grupo === g.grupo && c.suprimido === 0);
|
||||
if (!puntos.length) continue;
|
||||
const x = puntos.map(c => +(c.t / DIAS_POR_MES).toFixed(2));
|
||||
maximo = Math.max(maximo, ...puntos.map(c => c.ic_alto!)); minimo = Math.min(minimo, ...puntos.map(c => c.ic_bajo!));
|
||||
const comun = { type: 'scatter', mode: 'lines', x, legendgroup: g.grupo, line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false };
|
||||
data.push({ ...comun, y: puntos.map(c => c.ic_bajo) });
|
||||
data.push({ ...comun, y: puntos.map(c => c.ic_alto), fill: 'tonexty', fillcolor: transparente(g.color, tema === 'oscuro' ? .28 : .16) });
|
||||
data.push({
|
||||
type: 'scatter', mode: 'lines', x, y: puntos.map(c => c.valor), name: `${escapar(g.etiqueta)} (n = ${miles(g.n!)}, ${miles(g.eventos!)} eventos)`,
|
||||
legendgroup: g.grupo, meta: g.grupo, line: { shape: 'hv', width: 2.5, color: g.color },
|
||||
customdata: puntos.map(c => [pct(c.valor!), pct(c.ic_bajo!), pct(c.ic_alto!), miles(c.n_riesgo!), miles(c.n_eventos!)]),
|
||||
hovertemplate: `<b>${escapar(g.etiqueta)}</b><br>Mes %{x:.1f}: %{customdata[0]} % (IC 95 %: %{customdata[1]} a %{customdata[2]})<br>En riesgo: %{customdata[3]} · eventos acumulados: %{customdata[4]}<extra></extra>`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
data,
|
||||
layout: {
|
||||
autosize: true, height: 460, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 16, l: 64, r: 16, b: 96 }, hovermode: 'closest',
|
||||
legend: { orientation: 'h', y: -0.22, itemclick: false, itemdoubleclick: false },
|
||||
xaxis: { title: { text: 'Meses desde el origen' }, range: [0, meses], dtick: 6, gridcolor: p.grid, zeroline: false, fixedrange: true },
|
||||
yaxis: { title: { text: nombreMedida(r.medida) + ' (%)' }, range: supervivencia ? [Math.max(0, minimo - 10), 100] : [0, Math.min(100, maximo * 1.1)],
|
||||
gridcolor: p.grid, zeroline: false, fixedrange: true, ticksuffix: ' %' },
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
/** Hazard ratio of each group against the reference, on a log axis; an open marker flags a failed proportional-hazards check. */
|
||||
export function forestFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), e = r.efectos;
|
||||
if (e.estado !== 'listo' || !e.filas.length) return { data: [], layout: {} };
|
||||
const etiquetas = [`${escapar(e.etiqueta_referencia ?? e.referencia ?? '')} (referencia)`, ...e.filas.map(f => escapar(f.etiqueta))];
|
||||
const falla = (ph: number | null) => ph !== null && ph < .05;
|
||||
const minimo = Math.min(1, ...e.filas.map(f => f.ic_bajo)), maximo = Math.max(1, ...e.filas.map(f => f.ic_alto));
|
||||
return {
|
||||
data: [
|
||||
{ type: 'scatter', mode: 'markers', x: [1], y: [etiquetas[0]], marker: { symbol: 'diamond', size: 10, color: p.outline }, hoverinfo: 'skip', showlegend: false },
|
||||
{
|
||||
type: 'scatter', mode: 'markers', x: e.filas.map(f => f.hr), y: etiquetas.slice(1), showlegend: false,
|
||||
error_x: { type: 'data', symmetric: false, array: e.filas.map(f => f.ic_alto - f.hr), arrayminus: e.filas.map(f => f.hr - f.ic_bajo), color: p.text, thickness: 1.5, width: 6 },
|
||||
marker: { size: 11, color: e.filas.map(f => falla(f.ph_p) ? p.background : p.text), line: { color: p.text, width: 2 }, symbol: 'square' },
|
||||
customdata: e.filas.map(f => [f.ic_bajo.toLocaleString('es-MX'), f.ic_alto.toLocaleString('es-MX'), miles(f.n_eventos), falla(f.ph_p) ? '<br>Riesgos no proporcionales: el HR promedia un efecto que cambia.' : '']),
|
||||
hovertemplate: '%{y}<br>HR %{x:.2f} (IC 95 %: %{customdata[0]} a %{customdata[1]})<br>%{customdata[2]} eventos%{customdata[3]}<extra></extra>',
|
||||
},
|
||||
],
|
||||
layout: {
|
||||
autosize: true, height: Math.max(220, 70 + 44 * etiquetas.length), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 16, l: 16, r: 24, b: 56 },
|
||||
xaxis: { type: 'log', title: { text: 'Razón de riesgos (HR), escala logarítmica' }, range: [Math.log10(minimo * .7), Math.log10(maximo * 1.4)], gridcolor: p.grid, zeroline: false, fixedrange: true },
|
||||
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
|
||||
shapes: [{ type: 'line', xref: 'x', yref: 'paper', x0: 1, x1: 1, y0: 0, y1: 1, line: { color: p.outline, dash: 'dot', width: 1.5 } }],
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The stage's measure at the horizon by its two variables (rows and columns). A suppressed cell is drawn grey with its
|
||||
* reason, never as a colour; each cell carries its pair of codes, so a click only changes the filters.
|
||||
*/
|
||||
export function subgruposFigura(s: AnalisisSubgrupos, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), horizonte = Math.round(s.horizonte_dias / DIAS_POR_MES);
|
||||
const celda = (f: string, c: string) => s.celdas.find(x => x.fila === f && x.columna === c);
|
||||
const z = s.filas.map(f => s.columnas.map(c => { const x = celda(f.codigo, c.codigo); return x && !x.suprimido ? x.valor : null; }));
|
||||
const texto = s.filas.map(f => s.columnas.map(c => {
|
||||
const x = celda(f.codigo, c.codigo);
|
||||
if (!x || x.suprimido) return '<span style="opacity:.75">Suprimido</span>';
|
||||
const meses = Math.round(x.t_dias! / DIAS_POR_MES);
|
||||
return `<b>${pct(x.valor!)} %</b><br>${miles(x.eventos!)} de ${miles(x.n!)}${meses < horizonte ? `<br>a ${meses} meses` : ''}`;
|
||||
}));
|
||||
const ayuda = s.filas.map(f => s.columnas.map(c => {
|
||||
const x = celda(f.codigo, c.codigo);
|
||||
if (!x || x.suprimido) return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}: suprimido (${(x?.motivo ?? 'sin datos').toLowerCase()})`;
|
||||
return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}<br>${pct(x.valor!)} % (IC 95 %: ${pct(x.ic_bajo!)} a ${pct(x.ic_alto!)})<br>${miles(x.eventos!)} eventos en ${miles(x.n!)} pacientes`;
|
||||
}));
|
||||
const maximo = Math.max(1, ...z.flat().filter((v): v is number => v !== null));
|
||||
return {
|
||||
data: [
|
||||
// The grey layer under the colour: the cells the answer suppressed.
|
||||
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z: z.map(r => r.map(v => v === null ? 1 : null)),
|
||||
colorscale: [[0, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9'], [1, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9']], showscale: false, hoverinfo: 'skip', xgap: 3, ygap: 3 },
|
||||
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z, zmin: 0, zmax: maximo, xgap: 3, ygap: 3,
|
||||
customdata: s.filas.map(f => s.columnas.map(c => [f.codigo, c.codigo])), text: ayuda, hovertemplate: '%{text}<extra></extra>',
|
||||
colorscale: [[0, tema === 'oscuro' ? '#1B3A5B' : '#EAF1F8'], [1, tema === 'oscuro' ? '#9DBFE3' : '#1F5F8B']],
|
||||
colorbar: { title: { text: nombreMedida(s.medida) + ' (%)' }, ticksuffix: ' %', thickness: 12 } },
|
||||
],
|
||||
layout: {
|
||||
autosize: true, height: 80 + 64 * s.filas.length, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 16, l: 16, r: 16, b: 56 },
|
||||
xaxis: { title: { text: escapar(s.dimension_columnas.etiqueta) }, side: 'bottom', fixedrange: true, automargin: true },
|
||||
yaxis: { title: { text: escapar(s.dimension_filas.etiqueta) }, autorange: 'reversed', fixedrange: true, automargin: true },
|
||||
annotations: s.filas.flatMap((f, i) => s.columnas.map((c, j) => {
|
||||
const v = z[i][j];
|
||||
return { x: c.etiqueta, y: f.etiqueta, xref: 'x', yref: 'y', showarrow: false, text: texto[i][j], font: { size: 12, color: v !== null && v > maximo * .55 ? '#FFFFFF' : p.text } };
|
||||
})),
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
export const mesesDe = (dias: number) => Math.round(dias / DIAS_POR_MES);
|
||||
@@ -0,0 +1,180 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { Dominio, requireDominio } from './indicadores.models';
|
||||
|
||||
// Exploratory outcomes of a domain's cohort: what can be asked (`/analisis`) and its aggregate answer
|
||||
// (`/analisis/resultados`). The answer is curves (C9b), tests, effects (C12) and checks (C13), never patient rows.
|
||||
// The analysis goes by stages (development, recurrence, survival). Each stage has its scenarios, its estimators
|
||||
// and the two variables it is stratified and filtered by; each variable says its NOM numeral and whether the schema
|
||||
// records it or the answer assumes it.
|
||||
export interface AnalisisOpcion { clave: string; etiqueta: string; }
|
||||
// `filtro_seguimiento`: the follow-up list's filters that list this scenario's population.
|
||||
export interface AnalisisEscenario extends AnalisisOpcion { evento: string; origen: string; poblacion: string; etapa: string; filtro_seguimiento: Record<string, string>; }
|
||||
export interface AnalisisEstimador extends AnalisisOpcion { nota: string; }
|
||||
export type EstadoVariable = 'registrado' | 'supuesto';
|
||||
export interface AnalisisVariable extends AnalisisOpcion { nom: string; estado: EstadoVariable; fuente: string; opciones: { codigo: string; etiqueta: string }[]; }
|
||||
export interface AnalisisEtapa extends AnalisisOpcion {
|
||||
pregunta: string; escenarios: string[]; estimadores: string[]; medida: 'incidencia' | 'supervivencia';
|
||||
// The variables the stage can be compared by: one at a time in the curves, two at a time in the grid.
|
||||
variables: string[]; evento_supuesto: string | null;
|
||||
// Every variable the NOM asks for at this stage, and whether the schema has it.
|
||||
requeridas: { variable: string; nom: string; estado: string }[];
|
||||
}
|
||||
export interface AnalisisBloqueado { clave: string; titulo: string; motivo: string; }
|
||||
export interface AnalisisCatalogo {
|
||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||
etapas: AnalisisEtapa[]; escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[];
|
||||
variables: AnalisisVariable[]; bloqueados: AnalisisBloqueado[];
|
||||
}
|
||||
// `grupos`: the values of the variable to compare, two or more; empty compares them all.
|
||||
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; grupos: string[]; filtros: Record<string, string>; }
|
||||
export interface PedidoSubgrupos { escenario: string; estimador: string; filas: string; columnas: string; }
|
||||
// The log-rank of one variable of the grid, plain and at equal value of the other one.
|
||||
export interface PruebaCruzada {
|
||||
variable: string; etiqueta: string; estratificada_por: string; etiqueta_estrato: string;
|
||||
logrank: { chi2: number; gl: number; p: number; grupos: number } | null; estratificado: { chi2: number; gl: number; p: number; grupos: number } | null;
|
||||
}
|
||||
// One epidemiological figure of the cohort at the horizon (incidence, recurrence, adherence or survival).
|
||||
export interface IndicadorEpidemiologico {
|
||||
clave: string; titulo: string; etapa: string; unidad: string; descripcion: string; supuesto: string | null; suprimido: boolean;
|
||||
n: number | null; eventos: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; t_dias: number | null;
|
||||
}
|
||||
export interface AnalisisIndicadores { simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; indicadores: IndicadorEpidemiologico[]; }
|
||||
|
||||
export interface GrupoAnalisis { grupo: string; etiqueta: string; color: string; suprimido: boolean; motivo: string | null; n: number | null; eventos: number | null; competitivos: number | null; }
|
||||
// C9b: one row per group and event time; a suppressed row ends the published curve.
|
||||
export interface PuntoCurva { grupo: string; t: number; estimador: 'KM' | 'CIF'; valor: number | null; ic_bajo: number | null; ic_alto: number | null; n_riesgo: number | null; n_eventos: number | null; suprimido: 0 | 1; }
|
||||
// C12
|
||||
export interface FilaEfecto { termino: string; etiqueta: string; hr: number; ic_bajo: number; ic_alto: number; n_eventos: number; metodo: 'cox' | 'bayes'; ph_p: number | null; }
|
||||
export interface Efectos { estado: 'listo' | 'insuficiente' | 'no_aplica'; motivo: string | null; metodo: string; referencia: string | null; etiqueta_referencia?: string; filas: FilaEfecto[]; }
|
||||
// C13
|
||||
export interface FilaValidacion { chequeo: string; escopo: string; estadistico: number | null; p: number | null; umbral: number | null; aprobado: boolean | null; nota: string | null; version_modelo: string; sql_sha: string | null; }
|
||||
export interface AnalisisResultados {
|
||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||
etapa: string; medida: 'incidencia' | 'supervivencia';
|
||||
escenario: string; estimador: string; estrato: string; filtros: Record<string, string>; grupos_elegidos: string[] | null;
|
||||
// What of this answer rests on data the schema does not record.
|
||||
supuestos: string[];
|
||||
poblacion: { n: number | null; eventos: number | null; totales_ocultos: boolean; seguimiento_mediano_dias: number | null };
|
||||
grupos: GrupoAnalisis[]; curvas: PuntoCurva[];
|
||||
tabla_riesgo: { cortes_dias: number[]; filas: { grupo: string; cortes: (number | null)[] }[] };
|
||||
pruebas: {
|
||||
logrank: { chi2: number; gl: number; p: number } | null;
|
||||
pares: { a: string; b: string; p: number; p_holm: number }[];
|
||||
rmst: { grupo: string; rmst: number; dif: number | null; ic_bajo: number | null; ic_alto: number | null }[];
|
||||
rmst_referencia?: string; nota: string | null;
|
||||
};
|
||||
efectos: Efectos; validacion: FilaValidacion[]; avisos: string[];
|
||||
}
|
||||
|
||||
// The BI-RADS by age-group grid: the incidence at the horizon in each cell, or the reason it is suppressed.
|
||||
export interface CeldaSubgrupo {
|
||||
fila: string; columna: string; suprimido: boolean; motivo: string | null;
|
||||
n: number | null; eventos: number | null; t_dias: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
|
||||
}
|
||||
export interface AnalisisSubgrupos {
|
||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; escenario: string; estimador: string;
|
||||
etapa: string; medida: 'incidencia' | 'supervivencia'; supuestos: string[];
|
||||
dimension_filas: AnalisisOpcion; dimension_columnas: AnalisisOpcion; pruebas: PruebaCruzada[];
|
||||
filas: { codigo: string; etiqueta: string }[]; columnas: { codigo: string; etiqueta: string }[]; celdas: CeldaSubgrupo[];
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||
const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
|
||||
const numONulo = (v: unknown) => v === null || num(v);
|
||||
const lista = (v: unknown, f: (x: unknown) => boolean) => Array.isArray(v) && v.every(f);
|
||||
const opcion = (v: unknown) => record(v) && text(v['clave']) && text(v['etiqueta']);
|
||||
// Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth.
|
||||
const DE_PACIENTE = new Set(['id_seudonimo', 'pac_id', 'paciente', 'pacientes', 'items', 'fecha_nacimiento', 'curp', 'nss']);
|
||||
function sinFilasDePaciente(v: unknown): boolean {
|
||||
if (Array.isArray(v)) return v.every(sinFilasDePaciente);
|
||||
if (!record(v)) return true;
|
||||
return Object.entries(v).every(([k, x]) => !DE_PACIENTE.has(k) && sinFilasDePaciente(x));
|
||||
}
|
||||
const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); };
|
||||
|
||||
export function analisisCatalogo(v: unknown): AnalisisCatalogo {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (!text(v['corte']) || !num(v['horizonte_dias']) || !num(v['umbral_supresion'])
|
||||
|| !lista(v['escenarios'], e => opcion(e) && record(e) && text(e['evento']) && text(e['origen']) && text(e['poblacion']) && text(e['etapa'])
|
||||
&& record(e['filtro_seguimiento']) && Object.values(e['filtro_seguimiento']).every(text)) || !(v['escenarios'] as unknown[]).length
|
||||
|| !lista(v['estimadores'], e => opcion(e) && record(e) && text(e['nota'])) || !(v['estimadores'] as unknown[]).length
|
||||
|| !lista(v['variables'], x => opcion(x) && record(x) && text(x['nom']) && ['registrado', 'supuesto'].includes(x['estado'] as string)
|
||||
&& text(x['fuente']) && lista(x['opciones'], o => record(o) && text(o['codigo']) && text(o['etiqueta'])))
|
||||
|| !lista(v['etapas'], e => opcion(e) && record(e) && text(e['pregunta']) && ['incidencia', 'supervivencia'].includes(e['medida'] as string)
|
||||
&& lista(e['escenarios'], text) && (e['escenarios'] as unknown[]).length > 0 && lista(e['estimadores'], text) && (e['estimadores'] as unknown[]).length > 0
|
||||
&& lista(e['variables'], text) && (e['variables'] as unknown[]).length >= 2 && lista(e['requeridas'], record)) || !(v['etapas'] as unknown[]).length
|
||||
|| !lista(v['bloqueados'], b => record(b) && text(b['clave']) && text(b['titulo']) && text(b['motivo']))
|
||||
|| !sinFilasDePaciente(v)) invalido();
|
||||
return v as unknown as AnalisisCatalogo;
|
||||
}
|
||||
|
||||
export function analisisResultados(v: unknown): AnalisisResultados {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (!['incidencia', 'supervivencia'].includes(v['medida'] as string) || !lista(v['supuestos'], text)) invalido();
|
||||
const pob = v['poblacion'], tabla = v['tabla_riesgo'], pruebas = v['pruebas'], efectos = v['efectos'];
|
||||
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador']) || !text(v['estrato'])
|
||||
|| !record(v['filtros']) || !record(pob) || !numONulo(pob['n']) || !numONulo(pob['eventos'])
|
||||
|| !lista(v['grupos'], g => record(g) && text(g['grupo']) && text(g['etiqueta']) && text(g['color']) && typeof g['suprimido'] === 'boolean'
|
||||
&& numONulo(g['n']) && numONulo(g['eventos']) && (!g['suprimido'] || g['n'] === null && g['eventos'] === null))
|
||||
|| !lista(v['curvas'], c => record(c) && text(c['grupo']) && num(c['t']) && (c['estimador'] === 'KM' || c['estimador'] === 'CIF')
|
||||
&& (c['suprimido'] === 1 ? c['valor'] === null && c['n_riesgo'] === null : num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['n_riesgo'])))
|
||||
|| !record(tabla) || !lista(tabla['cortes_dias'], num) || !lista(tabla['filas'], f => record(f) && text(f['grupo']) && lista(f['cortes'], numONulo))
|
||||
|| !record(pruebas) || !lista(pruebas['pares'], record) || !lista(pruebas['rmst'], record)
|
||||
|| !record(efectos) || !['listo', 'insuficiente', 'no_aplica'].includes(efectos['estado'] as string)
|
||||
|| !lista(efectos['filas'], f => record(f) && text(f['termino']) && num(f['hr']) && num(f['ic_bajo']) && num(f['ic_alto']) && num(f['n_eventos']))
|
||||
|| !lista(v['validacion'], f => record(f) && text(f['chequeo']) && text(f['escopo']) && (f['aprobado'] === null || typeof f['aprobado'] === 'boolean'))
|
||||
|| !lista(v['avisos'], text)) invalido();
|
||||
// A published point must stay at or above the threshold of patients at risk.
|
||||
const umbral = v['umbral_supresion'] as number;
|
||||
if ((v['curvas'] as PuntoCurva[]).some(c => c.suprimido === 0 && c.n_riesgo! < umbral)) invalido();
|
||||
return v as unknown as AnalisisResultados;
|
||||
}
|
||||
|
||||
export function analisisSubgrupos(v: unknown): AnalisisSubgrupos {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
const eje = (x: unknown) => lista(x, o => record(o) && text(o['codigo']) && text(o['etiqueta']));
|
||||
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador'])
|
||||
|| !eje(v['filas']) || !eje(v['columnas']) || !opcion(v['dimension_filas']) || !opcion(v['dimension_columnas']) || !lista(v['supuestos'], text)
|
||||
|| !lista(v['pruebas'], x => record(x) && text(x['variable']) && text(x['estratificada_por']) && (x['logrank'] === null || record(x['logrank'])) && (x['estratificado'] === null || record(x['estratificado'])))
|
||||
|| !lista(v['celdas'], c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean'
|
||||
&& (c['suprimido'] ? c['n'] === null && c['eventos'] === null && c['valor'] === null
|
||||
: num(c['n']) && num(c['eventos']) && num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['t_dias'])))) invalido();
|
||||
// A published cell never has fewer patients or events than the threshold.
|
||||
const umbral = v['umbral_supresion'] as number;
|
||||
if ((v['celdas'] as CeldaSubgrupo[]).some(c => !c.suprimido && (c.n! < umbral || c.eventos! < umbral))) invalido();
|
||||
return v as unknown as AnalisisSubgrupos;
|
||||
}
|
||||
|
||||
export function analisisIndicadores(v: unknown): AnalisisIndicadores {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (!sinFilasDePaciente(v) || !num(v['umbral_supresion']) || !lista(v['indicadores'], x => record(x) && text(x['clave']) && text(x['titulo'])
|
||||
&& text(x['descripcion']) && typeof x['suprimido'] === 'boolean'
|
||||
&& (x['suprimido'] ? x['valor'] === null && x['eventos'] === null : num(x['valor']) && num(x['n']) && num(x['eventos'])))) invalido();
|
||||
// A published figure never stands on fewer patients than the threshold.
|
||||
if ((v['indicadores'] as IndicadorEpidemiologico[]).some(x => !x.suprimido && x.n! < (v['umbral_supresion'] as number))) invalido();
|
||||
return v as unknown as AnalisisIndicadores;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AnalisisService {
|
||||
private readonly http = inject(HttpClient);
|
||||
catalogo(dominio: Dominio) {
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis`).pipe(map(analisisCatalogo));
|
||||
}
|
||||
resultados(dominio: Dominio, pedido: AnalisisPedido) {
|
||||
let params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('estrato', pedido.estrato);
|
||||
if (pedido.grupos.length) params = params.set('grupos', pedido.grupos.join(','));
|
||||
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/resultados`, { params }).pipe(map(analisisResultados));
|
||||
}
|
||||
subgrupos(dominio: Dominio, pedido: PedidoSubgrupos) {
|
||||
const params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('filas', pedido.filas).set('columnas', pedido.columnas);
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/subgrupos`, { params }).pipe(map(analisisSubgrupos));
|
||||
}
|
||||
indicadores(dominio: Dominio) {
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`).pipe(map(analisisIndicadores));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { Component, 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 { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import {
|
||||
IndicadoresAnalisis, SeleccionPacientes, celdaDelClic, cruceDeEtapa, grupoDelClic, pedidoDeEtapa, seleccionDeCelda, seleccionDeCurva,
|
||||
} from './indicadores-analisis';
|
||||
import { curvasFigura, forestFigura, subgruposFigura } from './indicadores-analisis-figuras';
|
||||
import {
|
||||
AnalisisCatalogo, AnalisisIndicadores, AnalisisResultados, AnalisisSubgrupos, analisisCatalogo, analisisIndicadores, analisisResultados, analisisSubgrupos,
|
||||
} from './indicadores-analisis.service';
|
||||
|
||||
// Covers the «Análisis epidemiológico» tab of breast cancer: the guards of its answers (aggregates only, nothing
|
||||
// under the threshold), the figures built from them, the selections a curve or a cell sends to Seguimiento, and the
|
||||
// tab's requests: the epidemiological figures, the curves of two or more values of one variable, and the heatmap of
|
||||
// two distinct variables.
|
||||
// Fixtures, all built below: `catalogo` (two stages, development with three variables and survival with two, one of
|
||||
// them assumed; one blocked analysis), `resultados` (two published BI-RADS groups, one suppressed, a ready Cox model),
|
||||
// `subgrupos` (a two-by-two BI-RADS and age grid with one suppressed cell and its crossed tests) and `indicadores`
|
||||
// (one published figure and one suppressed).
|
||||
|
||||
const catalogo = (): AnalisisCatalogo => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5,
|
||||
etapas: [
|
||||
{ clave: 'desarrollo', etiqueta: 'Desarrollo', pregunta: '¿Quién llega a cáncer?', escenarios: ['diagnostico', 'incidencia'], estimadores: ['cif', 'km'],
|
||||
medida: 'incidencia', variables: ['birads', 'grupo_edad', 'brca'], evento_supuesto: null,
|
||||
requeridas: [{ variable: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado' }] },
|
||||
{ clave: 'supervivencia', etiqueta: 'Supervivencia', pregunta: '¿Quién sigue viva?', escenarios: ['supervivencia'], estimadores: ['km'],
|
||||
medida: 'supervivencia', variables: ['estadio', 'grupo_edad'], evento_supuesto: 'Estado vital supuesto.',
|
||||
requeridas: [{ variable: 'Estado vital y causa de muerte', nom: '16.8', estado: 'supuesto' }] },
|
||||
],
|
||||
escenarios: [
|
||||
{ clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más', etapa: 'desarrollo', filtro_seguimiento: {} },
|
||||
{ clave: 'incidencia', etiqueta: 'Cáncer posterior', evento: 'Cáncer posterior', origen: 'Biopsia benigna', poblacion: 'Biopsia benigna', etapa: 'desarrollo', filtro_seguimiento: { resultado: 'BENIGNO' } },
|
||||
{ clave: 'supervivencia', etiqueta: 'Supervivencia', evento: 'Muerte', origen: 'Diagnóstico', poblacion: 'Cáncer invasor', etapa: 'supervivencia', filtro_seguimiento: { resultado: 'INVASOR' } },
|
||||
],
|
||||
estimadores: [{ clave: 'km', etiqueta: '1 − Kaplan-Meier', nota: 'Censura la muerte.' }, { clave: 'cif', etiqueta: 'Aalen-Johansen', nota: 'Muerte competitiva.' }],
|
||||
variables: [
|
||||
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado', fuente: 'mastografia.birads',
|
||||
opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }, { codigo: 'B6', etiqueta: 'BI-RADS 6' }] },
|
||||
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', nom: '16.5', estado: 'registrado', fuente: 'paciente.fecha_nacimiento',
|
||||
opciones: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }] },
|
||||
{ clave: 'brca', etiqueta: 'BRCA1/2', nom: 'Factores de riesgo', estado: 'supuesto', fuente: 'Prueba genética.',
|
||||
opciones: [{ codigo: 'BRCA1', etiqueta: 'Mutación BRCA1' }, { codigo: 'NEGATIVO', etiqueta: 'Sin mutación' }] },
|
||||
{ clave: 'estadio', etiqueta: 'Estadio clínico', nom: '10.3.2', estado: 'supuesto', fuente: 'Nota de oncología.',
|
||||
opciones: [{ codigo: 'I', etiqueta: 'Estadio I' }, { codigo: 'IV', etiqueta: 'Estadio IV' }] },
|
||||
],
|
||||
bloqueados: [{ clave: 'sobrevida', titulo: 'Sobrevida por etapa clínica', motivo: 'No hay etapa clínica ni estado vital.' }],
|
||||
});
|
||||
const punto = (grupo: string, t: number, valor: number, n_riesgo: number, n_eventos: number) =>
|
||||
({ grupo, t, estimador: 'CIF' as const, valor, ic_bajo: valor * .8, ic_alto: valor * 1.2, n_riesgo, n_eventos, suprimido: 0 as const });
|
||||
const resultados = (): AnalisisResultados => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
|
||||
escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {}, grupos_elegidos: null,
|
||||
poblacion: { n: null, eventos: null, totales_ocultos: true, seguimiento_mediano_dias: 700 },
|
||||
grupos: [
|
||||
{ grupo: 'B4A', etiqueta: 'BI-RADS 4A', color: '#1F5F8B', suprimido: false, motivo: null, n: 180, eventos: 11, competitivos: null },
|
||||
{ grupo: 'B5', etiqueta: 'BI-RADS 5', color: '#C26A2B', suprimido: false, motivo: null, n: 120, eventos: 100, competitivos: null },
|
||||
{ grupo: 'B6', etiqueta: 'BI-RADS 6', color: '#4E8A4B', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, competitivos: null },
|
||||
],
|
||||
curvas: [punto('B4A', 0, 0, 180, 0), punto('B4A', 90, 4, 150, 7), punto('B4A', 730, 6, 90, 11),
|
||||
punto('B5', 0, 0, 120, 0), punto('B5', 40, 70, 30, 85),
|
||||
{ grupo: 'B5', t: 300, estimador: 'CIF', valor: null, ic_bajo: null, ic_alto: null, n_riesgo: null, n_eventos: null, suprimido: 1 }],
|
||||
tabla_riesgo: { cortes_dias: [0, 365, 730], filas: [{ grupo: 'B4A', cortes: [180, 130, 90] }, { grupo: 'B5', cortes: [120, 6, null] }] },
|
||||
pruebas: { logrank: { chi2: 120.5, gl: 1, p: 1e-20 }, pares: [{ a: 'B4A', b: 'B5', p: 1e-20, p_holm: 1e-20 }],
|
||||
rmst: [{ grupo: 'B4A', rmst: 700, dif: null, ic_bajo: null, ic_alto: null }, { grupo: 'B5', rmst: 210, dif: -490, ic_bajo: -520, ic_alto: -460 }],
|
||||
rmst_referencia: 'B4A', nota: 'Prueba de Gray pendiente.' },
|
||||
efectos: { estado: 'listo', motivo: null, metodo: 'cox', referencia: 'B4A', etiqueta_referencia: 'BI-RADS 4A',
|
||||
filas: [{ termino: 'B5', etiqueta: 'BI-RADS 5', hr: 30, ic_bajo: 16, ic_alto: 59, n_eventos: 100, metodo: 'cox', ph_p: .01 }] },
|
||||
validacion: [{ chequeo: 'Eventos por grupo', escopo: 'BI-RADS 6', estadistico: null, p: null, umbral: 5, aprobado: false, nota: 'Menos de 5 eventos', version_modelo: 'mock-0.1', sql_sha: null }],
|
||||
avisos: ['Análisis descriptivo, no causal.', 'Horizonte de 2 años (730 días).', 'Requiere el estado vital.'],
|
||||
});
|
||||
const subgrupos = (): AnalisisSubgrupos => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, escenario: 'diagnostico', estimador: 'cif',
|
||||
etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
|
||||
dimension_filas: { clave: 'birads', etiqueta: 'Categoría BI-RADS' }, dimension_columnas: { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
|
||||
pruebas: [{ variable: 'birads', etiqueta: 'Categoría BI-RADS', estratificada_por: 'grupo_edad', etiqueta_estrato: 'Grupo de edad',
|
||||
logrank: { chi2: 90, gl: 1, p: 1e-10, grupos: 2 }, estratificado: { chi2: 85, gl: 1, p: 1e-9, grupos: 2 } },
|
||||
{ variable: 'grupo_edad', etiqueta: 'Grupo de edad', estratificada_por: 'birads', etiqueta_estrato: 'Categoría BI-RADS', logrank: null, estratificado: null }],
|
||||
filas: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }],
|
||||
columnas: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }],
|
||||
celdas: [
|
||||
{ fila: 'B4A', columna: '40-49', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, t_dias: null, valor: null, ic_bajo: null, ic_alto: null },
|
||||
{ fila: 'B4A', columna: '50-59', suprimido: false, motivo: null, n: 60, eventos: 6, t_dias: 730, valor: 10, ic_bajo: 4, ic_alto: 20 },
|
||||
{ fila: 'B5', columna: '40-49', suprimido: false, motivo: null, n: 40, eventos: 36, t_dias: 120, valor: 90, ic_bajo: 78, ic_alto: 96 },
|
||||
{ fila: 'B5', columna: '50-59', suprimido: false, motivo: null, n: 50, eventos: 45, t_dias: 730, valor: 92, ic_bajo: 81, ic_alto: 97 },
|
||||
],
|
||||
});
|
||||
const indicadores = (): AnalisisIndicadores => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, indicadores: [
|
||||
{ clave: 'desarrollo', titulo: 'Incidencia de cáncer a 24 meses', etapa: 'desarrollo', unidad: '%', descripcion: 'Llegan a cáncer.', supuesto: null,
|
||||
suprimido: false, n: 600, eventos: 274, valor: 45.7, ic_bajo: 41.6, ic_alto: 49.6, t_dias: 730 },
|
||||
{ clave: 'recaida', titulo: 'Recaída a 24 meses', etapa: 'recaida', unidad: '%', descripcion: 'Recaen.', supuesto: 'Recaída supuesta.',
|
||||
suprimido: true, n: null, eventos: null, valor: null, ic_bajo: null, ic_alto: null, t_dias: null },
|
||||
],
|
||||
});
|
||||
|
||||
describe('Respuestas del análisis', () => {
|
||||
it('admiten solo agregados de demostración', () => {
|
||||
// Fails if the guards stop rejecting real records or anything shaped like a patient row, at any depth.
|
||||
expect(analisisResultados(resultados()).grupos).toHaveLength(3);
|
||||
expect(analisisCatalogo(catalogo()).etapas).toHaveLength(2);
|
||||
expect(analisisIndicadores(indicadores()).indicadores).toHaveLength(2);
|
||||
expect(() => analisisResultados({ ...resultados(), simulado: false })).toThrow();
|
||||
expect(() => analisisResultados({ ...resultados(), pruebas: { ...resultados().pruebas, items: [{ id_seudonimo: 'M-1' }] } })).toThrow();
|
||||
expect(() => analisisCatalogo({ ...catalogo(), pacientes: [] })).toThrow();
|
||||
});
|
||||
it('rechazan cifras bajo el umbral: un punto de curva, un grupo suprimido con conteos, una celda o un indicador', () => {
|
||||
// Fails if a curve's tail, a suppressed group, a heatmap cell or an epidemiological figure can carry counts under the threshold.
|
||||
const r = resultados();
|
||||
expect(() => analisisResultados({ ...r, curvas: [...r.curvas, punto('B4A', 740, 7, 3, 12)] })).toThrow();
|
||||
expect(() => analisisResultados({ ...r, grupos: r.grupos.map(g => g.suprimido ? { ...g, n: 4 } : g) })).toThrow();
|
||||
expect(() => analisisSubgrupos({ ...subgrupos(), celdas: subgrupos().celdas.map(c => c.suprimido ? c : { ...c, eventos: 3 }) })).toThrow();
|
||||
expect(() => analisisIndicadores({ ...indicadores(), indicadores: [{ ...indicadores().indicadores[0], n: 3 }] })).toThrow();
|
||||
});
|
||||
it('una etapa necesita al menos dos variables para comparar', () => {
|
||||
// Fails if a stage with a single variable reaches the curves or the heatmap, which compare two or more.
|
||||
expect(() => analisisCatalogo({ ...catalogo(), etapas: [{ ...catalogo().etapas[0], variables: ['birads'] }] })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Figuras del análisis', () => {
|
||||
it('dibuja una curva con su banda por grupo publicado y la corta donde la respuesta la suprime', () => {
|
||||
// Fails if a suppressed group gets a trace, the curve runs past its suppressed tail, or a line loses its group.
|
||||
const fig = curvasFigura(resultados(), 'claro');
|
||||
const lineas = fig.data.filter(t => t['meta']);
|
||||
expect(lineas.map(t => t['meta'])).toEqual(['B4A', 'B5']);
|
||||
expect(fig.data).toHaveLength(6);
|
||||
expect(lineas[1]['y'] as number[]).toEqual([0, 70]);
|
||||
});
|
||||
it('en la etapa de supervivencia la curva baja desde 100 % y el eje dice Supervivencia', () => {
|
||||
// Fails if the survival stage is drawn on the incidence axis.
|
||||
const r = resultados();
|
||||
const fig = curvasFigura({ ...r, medida: 'supervivencia', curvas: r.curvas.map(c => c.valor === null ? c : { ...c, valor: 100 - c.valor, ic_bajo: 100 - c.ic_alto!, ic_alto: 100 - c.ic_bajo! }) }, 'claro');
|
||||
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Supervivencia (%)');
|
||||
expect((fig.data.find(t => t['meta'] === 'B4A')!['y'] as number[])[0]).toBe(100);
|
||||
});
|
||||
it('marca vacío el HR con riesgos no proporcionales y no dibuja nada sin modelo', () => {
|
||||
// Fails if the forest plot hides the PH warning or draws an effect the answer did not publish.
|
||||
const fig = forestFigura(resultados(), 'claro');
|
||||
expect((fig.data[1]['marker'] as { color: string[] }).color[0]).toBe('#FFFFFF');
|
||||
expect(forestFigura({ ...resultados(), efectos: { ...resultados().efectos, estado: 'insuficiente', filas: [] } }, 'claro').data).toEqual([]);
|
||||
});
|
||||
it('el mapa de calor dibuja gris lo suprimido y nombra sus dos variables', () => {
|
||||
// Fails if a suppressed cell is drawn as a colour, or the axes stop naming the variables chosen.
|
||||
const fig = subgruposFigura(subgrupos(), 'claro');
|
||||
expect((fig.data[1]['z'] as (number | null)[][])[0]).toEqual([null, 10]);
|
||||
expect((fig.data[0]['z'] as (number | null)[][])[0]).toEqual([1, null]);
|
||||
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Categoría BI-RADS');
|
||||
expect((fig.layout['annotations'] as { text: string }[])[2].text).toContain('a 4 meses');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Selecciones que van a Seguimiento', () => {
|
||||
it('una curva lleva la población del escenario y el valor del grupo', () => {
|
||||
// Fails if a curve opens a list wider than its own patients, or names another group.
|
||||
const pedido = { escenario: 'supervivencia', estimador: 'km', estrato: 'estadio', grupos: [], filtros: {} };
|
||||
expect(grupoDelClic({ points: [{ data: { meta: 'IV' } }] })).toBe('IV');
|
||||
expect(grupoDelClic({ points: [{ data: {} }] })).toBeUndefined();
|
||||
expect(seleccionDeCurva(catalogo(), pedido, 'IV')).toEqual({ filtros: { resultado: 'INVASOR', estadio: 'IV' }, etiqueta: 'Supervivencia: Estadio clínico, Estadio IV' });
|
||||
expect(seleccionDeCurva(catalogo(), pedido, 'XX')).toBeUndefined();
|
||||
});
|
||||
it('una celda lleva sus dos valores, y una celda gris nada', () => {
|
||||
// Fails if a click on a suppressed cell could open the patients the answer hid.
|
||||
expect(celdaDelClic({ points: [{ customdata: ['B5', '40-49'], z: 90 }] })).toEqual({ fila: 'B5', columna: '40-49' });
|
||||
expect(celdaDelClic({ points: [{ customdata: ['B4A', '40-49'], z: null }] })).toBeUndefined();
|
||||
expect(seleccionDeCelda(catalogo(), subgrupos(), { fila: 'B5', columna: '40-49' }))
|
||||
.toEqual({ filtros: { birads: 'B5', grupo_edad: '40-49' }, etiqueta: 'Cáncer confirmado: BI-RADS 5 y 40-49 años' });
|
||||
});
|
||||
it('cada etapa abre con su primera variable y su primer cruce, y conserva un cruce que le pertenece', () => {
|
||||
// Fails if a stage keeps another stage's variable or an estimator it does not admit.
|
||||
expect(pedidoDeEtapa(catalogo(), 'supervivencia', { escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', grupos: ['B5', 'B6'], filtros: {} }))
|
||||
.toEqual({ escenario: 'supervivencia', estimador: 'km', estrato: 'estadio', grupos: [], filtros: {} });
|
||||
const [desarrollo, supervivencia] = catalogo().etapas;
|
||||
expect(cruceDeEtapa(desarrollo, { filas: 'brca', columnas: 'birads' })).toEqual({ filas: 'brca', columnas: 'birads' });
|
||||
expect(cruceDeEtapa(supervivencia, { filas: 'brca', columnas: 'birads' })).toEqual({ filas: 'estadio', columnas: 'grupo_edad' });
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { readonly plotClick = output<unknown>(); }
|
||||
|
||||
describe('Pestaña Análisis epidemiológico', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const text = () => fixture.nativeElement.textContent as string;
|
||||
const curvas = () => http.expectOne(r => r.url === '/cama/analisis/resultados');
|
||||
const abrir = () => {
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
http.expectOne('/cama/analisis').flush(catalogo()); fixture.detectChanges();
|
||||
http.expectOne('/cama/analisis/indicadores').flush(indicadores());
|
||||
};
|
||||
|
||||
it('no pide nada hasta abrirse; luego los indicadores y la primera variable con todos sus valores', () => {
|
||||
// Fails if the tab loads while hidden, or its first request stops being the stage's first variable.
|
||||
fixture.detectChanges();
|
||||
http.expectNone('/cama/analisis');
|
||||
abrir();
|
||||
const req = curvas();
|
||||
expect(['escenario', 'estimador', 'estrato', 'grupos'].map(k => req.request.params.get(k))).toEqual(['diagnostico', 'cif', 'birads', null]);
|
||||
req.flush(resultados()); fixture.detectChanges();
|
||||
expect(text()).toContain('Indicadores epidemiológicos');
|
||||
expect(text()).toContain('IC 95 %: 41.6 a 49.6 %');
|
||||
expect(text()).toContain('Dato oculto por tamaño');
|
||||
expect(text()).toContain('Grupos suprimidos: BI-RADS 6');
|
||||
});
|
||||
it('compara dos o más grupos: con uno avisa y no consulta; con todos no los nombra', () => {
|
||||
// Fails if a single group is sent for a log-rank, or a full selection is sent as a list.
|
||||
abrir(); curvas().flush(resultados());
|
||||
const tab = fixture.componentInstance;
|
||||
tab.elegirGrupos(['B5']); fixture.detectChanges();
|
||||
http.expectNone(r => r.url === '/cama/analisis/resultados');
|
||||
expect(text()).toContain('Elija al menos dos grupos para comparar.');
|
||||
tab.elegirGrupos(['B4A', 'B5']);
|
||||
let req = curvas(); expect(req.request.params.get('grupos')).toBe('B4A,B5'); req.flush(resultados());
|
||||
tab.elegirGrupos(['B4A', 'B5', 'B6']);
|
||||
req = curvas(); expect(req.request.params.has('grupos')).toBe(false); req.flush(resultados());
|
||||
tab.estratificar('brca');
|
||||
req = curvas(); expect([req.request.params.get('estrato'), req.request.params.get('grupos')]).toEqual(['brca', null]); req.flush(resultados());
|
||||
});
|
||||
it('el mapa de calor se pide al abrir su parte, con filas y columnas distintas que se eligen por separado', () => {
|
||||
// Fails if the grid loads with the tab, repeats a request without a change, or accepts the same variable twice.
|
||||
abrir(); curvas().flush(resultados());
|
||||
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
|
||||
const tab = fixture.componentInstance;
|
||||
tab.elegirVista('subgrupos'); fixture.detectChanges();
|
||||
let req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
|
||||
expect(['filas', 'columnas'].map(k => req.request.params.get(k))).toEqual(['birads', 'grupo_edad']);
|
||||
req.flush(subgrupos()); fixture.detectChanges();
|
||||
expect(text()).toContain('Estratificado por la otra');
|
||||
tab.cruzar({ columnas: 'birads' }); fixture.detectChanges();
|
||||
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
|
||||
tab.cruzar({ columnas: 'brca' }); fixture.detectChanges();
|
||||
req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
|
||||
expect(['filas', 'columnas'].map(k => req.request.params.get(k))).toEqual(['birads', 'brca']);
|
||||
req.flush(subgrupos());
|
||||
});
|
||||
it('una curva, su botón de la tabla o una celda emiten la selección para Seguimiento', () => {
|
||||
// Fails if a click stops reaching Seguimiento, or sends a selection without the scenario's population.
|
||||
const emitidas: SeleccionPacientes[] = [];
|
||||
fixture.componentInstance.verPacientes.subscribe(s => emitidas.push(s));
|
||||
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||
fixture.componentInstance.clicCurva({ points: [{ data: { meta: 'B5' } }] });
|
||||
(fixture.nativeElement.querySelector('.riesgo .ver') as HTMLButtonElement).click();
|
||||
fixture.componentInstance.elegirVista('subgrupos'); fixture.detectChanges();
|
||||
http.expectOne(r => r.url === '/cama/analisis/subgrupos').flush(subgrupos()); fixture.detectChanges();
|
||||
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B5', '50-59'], z: 92 }] });
|
||||
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B4A', '40-49'], z: null }] });
|
||||
expect(emitidas.map(e => e.filtros)).toEqual([{ birads: 'B5' }, { birads: 'B4A' }, { birads: 'B5', grupo_edad: '50-59' }]);
|
||||
});
|
||||
it('cambiar de etapa pide su primera variable y anuncia lo supuesto', () => {
|
||||
// Fails if a stage keeps another stage's variable or an estimator it does not admit, or hides its assumptions.
|
||||
abrir(); curvas().flush(resultados());
|
||||
fixture.componentInstance.elegirEtapa('supervivencia'); fixture.detectChanges();
|
||||
const req = curvas();
|
||||
expect(['escenario', 'estimador', 'estrato'].map(k => req.request.params.get(k))).toEqual(['supervivencia', 'km', 'estadio']);
|
||||
req.flush({ ...resultados(), etapa: 'supervivencia', medida: 'supervivencia', escenario: 'supervivencia', estimador: 'km', estrato: 'estadio',
|
||||
supuestos: ['Estado vital supuesto.'] });
|
||||
fixture.detectChanges();
|
||||
expect(text()).toContain('¿Quién sigue viva?');
|
||||
expect(fixture.nativeElement.querySelector('.supuestos')?.textContent).toContain('Estado vital supuesto.');
|
||||
expect(fixture.nativeElement.querySelector('#analisis-curvas h2')?.textContent).toContain('Supervivencia a 24 meses');
|
||||
});
|
||||
it('el diagnóstico muestra el estado de la cohorte, la validación y las variables de la NOM', () => {
|
||||
// Fails if the cohort's status loses a figure, or a hidden total is shown as a number.
|
||||
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||
const diagnostico = fixture.nativeElement.querySelector('#analisis-diagnostico') as HTMLElement;
|
||||
expect(diagnostico.querySelectorAll('.dato')).toHaveLength(5);
|
||||
expect(diagnostico.querySelector('.dato .cifra')?.textContent).toBe('Oculto');
|
||||
expect(diagnostico.querySelector('.requeridas')?.textContent).toContain('Categoría BI-RADS');
|
||||
expect(diagnostico.querySelector('tr.falla')?.textContent).toContain('No cumple');
|
||||
});
|
||||
it('las flechas mueven entre las tres partes', () => {
|
||||
// Fails if the parts stop behaving as a keyboard tab list.
|
||||
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||
const lista = fixture.nativeElement.querySelector('.subsecciones') as HTMLElement;
|
||||
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'End' })); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.vista()).toBe('diagnostico');
|
||||
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' })); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.vista()).toBe('curvas');
|
||||
});
|
||||
it('sin análisis publicado queda pendiente', () => {
|
||||
// Fails if a 404 on the catalog is shown as an error instead of a feature not yet published.
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
http.expectOne('/cama/analisis').flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
|
||||
expect(text()).toContain('Funcionalidad pendiente de publicación');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,535 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, output, signal, untracked } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { curvasFigura, forestFigura, mesesDe, nombreMedida, subgruposFigura } from './indicadores-analisis-figuras';
|
||||
import {
|
||||
AnalisisCatalogo, AnalisisEtapa, AnalisisIndicadores, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos, AnalisisVariable,
|
||||
IndicadorEpidemiologico, PedidoSubgrupos,
|
||||
} from './indicadores-analisis.service';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { Dominio, Tema } from './indicadores.models';
|
||||
|
||||
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' };
|
||||
|
||||
export const formatoP = (p: number | null) => p === null ? '—' : p < .001 ? '< 0.001' : p.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
|
||||
export type VistaAnalisis = 'curvas' | 'subgrupos' | 'diagnostico';
|
||||
export const VISTAS: readonly { id: VistaAnalisis; etiqueta: string }[] = [
|
||||
{ id: 'curvas', etiqueta: 'Curvas (Kaplan-Meier)' },
|
||||
{ id: 'subgrupos', etiqueta: 'Mapa de calor entre variables' },
|
||||
{ id: 'diagnostico', etiqueta: 'Diagnóstico de la cohorte' },
|
||||
];
|
||||
// The patients behind a curve or a heatmap cell: the follow-up list's filters and how to name the selection.
|
||||
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; }
|
||||
|
||||
/** The cell of the grid: its row and column codes, from the coloured layer only (grey cells are suppressed). */
|
||||
export function celdaDelClic(evento: unknown): { fila: string; columna: string } | undefined {
|
||||
const punto = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
|
||||
const c = punto?.customdata;
|
||||
return Array.isArray(c) && typeof c[0] === 'string' && typeof c[1] === 'string' && typeof punto?.z === 'number' ? { fila: c[0], columna: c[1] } : undefined;
|
||||
}
|
||||
|
||||
/** The group of the clicked curve, from the line's `meta`; bands and empty clicks give nothing. */
|
||||
export function grupoDelClic(evento: unknown): string | undefined {
|
||||
const punto = (evento as { points?: { data?: { meta?: unknown } }[] } | undefined)?.points?.[0];
|
||||
return typeof punto?.data?.meta === 'string' ? punto.data.meta : undefined;
|
||||
}
|
||||
|
||||
/** The stage a scenario belongs to. */
|
||||
export const etapaDe = (catalogo: AnalisisCatalogo, escenario: string | undefined): AnalisisEtapa | undefined =>
|
||||
catalogo.etapas.find(e => e.escenarios.includes(escenario ?? ''));
|
||||
|
||||
/** The request a stage opens with: its first scenario and variable, all its values, the estimator if the stage admits it. */
|
||||
export function pedidoDeEtapa(catalogo: AnalisisCatalogo, clave: string, actual?: AnalisisPedido): AnalisisPedido {
|
||||
const etapa = catalogo.etapas.find(e => e.clave === clave) ?? catalogo.etapas[0];
|
||||
const estimador = actual && etapa.estimadores.includes(actual.estimador) ? actual.estimador : etapa.estimadores[0];
|
||||
return { escenario: etapa.escenarios[0], estimador, estrato: etapa.variables[0], grupos: [], filtros: {} };
|
||||
}
|
||||
|
||||
/** The grid a stage opens with: its first two variables, or the current ones while they belong to it. */
|
||||
export function cruceDeEtapa(etapa: AnalisisEtapa, actual?: { filas: string; columnas: string }) {
|
||||
const valido = actual && actual.filas !== actual.columnas && etapa.variables.includes(actual.filas) && etapa.variables.includes(actual.columnas);
|
||||
return valido ? { filas: actual.filas, columnas: actual.columnas } : { filas: etapa.variables[0], columnas: etapa.variables[1] };
|
||||
}
|
||||
|
||||
/** The follow-up filters of a curve: the scenario's population and the group's value of the compared variable. */
|
||||
export function seleccionDeCurva(catalogo: AnalisisCatalogo, pedido: AnalisisPedido, grupo: string): SeleccionPacientes | undefined {
|
||||
const escenario = catalogo.escenarios.find(e => e.clave === pedido.escenario), variable = catalogo.variables.find(v => v.clave === pedido.estrato);
|
||||
if (!escenario || !variable) return undefined;
|
||||
const valor = variable.opciones.find(o => o.codigo === grupo);
|
||||
if (!valor) return undefined;
|
||||
return { filtros: { ...escenario.filtro_seguimiento, [variable.clave]: grupo }, etiqueta: `${escenario.etiqueta}: ${variable.etiqueta}, ${valor.etiqueta}` };
|
||||
}
|
||||
|
||||
/** The follow-up filters of a grid cell: the scenario's population and both values. */
|
||||
export function seleccionDeCelda(catalogo: AnalisisCatalogo, sub: AnalisisSubgrupos, celda: { fila: string; columna: string }): SeleccionPacientes | undefined {
|
||||
const escenario = catalogo.escenarios.find(e => e.clave === sub.escenario);
|
||||
const fila = sub.filas.find(f => f.codigo === celda.fila), columna = sub.columnas.find(c => c.codigo === celda.columna);
|
||||
if (!escenario || !fila || !columna) return undefined;
|
||||
return { filtros: { ...escenario.filtro_seguimiento, [sub.dimension_filas.clave]: celda.fila, [sub.dimension_columnas.clave]: celda.columna },
|
||||
etiqueta: `${escenario.etiqueta}: ${fila.etiqueta} y ${columna.etiqueta}` };
|
||||
}
|
||||
|
||||
// Epidemiological analysis of the BI-RADS 4+ cohort. On top, the cohort's figures (incidence of cancer and of
|
||||
// recurrence, follow-up adherence and survival). Then, by stage (development, recurrence, survival), three parts:
|
||||
// the Kaplan-Meier curves of two or more values of one variable, the heatmap of two distinct variables, and the
|
||||
// cohort's diagnostics. A curve or a cell opens its patients in Seguimiento; nothing else leaves the aggregates.
|
||||
// Nothing is requested until the tab is first opened, and the grid only once its part is.
|
||||
@Component({
|
||||
selector: 'app-indicadores-analisis',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart, IndicadorKpiCard],
|
||||
template: `
|
||||
@switch (catalogo().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando el análisis" /> }
|
||||
@case ('pendiente') { <p role="status" class="panel">Funcionalidad pendiente de publicación.</p> }
|
||||
@case ('error') { <div role="alert" class="panel"><p>{{ $any(catalogo()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentarCatalogo()">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (cat(); as c) {
|
||||
<section class="epidemiologicos" aria-labelledby="indicadores-epidemiologicos">
|
||||
<h2 id="indicadores-epidemiologicos">Indicadores epidemiológicos</h2>
|
||||
<p class="nota">De toda la cohorte, a {{ meses(c.horizonte_dias) }} meses. Descriptivos, no causales.</p>
|
||||
@switch (indicadores().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores epidemiológicos" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(indicadores()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarIndicadores()">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (ind(); as i) {
|
||||
<div class="kpis">
|
||||
@for (x of i.indicadores; track x.clave) {
|
||||
<app-indicador-kpi-card [title]="x.titulo" [value]="x.valor === null ? null : x.valor.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 })"
|
||||
[unit]="x.unidad" [state]="x.suprimido ? 'Dato oculto por tamaño' : 'Disponible'" [quietWhenAvailable]="true" [additionalInfo]="infoIndicador(x)" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<div class="controles">
|
||||
<span id="analisis-etapa" class="etiqueta">Etapa</span>
|
||||
<mat-button-toggle-group class="etapas" aria-labelledby="analisis-etapa" hideSingleSelectionIndicator [value]="etapa()?.clave" (change)="elegirEtapa($event.value)">
|
||||
@for (e of c.etapas; track e.clave) { <mat-button-toggle [value]="e.clave">{{ e.etiqueta }}</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
@if (escenariosEtapa().length > 1) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Escenario</mat-label>
|
||||
<mat-select [value]="pedido()!.escenario" (selectionChange)="cambiar({ escenario: $event.value })">
|
||||
@for (e of escenariosEtapa(); track e.clave) { <mat-option [value]="e.clave">{{ e.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (estimadoresEtapa().length > 1) {
|
||||
<span id="analisis-estimador" class="etiqueta">Estimador</span>
|
||||
<mat-button-toggle-group aria-labelledby="analisis-estimador" hideSingleSelectionIndicator [value]="pedido()!.estimador" (change)="cambiar({ estimador: $event.value })">
|
||||
@for (e of estimadoresEtapa(); track e.clave) { <mat-button-toggle [value]="e.clave" [attr.title]="e.nota">{{ e.clave === 'cif' ? 'Aalen-Johansen' : '1 − Kaplan-Meier' }}</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
} @else { <span class="etiqueta">Kaplan-Meier</span> }
|
||||
</div>
|
||||
@if (escenario(); as e) {
|
||||
<p class="contexto">@if (etapa(); as et) { <strong>{{ et.pregunta }}</strong><br> }{{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.</p>
|
||||
}
|
||||
|
||||
<div class="subsecciones" role="tablist" aria-label="Partes del análisis" (keydown)="teclaVista($event)">
|
||||
@for (v of VISTAS; track v.id) {
|
||||
<button type="button" role="tab" [id]="'analisis-tab-' + v.id" [attr.aria-controls]="'analisis-' + v.id" [attr.aria-selected]="vista() === v.id"
|
||||
[tabIndex]="vista() === v.id ? 0 : -1" (click)="elegirVista(v.id)">{{ v.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Curves: two or more values of one variable, compared by log-rank and Cox. -->
|
||||
<section id="analisis-curvas" role="tabpanel" aria-labelledby="analisis-tab-curvas" [hidden]="vista() !== 'curvas'">
|
||||
<div class="controles-panel">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Comparar por</mat-label>
|
||||
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
|
||||
@for (v of variablesEtapa(); track v.clave) {
|
||||
<mat-option [value]="v.clave">{{ v.etiqueta }}@if (v.estado === 'supuesto') { <span class="motivo"> · supuesto</span> }</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@if (variableCurvas(); as v) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Grupos a comparar</mat-label>
|
||||
<mat-select multiple [value]="gruposMostrados()" (selectionChange)="elegirGrupos($event.value)">
|
||||
@for (o of v.opciones; track o.codigo) { <mat-option [value]="o.codigo">{{ o.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (pocosGrupos()) { <span class="aviso-grupos" role="alert">Elija al menos dos grupos para comparar.</span> }
|
||||
</div>
|
||||
@switch (resultados().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el análisis" /> }
|
||||
@case ('error') { <div role="alert" class="panel"><p>{{ $any(resultados()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (res(); as r) {
|
||||
<p class="resumen" role="status">
|
||||
@if (r.poblacion.n !== null) { {{ miles(r.poblacion.n) }} pacientes · {{ miles(r.poblacion.eventos ?? 0) }} eventos }
|
||||
@else if (r.poblacion.totales_ocultos) { Totales ocultos para no revelar un grupo suprimido }
|
||||
</p>
|
||||
@if (r.supuestos.length) {
|
||||
<div class="supuestos" role="note"><strong>Datos supuestos en el mock.</strong>
|
||||
<ul>@for (t of r.supuestos; track t) { <li>{{ t }}</li> }</ul></div>
|
||||
}
|
||||
<div class="paneles">
|
||||
<article class="panel ancho">
|
||||
<h2>{{ nombreMedida() }} a {{ meses(r.horizonte_dias) }} meses por {{ variableCurvas()?.etiqueta?.toLowerCase() }}</h2>
|
||||
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una curva para ver sus pacientes en Seguimiento.</p>
|
||||
@if (figuraCurvas().data.length) {
|
||||
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
|
||||
[label]="nombreMedida() + ' por ' + (variableCurvas()?.etiqueta ?? 'grupo')" />
|
||||
<table class="riesgo">
|
||||
<caption>Pacientes en riesgo</caption>
|
||||
<thead><tr><th scope="col">Grupo</th>@for (d of r.tabla_riesgo.cortes_dias; track d) { <th scope="col">Mes {{ meses(d) }}</th> }<th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<tbody>
|
||||
@for (f of r.tabla_riesgo.filas; track f.grupo) {
|
||||
<tr><th scope="row">{{ etiqueta(f.grupo) }}</th>@for (v of f.cortes; track $index) { <td>{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}</td> }
|
||||
<td><button type="button" class="ver" (click)="verGrupo(f.grupo)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(f.grupo) + ' en Seguimiento'">Ver pacientes</button></td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
} @else { <p role="status">Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con esta selección.</p> }
|
||||
@if (suprimidos().length) { <p class="nota">Grupos suprimidos: {{ textoSuprimidos() }}.</p> }
|
||||
<p class="nota">La curva termina donde quedan menos de {{ r.umbral_supresion }} pacientes en riesgo. La banda es el intervalo de confianza al 95 %.</p>
|
||||
@for (a of r.avisos.slice(2); track a) { <p class="nota">{{ a }}</p> }
|
||||
</article>
|
||||
|
||||
<article class="panel">
|
||||
<h2>Comparación entre grupos</h2>
|
||||
@if (r.pruebas.logrank; as lr) {
|
||||
<p>Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.</p>
|
||||
@if (r.pruebas.pares.length > 1) {
|
||||
<table><caption>Comparaciones por pares (corrección de Holm)</caption>
|
||||
<thead><tr><th scope="col">Grupos</th><th scope="col">p</th><th scope="col">p ajustada</th></tr></thead>
|
||||
<tbody>@for (par of r.pruebas.pares; track par.a + par.b) { <tr><td>{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}</td><td>{{ formatoP(par.p) }}</td><td>{{ formatoP(par.p_holm) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
}
|
||||
} @else { <p role="status">Se necesitan al menos dos grupos publicados para comparar.</p> }
|
||||
@if (r.pruebas.nota) { <p class="nota">{{ r.pruebas.nota }}</p> }
|
||||
@if (r.pruebas.rmst.length) {
|
||||
<table><caption>Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)</caption>
|
||||
<thead><tr><th scope="col">Grupo</th><th scope="col">Días</th><th scope="col">Diferencia (IC 95 %)</th></tr></thead>
|
||||
<tbody>@for (f of r.pruebas.rmst; track f.grupo) {
|
||||
<tr><td>{{ etiqueta(f.grupo) }}</td><td>{{ f.rmst.toLocaleString('es-MX') }}</td>
|
||||
<td>{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="panel">
|
||||
<h2>Razón de riesgos (Cox)</h2>
|
||||
@if (r.efectos.estado === 'listo') {
|
||||
<app-plotly-chart [style.--plot-height]="figuraForest().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraForest()" label="Razones de riesgos con intervalo al 95 %" />
|
||||
<p class="nota">Modelo de Cox de una variable ({{ variableCurvas()?.etiqueta?.toLowerCase() }}), contra {{ r.efectos.etiqueta_referencia }}. Un cuadro vacío marca riesgos no proporcionales. Describe diferencias; no estima un efecto causal.</p>
|
||||
} @else {
|
||||
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
|
||||
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}</p>
|
||||
}
|
||||
</article>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<!-- Heatmap: two distinct variables of the stage, each tested plain and at equal value of the other. -->
|
||||
<section id="analisis-subgrupos" role="tabpanel" aria-labelledby="analisis-tab-subgrupos" [hidden]="vista() !== 'subgrupos'">
|
||||
@if (cruce(); as x) {
|
||||
<div class="controles-panel">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Filas</mat-label>
|
||||
<mat-select [value]="x.filas" (selectionChange)="cruzar({ filas: $event.value })">
|
||||
@for (v of variablesEtapa(); track v.clave) { <mat-option [value]="v.clave" [disabled]="v.clave === x.columnas">{{ v.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Columnas</mat-label>
|
||||
<mat-select [value]="x.columnas" (selectionChange)="cruzar({ columnas: $event.value })">
|
||||
@for (v of variablesEtapa(); track v.clave) { <mat-option [value]="v.clave" [disabled]="v.clave === x.filas">{{ v.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
}
|
||||
<div class="paneles">
|
||||
<article class="panel ancho">
|
||||
<h2>{{ nombreMedida() }} a {{ meses(c.horizonte_dias) }} meses@if (sub(); as s) { por {{ s.dimension_filas.etiqueta.toLowerCase() }} y {{ s.dimension_columnas.etiqueta.toLowerCase() }} }</h2>
|
||||
@switch (subgrupos().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa de calor" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(subgrupos()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarSubgrupos(true)">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (sub(); as s) {
|
||||
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus pacientes en Seguimiento.</p>
|
||||
@if (s.supuestos.length) { <p class="nota">Supuesto en el mock: {{ s.supuestos.join(' ') }}</p> }
|
||||
<app-plotly-chart [style.--plot-height]="figuraSubgrupos().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraSubgrupos()" (plotClick)="clicCelda($event)"
|
||||
[label]="nombreMedida() + ' por ' + s.dimension_filas.etiqueta + ' y ' + s.dimension_columnas.etiqueta" />
|
||||
<p class="nota">Cada celda dice el porcentaje, los eventos y las pacientes. Una celda gris tiene menos de {{ s.umbral_supresion }} pacientes o eventos. «A N meses» marca una celda cuya curva termina antes del horizonte.</p>
|
||||
<table>
|
||||
<caption>Log-rank de cada variable</caption>
|
||||
<thead><tr><th scope="col">Variable</th><th scope="col">Log-rank</th><th scope="col">Estratificado por la otra</th></tr></thead>
|
||||
<tbody>@for (pr of s.pruebas; track pr.variable) {
|
||||
<tr><td>{{ pr.etiqueta }}</td>
|
||||
<td>{{ pr.logrank ? 'χ² ' + pr.logrank.chi2.toLocaleString('es-MX') + ', ' + pr.logrank.gl + ' gl, p ' + formatoP(pr.logrank.p) : 'Menos de dos grupos con eventos suficientes' }}</td>
|
||||
<td>{{ pr.estratificado ? 'p ' + formatoP(pr.estratificado.p) + ' (por ' + pr.etiqueta_estrato.toLowerCase() + ')' : '—' }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
<p class="nota">El log-rank estratificado compara los grupos de una variable dentro de cada valor de la otra: si la diferencia desaparece, la explicaba la otra variable.</p>
|
||||
}
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Diagnostics: the statistical status of the cohort and the checks behind every figure. -->
|
||||
<section id="analisis-diagnostico" role="tabpanel" aria-labelledby="analisis-tab-diagnostico" [hidden]="vista() !== 'diagnostico'">
|
||||
@if (res(); as r) {
|
||||
<div class="estado-cohorte">
|
||||
<div class="dato"><span class="cifra">{{ r.poblacion.n === null ? 'Oculto' : miles(r.poblacion.n) }}</span><span>pacientes en la población</span></div>
|
||||
<div class="dato"><span class="cifra">{{ r.poblacion.eventos === null ? 'Oculto' : miles(r.poblacion.eventos) }}</span><span>eventos en {{ meses(r.horizonte_dias) }} meses</span></div>
|
||||
<div class="dato"><span class="cifra">{{ r.poblacion.seguimiento_mediano_dias === null ? 'Sin dato' : meses(r.poblacion.seguimiento_mediano_dias) + ' meses' }}</span><span>seguimiento mediano</span></div>
|
||||
<div class="dato"><span class="cifra">{{ eventosPorParametro() ?? '—' }}</span><span>eventos por parámetro (mínimo 10)</span></div>
|
||||
<div class="dato"><span class="cifra">{{ r.umbral_supresion }}</span><span>umbral de supresión</span></div>
|
||||
</div>
|
||||
@if (r.poblacion.totales_ocultos) { <p class="nota">Los totales se ocultan porque un grupo está suprimido y se podría deducir.</p> }
|
||||
<article class="panel">
|
||||
<h2>Reporte de validación</h2>
|
||||
<p class="nota">De las curvas: {{ escenario()?.etiqueta?.toLowerCase() }}, por {{ variableCurvas()?.etiqueta?.toLowerCase() }}.</p>
|
||||
<table class="validacion">
|
||||
<thead><tr><th scope="col">Chequeo</th><th scope="col">Alcance</th><th scope="col">Valor</th><th scope="col">Umbral</th><th scope="col">Resultado</th><th scope="col">Nota</th></tr></thead>
|
||||
<tbody>@for (v of r.validacion; track $index) {
|
||||
<tr [class.falla]="v.aprobado === false">
|
||||
<td>{{ v.chequeo }}</td><td>{{ v.escopo }}</td>
|
||||
<td>{{ v.p !== null ? 'p ' + formatoP(v.p) : v.estadistico !== null ? v.estadistico.toLocaleString('es-MX') : '—' }}</td>
|
||||
<td>{{ v.umbral === null ? '—' : v.umbral.toLocaleString('es-MX') }}</td>
|
||||
<td>{{ v.aprobado === null ? 'No aplica' : v.aprobado ? 'Cumple' : 'No cumple' }}</td>
|
||||
<td>{{ v.nota ?? '' }}</td>
|
||||
</tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
<p class="nota">Versión del modelo: {{ r.validacion[0]?.version_modelo }}.</p>
|
||||
</article>
|
||||
}
|
||||
@if (etapa(); as et) {
|
||||
<article class="panel requeridas">
|
||||
<h2>Variables de la NOM para la etapa de {{ et.etiqueta.toLowerCase() }}</h2>
|
||||
<p class="nota">Lo que hay que registrar para estratificar estas curvas, ajustar Cox y aplicar el log-rank. Las de esta etapa:
|
||||
@for (v of variablesEtapa(); track v.clave) { {{ v.etiqueta }} ({{ v.estado === 'registrado' ? 'registrada' : 'supuesta' }}){{ $last ? '.' : ';' }} }</p>
|
||||
<table>
|
||||
<thead><tr><th scope="col">Variable</th><th scope="col">NOM</th><th scope="col">En el esquema</th></tr></thead>
|
||||
<tbody>@for (v of et.requeridas; track v.variable) {
|
||||
<tr [class.falta]="v.estado !== 'registrado'"><td>{{ v.variable }}</td><td>{{ v.nom }}</td><td>{{ v.estado }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</article>
|
||||
}
|
||||
<section class="pendientes" aria-labelledby="analisis-pendientes">
|
||||
<h2 id="analisis-pendientes">Lo que la cohorte aún no permite</h2>
|
||||
<div class="tarjetas">
|
||||
@for (b of c.bloqueados; track b.clave) { <article class="bloqueado"><h3>{{ b.titulo }}</h3><p>{{ b.motivo }}</p></article> }
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.controles mat-form-field { min-width: 12rem; }
|
||||
.controles mat-form-field:first-child { min-width: 20rem; }
|
||||
.contexto, .resumen { margin: var(--issste-space-3) 0 0; font: var(--mat-sys-body-medium); color: var(--issste-text); }
|
||||
.resumen { margin: 0 0 var(--issste-space-4); color: var(--issste-text-secondary); }
|
||||
.motivo, .nota, .etiqueta { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.panel.ancho { grid-column: 1 / -1; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
table { width: 100%; margin-top: var(--issste-space-4); border-collapse: collapse; font: var(--mat-sys-body-medium); }
|
||||
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
|
||||
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
|
||||
.riesgo td { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.validacion tr.falla td { font-weight: 600; }
|
||||
.estado-modelo { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.estado-modelo.insuficiente { border-style: solid; }
|
||||
.pendientes { margin-top: var(--issste-space-6); }
|
||||
.tarjetas { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
.bloqueado { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); background: transparent; }
|
||||
.bloqueado h3 { margin: 0; font: var(--mat-sys-title-small); }
|
||||
.epidemiologicos { margin-bottom: var(--issste-space-6); }
|
||||
.epidemiologicos .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); grid-auto-rows: 1fr; gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
.controles-panel { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
|
||||
.controles-panel mat-form-field { min-width: 14rem; }
|
||||
.ver { padding: 0; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
|
||||
.ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.aviso-grupos { color: var(--issste-text); font-weight: 600; }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
.subsecciones { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin: var(--issste-space-4) 0; border-bottom: 1px solid var(--issste-border); }
|
||||
.subsecciones button { padding: var(--issste-space-2) var(--issste-space-4); border: 0; border-bottom: 3px solid transparent; background: none; color: var(--issste-text-secondary);
|
||||
font: var(--mat-sys-title-small); cursor: pointer; min-height: 44px; }
|
||||
.subsecciones button[aria-selected='true'] { color: var(--issste-text); border-bottom-color: var(--issste-accent); }
|
||||
.subsecciones button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.supuestos { margin: 0 0 var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border-left: 4px solid var(--issste-accent);
|
||||
background: var(--issste-surface); color: var(--issste-text); font: var(--mat-sys-body-medium); }
|
||||
.supuestos ul { margin: var(--issste-space-1) 0 0; padding-left: var(--issste-space-6); }
|
||||
.requeridas { margin-top: var(--issste-space-6); }
|
||||
.requeridas tr.falta td:last-child { font-weight: 600; }
|
||||
.comparacion { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@container dashboard (min-width: 960px) { .comparacion { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.estado-cohorte { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: var(--issste-space-4); margin-bottom: var(--issste-space-4); }
|
||||
.dato { display: flex; flex-direction: column; gap: var(--issste-space-1); padding: var(--issste-space-4); background: var(--issste-surface);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.dato .cifra { color: var(--issste-text); font-size: 1.5rem; font-weight: 500; line-height: 1.2; }
|
||||
@media (max-width: 600px) { .controles { padding: var(--issste-space-3); } .controles mat-form-field, .controles mat-form-field:first-child { min-width: 100%; } }
|
||||
`,
|
||||
|
||||
})
|
||||
export class IndicadoresAnalisis {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
// The patients of a curve or a heatmap cell, for the page to open them in Seguimiento.
|
||||
readonly verPacientes = output<SeleccionPacientes>();
|
||||
readonly formatoP = formatoP;
|
||||
readonly miles = (v: number) => v.toLocaleString('es-MX');
|
||||
readonly meses = mesesDe;
|
||||
readonly VISTAS = VISTAS;
|
||||
private readonly service = inject(AnalisisService);
|
||||
readonly catalogo = signal<Carga<AnalisisCatalogo>>({ estado: 'cargando' });
|
||||
readonly resultados = signal<Carga<AnalisisResultados>>({ estado: 'cargando' });
|
||||
readonly subgrupos = signal<Carga<AnalisisSubgrupos>>({ estado: 'cargando' });
|
||||
readonly indicadores = signal<Carga<AnalisisIndicadores>>({ estado: 'cargando' });
|
||||
readonly pedido = signal<AnalisisPedido | undefined>(undefined);
|
||||
readonly cruce = signal<{ filas: string; columnas: string } | undefined>(undefined);
|
||||
readonly vista = signal<VistaAnalisis>('curvas');
|
||||
readonly pocosGrupos = signal(false);
|
||||
private readonly pedidos = new Subject<AnalisisPedido>();
|
||||
private readonly pedidosSubgrupos = new Subject<PedidoSubgrupos>();
|
||||
private readonly catalogos = new Subject<void>();
|
||||
private readonly pedidosIndicadores = new Subject<void>();
|
||||
private abierto = false;
|
||||
private subgruposDe?: string;
|
||||
|
||||
readonly cat = computed(() => { const c = this.catalogo(); return c.estado === 'listo' ? c.datos : undefined; });
|
||||
readonly res = computed(() => { const r = this.resultados(); return r.estado === 'listo' ? r.datos : undefined; });
|
||||
readonly sub = computed(() => { const s = this.subgrupos(); return s.estado === 'listo' ? s.datos : undefined; });
|
||||
readonly ind = computed(() => { const i = this.indicadores(); return i.estado === 'listo' ? i.datos : undefined; });
|
||||
readonly escenario = computed(() => this.cat()?.escenarios.find(e => e.clave === this.pedido()?.escenario));
|
||||
readonly estimadorElegido = computed(() => this.cat()?.estimadores.find(e => e.clave === this.pedido()?.estimador));
|
||||
readonly etapa = computed(() => { const c = this.cat(); return c ? etapaDe(c, this.pedido()?.escenario) : undefined; });
|
||||
readonly nombreMedida = computed(() => nombreMedida(this.etapa()?.medida ?? 'incidencia'));
|
||||
readonly variablesEtapa = computed(() => (this.etapa()?.variables ?? [] as readonly string[])
|
||||
.map(k => this.cat()?.variables.find(v => v.clave === k)).filter((v): v is AnalisisVariable => !!v));
|
||||
readonly escenariosEtapa = computed(() => this.cat()?.escenarios.filter(e => this.etapa()?.escenarios.includes(e.clave)) ?? []);
|
||||
readonly estimadoresEtapa = computed(() => this.cat()?.estimadores.filter(e => this.etapa()?.estimadores.includes(e.clave)) ?? []);
|
||||
readonly variableCurvas = computed(() => this.variablesEtapa().find(v => v.clave === this.pedido()?.estrato));
|
||||
// Every value when none was picked; the selector shows them checked.
|
||||
readonly gruposMostrados = computed(() => { const p = this.pedido(); return p?.grupos.length ? p.grupos : this.variableCurvas()?.opciones.map(o => o.codigo) ?? []; });
|
||||
readonly suprimidos = computed(() => this.res()?.grupos.filter(g => g.suprimido) ?? []);
|
||||
readonly textoSuprimidos = computed(() => this.suprimidos().map(g => `${g.etiqueta} (${(g.motivo ?? 'suprimido').toLowerCase()})`).join('; '));
|
||||
readonly figuraCurvas = computed(() => { const r = this.res(); return r ? curvasFigura(r, this.tema()) : { data: [], layout: {} }; });
|
||||
readonly figuraForest = computed(() => { const r = this.res(); return r ? forestFigura(r, this.tema()) : { data: [], layout: {} }; });
|
||||
readonly figuraSubgrupos = computed(() => { const s = this.sub(); return s ? subgruposFigura(s, this.tema()) : { data: [], layout: {} }; });
|
||||
readonly eventosPorParametro = computed(() => {
|
||||
const fila = this.res()?.validacion.find(v => v.chequeo === 'Eventos por parámetro');
|
||||
return fila?.estadistico == null ? null : fila.estadistico.toLocaleString('es-MX');
|
||||
});
|
||||
|
||||
constructor() {
|
||||
const destroy = inject(DestroyRef);
|
||||
const cargar = <T>(fuente: () => Observable<T>, pendiente = false) => fuente().pipe(
|
||||
map((datos): Carga<T> => ({ estado: 'listo', datos })),
|
||||
catchError(error => of<Carga<T>>(pendiente && error?.status === 404 ? { estado: 'pendiente' } : { estado: 'error', mensaje: httpMessage(error) })),
|
||||
startWith<Carga<T>>({ estado: 'cargando' }));
|
||||
this.catalogos.pipe(switchMap(() => cargar(() => this.service.catalogo(this.dominio()), true)), takeUntilDestroyed(destroy)).subscribe(carga => {
|
||||
this.catalogo.set(carga);
|
||||
if (carga.estado === 'listo' && !this.pedido()) {
|
||||
this.cambiar(pedidoDeEtapa(carga.datos, carga.datos.etapas[0].clave));
|
||||
this.cargarIndicadores();
|
||||
}
|
||||
});
|
||||
this.pedidos.pipe(switchMap(p => cargar(() => this.service.resultados(this.dominio(), p))), takeUntilDestroyed(destroy)).subscribe(c => this.resultados.set(c));
|
||||
this.pedidosSubgrupos.pipe(switchMap(p => cargar(() => this.service.subgrupos(this.dominio(), p))), takeUntilDestroyed(destroy)).subscribe(c => this.subgrupos.set(c));
|
||||
this.pedidosIndicadores.pipe(switchMap(() => cargar(() => this.service.indicadores(this.dominio()))), takeUntilDestroyed(destroy)).subscribe(c => this.indicadores.set(c));
|
||||
// The grid follows the stage, the scenario, the estimator and its two variables; it is asked for when its part is open.
|
||||
effect(() => {
|
||||
const vista = this.vista(), pedido = this.pedido(), cruce = this.cruce();
|
||||
if (vista === 'subgrupos' && pedido && cruce) untracked(() => this.cargarSubgrupos());
|
||||
});
|
||||
effect(() => {
|
||||
if (!this.active() || this.abierto) return;
|
||||
untracked(() => { this.abierto = true; this.catalogos.next(); });
|
||||
});
|
||||
}
|
||||
|
||||
cambiar(cambio: Partial<AnalisisPedido>) {
|
||||
const pedido: AnalisisPedido = { escenario: '', estimador: '', estrato: '', grupos: [], filtros: {}, ...this.pedido(), ...cambio };
|
||||
this.pedido.set(pedido);
|
||||
this.pocosGrupos.set(false);
|
||||
const etapa = this.cat() && etapaDe(this.cat()!, pedido.escenario);
|
||||
if (etapa) this.cruce.set(cruceDeEtapa(etapa, this.cruce()));
|
||||
this.pedidos.next(pedido);
|
||||
}
|
||||
// A stage keeps the estimator when it admits it, and starts from its first scenario and variable.
|
||||
elegirEtapa(clave: string) {
|
||||
const c = this.cat();
|
||||
if (c && clave !== this.etapa()?.clave) this.cambiar(pedidoDeEtapa(c, clave, this.pedido()));
|
||||
}
|
||||
estratificar(estrato: string) { this.cambiar({ estrato, grupos: [] }); }
|
||||
// Two or more values are compared; with all of them checked, the request names none.
|
||||
elegirGrupos(grupos: string[]) {
|
||||
if (grupos.length < 2) { this.pocosGrupos.set(true); return; }
|
||||
const todos = this.variableCurvas()?.opciones.length ?? 0;
|
||||
this.cambiar({ grupos: grupos.length === todos ? [] : grupos });
|
||||
}
|
||||
cruzar(cambio: Partial<{ filas: string; columnas: string }>) {
|
||||
const actual = this.cruce();
|
||||
if (!actual) return;
|
||||
const siguiente = { ...actual, ...cambio };
|
||||
if (siguiente.filas !== siguiente.columnas) this.cruce.set(siguiente);
|
||||
}
|
||||
infoIndicador(x: IndicadorEpidemiologico) {
|
||||
if (x.suprimido) return x.descripcion;
|
||||
const intervalo = x.ic_bajo !== null && x.ic_alto !== null ? `IC 95 %: ${x.ic_bajo.toLocaleString('es-MX')} a ${x.ic_alto.toLocaleString('es-MX')} %. ` : '';
|
||||
const conteo = x.clave === 'adherencia' ? `${this.miles(x.eventos!)} de ${this.miles(x.n!)} pacientes. ` : `${this.miles(x.eventos!)} eventos en ${this.miles(x.n!)} pacientes. `;
|
||||
return intervalo + conteo + x.descripcion + (x.supuesto ? ' ' + x.supuesto : '');
|
||||
}
|
||||
clicCurva(evento: unknown) {
|
||||
const grupo = grupoDelClic(evento);
|
||||
if (grupo) this.verGrupo(grupo);
|
||||
}
|
||||
verGrupo(grupo: string) {
|
||||
const c = this.cat(), p = this.pedido(), seleccion = c && p ? seleccionDeCurva(c, p, grupo) : undefined;
|
||||
if (seleccion) this.verPacientes.emit(seleccion);
|
||||
}
|
||||
clicCelda(evento: unknown) {
|
||||
const celda = celdaDelClic(evento), c = this.cat(), s = this.sub();
|
||||
const seleccion = celda && c && s ? seleccionDeCelda(c, s, celda) : undefined;
|
||||
if (seleccion) this.verPacientes.emit(seleccion);
|
||||
}
|
||||
elegirVista(vista: VistaAnalisis) { this.vista.set(vista); }
|
||||
teclaVista(event: KeyboardEvent) {
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const i = VISTAS.findIndex(v => v.id === this.vista());
|
||||
const j = event.key === 'Home' ? 0 : event.key === 'End' ? VISTAS.length - 1 : (i + (event.key === 'ArrowRight' ? 1 : -1) + VISTAS.length) % VISTAS.length;
|
||||
this.vista.set(VISTAS[j].id);
|
||||
(event.currentTarget as HTMLElement).querySelectorAll<HTMLButtonElement>('[role="tab"]')[j]?.focus();
|
||||
}
|
||||
cargarSubgrupos(forzar = false) {
|
||||
const p = this.pedido(), x = this.cruce();
|
||||
if (!p || !x) return;
|
||||
const pedido = { escenario: p.escenario, estimador: p.estimador, ...x };
|
||||
const clave = JSON.stringify(pedido);
|
||||
if (!forzar && clave === this.subgruposDe) return;
|
||||
this.subgruposDe = clave;
|
||||
this.pedidosSubgrupos.next(pedido);
|
||||
}
|
||||
cargarIndicadores() { this.pedidosIndicadores.next(); }
|
||||
etiqueta(grupo: string) { return this.res()?.grupos.find(g => g.grupo === grupo)?.etiqueta ?? grupo; }
|
||||
reintentar() { const p = this.pedido(); if (p) this.pedidos.next(p); }
|
||||
reintentarCatalogo() { this.catalogos.next(); }
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { c1DonutCapability, c1DonutFigure, c1DonutLabels } from './indicadores-c1-donut';
|
||||
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const fila = (estrato: string, numerador: number, denominador: number, extra: object = {}) => ({
|
||||
periodo: '2025-S2', grupo: 'TOTAL', estrato, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
|
||||
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
|
||||
});
|
||||
const datos = (filas = [fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]): IndicadorDatos => ({
|
||||
id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unidad: 'paciente',
|
||||
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'grupo_edad', valores_estrato: ['16-23', '24-29', '30-36'],
|
||||
etiquetas_estrato: { '16-23': '16 a 23 meses', '24-29': '24 a 29 meses', '30-36': '30 a 36 meses' },
|
||||
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
|
||||
});
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'M21_diagnosticados_con_eeg', figura: 'fig_c1_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
|
||||
describe('Dona de dos anillos para C1', () => {
|
||||
it('solo aplica a C1 con las figuras por grupo de edad', () => {
|
||||
expect(c1DonutCapability('C1', 'fig_c1_donas')).toBe(true);
|
||||
expect(c1DonutCapability('C1', 'fig_c1_dona_edad')).toBe(true);
|
||||
expect(c1DonutCapability('C1', 'fig_c1_barras_edad')).toBe(true);
|
||||
expect(c1DonutCapability('C2', 'fig_c1_donas')).toBe(false);
|
||||
expect(c1DonutCapability('C1', 'fig_c1_grupos')).toBe(false);
|
||||
});
|
||||
it('anillo interior con y sin el evento; exterior por grupo de edad, con el total al centro', () => {
|
||||
const result = c1DonutFigure(datos(), selection);
|
||||
expect(result.status).toBe('supported');
|
||||
if (result.status !== 'supported') return;
|
||||
const [center, inner, outer] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
|
||||
expect(center.text[0]).toContain('<b>64</b>');
|
||||
expect(inner.labels).toEqual(['Con EEG', 'Sin EEG']);
|
||||
expect(inner.values).toEqual([46, 18]);
|
||||
expect(inner.text).toEqual(['Con EEG<br>71.9 %', 'Sin EEG<br>28.1 %']);
|
||||
expect(outer.labels).toEqual(['Con EEG · 16 a 23 meses', 'Con EEG · 24 a 29 meses', 'Con EEG · 30 a 36 meses',
|
||||
'Sin EEG · 16 a 23 meses', 'Sin EEG · 24 a 29 meses', 'Sin EEG · 30 a 36 meses']);
|
||||
expect(outer.values).toEqual([16, 13, 17, 8, 5, 5]);
|
||||
// Inside the outer ring only the age group; slices under 5 % stay unlabeled.
|
||||
expect(outer.text[0]).toMatch(/^16 a 23 meses<br>/);
|
||||
expect(outer.text[4]).toMatch(/^24 a 29 meses<br>7.8/);
|
||||
const small = c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 14), fila('30-36', 17, 40)]), selection);
|
||||
if (small.status === 'supported') expect((small.figure.data[2] as { text: string[] }).text[4]).toBe('');
|
||||
expect(result.total).toBe(64);
|
||||
expect(result.notes).toEqual(['Datos ficticios.']);
|
||||
expect(result.highlight.groups.map(g => g.label)).toEqual(['Con EEG', 'Sin EEG']);
|
||||
expect(result.highlight.items.map(i => i.short)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.groups[1].center).toBe('<b>18</b><br>Sin EEG');
|
||||
expect(result.figure.layout['title']).toEqual({ text: 'Porcentaje de pacientes con diagnóstico de TEA con EEG, 2025-S2' });
|
||||
});
|
||||
it('dona por grupo de edad: solo los pacientes con el evento, con el porcentaje total al centro', () => {
|
||||
const result = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
expect(result.figure.data).toHaveLength(1);
|
||||
// Only the patients with EEG, by age group; each slice is its share of those 46 patients.
|
||||
const [ring] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
|
||||
expect(ring.labels).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(ring.values).toEqual([16, 13, 17]);
|
||||
expect(ring.text[0]).toMatch(/^16 a 23 meses<br>34.8/);
|
||||
expect((result.figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>71.9 %</b>');
|
||||
expect(result.highlight.groups).toEqual([]);
|
||||
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
||||
});
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
|
||||
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
|
||||
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||
if (dona.status !== 'supported') throw new Error('sin figura');
|
||||
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
||||
expect(dona.highlight.items.map(i => i.color)).toEqual(colores);
|
||||
const barras = c1DonutFigure({ ...datos(), id: 'M22_diagnosticados_sin_eeg' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
|
||||
if (barras.status !== 'supported') throw new Error('sin figura');
|
||||
expect((barras.figure.data[0] as { marker: { color: string[] } }).marker.color).toEqual(colores);
|
||||
expect(barras.highlight.items.map(i => i.color)).toEqual(colores);
|
||||
});
|
||||
it('barras apiladas por grupo de edad: confirmados y en proceso, con un botón por estado', () => {
|
||||
const result = c1DonutFigure({ ...datos(), id: 'M24_confirmacion_diagnostico' }, { ...selection, indicador: 'M24_confirmacion_diagnostico', figura: 'fig_c1_barras_apiladas_edad' });
|
||||
if (result.status !== 'supported') throw new Error('sin figura');
|
||||
expect(result.figure.layout['barmode']).toBe('stack');
|
||||
expect(result.figure.data.map(t => [t['name'], t['y']])).toEqual([['Diagnóstico confirmado', [16, 13, 17]], ['En proceso', [8, 5, 5]]]);
|
||||
expect(result.figure.data[1]['text']).toEqual(['8 (33.3 %)', '5 (27.8 %)', '5 (22.7 %)']);
|
||||
expect(result.highlight.items.map(i => i.label)).toEqual(['Diagnóstico confirmado', 'En proceso']);
|
||||
});
|
||||
it('barras por grupo de edad: una barra por grupo con su porcentaje', () => {
|
||||
const result = c1DonutFigure({ ...datos([fila('16-23', 8, 24), fila('24-29', 5, 18), fila('30-36', 5, 22)]), id: 'M22_diagnosticados_sin_eeg' },
|
||||
{ ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
const [bars] = result.figure.data as { type: string; x: string[]; y: number[]; text: string[] }[];
|
||||
expect(bars.type).toBe('bar');
|
||||
expect(bars.x).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(bars.text).toEqual(['33.3 %', '27.8 %', '22.7 %']);
|
||||
expect(JSON.stringify(result.figure.layout['yaxis'])).toContain('% de pacientes sin EEG');
|
||||
expect(result.highlight.items.map(i => i.points)).toEqual([[{ trace: 0, index: 0 }], [{ trace: 0, index: 1 }], [{ trace: 0, index: 2 }]]);
|
||||
});
|
||||
it('usa etiquetas propias por indicador y neutrales para otros', () => {
|
||||
expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Diagnóstico confirmado', 'En proceso']);
|
||||
expect(c1DonutLabels('M22_diagnosticados_sin_eeg')).toEqual(['Sin EEG', 'Con EEG']);
|
||||
expect(c1DonutLabels('otro')).toEqual(['Con el evento', 'Sin el evento']);
|
||||
});
|
||||
it('solo un semestre', () => {
|
||||
expect(c1DonutFigure({ ...datos(), tipo_periodo: 'mes', periodos: ['2025-12'] }, { ...selection, tipoPeriodo: 'mes', periodos: ['2025-12'] }))
|
||||
.toEqual({ status: 'unsupported', reason: 'Esta figura solo está disponible para un semestre.' });
|
||||
expect(c1DonutFigure({ ...datos(), periodos: ['2025-S1', '2025-S2'] }, { ...selection, periodos: ['2025-S1', '2025-S2'] }).status).toBe('unsupported');
|
||||
expect(c1DonutFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
|
||||
});
|
||||
it('rechaza estratos incompletos, suprimidos o imposibles', () => {
|
||||
expect(c1DonutFigure({ ...datos(), estrato: null }, selection).status).toBe('unsupported');
|
||||
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18)]), selection).status).toBe('unsupported');
|
||||
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', null as unknown as number, 22, { suprimido: 1 })]), selection).status).toBe('unsupported');
|
||||
expect(c1DonutFigure(datos([fila('16-23', 30, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]), selection).status).toBe('unsupported');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
// Figures by age group for a C1 proportion over one semester, built from the age-stratified C1 rows:
|
||||
// - fig_c1_donas: double donut drawn like CaCu's «Distribución de resultados citológicos»; the inner ring
|
||||
// splits the denominator into patients with and without the event, the outer ring each of them by age group.
|
||||
// - fig_c1_dona_edad: only the patients with the event, by age group, with the overall percentage in the centre.
|
||||
// - fig_c1_barras_edad: one bar per age group with its percentage.
|
||||
export const C1_DONUT = 'fig_c1_donas';
|
||||
export const C1_RING = 'fig_c1_dona_edad';
|
||||
export const C1_AGE_BARS = 'fig_c1_barras_edad';
|
||||
export const C1_AGE_STACK = 'fig_c1_barras_apiladas_edad';
|
||||
const C1_AGE_FIGURES = [C1_DONUT, C1_RING, C1_AGE_BARS, C1_AGE_STACK];
|
||||
export const C1_DONUT_ESTRATO = 'grupo_edad';
|
||||
// Mock (TEA): ring labels per indicator; any other C1 indicator falls back to a neutral wording.
|
||||
const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
|
||||
M21_diagnosticados_con_eeg: ['Con EEG', 'Sin EEG'],
|
||||
M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'],
|
||||
M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'],
|
||||
};
|
||||
// Green for the event, red for its complement; age groups get lighter shades.
|
||||
const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const;
|
||||
// One colour per age group, the same in the donut (M21) and the bars (M22).
|
||||
const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length];
|
||||
|
||||
export type C1DonutResult = { status: 'unsupported'; reason: string }
|
||||
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
|
||||
export function c1DonutCapability(contract: string, representation: string): boolean {
|
||||
return contract === 'C1' && C1_AGE_FIGURES.includes(representation);
|
||||
}
|
||||
export function c1DonutLabels(indicador: string): readonly [string, string] {
|
||||
return EVENT_LABELS[indicador] ?? ['Con el evento', 'Sin el evento'];
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
function shade(hex: string, step: number, steps: number): string {
|
||||
const t = steps > 1 ? 0.65 * step / (steps - 1) : 0;
|
||||
const rgb = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)).map(c => Math.round(c + (255 - c) * t));
|
||||
return '#' + rgb.map(c => c.toString(16).padStart(2, '0')).join('').toUpperCase();
|
||||
}
|
||||
|
||||
export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): C1DonutResult {
|
||||
const unsupported = (reason: string): C1DonutResult => ({ status: 'unsupported', reason });
|
||||
if (!c1DonutCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
|
||||
if (selection.tipoPeriodo !== 'semestre' || data.tipo_periodo !== 'semestre') return unsupported('Esta figura solo está disponible para un semestre.');
|
||||
if (data.periodos.length !== 1 || (selection.periodos && (selection.periodos.length !== 1 || selection.periodos[0] !== data.periodos[0])))
|
||||
return unsupported('Se requiere un semestre único concordante');
|
||||
const values = data['valores_estrato'], names = data['etiquetas_estrato'];
|
||||
if (data['estrato'] !== C1_DONUT_ESTRATO || !Array.isArray(values) || !values.length || !values.every(v => typeof v === 'string')
|
||||
|| new Set(values).size !== values.length || (names != null && !record(names))) return unsupported('Estratificación por grupo de edad no verificable');
|
||||
const period = data.periodos[0];
|
||||
const rows = values.map(v => data.filas.filter(r => r['periodo'] === period && r['estrato'] === v));
|
||||
if (rows.some(r => r.length !== 1) || data.filas.length !== values.length) return unsupported('Partición por grupo de edad incompleta');
|
||||
const strata = rows.map(([r], i) => ({ id: values[i] as string, label: typeof names?.[values[i]] === 'string' ? names[values[i]] as string : values[i] as string,
|
||||
numerador: r['numerador'], denominador: r['denominador'], suprimido: r['suprimido'], grupo: r['grupo'] }));
|
||||
if (strata.some(s => s.grupo !== 'TOTAL' || (s.suprimido !== 0 && s.suprimido !== false)
|
||||
|| !count(s.numerador) || !count(s.denominador) || s.numerador > s.denominador)) return unsupported('Conteos por grupo de edad suprimidos o no verificables');
|
||||
|
||||
const labels = c1DonutLabels(data.id);
|
||||
const notes = Array.isArray(data.notas) ? [...data.notas] : [];
|
||||
const title = { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period };
|
||||
const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0);
|
||||
if (selection.figura === C1_AGE_STACK) {
|
||||
const figure = ageStack(strata, labels, selection);
|
||||
figure.layout = { ...figure.layout, title };
|
||||
const highlight: FigureHighlight = { groups: [], traces: [0, 1], allLabel: 'Todos los pacientes',
|
||||
items: labels.map((label, g) => ({ id: g ? 'SIN' : 'CON', label, color: RING_COLORS[g], points: strata.map((_, i) => ({ trace: g, index: i })) })) };
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
if (selection.figura === C1_AGE_BARS) {
|
||||
const figure = ageBars(strata, labels[0], selection);
|
||||
figure.layout = { ...figure.layout, title };
|
||||
const highlight: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todos los grupos de edad',
|
||||
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }] })) };
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
|
||||
const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] }));
|
||||
const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {};
|
||||
grupos.forEach((g, gi) => strata.forEach((s, i) => {
|
||||
const id = g.id + ':' + s.id, n = gi ? (s.denominador as number) - (s.numerador as number) : s.numerador as number;
|
||||
// Unique labels: Plotly merges pie slices that share one.
|
||||
categorias.push({ id, etiqueta: g.etiqueta + ' · ' + s.label, color: shade(g.color, i, strata.length), grupo: g.id });
|
||||
celdas[id] = { n, estado: 'Publicado' };
|
||||
}));
|
||||
const modelo: Modelo = { periodo: period, categorias, grupos, celdas, total, sinDato: { n: 0, estado: 'Publicado' },
|
||||
escenarios: [], vacio: total === 0, notas: notes, sinDatoEtiqueta: '' };
|
||||
const figure = dona(modelo, {}, selection.tema);
|
||||
if (figure.data.length === 3) {
|
||||
const [, inner, outer] = figure.data as Record<string, unknown>[];
|
||||
const hover = '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de ' + total + '<extra></extra>';
|
||||
inner['hovertemplate'] = outer['hovertemplate'] = hover;
|
||||
// Inside the outer ring the colour already tells the group: show only the age group and its share.
|
||||
const outerValues = outer['values'] as number[];
|
||||
outer['text'] = categorias.map((c, i) => outerValues[i] / total < .05 ? ''
|
||||
: escape(strata[i % strata.length].label) + '<br>' + shareText(outerValues[i], total));
|
||||
inner['text'] = grupos.map((g, i) => {
|
||||
const n = (inner['values'] as number[])[i];
|
||||
return n / total < .05 ? '' : escape(g.etiqueta) + '<br>' + percentNumber(100 * n / total) + ' %';
|
||||
});
|
||||
if (selection.figura === C1_RING) {
|
||||
// Only the patients with the event, by age group, around the overall percentage of the event.
|
||||
// Each slice is its age group's share of those patients.
|
||||
const numerador = strata.reduce((sum, s) => sum + (s.numerador as number), 0);
|
||||
const values = strata.map(s => s.numerador as number);
|
||||
figure.data = [{ ...outer, hole: .6, values, labels: strata.map(s => escape(s.label)),
|
||||
marker: { ...(outer['marker'] as object), colors: strata.map((_, i) => ageColor(i)) },
|
||||
text: values.map((n, i) => !numerador || n / numerador < .05 ? '' : escape(strata[i].label) + '<br>' + shareText(n, numerador)),
|
||||
customdata: values.map(n => [n, numerador ? percentNumber(100 * n / numerador) : '0']),
|
||||
hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de los ' + numerador + ' ' + escape(what(labels[0])) + '<extra></extra>' }];
|
||||
figure.layout = { ...figure.layout, title, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false,
|
||||
text: '<b>' + percentNumber(100 * numerador / total) + ' %</b>', font: { size: 26, color: c2Theme(selection.tema).text } }] };
|
||||
const highlight: FigureHighlight = { groups: [], traces: [0], center: { annotation: 0 }, allLabel: labels[0],
|
||||
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }],
|
||||
center: '<b>' + (numerador ? percentNumber(100 * values[i] / numerador) : '0') + ' %</b><br>' + escape(s.label) })) };
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
}
|
||||
figure.layout = { ...figure.layout, title };
|
||||
// Next to its group's button, a category only needs its age group.
|
||||
const highlight = donaHighlight(modelo, id => strata.find(s => id.endsWith(':' + s.id))?.label);
|
||||
return { status: 'supported', figure, highlight, total, notes };
|
||||
}
|
||||
|
||||
// "Con EEG" -> "con EEG", to follow «pacientes».
|
||||
const what = (label: string) => label.charAt(0).toLowerCase() + label.slice(1);
|
||||
// One stacked bar per age group: how many of its patients have the event and how many don't.
|
||||
function ageStack(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], labels: readonly [string, string], selection: FigureSelection): PlotlyFigure {
|
||||
const theme = c2Theme(selection.tema);
|
||||
const x = strata.map(s => escape(s.label));
|
||||
const conEvento = strata.map(s => s.numerador as number), sinEvento = strata.map(s => (s.denominador as number) - (s.numerador as number));
|
||||
return { data: [conEvento, sinEvento].map((y, g) => ({ type: 'bar', name: escape(labels[g]), x, y, marker: { color: RING_COLORS[g], line: { color: theme.background, width: 1 } },
|
||||
text: y.map((n, i) => (strata[i].denominador as number) ? n + ' (' + percentNumber(100 * n / (strata[i].denominador as number)) + ' %)' : ''),
|
||||
textposition: 'inside', insidetextanchor: 'middle', hovertemplate: '%{x}<br>%{fullData.name}: %{y} pacientes<extra></extra>' })),
|
||||
layout: { autosize: true, height: 400, barmode: 'stack', margin: { t: 24, l: 72, r: 24, b: 80 }, showlegend: true,
|
||||
legend: { orientation: 'h', y: -0.28, itemclick: false, itemdoubleclick: false },
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
|
||||
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero', gridcolor: theme.grid, zeroline: false } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
// One bar per age group: the share of its patients with the event.
|
||||
function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, selection: FigureSelection): PlotlyFigure {
|
||||
const theme = c2Theme(selection.tema);
|
||||
const x = strata.map(s => escape(s.label));
|
||||
const y = strata.map(s => (s.denominador as number) ? 100 * (s.numerador as number) / (s.denominador as number) : null);
|
||||
return { data: [{ type: 'bar', x, y, marker: { color: strata.map((_, i) => ageColor(i)), line: { color: theme.background, width: 1 } },
|
||||
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
|
||||
customdata: strata.map(s => [s.numerador, s.denominador]),
|
||||
hovertemplate: '%{x}<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} pacientes)<extra></extra>' }],
|
||||
layout: { autosize: true, height: 400, margin: { t: 24, l: 72, r: 24, b: 64 }, showlegend: false,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
|
||||
yaxis: { title: { text: '% de pacientes ' + escape(what(event)) }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { numericRows } from './indicadores-numeric-rows';
|
||||
import { figurePresentation } from './indicadores.presentation';
|
||||
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
@@ -26,7 +25,7 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
const donut = supported(data), bars = supported(data, { ...selection, figura: 'fig_c2_barras' });
|
||||
expect(donut.figure.data).toHaveLength(1); expect(donut.hierarchy).toBeUndefined();
|
||||
expect(bars.figure.data[0]['x']).toEqual(donut.figure.data[0]['values']); expect(bars.figure.data[0]['y']).toEqual(donut.figure.data[0]['labels']);
|
||||
expect(bars.figure.layout['xaxis']).toMatchObject({ title: { text: 'Conteo · paciente' } });
|
||||
expect(bars.figure.layout['xaxis']).toMatchObject({ title: { text: 'Conteo (paciente)' } });
|
||||
});
|
||||
it('el layout final de barras muestra ambos ejes y el hover no repite el periodo', () => {
|
||||
const bars = supported(c2Fixture(), { ...selection, figura: 'fig_c2_barras' });
|
||||
@@ -44,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
|
||||
const legend = donutLegend(final), view = donutSimpleView(final);
|
||||
expect(legend).toEqual([
|
||||
{ label: 'A', color: '#7184A2' }, { label: 'B', color: '#A4B88A' }, { label: 'C', color: '#D0B778' },
|
||||
{ label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' },
|
||||
]);
|
||||
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
|
||||
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||
@@ -109,7 +108,6 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
const data = c2Fixture(); data.filas.forEach(r => r['denominador'] = 10); data['denominador'] = 10;
|
||||
const result = supported(data); expect(result.figure.layout['meta']).toMatchObject({ denominator: 10 });
|
||||
expect(result.figure.data[0]['hovertemplate']).toContain('10 paciente publicados');
|
||||
expect(numericRows(data).map(r => r.value)).toEqual(result.model.categories.map(c => String(c.value)));
|
||||
});
|
||||
it('explorar, cambiar padre y restaurar parte del original y no modifica las barras', () => {
|
||||
const data = c2Fixture(), result = supported(data), original = structuredClone(result.figure);
|
||||
@@ -163,12 +161,12 @@ describe('paleta C2 institucional y semántica', () => {
|
||||
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
|
||||
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
||||
const figure = supported(data, { ...selection, tema }).figure;
|
||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#A4B88A', '#D0B778']);
|
||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']);
|
||||
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
|
||||
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
||||
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
|
||||
expect(c2Color(undefined, 0)).toBe('#7184A2'); expect(c2Color(undefined, 1)).toBe('#A4B88A');
|
||||
expect(c2Color(undefined, 2)).toBe('#D0B778'); expect(c2Color(undefined, 3)).toBe('#B78B8E');
|
||||
expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A');
|
||||
expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778');
|
||||
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
||||
});
|
||||
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
|
||||
|
||||
@@ -83,7 +83,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
|
||||
const colors = categories.map((c, i) => c2Color(c.color, i));
|
||||
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
|
||||
const layout: Record<string, unknown> = { title: { text: model.title + ' · ' + period }, autosize: true,
|
||||
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
|
||||
margin: { l: 76, r: 28, t: 112, b: 62, pad: 4 },
|
||||
legend: selection.figura === 'fig_c2_donas'
|
||||
@@ -95,7 +95,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels,
|
||||
marker: { color: colors, line: { color: theme.outline, width: 0.7 } },
|
||||
hovertemplate: '%{y}<br>%{x} ' + model.unit + '<extra></extra>' }];
|
||||
layout['xaxis'] = { title: { text: 'Conteo · ' + model.unit }, rangemode: 'tozero', showgrid: true,
|
||||
layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true,
|
||||
gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1,
|
||||
ticks: 'outside', tickcolor: '#AEB7C2', automargin: true };
|
||||
layout['yaxis'] = { type: 'category', categoryorder: 'array', categoryarray: [...labels].reverse(), automargin: true,
|
||||
|
||||
@@ -37,7 +37,7 @@ describe('barras generales conectadas con la selección compartida de la dona',
|
||||
select({ parent: 'G2', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B', 'C']);
|
||||
select({ parent: 'G2', category: 'B', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B']);
|
||||
expect(panel().result().figure).toBe(original); expect(original).toEqual(before);
|
||||
expect(fixture.nativeElement.querySelector('.selection-status').getAttribute('aria-label')).toContain('G2 · B · 2025-S2');
|
||||
expect(fixture.nativeElement.querySelector('.selection-status').getAttribute('aria-label')).toContain('G2, B, 2025-S2');
|
||||
select({}); expect(displayed()).toEqual(all); expect(panel().generalSelectionContext).toBeUndefined();
|
||||
expect(panel().applied).toEqual(filter); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true);
|
||||
});
|
||||
|
||||
@@ -19,10 +19,10 @@ describe('selección local segura de barras generales C2', () => {
|
||||
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
|
||||
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
|
||||
const view = c2GeneralSelection(source, data, selection, local)!;
|
||||
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#A4B88A', '#D0B778'] } });
|
||||
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } });
|
||||
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
|
||||
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
|
||||
expect(view.context).toContain('G2 · 2025-S2');
|
||||
expect(view.context).toContain('G2, 2025-S2');
|
||||
expect({ data, source }).toEqual(before);
|
||||
(view.figure.data[0]['x'] as number[])[0] = 999;
|
||||
expect(source).toEqual(before.source);
|
||||
@@ -117,7 +117,7 @@ describe('selección local segura de barras generales C2', () => {
|
||||
expect(source).toEqual(before);
|
||||
});
|
||||
it.each([
|
||||
{ id: 'cacu_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' },
|
||||
{ id: 'c2_grados_biopsia_sintetico', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' },
|
||||
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['LIEBG', 'LIEBG (CIN 1)', 'NO_ANORMAL'], ['LIEAG', 'LIEAG (CIN 2 y 3)', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
{ id: 'cacu_eu7', unit: 'paciente', groups: { NO_ANORMAL: 'Sin anomalía', ANORMAL: 'Anormal', SIN_DATO: 'Sin dato' },
|
||||
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['ASC-US', 'ASC-US', 'NO_ANORMAL'], ['LIEBG', 'LIEBG', 'ANORMAL'], ['ASC-H', 'ASC-H', 'ANORMAL'], ['LIEAG', 'LIEAG', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
|
||||
@@ -70,6 +70,6 @@ export function c2GeneralSelection(source: PlotlyFigure, data: IndicadorDatos,
|
||||
if (record(figure.layout['yaxis']) && Array.isArray(figure.layout['yaxis']['categoryarray'])) {
|
||||
figure.layout['yaxis']['categoryarray'] = figure.layout['yaxis']['categoryarray'].filter(v => selected.some(c => c.label === v));
|
||||
}
|
||||
return { figure, context: 'Vista local de la dona: ' + [local.parent, local.category, period].filter(Boolean).join(' · ')
|
||||
return { figure, context: 'Vista local de la dona: ' + [local.parent, local.category, period].filter(Boolean).join(', ')
|
||||
+ '. Sólo se muestran las categorías seleccionadas de este periodo. Los conteos y porcentajes conservan el denominador de la distribución completa del periodo.' };
|
||||
}
|
||||
|
||||
@@ -3,10 +3,14 @@ import { Tema } from './indicadores.models';
|
||||
// Matches src/styles.scss: interface tokens are the source of these candidates,
|
||||
// not a certified brand guide. Published semantic colours always take priority.
|
||||
export const C2_PALETTE = Object.freeze({
|
||||
series: Object.freeze(['#7184A2', '#A4B88A', '#D0B778', '#B78B8E']),
|
||||
// ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness.
|
||||
series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']),
|
||||
// Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest.
|
||||
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
|
||||
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
|
||||
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1' }),
|
||||
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F' }),
|
||||
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
|
||||
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
||||
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }),
|
||||
});
|
||||
export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; }
|
||||
export function c2Color(published: string | undefined, index: number): string {
|
||||
|
||||
@@ -59,7 +59,18 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({}, {status:503,statusText:'Failure'});
|
||||
expect(fixture.componentInstance.result().status).toBe('error');
|
||||
});
|
||||
it('TEA: dona de un periodo con ambos anillos y botones para resaltar grupos y categorías', () => {
|
||||
fixture.detectChanges(); dataRequest().flush(c2Fixture());
|
||||
const result = fixture.componentInstance.result();
|
||||
expect(result.status).toBe('ready');
|
||||
expect(result.hierarchy).toBeUndefined();
|
||||
expect(result.figure?.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
|
||||
expect(result.highlight?.groups.length).toBeGreaterThan(0);
|
||||
expect(result.highlight?.items.every(i => i.group)).toBe(true);
|
||||
});
|
||||
it('cambio de periodo cancela lectura, limpia selección y no expone snapshot previo', () => {
|
||||
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
|
||||
fixture.componentRef.setInput('dominio', 'cama');
|
||||
fixture.detectChanges(); const old = dataRequest();
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision:2,selection:{mode:'explicit',periodos:['2026-S1']} }); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true); const current = dataRequest(); expect(current.request.params.get('periodos')).toBe('2026-S1');
|
||||
|
||||
@@ -11,7 +11,6 @@ import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { IndicadoresNumericSummary } from './indicadores-numeric-summary';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { figureApplied } from './indicadores-figure-selection';
|
||||
@@ -23,7 +22,7 @@ const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'):
|
||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
|
||||
});
|
||||
const catalog = [
|
||||
item('cacu_eu13', 'Tasa de confirmación histopatológica'),
|
||||
item('cacu_eu13', 'Tasa de detección histopatológica'),
|
||||
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r'),
|
||||
item('ind1', 'Pacientes con citología anómala'),
|
||||
item('ordinary', 'Otra gráfica'),
|
||||
@@ -79,33 +78,35 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
page.filters!.editors[tipo] = { added: [], draft: { mode: 'explicit', periodos: selected } };
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
}
|
||||
it('encabezados, tres tarjetas en orden y placeholder inerte sin periodo, unidad ni HTTP', () => {
|
||||
it('encabezados, cinco tarjetas en orden y placeholders inertes sin periodo, unidad ni HTTP', () => {
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
|
||||
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
|
||||
'Pacientes evaluadas', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de diagnóstico a tratamiento',
|
||||
'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
expect(kpis[2].querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpis[2].querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 3');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(2);
|
||||
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('confirmación histopatológica');
|
||||
for (const kpi of kpis.slice(3)) {
|
||||
expect(kpi.querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
}
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
|
||||
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('detección histopatológica');
|
||||
expect(card('cacu_eu13')).toBeDefined();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('EU7 primero sin alterar catálogo; búsqueda y fijación prevalecen y conservan identidades y memoria', () => {
|
||||
it('EU7 primero sin alterar catálogo; selección y fijación prevalecen y conservan identidades y memoria', () => {
|
||||
const original = page.catalog(), before = cards();
|
||||
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
|
||||
expect(before[0].indicador.id).toBe('cacu_eu7');
|
||||
page.togglePinned(original[0]); fixture.detectChanges();
|
||||
expect(cards()[0]).toBe(card('cacu_eu13'));
|
||||
page.changeSearchQuery('anómala'); fixture.detectChanges();
|
||||
expect(cards()[0].indicador.id).toBe('ind1');
|
||||
page.changeSearchQuery(''); fixture.detectChanges();
|
||||
page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
|
||||
expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
|
||||
for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
|
||||
page.showAllIndicators(); fixture.detectChanges();
|
||||
expect(cards()[0].indicador.id).toBe('cacu_eu13');
|
||||
for (const c of before) expect(card(c.indicador.id)).toBe(c);
|
||||
expect(page.catalog()).toBe(original);
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
@@ -167,13 +168,6 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
apply('mes', ['2026-01']);
|
||||
http.expectNone(r => /\/(cacu_eu13|ind1)\/datos/.test(r.url));
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] }));
|
||||
const summary = fixture.debugElement.query(By.directive(IndicadoresNumericSummary)).componentInstance as IndicadoresNumericSummary;
|
||||
for (const id of ['cacu_eu13', 'ind1']) {
|
||||
const selected = page.catalog().find(i => i.id === id)!;
|
||||
const reading = summary.snapshots.reading('cacu', selected, summary.figureSelection(selected))!;
|
||||
expect(summary.rows(reading.data!).map(row => row.period)).toEqual(periods);
|
||||
expect(reading.data!.filas.map(row => row['denominador'])).toEqual([4, 10]);
|
||||
}
|
||||
});
|
||||
it('reintento individual tras error usa Todos; una nueva versión de catálogo puede revalidar sin tocar otra selección', () => {
|
||||
open('cacu_eu13', 'ind1');
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
// Covers the three CaMa indicators WebApi now publishes (CAM-01 tasa de detección, CAM-02 resultado a diagnóstico,
|
||||
// CAM-03 histopatología por BI-RADS) as they reach the summary and the history. The payloads are what WebApi
|
||||
// answered for an isolated synthetic base (fixtures/cama_*): `visible` with the suppression threshold lowered so
|
||||
// the figures show, and `suprimido` with the normal threshold of 5, where the small synthetic counts are hidden.
|
||||
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 { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import tasaVisible from './fixtures/cama_tasa_deteccion_visible.json';
|
||||
import tasaSuprimida from './fixtures/cama_tasa_deteccion_suprimido.json';
|
||||
import diasVisible from './fixtures/cama_dias_resultado_visible.json';
|
||||
import diasSuprimido from './fixtures/cama_dias_resultado_suprimido.json';
|
||||
import generalFixture from './fixtures/cama_histopatologia_birads_general.json';
|
||||
import catalogoFixture from './fixtures/cama_catalogo_f4c.json';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
import { CAMA_FUERA_DEL_RESUMEN, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TASA_DETECCION_KPI, KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
|
||||
const dato = (v: unknown) => structuredClone(v) as unknown as IndicadorDatos;
|
||||
const REALES = catalogoFixture as unknown as Indicador[];
|
||||
|
||||
describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () => {
|
||||
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
|
||||
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
|
||||
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
|
||||
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con resultado maligno.' });
|
||||
});
|
||||
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
|
||||
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(r.state).toBe('Dato oculto por tamaño'); expect(r.value).toBeUndefined();
|
||||
});
|
||||
it('CAM-02 con el umbral de prueba: mediana, Q1 y Q3 tal como las publica el C3r, sin recalcular', () => {
|
||||
expect(kpiResult(dato(diasVisible), CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', applied))
|
||||
.toEqual({ state: 'Disponible', value: 6.5, info: '4 mastografías; Q1 a Q3: 2.25 a 12.5 días.' });
|
||||
});
|
||||
it('CAM-02 con el umbral normal: suprimido, sin mediana ni cero', () => {
|
||||
const r = kpiResult(dato(diasSuprimido), CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', applied);
|
||||
expect(r.state).toBe('Dato oculto por tamaño'); expect(r.value).toBeUndefined();
|
||||
});
|
||||
it('CAM-01 y CAM-02 sin valores (nulos, no suprimidos) no se vuelven cero', () => {
|
||||
const c1 = dato(tasaVisible); Object.assign((c1.filas[0]), { valor: null, numerador: null, denominador: null });
|
||||
const c3 = dato(diasVisible); Object.assign((c3.filas[0]), { n: null, mediana: null, q1: null, q3: null });
|
||||
expect(kpiResult(c1, CAMA_TASA_DETECCION_KPI, 'cama', applied)).toMatchObject({ state: 'Sin valor disponible' });
|
||||
expect(kpiResult(c3, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', applied)).toMatchObject({ state: 'Sin valor disponible' });
|
||||
const sinFilas = { ...dato(tasaVisible), periodos: [], filas: [] };
|
||||
expect(kpiResult(sinFilas, CAMA_TASA_DETECCION_KPI, 'cama', applied).state).toBe('Sin filas utilizables');
|
||||
});
|
||||
it('la respuesta de una medida no pasa por la tarjeta de otra, ni de otro periodo', () => {
|
||||
expect(kpiResult(dato(tasaVisible), CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', applied).state).toBe('Error de contrato');
|
||||
expect(kpiResult(dato(diasVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied).state).toBe('Error de contrato');
|
||||
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', { ...applied, tipo: 'mes' }).state).toBe('Error de contrato');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CAM-01, CAM-02 y CAM-03: histórico con las respuestas reales', () => {
|
||||
it('CAM-01: la línea y su banda de confianza dibujan el cero válido y el cero no se confunde con «sin dato»', () => {
|
||||
const f = historicoFigura(dato(tasaVisible), 'claro');
|
||||
expect(f.contrato).toBe('C1'); expect(f.suprimidos).toEqual([]); expect(f.sinDato).toEqual([]);
|
||||
const linea = f.figure.data.find(t => t['name'] === 'Porcentaje')!;
|
||||
expect(linea['y']).toEqual([0]); expect(linea['x']).toEqual(['2025 S1']);
|
||||
expect(f.figure.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([79.3450688208, 0]);
|
||||
});
|
||||
it('CAM-01 y CAM-02 suprimidos: el periodo se sombrea, se nombra y la línea queda sin valor', () => {
|
||||
for (const d of [tasaSuprimida, diasSuprimido]) {
|
||||
const f = historicoFigura(dato(d), 'claro');
|
||||
expect(f.suprimidos).toEqual(['2025 S1']); expect(f.sinDato).toEqual([]);
|
||||
expect(f.figure.data.find(t => t['name'] === 'Porcentaje' || t['name'] === 'Mediana')!['y']).toEqual([null]);
|
||||
expect(f.figure.layout['shapes']).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
it('CAM-02: la mediana y la banda de cuartiles salen de lo publicado', () => {
|
||||
const f = historicoFigura(dato(diasVisible), 'claro');
|
||||
expect(f.figure.data.find(t => t['name'] === 'Mediana')!['y']).toEqual([6.5]);
|
||||
expect(f.figure.data.find(t => t['name'] === 'Primer a tercer cuartil')!['y']).toEqual([12.5, 2.25]);
|
||||
});
|
||||
it('CAM-03: el C2 general se apila en las seis categorías del catálogo, con sus colores y en su orden', () => {
|
||||
const f = historicoFigura(dato(generalFixture), 'claro');
|
||||
expect(f.contrato).toBe('C2'); expect(f.suprimidos).toEqual([]); expect(f.sinDato).toEqual([]);
|
||||
expect(f.figure.data.map(t => [t['name'], (t['y'] as number[])[0]])).toEqual([
|
||||
['Benigno', 7], ['Lesión de riesgo (B3)', 5], ['Carcinoma in situ', 6], ['Carcinoma invasor', 7], ['Sin biopsia reportada', 6], ['Sin dato', 6]]);
|
||||
expect(f.figure.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', '#D9822B', '#B5482E', '#C9CDD2', '#C9CDD2']);
|
||||
expect(f.figure.layout['barmode']).toBe('stack');
|
||||
expect(f.comoLeer).toContain('pacientes');
|
||||
});
|
||||
it('CAM-03: una celda suprimida o ausente en el periodo se avisa, y no se dibuja como cero', () => {
|
||||
const suprimida = dato(generalFixture); Object.assign(suprimida.filas[2], { n: null, suprimido: 1 });
|
||||
expect(historicoFigura(suprimida, 'claro').suprimidos).toEqual(['2025 S1']);
|
||||
const ausente = dato(generalFixture); ausente.filas.splice(3, 1);
|
||||
const f = historicoFigura(ausente, 'claro');
|
||||
expect(f.sinDato).toEqual(['2025 S1']);
|
||||
expect(f.figure.data.find(t => t['name'] === 'Carcinoma invasor')!['y']).toEqual([null]);
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: { data: { name?: string }[] }; label?: string; }
|
||||
|
||||
describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
|
||||
function montar(visibles: boolean) {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: vi.fn() } }] });
|
||||
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', REALES);
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true);
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges();
|
||||
const respuestas: Record<string, unknown> = visibles
|
||||
? { cama_tasa_deteccion_histopatologica: tasaVisible, cama_dias_resultado_diagnostico: diasVisible, cama_histopatologia_birads: generalFixture }
|
||||
: { cama_tasa_deteccion_histopatologica: tasaSuprimida, cama_dias_resultado_diagnostico: diasSuprimido, cama_histopatologia_birads: generalFixture };
|
||||
const pedidos: string[] = [];
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
const id = r.request.url.split('/').at(-2)!;
|
||||
pedidos.push(r.request.url + (r.request.params.get('periodos') ? '?periodos=' + r.request.params.get('periodos') : ''));
|
||||
if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: [{ periodo: '2025-S1', tipo: 'semestre' }] });
|
||||
else r.flush(respuestas[id] as Record<string, unknown>);
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
return pedidos;
|
||||
}
|
||||
afterEach(() => { fixture?.destroy(); http.verify(); });
|
||||
const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
|
||||
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
|
||||
it('los tres indicadores publicados se piden y se dibujan; los cinco restantes de la lista siguen pendientes', () => {
|
||||
const pedidos = montar(true);
|
||||
expect(pedidos.filter(p => p.includes('/datos'))).toEqual([
|
||||
'/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1',
|
||||
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1',
|
||||
'/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
|
||||
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
||||
expect(titulos.filter(([t]) => ['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
|
||||
.toEqual([['Resultado histopatológico por categoría BI-RADS', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
|
||||
expect(graficas()).toHaveLength(3);
|
||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2, 2]);
|
||||
});
|
||||
it('con el umbral normal los dos paneles C1 y C3r avisan el periodo suprimido, y la matriz CAM-03 sigue visible', () => {
|
||||
montar(false);
|
||||
const texto = paneles().map(p => p.textContent!);
|
||||
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(2);
|
||||
expect(graficas()).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama');
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
||||
const propios = (d: KpiDefinition): Indicador => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as Indicador;
|
||||
const row = { periodo: '2025-S1', estrato: null, suprimido: 0 };
|
||||
function cargar(catalogo: Indicador[]) {
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
http.expectOne('/cama/indicadores').flush(catalogo);
|
||||
for (let ola = http.match(r => r.url.endsWith('/periodos')); ola.length; ola = http.match(r => r.url.endsWith('/periodos'))) {
|
||||
ola.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] }));
|
||||
}
|
||||
fixture.detectChanges();
|
||||
const pedidos: string[] = [];
|
||||
for (let ola = http.match(r => r.url.endsWith('/datos')); ola.length; ola = http.match(r => r.url.endsWith('/datos'))) {
|
||||
ola.forEach(r => {
|
||||
const id = r.request.url.split('/').at(-2)!;
|
||||
pedidos.push(id);
|
||||
r.flush(id === 'cama_tasa_deteccion_histopatologica' ? tasaVisible : id === 'cama_dias_resultado_diagnostico' ? diasVisible
|
||||
: id === 'cama_birads_456_paciente' ? { id, contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas: [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 5 }] }
|
||||
: { id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: {}, filas: [{ ...row, grupo: 'TOTAL', unidad: 'dias', mediana: 7, n: 5, q1: 3, q3: 9 }] });
|
||||
});
|
||||
fixture.detectChanges();
|
||||
}
|
||||
return pedidos;
|
||||
}
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const kpis = () => [...root().querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const tarjetas = () => [...root().querySelectorAll('.catalog-grid > *')] as HTMLElement[];
|
||||
const completo = () => [...KPI_BY_DOMAIN.cama.map(propios), ...REALES];
|
||||
|
||||
it('las cuatro tarjetas de oportunidad tienen datos, ninguna pendiente, con los valores publicados', () => {
|
||||
cargar(completo());
|
||||
expect(kpis()).toHaveLength(4);
|
||||
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
||||
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.');
|
||||
expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.');
|
||||
});
|
||||
it('CAM-03 ocupa el lugar de la tarjeta pendiente, primero y con su vista especializada; no se consulta mientras no es visible', () => {
|
||||
const pedidos = cargar(completo());
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
const primera = tarjetas()[0];
|
||||
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
expect(primera.querySelector('h2')!.textContent).toBe('Histopatología por BI-RADS');
|
||||
expect(pedidos).not.toContain('cama_histopatologia_birads');
|
||||
});
|
||||
it('CAM-01 y CAM-02 son solo tarjetas de oportunidad: no dibujan una figura propia en el Resumen', () => {
|
||||
cargar(completo());
|
||||
const titulos = tarjetas().map(t => t.querySelector('h2')?.textContent ?? '');
|
||||
expect(titulos.some(t => t.includes('Detección histopatológica') || t.includes('resultado a diagnóstico'))).toBe(false);
|
||||
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_tasa_deteccion_histopatologica');
|
||||
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico');
|
||||
});
|
||||
it('sin CAM-03 en el catálogo la tarjeta sigue pendiente, como antes', () => {
|
||||
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).not.toBeNull();
|
||||
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
||||
});
|
||||
it('solo CAM-01 y CAM-02 sin CAM-03: dos tarjetas con datos y la de histopatología pendiente', () => {
|
||||
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||
expect(kpis()).toHaveLength(4); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,349 @@
|
||||
// Covers CaMa's four opportunity cards: their definitions, how each indicator's response becomes a card,
|
||||
// which cards are pending while the catalog lacks their indicator, and the page drawing them.
|
||||
// Fixtures are synthetic rows shaped like the /cama/indicadores/<id>/datos contract; no card reads a bundled value.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, TestRequest, 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 { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { emptyAvailability } from './indicadores-periodos';
|
||||
import {
|
||||
CAMA_CONFIRMACION_KPI, CAMA_TOMA_DIAGNOSTICO_KPI, CAMA_OPORTUNIDAD_KPIS, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI,
|
||||
KPI_BY_DOMAIN, KpiDefinition, camaKpiCards, kpiResult,
|
||||
} from './indicadores-kpi';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
|
||||
const row = { periodo: '2025-S1', estrato: null, suprimido: 0 };
|
||||
const datos = (definition: KpiDefinition, filas: Record<string, unknown>[]): IndicadorDatos => ({
|
||||
id: definition.id, contrato: definition.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas });
|
||||
const c1 = (fields: Record<string, unknown>) => datos(CAMA_TASA_DETECCION_KPI, [{ ...row, grupo: 'total', ...fields }]);
|
||||
const c3r = (definition: KpiDefinition, fields: Record<string, unknown>) => datos(definition, [{ ...row, grupo: 'TOTAL', unidad: 'dias', ...fields }]);
|
||||
|
||||
describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
|
||||
it('son cuatro, en este orden, y la primera sigue siendo el ancla del periodo inicial', () => {
|
||||
// Fails if a card is dropped or reordered, or if the anchor (KPI_BY_DOMAIN.cama[0]) stops leading.
|
||||
expect(CAMA_OPORTUNIDAD_KPIS.map(d => [d.id, d.contrato, d.unit])).toEqual([
|
||||
['cama_birads_456_paciente', 'C2', 'pacientes'],
|
||||
['cama_tasa_deteccion_histopatologica', 'C1', '%'],
|
||||
['cama_eu38a', 'C3r', 'días (mediana)'],
|
||||
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
|
||||
]);
|
||||
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
|
||||
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
|
||||
});
|
||||
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
|
||||
// Fails if an indicator the catalog does not publish is queried by default, or if a card the summary retired comes back.
|
||||
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
|
||||
expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_TASA_DETECCION_KPI);
|
||||
expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_RESULTADO_DIAGNOSTICO_KPI);
|
||||
expect([CAMA_CONFIRMACION_KPI, CAMA_TOMA_DIAGNOSTICO_KPI].map(d => [d.id, d.contrato])).toEqual([
|
||||
['cama_confirmacion_birads45', 'C1'], ['cama_dias_toma_diagnostico', 'C3r'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tarjetas de oportunidad de CaMa: valores', () => {
|
||||
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
|
||||
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
|
||||
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con resultado maligno.' });
|
||||
});
|
||||
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
|
||||
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result.state).toBe('Disponible'); expect(result.value).toBe('0.0');
|
||||
});
|
||||
it('un denominador de cero no se presenta como una tasa válida', () => {
|
||||
// Fails if the 0/0 response that activated the CaMa card is drawn as a valid 0.0%.
|
||||
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 0 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result.state).toBe('Sin valor disponible'); expect(result.value).toBeUndefined();
|
||||
});
|
||||
it.each([
|
||||
['valor nulo', { valor: null, numerador: 0, denominador: 8 }],
|
||||
['denominador nulo', { valor: 0, numerador: 0, denominador: null }],
|
||||
['denominador ausente', { valor: 0, numerador: 0 }],
|
||||
])('la tasa con %s no se convierte en cero', (_name, fields) => {
|
||||
// Fails if a missing or incoherent rate is drawn as a value.
|
||||
const result = kpiResult(c1(fields), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result.value).toBeUndefined(); expect(result.state).toBe('Sin valor disponible');
|
||||
});
|
||||
it.each([
|
||||
['numerador mayor que denominador', { valor: 100, numerador: 9, denominador: 8 }],
|
||||
['numerador positivo con denominador cero', { valor: 0, numerador: 1, denominador: 0 }],
|
||||
['denominador negativo', { valor: 0, numerador: 0, denominador: -1 }],
|
||||
])('los conteos incompatibles (%s) son error de contrato', (_name, fields) => {
|
||||
// Fails if structurally impossible counts are collapsed into a legitimate no-value response.
|
||||
const result = kpiResult(c1(fields), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result.state).toBe('Error de contrato'); expect(result.value).toBeUndefined();
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('el 0/0 se trata como tasa sin valor para %s', domain => {
|
||||
// Fails if the shared C1 result path regresses another domain's zero-denominator semantics.
|
||||
const definition = domain === 'cacu'
|
||||
? { id: 'cacu_c1_regression', title: 'Prueba C1 de CaCu', contrato: 'C1' as const, unit: '%' }
|
||||
: domain === 'cama' ? CAMA_TASA_DETECCION_KPI : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!;
|
||||
const group = domain === 'tea' ? 'TOTAL' : 'total';
|
||||
const data = { ...c1({ valor: 0, numerador: 0, denominador: 0 }), id: definition.id,
|
||||
filas: [{ ...row, grupo: group, valor: 0, numerador: 0, denominador: 0 }] };
|
||||
const result = kpiResult(data, definition, domain, applied);
|
||||
expect(result.state).toBe('Sin valor disponible'); expect(result.value).toBeUndefined();
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('el cero con denominador positivo permanece disponible para %s', domain => {
|
||||
// Fails if the denominator guard accidentally rejects a real zero rate in any C1 domain.
|
||||
const definition = domain === 'cacu'
|
||||
? { id: 'cacu_c1_regression', title: 'Prueba C1 de CaCu', contrato: 'C1' as const, unit: '%' }
|
||||
: domain === 'cama' ? CAMA_TASA_DETECCION_KPI : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!;
|
||||
const group = domain === 'tea' ? 'TOTAL' : 'total';
|
||||
const data = { ...c1({ valor: 0, numerador: 0, denominador: 8 }), id: definition.id,
|
||||
filas: [{ ...row, grupo: group, valor: 0, numerador: 0, denominador: 8 }] };
|
||||
const result = kpiResult(data, definition, domain, applied);
|
||||
expect(result.state).toBe('Disponible'); expect(result.value).toBe('0.0');
|
||||
});
|
||||
it('un dato suprimido por tamaño oculta la cifra en las cuatro tarjetas', () => {
|
||||
// Fails if a suppressed row leaks a number.
|
||||
const cases: [KpiDefinition, IndicadorDatos][] = [
|
||||
[CAMA_OPORTUNIDAD_KPIS[0], datos(CAMA_OPORTUNIDAD_KPIS[0], [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 3, suprimido: 1 }])],
|
||||
[CAMA_TASA_DETECCION_KPI, c1({ valor: 10, numerador: 1, denominador: 10, suprimido: 1 })],
|
||||
[CAMA_TAMIZAJE_RESULTADO_KPI, c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 4, n: 9, q1: 2, q3: 6, suprimido: 1 })],
|
||||
[CAMA_RESULTADO_DIAGNOSTICO_KPI, c3r(CAMA_RESULTADO_DIAGNOSTICO_KPI, { mediana: 4, n: 9, q1: 2, q3: 6, suprimido: 1 })],
|
||||
];
|
||||
for (const [definition, data] of cases) {
|
||||
const result = kpiResult(data, definition, 'cama', applied);
|
||||
expect(result.state).toBe('Dato oculto por tamaño'); expect(result.value).toBeUndefined();
|
||||
}
|
||||
});
|
||||
it.each([CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI])('$title: mediana y cuartiles tal como los publica el C3r', definition => {
|
||||
const result = kpiResult(c3r(definition, { mediana: 6.5, n: 40, q1: 3, q3: 11 }), definition, 'cama', applied);
|
||||
expect(result).toEqual({ state: 'Disponible', value: 6.5, info: '40 mastografías; Q1 a Q3: 3 a 11 días.' });
|
||||
});
|
||||
it.each([CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI])('$title: mediana de cero días con observaciones es un valor; sin observaciones no hay valor', definition => {
|
||||
// Fails if a median over zero observations is drawn as "0 días", or a true same-day median is dropped.
|
||||
expect(kpiResult(c3r(definition, { mediana: 0, n: 5, q1: 0, q3: 2 }), definition, 'cama', applied).value).toBe(0);
|
||||
const empty = kpiResult(c3r(definition, { mediana: 0, n: 0, q1: 0, q3: 0 }), definition, 'cama', applied);
|
||||
expect(empty.value).toBeUndefined(); expect(empty.state).toBe('Sin valor disponible');
|
||||
});
|
||||
it('los cuartiles inconsistentes o la unidad ajena no producen cifra', () => {
|
||||
const bad = kpiResult(c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 9, n: 5, q1: 3, q3: 6 }), CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', applied);
|
||||
const unit = kpiResult(c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 2, n: 5, q1: 1, q3: 3, unidad: 'horas' }), CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', applied);
|
||||
expect(bad.value).toBeUndefined(); expect(unit.value).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tarjetas de oportunidad de CaMa: cuáles se dibujan', () => {
|
||||
const only = (...ids: string[]) => (id: string) => ids.includes(id);
|
||||
it('sin ningún indicador de oportunidad publicado no hay tarjetas, ni siquiera pendientes', () => {
|
||||
// Fails if "Integración pendiente" is shown while the catalog is empty, loading or failed, or because of other CaMa indicators.
|
||||
expect(camaKpiCards(only())).toEqual([]);
|
||||
expect(camaKpiCards(only('cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_biopsias'))).toEqual([]);
|
||||
expect(camaKpiCards(only('cama_tasa_deteccion_histopatologica')).filter(c => !c.pending).length).toBe(1);
|
||||
});
|
||||
it('con el catálogo actual del laboratorio hay dos tarjetas vivas y dos pendientes, y nada más', () => {
|
||||
// Fails if the confirmation and screening-to-diagnosis cards, retired from the strip, are drawn again.
|
||||
const cards = camaKpiCards(only('cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a'));
|
||||
expect(cards.map(c => [c.definition.id, c.pending])).toEqual([
|
||||
['cama_birads_456_paciente', false], ['cama_tasa_deteccion_histopatologica', true],
|
||||
['cama_eu38a', false], ['cama_dias_resultado_diagnostico', true]]);
|
||||
});
|
||||
it('una tarjeta pendiente pasa a viva cuando el catálogo publica su indicador, sin tocar código', () => {
|
||||
const cards = camaKpiCards(only(...CAMA_OPORTUNIDAD_KPIS.map(d => d.id)));
|
||||
expect(cards.map(c => c.pending)).toEqual([false, false, false, false]);
|
||||
});
|
||||
it('un indicador de las tarjetas que el catálogo retira no deja una tarjeta consultable', () => {
|
||||
expect(camaKpiCards(only('cama_birads_456_paciente')).map(c => c.pending)).toEqual([false, true, true, true]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
// The initial-period search has its own suites; these tests begin once it has finished.
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama');
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
||||
const catalog = (definitions: KpiDefinition[]) => definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }));
|
||||
// What 18080 publishes besides the opportunity indicators: none of them has a card in the strip.
|
||||
const otros = (): KpiDefinition[] => [
|
||||
{ id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' },
|
||||
{ id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'cama_biopsias', title: 'Distribución de resultados de biopsia', contrato: 'C2', unit: 'biopsias' },
|
||||
{ id: 'cama_birads_456_mastografia', title: 'Porcentaje individual de mastografías', contrato: 'C2', unit: 'mastografías' }];
|
||||
const dataFor = (definition: KpiDefinition): IndicadorDatos => {
|
||||
if (definition.contrato === 'C2') return datos(definition, [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 5 }]);
|
||||
if (definition.contrato === 'C1') return datos(definition, [{ ...row, grupo: 'total', valor: 40, numerador: 2, denominador: 5 }]);
|
||||
return c3r(definition, { mediana: 7, n: 5, q1: 3, q3: 9 });
|
||||
};
|
||||
// The period inventory runs four requests at a time: answer it in waves.
|
||||
function inventory() {
|
||||
for (let wave = http.match(r => r.url.endsWith('/periodos')); wave.length; wave = http.match(r => r.url.endsWith('/periodos'))) {
|
||||
wave.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] }));
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
type Served = { listed?: ReturnType<typeof catalog>; answer?: (r: TestRequest, definition: KpiDefinition) => void };
|
||||
function load(definitions: KpiDefinition[], served: Served = {}) {
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
http.expectOne('/cama/indicadores').flush(served.listed ?? catalog(definitions));
|
||||
inventory();
|
||||
// Data requests also go out in waves of four.
|
||||
const requested: string[] = [];
|
||||
for (let wave = http.match(r => r.url.endsWith('/datos')); wave.length; wave = http.match(r => r.url.endsWith('/datos'))) {
|
||||
wave.forEach(r => {
|
||||
requested.push(r.request.url);
|
||||
const definition = definitions.find(d => r.request.url.endsWith('/' + d.id + '/datos'))!;
|
||||
if (served.answer) served.answer(r, definition); else r.flush(dataFor(definition));
|
||||
});
|
||||
fixture.detectChanges();
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const text = (card: HTMLElement, selector: string) => card.querySelector(selector)?.textContent?.trim();
|
||||
|
||||
it('con el catálogo actual: dos tarjetas con datos, dos pendientes y ninguna consulta a indicadores sin publicar', () => {
|
||||
// Fails if a pending indicator is requested, or if a pending card is drawn with a number.
|
||||
const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica') || url.includes('cama_dias_resultado_diagnostico'))).toBe(false);
|
||||
expect(urls.some(url => url.includes('cama_confirmacion_birads45') || url.includes('cama_dias_toma_diagnostico'))).toBe(false);
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
||||
expect(cards().map(card => text(card, 'h3'))).toEqual([
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
|
||||
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined]);
|
||||
expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
|
||||
expect(cards()[1].textContent).toContain('aún no está publicado');
|
||||
expect(cards()[1].textContent).not.toMatch(/\d/);
|
||||
});
|
||||
it('si el catálogo publica los cuatro indicadores no queda ninguna tarjeta pendiente', () => {
|
||||
// Fails if a published opportunity indicator is not queried and drawn.
|
||||
const urls = load([...KPI_BY_DOMAIN.cama, CAMA_TASA_DETECCION_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI]);
|
||||
expect(cards()).toHaveLength(4);
|
||||
expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica'))).toBe(true);
|
||||
expect(urls.some(url => url.includes('cama_dias_resultado_diagnostico'))).toBe(true);
|
||||
expect(cards().map(card => text(card, 'h3'))).toEqual(CAMA_OPORTUNIDAD_KPIS.map(d => d.title));
|
||||
expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false);
|
||||
expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.');
|
||||
});
|
||||
it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => {
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
http.expectOne('/cama/indicadores').flush([]); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Integración pendiente'); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('un indicador publicado con otro contrato no se muestra como la tarjeta esperada', () => {
|
||||
// Fails if a contract mismatch (C1 served where C3r is expected) is drawn as a median.
|
||||
load(KPI_BY_DOMAIN.cama, { listed: catalog(KPI_BY_DOMAIN.cama).map(i => i.id === 'cama_eu38a' ? { ...i, contrato: 'C1' } : i) });
|
||||
const panel = fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel)
|
||||
.find(p => p.definition.id === 'cama_eu38a')!;
|
||||
expect(panel.result().state).toBe('Error de contrato'); expect(panel.result().value).toBeUndefined();
|
||||
});
|
||||
it('el error de una consulta se muestra en su tarjeta y las demás conservan sus datos', () => {
|
||||
load(KPI_BY_DOMAIN.cama, { answer: (r, definition) => definition.id === 'cama_eu38a' ? r.flush('private', { status: 500, statusText: 'Error' }) : r.flush(dataFor(definition)) });
|
||||
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
|
||||
expect(text(cards()[0], '.value')).toBe('5pacientes');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de mastografía a resultado"]')).not.toBeNull();
|
||||
});
|
||||
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
|
||||
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
|
||||
load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
const ids = fixture.componentInstance.searchResults().items.map(item => item.id);
|
||||
expect(ids).not.toContain('cama_biopsias');
|
||||
expect(ids).toContain('cama_birads_456_mastografia');
|
||||
expect(fixture.nativeElement.querySelector('.catalog-grid').textContent).not.toContain('Distribución de resultados de biopsia');
|
||||
});
|
||||
it('los rótulos de CaMa dicen «cáncer de mama»', () => {
|
||||
load(KPI_BY_DOMAIN.cama);
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).toContain('Cáncer de mama, investigación');
|
||||
expect(text).toContain('Explora los indicadores de cáncer de mama.');
|
||||
expect(text).toContain('Filtros generales de cáncer de mama');
|
||||
expect(text).toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
|
||||
});
|
||||
it('Disponible queda visualmente oculto y sigue en un único estado accesible en CaMa', () => {
|
||||
const card = TestBed.createComponent(IndicadorKpiCard);
|
||||
card.componentRef.setInput('title', 'Indicador'); card.componentRef.setInput('state', 'Disponible'); card.detectChanges();
|
||||
expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Disponible');
|
||||
card.componentRef.setInput('quietWhenAvailable', true); card.detectChanges();
|
||||
const status = card.nativeElement.querySelectorAll('[role="status"]');
|
||||
expect(status).toHaveLength(1);
|
||||
expect(status[0].textContent).toBe('Disponible');
|
||||
expect(status[0].classList.contains('visually-hidden')).toBe(true);
|
||||
card.componentRef.setInput('state', 'Sin datos del periodo'); card.detectChanges();
|
||||
expect(card.nativeElement.querySelectorAll('[role="status"]')).toHaveLength(1);
|
||||
expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Sin datos del periodo');
|
||||
expect(card.nativeElement.querySelector('.kpi-state').classList.contains('visually-hidden')).toBe(false);
|
||||
card.componentRef.setInput('quietWhenAvailable', false); card.componentRef.setInput('state', 'Disponible'); card.detectChanges();
|
||||
expect(card.nativeElement.querySelectorAll('[role="status"]')).toHaveLength(1);
|
||||
expect(card.nativeElement.querySelector('.kpi-state').classList.contains('visually-hidden')).toBe(false);
|
||||
card.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Filtros generales de CaMa: periodo único', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorPeriodFilters>>;
|
||||
const availability = () => ({ ...emptyAvailability('ready'), options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
|
||||
function mount(compact: boolean, draft: unknown = { mode: 'explicit', periodos: ['2025-S2'] }, applied: unknown = { mode: 'explicit', periodos: ['2025-S2'] }) {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorPeriodFilters] });
|
||||
fixture = TestBed.createComponent(IndicadorPeriodFilters);
|
||||
fixture.componentRef.setInput('types', ['semestre', 'mes']);
|
||||
fixture.componentRef.setInput('compact', compact);
|
||||
fixture.componentRef.setInput('availability', availability());
|
||||
fixture.componentRef.setInput('state', { tipo: 'semestre', editors: { semestre: { added: [], draft }, mes: { added: [], draft: { mode: 'empty' } } },
|
||||
applied: { tipo: 'semestre', selection: applied } });
|
||||
fixture.detectChanges();
|
||||
return fixture.componentInstance;
|
||||
}
|
||||
afterEach(() => fixture.destroy());
|
||||
const labels = () => [...fixture.nativeElement.querySelectorAll('mat-label')].map(e => (e as HTMLElement).textContent?.trim());
|
||||
|
||||
it('muestra Intervalo de análisis, Periodo seleccionado y Aplicar en una fila, sin modalidad ni resúmenes de edición', () => {
|
||||
// Fails if the multi-period controls or the editing summaries come back to CaMa.
|
||||
mount(true);
|
||||
expect(labels()).toEqual(['Intervalo de análisis', 'Periodo seleccionado']);
|
||||
expect(fixture.nativeElement.querySelector('.fields.compact .apply-button')).not.toBeNull();
|
||||
const text = fixture.nativeElement.textContent as string;
|
||||
expect(text).not.toContain('Modalidad');
|
||||
expect(text).not.toContain('Selección en edición');
|
||||
expect(text).not.toContain('Sin cambios pendientes');
|
||||
expect(text).toContain('Filtro general aplicado: 2025-S2. Existe reporte en al menos un indicador del dominio.');
|
||||
});
|
||||
it('elegir otro periodo deja un solo periodo en el borrador y avisa que hay cambios sin aplicar', () => {
|
||||
// Fails if the control keeps more than one period, or if the pending notice is lost.
|
||||
const control = mount(true);
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Hay cambios sin aplicar.');
|
||||
control.select(['2025-S1']); fixture.componentRef.setInput('state', { ...control.state }); fixture.detectChanges();
|
||||
expect(control.state.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar.');
|
||||
let applied = 0; control.apply.subscribe(() => applied++);
|
||||
(fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).click();
|
||||
expect(applied).toBe(1);
|
||||
});
|
||||
it('el bloque compacto de CaMa lleva la clase de densidad reducida y los demás dominios no', () => {
|
||||
mount(true); expect((fixture.nativeElement as HTMLElement).classList.contains('compacto')).toBe(true);
|
||||
fixture.destroy(); TestBed.resetTestingModule();
|
||||
mount(false, { mode: 'todos' }, { mode: 'todos' }); expect((fixture.nativeElement as HTMLElement).classList.contains('compacto')).toBe(false);
|
||||
});
|
||||
it('Aplicar no se puede pulsar sin cambios pendientes', () => {
|
||||
mount(true);
|
||||
expect((fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
it('sin periodo elegido no hay nada que aplicar', () => {
|
||||
const control = mount(true, { mode: 'empty' });
|
||||
expect(control.canApply).toBe(false);
|
||||
expect(fixture.nativeElement.textContent).toContain('Selecciona un periodo válido para aplicar.');
|
||||
});
|
||||
it('los demás dominios usan la misma selección de un periodo, sin la fila compacta', () => {
|
||||
// Every domain selects one period; fails if the compact row of CaMa leaks to CaCu or TEA.
|
||||
mount(false, { mode: 'todos' }, { mode: 'todos' });
|
||||
expect(labels()).toEqual(['Intervalo de análisis', 'Periodo seleccionado']);
|
||||
expect(fixture.nativeElement.querySelector('.fields.compact')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
// Covers the clinical section of CaMa's summary: its heading and counter, and the controls the mockup does not
|
||||
// have (search, pins, floating navigation, representation selector, figure count), which CaCu and TEA keep.
|
||||
// Fixtures are catalogs shaped like /<dominio>/indicadores; no figure is requested (the cards stay out of view).
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { Dominio } from './indicadores.models';
|
||||
|
||||
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||
// The catalog 18080 publishes for CaMa.
|
||||
const CAMA = [
|
||||
item('cama_biopsias', 'Distribución de resultados de biopsia', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
||||
item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
||||
item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
||||
item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']),
|
||||
item('cama_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja']),
|
||||
];
|
||||
const OTRO = (prefijo: string) => ['a', 'b', 'c', 'd', 'e', 'f'].map(letra => item(`${prefijo}_${letra}`, `Indicador ${letra}`, 'C2', ['f', 'g']));
|
||||
|
||||
describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
// The KPI and period requests are not what these tests are about.
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
function open(domain: Dominio, catalog: unknown[]) {
|
||||
// The page starts in TEA, whose catalog is already answered: leave it first to load it again.
|
||||
if (domain === fixture.componentInstance.dominio) {
|
||||
fixture.componentInstance.changeDominio(domain === 'cacu' ? 'cama' : 'cacu'); fixture.detectChanges();
|
||||
http.match(() => true);
|
||||
}
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
|
||||
http.match(() => true); fixture.detectChanges();
|
||||
}
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const section = () => root().querySelector('.graphic-section') as HTMLElement;
|
||||
const titles = () => [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
|
||||
it('CaMa: «Indicadores clínicos» y un contador que cuenta lo que la sección muestra', () => {
|
||||
// Fails if the heading or the counter go back to the whole catalog (6) while a card is not drawn.
|
||||
open('cama', CAMA);
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
expect(titles()).not.toContain('Distribución de resultados de biopsia');
|
||||
// The patients' counts go on the exams' card, so the partner indicator has no card of its own.
|
||||
expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6');
|
||||
// Only the paired card is a published indicator the summary draws; the other three are in Histórico.
|
||||
expect(titles()).toEqual(['Porcentaje individual de mastografías']);
|
||||
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('1 indicador publicado');
|
||||
});
|
||||
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
|
||||
// Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones.
|
||||
open('cama', CAMA);
|
||||
for (const titulo of ['Tasa de confirmación histopatológica', 'Tiempo de tamizaje a diagnóstico', 'Días de la toma de la mastografía a su resultado']) {
|
||||
expect(section().textContent).not.toContain(titulo);
|
||||
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
|
||||
}
|
||||
});
|
||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
||||
open('cama', CAMA);
|
||||
const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement;
|
||||
expect(tarjeta).not.toBeNull();
|
||||
expect(tarjeta.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
|
||||
expect(tarjeta.querySelector('[role=status]')?.textContent).toContain('Integración pendiente');
|
||||
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
|
||||
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
|
||||
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
|
||||
// It comes first, as in the reference, and is not counted as a published indicator.
|
||||
expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta);
|
||||
});
|
||||
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
|
||||
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
expect(titles()).toContain('Resultado histopatológico por categoría BI-RADS');
|
||||
});
|
||||
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica pendiente', domain => {
|
||||
open(domain, OTRO(domain));
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
});
|
||||
it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => {
|
||||
// Fails if any of the controls the mockup does not have comes back to CaMa's summary.
|
||||
open('cama', CAMA);
|
||||
expect(root().querySelector('.catalog-search')).toBeNull();
|
||||
expect(section().textContent).not.toContain('Buscar indicadores');
|
||||
expect(root().querySelector('.pin-toggle')).toBeNull();
|
||||
expect(section().textContent).not.toContain('Fijar indicador');
|
||||
expect(root().querySelector('.graphic-navigation-trigger')).toBeNull();
|
||||
expect(section().querySelector('mat-form-field')).toBeNull();
|
||||
expect(section().textContent).not.toContain('Representación gráfica');
|
||||
expect(section().textContent).not.toContain('figuras publicadas');
|
||||
});
|
||||
it('CaMa: las figuras guardadas como fijadas no reordenan las tarjetas', () => {
|
||||
// Fails if a pin saved earlier (the control is gone) still changes the order of CaMa's cards.
|
||||
open('cama', CAMA);
|
||||
const before = titles();
|
||||
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
|
||||
expect(titles()).toEqual(before);
|
||||
});
|
||||
it.each(['tea', 'cacu'] as const)('%s conserva el selector de indicadores y los fijados desde cinco indicadores', domain => {
|
||||
// Fails if CaMa's simplified section leaks into the other domains. In every domain the cards carry no
|
||||
// representation selector or figure count, and there is no floating navigation: the selector replaces it.
|
||||
open(domain, OTRO(domain));
|
||||
expect(root().querySelector('.catalog-search')).not.toBeNull();
|
||||
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||
expect(root().querySelector('.graphic-navigation-trigger')).toBeNull();
|
||||
expect(section().textContent).not.toContain('figuras publicadas');
|
||||
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados');
|
||||
});
|
||||
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
|
||||
open('cacu', OTRO('cacu'));
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
open('tea', OTRO('tea'));
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores gráficos');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// Covers switching domains with requests still pending: nothing of the domain that was left may show up in
|
||||
// the one that was chosen, and the controls particular to each domain stay as they were.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
|
||||
const item = (id: string, titulo: string, contrato: string) => ({ id, titulo, contrato, figuras: ['f', 'g'], tipos_periodo: ['semestre', 'mes'] });
|
||||
|
||||
describe('Cambio de dominio con consultas pendientes', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const d of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(d);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
const text = () => (fixture.nativeElement as HTMLElement).textContent!;
|
||||
|
||||
it('el catálogo pendiente del dominio que se dejó se cancela y su respuesta tardía no se dibuja', () => {
|
||||
// Fails if a late answer of CaMa shows its indicators in CaCu.
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
const cama = http.expectOne('/cama/indicadores');
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
expect(cama.cancelled).toBe(true);
|
||||
http.expectOne('/cacu/indicadores').flush([item('cacu_x', 'Indicador de CaCu', 'C2')]); fixture.detectChanges();
|
||||
expect(text()).toContain('Indicador de CaCu');
|
||||
expect(() => cama.flush([item('cama_x', 'Indicador de CaMa', 'C2')])).toThrow();
|
||||
fixture.detectChanges();
|
||||
expect(text()).not.toContain('Indicador de CaMa');
|
||||
});
|
||||
it('los controles propios de cada dominio se conservan al ir y volver', () => {
|
||||
// CaCu keeps its search and pins; CaMa, with fewer cards, does not have them; neither state contaminates the other.
|
||||
const abrir = (d: 'cacu' | 'cama', n: number) => {
|
||||
fixture.componentInstance.changeDominio(d); fixture.detectChanges();
|
||||
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
|
||||
http.match(() => true);
|
||||
};
|
||||
const el = () => fixture.nativeElement as HTMLElement;
|
||||
abrir('cacu', 6);
|
||||
expect(el().querySelector('.catalog-search')).not.toBeNull();
|
||||
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||
abrir('cama', 6);
|
||||
expect(el().querySelector('.catalog-search')).toBeNull();
|
||||
expect(el().querySelector('.pin-toggle')).toBeNull();
|
||||
expect(el().textContent).not.toContain('cacu_');
|
||||
abrir('cacu', 6);
|
||||
// On the way back the page state (not only the DOM) says CaCu has its search again.
|
||||
expect(fixture.componentInstance.dominio).toBe('cacu');
|
||||
expect(fixture.componentInstance.searchVisible()).toBe(true);
|
||||
expect(el().textContent).not.toContain('cama_');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,287 @@
|
||||
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 { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, CONFIRMACION_CAMA, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||
periodosConfirmacion, rangoTasas, seleccionBase, seleccionEtiqueta, tasas, vistaConfirmacion, wilson } from './indicadores-confirmacion-citologia';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
|
||||
|
||||
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
|
||||
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
|
||||
// valores_estrato as texts. Counts per cytology: NORMAL, LIEBG, LIEAG, CIS, CARCINOMA,
|
||||
// SIN_BIOPSIA (no biopsy yet), SIN_DATO (biopsy without grade), CIN2.
|
||||
const CATEGORIAS = [...GRADOS, 'SIN_BIOPSIA', 'SIN_DATO', 'CIN2'];
|
||||
const CONTEOS: Record<string, number[]> = {
|
||||
'ASC-H': [16, 11, 9, 1, 1, 20, 2, 0], LIEAG: [6, 10, 31, 8, 2, 22, 2, 1], CIS: [0, 1, 4, 4, 3, 11, 2, 0],
|
||||
};
|
||||
function respuesta(periodos = ['2026-S2'], conteos = CONTEOS): IndicadorDatos {
|
||||
const filas = periodos.flatMap(periodo => Object.entries(conteos).flatMap(([estrato, ns]) =>
|
||||
CATEGORIAS.map((categoria, orden) => ({ periodo, grupo: 'TOTAL', estrato, categoria, n: ns[orden], orden, suprimido: 0 }))));
|
||||
const color = ['#9DBFE3', '#E8C28E', '#D98E4A', '#B55A1F', '#7A2E0E'];
|
||||
const estratos = Object.keys(conteos);
|
||||
return {
|
||||
id: 'cacu_confirmacion_citologia', contrato: 'C2', tipo_periodo: 'semestre', periodos, filas, version: '1',
|
||||
estrato: 'citologia_alto_grado', valores_estrato: estratos,
|
||||
etiquetas_estrato: Object.fromEntries(estratos.map(e => [e, e === 'CIS' ? 'Carcinoma in situ' : e])),
|
||||
totales_estrato: periodos.flatMap(periodo => estratos.map(estrato => ({ periodo, grupo: 'TOTAL', estrato,
|
||||
n: conteos[estrato].reduce((a, b) => a + b, 0), suprimido: 0 }))),
|
||||
categorias: {
|
||||
...Object.fromEntries(GRADOS.map((id, i) => [id, { etiqueta: id === 'CIS' ? 'Carcinoma in situ' : id, color: color[i],
|
||||
grupo: i < 2 ? 'NO_ANORMAL' : 'ANORMAL', gravedad: i + 1 }])),
|
||||
SIN_BIOPSIA: { etiqueta: 'Sin biopsia aún', color: '#C9CDD2', grupo: null, gravedad: null },
|
||||
SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2', grupo: 'SIN_DATO', gravedad: null },
|
||||
CIN2: { etiqueta: 'CIN2', color: null, grupo: 'NO_ANORMAL', gravedad: null },
|
||||
},
|
||||
grupos_de_categoria: { NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Sin dato' },
|
||||
};
|
||||
}
|
||||
|
||||
describe('Confirmación histopatológica: modelo', () => {
|
||||
it('denominador: mujeres con biopsia y grado; SIN_BIOPSIA y SIN_DATO van aparte; CIN2 cuenta en su grupo', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||
expect(m.filas.map(f => f.id)).toEqual(['CIS', 'LIEAG', 'ASC-H']);
|
||||
expect(m.filas.map(f => f.etiqueta)).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
|
||||
expect(m.filas.map(f => f.den)).toEqual([12, 58, 38]);
|
||||
expect(m.aparte).toEqual([{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' }, { id: 'SIN_DATO', etiqueta: 'Sin dato' }]);
|
||||
expect(m.filas.map(f => [f.aparte['SIN_BIOPSIA'].n, f.aparte['SIN_DATO'].n])).toEqual([[11, 2], [22, 2], [20, 2]]);
|
||||
expect(m.grados.map(g => g.id)).toEqual([...GRADOS, 'CIN2']);
|
||||
expect(m.grados.find(g => g.id === 'CIN2')).toMatchObject({ grupo: 'NO_ANORMAL', color: '#8A9199' });
|
||||
expect(m.grupos.find(g => g.id === 'NO_ANORMAL')!.grados).toEqual(['NORMAL', 'LIEBG', 'CIN2']);
|
||||
expect(m.conBiopsia).toBe(108); expect(m.base).toBe('ANORMAL');
|
||||
});
|
||||
it('estratos ausentes de valores_estrato dicen «Sin mujeres con biopsia»; total suprimido suprime la fila', () => {
|
||||
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
|
||||
const m = modeloConfirmacion(d, '2026-S2');
|
||||
expect(m.filas.map(f => f.den)).toEqual([0, 58, 0]);
|
||||
expect(tasas(m, seleccionBase(m)).map(t => estadoTasa(t))).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
|
||||
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
|
||||
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
|
||||
const s = modeloConfirmacion(d, '2026-S2');
|
||||
expect([s.filas[1].den, s.filas[1].estado]).toEqual([null, 'Suprimido']);
|
||||
expect(s.conBiopsia).toBeNull();
|
||||
expect((figuraTasas(s, seleccionBase(s), 'claro').layout['annotations'] as { text: string }[])[1].text).toBe('Suprimido');
|
||||
});
|
||||
it('Wilson al 95 % con la fórmula del kit y extremos 0 y n', () => {
|
||||
const [bajo, alto] = wilson(11, 12);
|
||||
expect(bajo).toBeCloseTo(64.61, 1); expect(alto).toBeCloseTo(98.51, 1);
|
||||
expect(wilson(0, 10)[0]).toBe(0); expect(wilson(10, 10)[1]).toBe(100);
|
||||
});
|
||||
it('vista base LIEAG o más; grupo, grado, segundo clic al grupo y centro a la base', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||
const base = seleccionBase(m);
|
||||
expect(tasas(m, base).map(t => [t.k, t.fila.den])).toEqual([[11, 12], [41, 58], [11, 38]]);
|
||||
expect(lectura(m, base)).toBe('Verdaderos positivos (valor predictivo positivo)');
|
||||
const menor = clicConfirmacion(m, base, 'grupos', m.grupos.findIndex(g => g.id === 'NO_ANORMAL'));
|
||||
expect(menor).toEqual({ grupo: 'NO_ANORMAL' }); expect(lectura(m, menor)).toBe('Sin confirmación de alto grado');
|
||||
const normal = clicConfirmacion(m, menor, 'categorias', 0);
|
||||
expect(normal).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
expect(lectura(m, normal)).toBe('Falsos positivos: la biopsia no confirmó lesión');
|
||||
expect(tasas(m, normal).map(t => t.k)).toEqual([0, 6, 16]);
|
||||
expect(clicConfirmacion(m, normal, 'categorias', 0)).toEqual({ grupo: 'NO_ANORMAL' });
|
||||
const cis = clicConfirmacion(m, normal, 'categorias', 3);
|
||||
expect(lectura(m, cis)).toBe('Proporción con biopsia Carcinoma in situ');
|
||||
expect(clicConfirmacion(m, cis, 'centro', 0)).toEqual(base);
|
||||
});
|
||||
it('figura de tasas: una traza siempre, etiquetas «xx.x %» y «k/n», eje acotado a múltiplos de 5', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
|
||||
const f = figuraTasas(m, base, 'claro');
|
||||
expect(f.data).toHaveLength(1); expect(f.data[0]['type']).toBe('scatter');
|
||||
expect(f.data[0]['y']).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
|
||||
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray).toEqual(['ASC-H', 'LIEAG', 'Carcinoma in situ']);
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text))
|
||||
.toEqual(['<b>91.7 %</b><br>11/12', '<b>70.7 %</b><br>41/58', '<b>28.9 %</b><br>11/38']);
|
||||
const range = (f.layout['xaxis'] as { range: number[] }).range;
|
||||
expect(range).toEqual(rangoTasas(tasas(m, base)));
|
||||
expect(range[0] % 5).toBe(0); expect(range[1] % 5).toBe(0); expect(range[0]).toBeGreaterThanOrEqual(0); expect(range[1]).toBeLessThanOrEqual(100);
|
||||
expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Verdaderos positivos (valor predictivo positivo)');
|
||||
const otra = figuraTasas(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'oscuro');
|
||||
expect(otra.data).toHaveLength(1); expect(otra.layout['paper_bgcolor']).toBe('#081839');
|
||||
});
|
||||
it('fila suprimida o nula dice Suprimido o No disponible, nunca 0, y la dona no suma un total parcial', () => {
|
||||
const d = respuesta();
|
||||
Object.assign(d.filas.find(f => f['estrato'] === 'CIS' && f['categoria'] === 'LIEAG')!, { n: null, suprimido: 1 });
|
||||
d.filas = d.filas.filter(f => !(f['estrato'] === 'ASC-H' && f['categoria'] === 'NORMAL'));
|
||||
const m = modeloConfirmacion(d, '2026-S2'), base = seleccionBase(m);
|
||||
expect(m.filas.map(f => [f.den, f.estado])).toEqual([[null, 'Suprimido'], [58, 'Publicado'], [null, 'No disponible']]);
|
||||
const f = figuraTasas(m, base, 'claro');
|
||||
expect(f.data[0]['x']).toEqual([null, 100 * 41 / 58, null]);
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(['Suprimido', '<b>70.7 %</b><br>41/58', 'No disponible']);
|
||||
expect(JSON.stringify(f.layout['annotations'])).not.toContain('0/');
|
||||
expect(m.conBiopsia).toBeNull(); expect(donaConfirmacion(m, base, 'claro').data).toHaveLength(0);
|
||||
});
|
||||
it('dona de dos anillos; la selección atenúa sin cambiar valores y el centro dice «k de N con biopsia»', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
|
||||
const d = donaConfirmacion(m, base, 'claro');
|
||||
expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
|
||||
expect(d.data[1]['values']).toEqual([45, 63]);
|
||||
expect(d.data[2]['values']).toEqual([22, 22, 44, 13, 6, 1]);
|
||||
expect(d.data[0]['text']).toEqual(['<b>63</b><br>de 108 con biopsia']);
|
||||
const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro');
|
||||
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0.3\)$/);
|
||||
});
|
||||
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
|
||||
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||
expect(() => periodosConfirmacion({ ...respuesta(), estrato: 'estatus_seguimiento' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||
expect(() => periodosConfirmacion(respuesta(), 'semestre', ['2026-S1'])).toThrow(ConfirmacionIncompatible);
|
||||
const dup = respuesta(); dup.filas.push({ ...dup.filas[0] });
|
||||
expect(() => modeloConfirmacion(dup, '2026-S2')).toThrow(ConfirmacionIncompatible);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Confirmación histopatológica: componente', () => {
|
||||
const indicador: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1',
|
||||
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2026-S1', '2026-S2'] }, revision: 1 };
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorConfirmacionCitologia>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorConfirmacionCitologia, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorConfirmacionCitologia, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorConfirmacionCitologia);
|
||||
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(); });
|
||||
function flush(body: unknown = respuesta(['2026-S1', '2026-S2'])) {
|
||||
const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_confirmacion_citologia/datos');
|
||||
expect(r.request.params.get('estrato')).toBe('citologia_alto_grado');
|
||||
expect(r.request.params.get('periodos')).toBe('2026-S1,2026-S2');
|
||||
r.flush(body as Record<string, unknown>); f.detectChanges();
|
||||
}
|
||||
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible, periodos y tabla', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(f.componentInstance.model!.periodo).toBe('2026-S2');
|
||||
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
|
||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
|
||||
const normal = [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
|
||||
normal.click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
expect(normal.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Falsos positivos');
|
||||
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
|
||||
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Citología', ...GRADOS.map(g => g === 'CIS' ? 'Carcinoma in situ' : g), 'CIN2', 'Con biopsia', 'Sin biopsia aún', 'Sin dato']);
|
||||
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].slice(-3).map(td => td.textContent))).toEqual([['12', '11', '2'], ['58', '22', '2'], ['38', '20', '2']]);
|
||||
f.componentInstance.changePeriod(-1); f.detectChanges();
|
||||
expect(f.componentInstance.model!.periodo).toBe('2026-S1'); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
|
||||
});
|
||||
it('error se anuncia y el reintento recupera; respuesta incompatible no dibuja', () => {
|
||||
f.detectChanges();
|
||||
http.expectOne(req => req.url.endsWith('/datos')).flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
f.componentInstance.retry(); flush({ ...respuesta(['2026-S1', '2026-S2']), estrato: 'otro' });
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('filtro general incompatible no pide datos', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('«Cómo leer» muestra solo descripción y como_leer de fig_c2_donas y fig_c2_barras', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||
expect(requested).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('pendientes');
|
||||
f.componentRef.setInput('metadata', { descripcion: 'No va', ficha: { nota: 'Tampoco' }, figuras_detalle: [
|
||||
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] },
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] },
|
||||
{ figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.', 'Lee las tasas.']);
|
||||
for (const absent of ['No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent);
|
||||
});
|
||||
it('la tarjeta conecta el panel solo por id de CaCu; cacu_eu13 sigue igual', () => {
|
||||
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(IndicadorConfirmacionCitologia))).toHaveLength(1);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
||||
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['cama', 'cacu_confirmacion_citologia']] as const) {
|
||||
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(0);
|
||||
}
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
// Cáncer de mama's configuration of the same view. Fixture: a one-period answer of cama_histopatologia_birads
|
||||
// built below, with two BI-RADS categories published and biopsies without a result kept apart.
|
||||
describe('Confirmación histopatológica de cáncer de mama', () => {
|
||||
const categorias = {
|
||||
BENIGNO: { etiqueta: 'Benigno', color: '#9DBFE3', grupo: 'NO_MALIGNO' }, RIESGO_B3: { etiqueta: 'Lesión de riesgo (B3)', color: '#2F6DB3', grupo: 'NO_MALIGNO' },
|
||||
IN_SITU: { etiqueta: 'Carcinoma in situ', color: '#D9822B', grupo: 'MALIGNO' }, INVASOR: { etiqueta: 'Carcinoma invasor', color: '#B5482E', grupo: 'MALIGNO' },
|
||||
SIN_DATO: { etiqueta: 'Sin resultado histopatológico', color: '#BDBDBD', grupo: 'SIN_DATO' },
|
||||
};
|
||||
const n: Record<string, Record<string, number>> = {
|
||||
BIRADS_5: { BENIGNO: 3, RIESGO_B3: 0, IN_SITU: 11, INVASOR: 38, SIN_DATO: 3 },
|
||||
BIRADS_4A: { BENIGNO: 91, RIESGO_B3: 15, IN_SITU: 1, INVASOR: 7, SIN_DATO: 9 },
|
||||
};
|
||||
const datos = () => ({ id: 'cama_histopatologia_birads', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'birads',
|
||||
valores_estrato: Object.keys(n), categorias, grupos_de_categoria: { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' },
|
||||
filas: Object.entries(n).flatMap(([estrato, c]) => Object.entries(c).map(([categoria, v]) =>
|
||||
({ periodo: '2025-S2', grupo: 'TOTAL', estrato, categoria, n: v, suprimido: 0 }))) }) as IndicadorDatos;
|
||||
|
||||
it('la elige el dominio y el indicador', () => {
|
||||
// Fails if the view stops being found for cáncer de mama, or leaks to another indicator.
|
||||
expect(vistaConfirmacion('cama', { id: 'cama_histopatologia_birads' })).toBe(CONFIRMACION_CAMA);
|
||||
expect(vistaConfirmacion('cama', { id: 'cacu_confirmacion_citologia' })).toBeUndefined();
|
||||
});
|
||||
it('filas BI-RADS de la más grave a la menor, base maligna y sin resultado aparte', () => {
|
||||
// Fails if the rows don't follow the configuration, the base isn't malignancy or «Sin dato» enters the rate.
|
||||
const m = modeloConfirmacion(datos(), '2025-S2', CONFIRMACION_CAMA), base = seleccionBase(m);
|
||||
expect(m.filas.map(f => f.id)).toEqual(['BIRADS_6', 'BIRADS_5', 'BIRADS_4C', 'BIRADS_4B', 'BIRADS_4A']);
|
||||
expect(base).toEqual({ grupo: 'MALIGNO' });
|
||||
expect(lectura(m, base)).toBe('Detección de cáncer (valor predictivo positivo)');
|
||||
const t = tasas(m, base);
|
||||
expect(t[1].k).toBe(49); expect(t[1].fila.den).toBe(52);
|
||||
expect(t[4].k).toBe(8); expect(t[4].fila.den).toBe(114);
|
||||
expect(estadoTasa(t[0], m.vista.textos.sujetos)).toBe('Sin pacientes con biopsia');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Dona interactiva como la de CaCu (sin botones)', () => {
|
||||
const vista = { ...CONFIRMACION_CAMA, id: 'cacu_confirmacion_citologia', estrato: 'citologia_alto_grado' as const, filas: CONFIRMACION_CACU.filas, base: 'LIEAG' };
|
||||
const modelo = () => modeloConfirmacion(respuesta(), '2026-S2', vista);
|
||||
it('total → grupo → resultado y el centro regresa un paso hasta el total', () => {
|
||||
// Fails if the centre stops returning to the total, or a group click no longer narrows to it.
|
||||
const m = modelo(), g = m.grupos.findIndex(x => x.id === m.base), c = m.grados.findIndex(x => x.grupo === m.base);
|
||||
let s = clicDona(m, {}, 'grupos', g); expect(s).toEqual({ grupo: m.base });
|
||||
s = clicDona(m, s, 'categorias', c); expect(s).toEqual({ grupo: m.base, categoria: m.grados[c].id });
|
||||
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({ grupo: m.base });
|
||||
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({});
|
||||
expect(clicDona(m, { grupo: m.base }, 'grupos', g)).toEqual({});
|
||||
const otra = m.grados.findIndex(x => x.grupo !== m.base);
|
||||
expect(clicDona(m, { grupo: m.base }, 'categorias', otra)).toEqual({ grupo: m.base });
|
||||
});
|
||||
it('el grupo elegido llena los dos anillos y el total cuenta el grupo base en las tasas', () => {
|
||||
// Fails if the other group's slices stay (no expansion), or the total stops reading as the base rate.
|
||||
const m = modelo(), base = m.grupos.find(x => x.id === m.base)!;
|
||||
const d = donaExpandible(m, { grupo: m.base }, 'claro');
|
||||
const exterior = d.data[2]['values'] as number[];
|
||||
m.grados.forEach((g, i) => expect(exterior[i] === 0).toBe(g.grupo !== m.base));
|
||||
expect((d.data[1]['values'] as number[]).filter(v => v > 0)).toHaveLength(1);
|
||||
expect(d.data[0]['text']).toEqual([`<b>${base.grados.reduce((s, c) => s + m.totales[c]!, 0)}</b><br>${base.etiqueta}`]);
|
||||
expect(tasas(m, {}).map(t => t.k)).toEqual(tasas(m, seleccionBase(m)).map(t => t.k));
|
||||
expect(lectura(m, {})).toBe(vista.textos.base);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,324 @@
|
||||
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
||||
// a C2 stratified by the last valid cytology of the period; the category is the grade
|
||||
// of the biopsy it originated. Unknown or suppressed cells never become zero.
|
||||
export const ID_CONFIRMACION = 'cacu_confirmacion_citologia';
|
||||
export const ESTRATO_CITOLOGIA = 'citologia_alto_grado';
|
||||
// Outside the denominator and the donut, reported apart in the table:
|
||||
// SIN_BIOPSIA = no biopsy reported at the cut-off; SIN_DATO = biopsy reported without a grade.
|
||||
export const APARTE = [
|
||||
{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' },
|
||||
{ id: 'SIN_DATO', etiqueta: 'Biopsia sin grado' },
|
||||
] as const;
|
||||
const APARTE_IDS: readonly string[] = APARTE.map(a => a.id);
|
||||
// Grades outside the published catalog (CIN2, DESCONOCIDO…) arrive without a colour.
|
||||
const COLOR_RESPALDO = '#8A9199';
|
||||
// Fixed vertical axis, most severe cytology on top.
|
||||
export const FILAS_CITOLOGIA = [
|
||||
{ id: 'CIS', etiqueta: 'Carcinoma in situ' },
|
||||
{ id: 'LIEAG', etiqueta: 'LIEAG' },
|
||||
{ id: 'ASC-H', etiqueta: 'ASC-H' },
|
||||
] as const;
|
||||
export const Z95 = 1.959963984540054;
|
||||
|
||||
// One confirmation view: which indicator and stratum, its fixed rows (most severe on top), the grade whose group is
|
||||
// the base view (the true positives), the grade read as a false positive, and the words the view uses.
|
||||
export interface VistaConfirmacion {
|
||||
id: string; estrato: DimensionEstrato; filas: readonly { id: string; etiqueta: string }[];
|
||||
base: string; falsoPositivo: string;
|
||||
// With buttons, the choice is made on them; without, on the donut (donaExpandible), whose centre names it.
|
||||
botones: boolean;
|
||||
textos: { base: string; falsoPositivo: string; sinConfirmacion: string; filas: string; encabezado: string; sujetos: string; vacio: string };
|
||||
}
|
||||
export const CONFIRMACION_CACU: VistaConfirmacion = {
|
||||
id: ID_CONFIRMACION, estrato: ESTRATO_CITOLOGIA, filas: FILAS_CITOLOGIA, base: 'LIEAG', falsoPositivo: 'NORMAL', botones: true,
|
||||
textos: { base: 'Verdaderos positivos (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia no confirmó lesión',
|
||||
sinConfirmacion: 'Sin confirmación de alto grado', filas: 'Por resultado de la citología', encabezado: 'Citología', sujetos: 'mujeres',
|
||||
vacio: 'No hay citologías de alto grado publicadas para este periodo.' },
|
||||
};
|
||||
// Cáncer de mama: the biopsies by the BI-RADS of the mammogram that led to them; the base is malignancy.
|
||||
export const CONFIRMACION_CAMA: VistaConfirmacion = {
|
||||
id: 'cama_histopatologia_birads', estrato: 'birads', base: 'INVASOR', falsoPositivo: 'BENIGNO', botones: false,
|
||||
filas: [{ id: 'BIRADS_6', etiqueta: 'BI-RADS 6' }, { id: 'BIRADS_5', etiqueta: 'BI-RADS 5' }, { id: 'BIRADS_4C', etiqueta: 'BI-RADS 4C' },
|
||||
{ id: 'BIRADS_4B', etiqueta: 'BI-RADS 4B' }, { id: 'BIRADS_4A', etiqueta: 'BI-RADS 4A' }],
|
||||
textos: { base: 'Detección de cáncer (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia resultó benigna',
|
||||
sinConfirmacion: 'Sin malignidad', filas: 'Por categoría BI-RADS', encabezado: 'BI-RADS', sujetos: 'pacientes',
|
||||
vacio: 'No hay biopsias publicadas para este periodo.' },
|
||||
};
|
||||
const VISTAS_CONFIRMACION: Readonly<Partial<Record<Dominio, VistaConfirmacion>>> = { cacu: CONFIRMACION_CACU, cama: CONFIRMACION_CAMA };
|
||||
export function vistaConfirmacion(dominio: Dominio, indicador: Pick<Indicador, 'id'>): VistaConfirmacion | undefined {
|
||||
const vista = VISTAS_CONFIRMACION[dominio];
|
||||
return vista?.id === indicador.id ? vista : undefined;
|
||||
}
|
||||
|
||||
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
export interface Grado { id: string; etiqueta: string; color: string; grupo: string; }
|
||||
export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; }
|
||||
export interface FilaCitologia {
|
||||
id: string; etiqueta: string; celdas: Record<string, Celda>;
|
||||
// SIN_BIOPSIA and SIN_DATO cells, when the response publishes those categories.
|
||||
aparte: Record<string, Celda>;
|
||||
// Women of the row with a biopsy: the denominator. Null when any of its cells is unknown.
|
||||
den: number | null; estado: Celda['estado'];
|
||||
}
|
||||
export interface ModeloConfirmacion {
|
||||
periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string;
|
||||
filas: FilaCitologia[]; totales: Record<string, number | null>; conBiopsia: number | null;
|
||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; vista: VistaConfirmacion;
|
||||
}
|
||||
// Without a group, the total: every result is shown and the rates count the base group.
|
||||
export interface SeleccionConfirmacion { grupo?: string; categoria?: string; }
|
||||
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||
export class ConfirmacionIncompatible extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const texto = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0;
|
||||
const fail = (message: string): never => { throw new ConfirmacionIncompatible(message); };
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
|
||||
|
||||
/** Wilson score interval at 95 %, in percent; same formula as the kit (oro/calculo.py:wilson). */
|
||||
export function wilson(k: number, n: number): [number, number] {
|
||||
const p = k / n, z2 = Z95 * Z95, base = 1 + z2 / n;
|
||||
const centro = (p + z2 / (2 * n)) / base;
|
||||
const mitad = Z95 * Math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / base;
|
||||
return [100 * Math.max(0, Math.min(p, centro - mitad)), 100 * Math.min(1, Math.max(p, centro + mitad))];
|
||||
}
|
||||
|
||||
function celda(fila?: Record<string, unknown>): Celda {
|
||||
if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' };
|
||||
return typeof fila?.['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 && fila['suprimido'] === 0
|
||||
? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' };
|
||||
}
|
||||
function suma(celdas: Celda[]): number | null {
|
||||
return celdas.some(c => c.n === null) ? null : celdas.reduce((s, c) => s + c.n!, 0);
|
||||
}
|
||||
function estado(celdas: Celda[]): Celda['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function promedio(colores: string[]): string {
|
||||
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
|
||||
.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
// grupos_de_categoria publishes a label, or an object with `etiqueta`.
|
||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||
|
||||
/** Validated periods of one stratified response, in request order or sorted. */
|
||||
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[], vista = CONFIRMACION_CACU): string[] {
|
||||
if (datos.id !== vista.id || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== vista.estrato
|
||||
|| !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length
|
||||
|| datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|
||||
|| (solicitados && datos.periodos.some(p => !solicitados.includes(p)))
|
||||
|| datos.filas.some(f => !registro(f) || !datos.periodos.includes(f['periodo'] as string))) {
|
||||
return fail('Los datos no corresponden a la confirmación histopatológica o al periodo aplicado.');
|
||||
}
|
||||
return solicitados ? solicitados.filter(p => datos.periodos.includes(p)) : [...datos.periodos].sort();
|
||||
}
|
||||
|
||||
/** One /datos payload -> the contingency table of a single period. */
|
||||
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string, vista = CONFIRMACION_CACU): ModeloConfirmacion {
|
||||
periodosConfirmacion(datos, datos.tipo_periodo, undefined, vista);
|
||||
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
|
||||
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de grados incompleto.');
|
||||
const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => {
|
||||
const c = cats[a.id];
|
||||
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
||||
});
|
||||
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|
||||
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
|
||||
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
|
||||
});
|
||||
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
||||
// Off-catalogue grades share the group but not its colour.
|
||||
const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO);
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
|
||||
grados: propios.map(g => g.id) };
|
||||
});
|
||||
// The base view is the group of the view's base grade (CaCu: "LIEAG o más"): the true positives.
|
||||
const base = grados.find(g => g.id === vista.base)?.grupo ?? fail(`El catálogo no publica el grado ${vista.base}.`);
|
||||
if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.');
|
||||
const index = new Map<string, Record<string, unknown>>();
|
||||
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
|
||||
const c = row['categoria'], e = row['estrato'];
|
||||
if (!esTotal(row['grupo']) || typeof e !== 'string' || typeof c !== 'string'
|
||||
|| (!grados.some(g => g.id === c) && !aparte.some(a => a.id === c)) || ![0, 1].includes(row['suprimido'] as number)) {
|
||||
return fail('Fila de confirmación inválida.');
|
||||
}
|
||||
const key = JSON.stringify([e, c]);
|
||||
if (index.has(key)) return fail('Filas de confirmación duplicadas.');
|
||||
index.set(key, row);
|
||||
}
|
||||
// valores_estrato may list only the strata with data; a fixed row absent from it has no women.
|
||||
const publicados = Array.isArray(datos['valores_estrato']) ? (datos['valores_estrato'] as unknown[]) : undefined;
|
||||
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos inválidos.');
|
||||
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
|
||||
const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
|
||||
if (!totales.every(registro)) fail('Totales por estrato inválidos.');
|
||||
const filas = vista.filas.map(({ id, etiqueta }) => {
|
||||
const rotulo = texto(etiquetas[id]) ? etiquetas[id] : registro(cats[id]) && texto(cats[id]['etiqueta']) ? cats[id]['etiqueta'] : etiqueta;
|
||||
const tieneFilas = [...index.keys()].some(k => JSON.parse(k)[0] === id);
|
||||
const ausente = !tieneFilas && (!publicados || !publicados.includes(id));
|
||||
const cero = (): Celda => ({ n: 0, estado: 'Publicado' });
|
||||
const celdas = Object.fromEntries(grados.map(g => [g.id, ausente ? cero() : celda(index.get(JSON.stringify([id, g.id])))]));
|
||||
const otras = Object.fromEntries(aparte.map(a => [a.id, ausente ? cero() : celda(index.get(JSON.stringify([id, a.id])))]));
|
||||
// A suppressed published total suppresses the row, whatever its cells say.
|
||||
const suprimida = (totales as Record<string, unknown>[]).some(t => t['periodo'] === periodo && t['estrato'] === id && t['suprimido'] === 1);
|
||||
const valores = Object.values(celdas);
|
||||
return { id, etiqueta: rotulo, celdas, aparte: otras,
|
||||
den: suprimida ? null : suma(valores), estado: suprimida ? 'Suprimido' as const : estado(valores) };
|
||||
});
|
||||
const porGrado = Object.fromEntries(grados.map(g => [g.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[g.id]))]));
|
||||
return { periodo, grados, grupos, base, filas, totales: porGrado,
|
||||
conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))),
|
||||
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])], vista };
|
||||
}
|
||||
|
||||
export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; }
|
||||
export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] {
|
||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === (sel.grupo ?? m.base))?.grados ?? [];
|
||||
}
|
||||
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta
|
||||
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'Todos los resultados';
|
||||
}
|
||||
/** CaCu's interactive donut: a group narrows to it, a result is chosen inside its group, the centre steps back
|
||||
* (result -> its group -> the total), and choosing the chosen entry again also steps back. */
|
||||
export function clicDona(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||
if (traza === 'centro') return sel.categoria && sel.grupo ? { grupo: sel.grupo } : {};
|
||||
if (traza === 'grupos') { const g = m.grupos[indice]?.id; return !g ? sel : sel.grupo === g && !sel.categoria ? {} : { grupo: g }; }
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.grados[indice];
|
||||
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
}
|
||||
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
|
||||
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||
if (traza === 'centro') return seleccionBase(m);
|
||||
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.grados[indice];
|
||||
if (!c) return sel;
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
}
|
||||
/** The axis title says what the rate reads. */
|
||||
export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||
if (!sel.categoria && (sel.grupo ?? m.base) === m.base) return m.vista.textos.base;
|
||||
if (sel.categoria === m.vista.falsoPositivo) return m.vista.textos.falsoPositivo;
|
||||
if (!sel.categoria) return m.vista.textos.sinConfirmacion;
|
||||
return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel);
|
||||
}
|
||||
/** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */
|
||||
export function tasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion): Tasa[] {
|
||||
const cats = seleccionados(m, sel);
|
||||
return m.filas.map(fila => {
|
||||
if (fila.den === null || fila.den === 0) return { fila, k: null, valor: null, bajo: null, alto: null };
|
||||
const k = cats.reduce((s, c) => s + fila.celdas[c].n!, 0);
|
||||
const [bajo, alto] = wilson(k, fila.den);
|
||||
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
|
||||
});
|
||||
}
|
||||
export function estadoTasa(t: Tasa, sujetos = 'mujeres'): string {
|
||||
return t.fila.den === 0 ? `Sin ${sujetos} con biopsia` : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
|
||||
}
|
||||
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
|
||||
export function rangoTasas(valores: Tasa[]): [number, number] {
|
||||
const visibles = valores.filter(t => t.bajo !== null && t.alto !== null);
|
||||
if (!visibles.length) return [0, 100];
|
||||
const min = Math.min(...visibles.map(t => t.bajo!)), max = Math.max(...visibles.map(t => t.alto!));
|
||||
return [Math.max(0, Math.floor((min - 5) / 5) * 5), Math.min(100, Math.ceil((max + 5) / 5) * 5)];
|
||||
}
|
||||
|
||||
/** Rates on the left: one point and horizontal Wilson interval per cytology, one trace always. */
|
||||
export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const valores = tasas(m, sel);
|
||||
const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === (sel.grupo ?? m.base))!.color;
|
||||
const y = valores.map(t => t.fila.etiqueta);
|
||||
return { data: [{
|
||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: { size: 12, color }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t, m.vista.textos.sujetos), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||
}], layout: {
|
||||
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { l: 130, r: 96, t: 16, b: 64 },
|
||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true },
|
||||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } },
|
||||
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
||||
font: { size: 12, color: p.text },
|
||||
text: t.k === null ? estadoTasa(t, m.vista.textos.sujetos) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Donut on the right: groups inside, grades outside; selection dims, values stay. */
|
||||
export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), activos = new Set(seleccionados(m, sel)), total = m.conBiopsia;
|
||||
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
|
||||
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
|
||||
const exterior = m.grados.map(g => m.totales[g.id]!);
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Donut without buttons, drawn like CaCu's interactive one: the chosen group fills both rings (the other's
|
||||
* slices are zero, so its results expand), a chosen result keeps its colour and its siblings fade, and the
|
||||
* centre names the choice. The traces keep their names and counts, so a choice animates. */
|
||||
export function donaExpandible(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), total = m.conBiopsia;
|
||||
const nGrupo = (g: GrupoGrados) => g.grados.reduce((s, c) => s + m.totales[c]!, 0);
|
||||
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(g) : 0);
|
||||
const exterior = m.grados.map(g => !sel.grupo || sel.grupo === g.grupo ? m.totales[g.id]! : 0);
|
||||
const centro = sel.categoria ? m.totales[sel.categoria]! : sel.grupo ? nGrupo(m.grupos.find(g => g.id === sel.grupo)!) : total;
|
||||
const rotulos = (values: number[], labels: string[], pct: boolean) => {
|
||||
const suma = values.reduce((s, n) => s + n, 0);
|
||||
return values.map((v, i) => !suma || v / suma < .05 ? '' : escapar(labels[i]) + (pct ? '<br>' + shareText(v, suma) : ''));
|
||||
};
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'text', textposition: 'inside',
|
||||
insidetextorientation: 'horizontal' };
|
||||
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
||||
text: [`<b>${miles(centro)}</b><br>${escapar(sel.grupo || sel.categoria ? seleccionEtiqueta(m, sel) : 'Con biopsia')}`],
|
||||
textfont: { size: 16, color: p.text }, marker: { colors: [p.background] },
|
||||
hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Todos los resultados') + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
// Outer labels go outside the ring with a leader line, at full size; automargin makes room for them and
|
||||
// shrinks the three rings together, so they stay concentric.
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), textposition: 'outside', automargin: true,
|
||||
text: exterior.map((v, i) => v ? escapar(m.grados[i].etiqueta) + '<br>' + shareText(v, exterior.reduce((s, n) => s + n, 0)) : ''),
|
||||
textfont: { size: 12, color: p.text }, customdata: custom(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, sel.categoria && g.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 440, margin: { t: 30, l: 30, r: 30, b: 30 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// Covers CaMa's paired card (mammograms by BI-RADS category and patients by their most severe one): what the model
|
||||
// is allowed to add up, what it refuses to compute, and the card drawing it. Fixtures are shaped like the
|
||||
// /cama/indicadores/<id>/datos responses of cama_birads_456_mastografia and cama_birads_456_paciente (version 0.2.0)
|
||||
// served by WebApi for 2025-S2; the counts are synthetic.
|
||||
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 { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, esSocioConteos, modelosConteos, parConteos, PARES_CONTEOS, totalExamenes } from './indicadores-conteos-pareados';
|
||||
|
||||
const PAR = parConteos('cama', 'cama_birads_456_mastografia')!;
|
||||
const CATEGORIAS = {
|
||||
B4A: { etiqueta: 'BI-RADS 4A', color: '#E0A060', grupo: null, gravedad: 6 }, B4B: { etiqueta: 'BI-RADS 4B', color: '#CF7D3C', grupo: null, gravedad: 7 },
|
||||
B4C: { etiqueta: 'BI-RADS 4C', color: '#C26A2B', grupo: null, gravedad: 8 }, B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F', grupo: null, gravedad: 9 },
|
||||
B6: { etiqueta: 'BI-RADS 6', color: '#7A2E0E', grupo: null, gravedad: 10 }, SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2', grupo: null, gravedad: null },
|
||||
B4: { etiqueta: 'B4', color: null, grupo: null, gravedad: 5 },
|
||||
};
|
||||
type Conteos = Partial<Record<keyof typeof CATEGORIAS, number>>;
|
||||
function respuesta(id: string, unidad: string, conteos: Conteos, extra: Partial<IndicadorDatos> & Record<string, unknown> = {}, suprimidas: string[] = []): IndicadorDatos {
|
||||
return {
|
||||
id, titulo: id, version: '0.2.0', contrato: 'C2', unidad, tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, grupos: { TOTAL: 'Total' },
|
||||
categorias: CATEGORIAS, notas: [unidad === 'paciente' ? 'Pacientes cuyo BI-RADS más grave entre sus mastografías del semestre es 4, 5 o 6.' : 'Mastografías tomadas en el semestre con BI-RADS 4, 5 o 6, cada una con su categoría.'],
|
||||
filas: Object.keys(CATEGORIAS).map((categoria, orden) => ({
|
||||
periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, n: conteos[categoria as keyof Conteos] ?? 0, orden, suprimido: suprimidas.includes(categoria) ? 1 : 0 })),
|
||||
...extra } as unknown as IndicadorDatos;
|
||||
}
|
||||
const examenes = (c: Conteos, extra = {}, suprimidas: string[] = []) => respuesta('cama_birads_456_mastografia', 'examen', c, extra, suprimidas);
|
||||
const pacientes = (c: Conteos, extra = {}, suprimidas: string[] = []) => respuesta('cama_birads_456_paciente', 'paciente', c, extra, suprimidas);
|
||||
// The 2025-S2 counts of the laboratory instance.
|
||||
const LAB_E: Conteos = { B5: 18, B4: 15 }, LAB_P: Conteos = { B5: 18, B4: 13 };
|
||||
const modelo = (e: IndicadorDatos, p: IndicadorDatos) => modelosConteos(PAR, e, p, 'semestre')[0];
|
||||
|
||||
describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
|
||||
it('con los datos del laboratorio: BI-RADS 4 suma sus subcategorías en ambas unidades', () => {
|
||||
// Fails if the family rows stop adding the categories of each indicator (B4 without subcategory included).
|
||||
const m = modelo(examenes(LAB_E), pacientes(LAB_P));
|
||||
expect(m.filas.map(f => [f.etiqueta, f.pacientes, f.examenes])).toEqual([['BI-RADS 4', 13, 15], ['BI-RADS 5', 18, 18], ['BI-RADS 6', 0, 0]]);
|
||||
expect(totalExamenes(m)).toBe(33);
|
||||
expect(m.pacientesVerificados).toBe(true);
|
||||
});
|
||||
it('las subcategorías se suman dentro de cada indicador y los pacientes no se derivan de las mastografías', () => {
|
||||
// Fails if patients are taken from the exams' counts: here 10 exams belong to 7 patients.
|
||||
const m = modelo(examenes({ B4: 1, B4A: 2, B4B: 3, B4C: 4, B5: 5 }), pacientes({ B4: 1, B4A: 1, B4B: 2, B4C: 3, B5: 5 }));
|
||||
expect(m.filas[0]).toMatchObject({ pacientes: 7, examenes: 10 });
|
||||
expect(m.filas[1]).toMatchObject({ pacientes: 5, examenes: 5 });
|
||||
});
|
||||
it('una celda suprimida o sin fila deja desconocida la familia que la contiene, no en cero', () => {
|
||||
// Fails if an unknown cell is added as zero.
|
||||
const suprimida = modelo(examenes(LAB_E), pacientes({ B4: 13, B4B: 2, B5: 18 }, {}, ['B4B']));
|
||||
expect(suprimida.filas.map(f => f.pacientes)).toEqual([null, 18, 0]);
|
||||
const sinFila = pacientes(LAB_P); sinFila.filas = sinFila.filas.filter(f => f['categoria'] !== 'B4C');
|
||||
expect(modelo(examenes(LAB_E), sinFila).filas.map(f => f.pacientes)).toEqual([null, 18, 0]);
|
||||
const examenSuprimido = modelo(examenes(LAB_E, {}, ['B6']), pacientes(LAB_P));
|
||||
expect(examenSuprimido.filas.map(f => f.examenes)).toEqual([15, 18, null]);
|
||||
expect(totalExamenes(examenSuprimido)).toBeNull();
|
||||
expect(donaConteos(examenSuprimido, PAR, 'claro').data).toEqual([]);
|
||||
});
|
||||
it('una versión del indicador de pacientes que no se verificó no se suma', () => {
|
||||
// Fails if another version of the patients' indicator is added up without its definition being checked again.
|
||||
const m = modelo(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' }));
|
||||
expect(m.pacientesVerificados).toBe(false);
|
||||
expect(m.filas.map(f => f.pacientes)).toEqual([null, null, null]);
|
||||
expect(m.filas.map(f => f.examenes)).toEqual([15, 18, 0]);
|
||||
const texto = JSON.stringify(barrasConteos(m, PAR, 'claro').data[0]);
|
||||
expect(texto).toContain('Pendiente'); expect(texto).not.toContain('Sin dato');
|
||||
});
|
||||
it('la mastografía sin categoría solo cuenta si el indicador la publica', () => {
|
||||
expect(modelo(examenes({ ...LAB_E, SIN_DATO: 3 }), pacientes(LAB_P)).sinDato).toBe(3);
|
||||
const sin = examenes(LAB_E); delete (sin as unknown as Record<string, Record<string, unknown>>)['categorias']['SIN_DATO'];
|
||||
expect(modelo(sin, pacientes(LAB_P)).sinDato).toBe(0);
|
||||
});
|
||||
it('solo hay modelo para los periodos que publican los dos conteos, en orden cronológico', () => {
|
||||
const e = examenes(LAB_E), p = pacientes(LAB_P);
|
||||
e.periodos = ['2025-S2', '2025-S1', '2024-S2']; p.periodos = ['2025-S1', '2025-S2'];
|
||||
expect(modelosConteos(PAR, e, p, 'semestre').map(m => m.periodo)).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
it('la dona muestra las categorías de las mastografías con la etiqueta publicada y un nombre claro para el 4 sin subcategoría', () => {
|
||||
const m = modelo(examenes({ ...LAB_E, B4A: 2 }), pacientes(LAB_P));
|
||||
const dona = donaConteos(m, PAR, 'claro') as unknown as { data: { labels: string[]; values: number[] }[]; layout: { annotations: { text: string }[] } };
|
||||
expect(dona.data[0].labels).toEqual(['BI-RADS 4 (sin subcategoría)', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
|
||||
expect(dona.data[0].values).toEqual([15, 2, 0, 0, 18, 0]);
|
||||
expect(dona.layout.annotations[0].text).toBe('<b>35</b><br>mastografías');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Conteos pareados de CaMa: lo que no se calcula', () => {
|
||||
it('no hay razón de mastografías por paciente en la figura ni en el modelo', () => {
|
||||
// Fails if a "≈ x por paciente" annotation comes back: exams of a category include those of patients whose
|
||||
// most severe category is another one, so the quotient mixes populations.
|
||||
const m = modelo(examenes(LAB_E), pacientes(LAB_P));
|
||||
const barras = barrasConteos(m, PAR, 'claro') as unknown as { layout: Record<string, unknown> };
|
||||
expect(barras.layout['annotations']).toBeUndefined();
|
||||
expect(JSON.stringify(barras)).not.toMatch(/≈|por paciente|razón/i);
|
||||
expect(Object.keys(m.filas[0])).toEqual(['id', 'etiqueta', 'pacientes', 'examenes']);
|
||||
});
|
||||
it.each([
|
||||
['unidades cambiadas', () => [examenes(LAB_E, { unidad: 'paciente' }), pacientes(LAB_P)]],
|
||||
['indicador que no es el esperado', () => [examenes(LAB_E, { id: 'otro' }), pacientes(LAB_P)]],
|
||||
['contrato que no es C2', () => [examenes(LAB_E, { contrato: 'C1' }), pacientes(LAB_P)]],
|
||||
['categorías de pacientes de otro catálogo (BIRADS_4, 5 y 6)', () => [examenes(LAB_E), pacientes(LAB_P, { categorias: { BIRADS_4: {}, BIRADS_5: {}, BIRADS_6: {} } })]],
|
||||
])('respuesta incompatible: %s', (_nombre, datos) => {
|
||||
// Fails if a response that is not the pair of indicators is drawn as if it were.
|
||||
const [e, p] = datos();
|
||||
expect(() => modelosConteos(PAR, e, p, 'semestre')).toThrow(ConteosIncompatibles);
|
||||
});
|
||||
it('el par solo existe en CaMa y su socio no tiene tarjeta propia mientras la tarjeta de mastografías esté publicada', () => {
|
||||
expect(PARES_CONTEOS.map(p => p.dominio)).toEqual(['cama']);
|
||||
expect(parConteos('cacu', 'cama_birads_456_mastografia')).toBeUndefined();
|
||||
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_mastografia', 'cama_birads_456_paciente'])).toBe(true);
|
||||
// Without the exams' indicator in the catalog, the patients' one keeps its own card.
|
||||
expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_paciente'])).toBe(false);
|
||||
expect(esSocioConteos('cacu', 'cama_birads_456_paciente', ['cama_birads_456_mastografia'])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: { data: unknown[] }; label?: string; }
|
||||
|
||||
describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||
const CATALOGO = [
|
||||
item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
||||
item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
||||
item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']),
|
||||
];
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorConteosPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama');
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
http.expectOne('/cama/indicadores').flush(CATALOGO); fixture.detectChanges();
|
||||
// Only the card's own requests matter here. The period inventory is answered and the KPI requests are
|
||||
// closed, because unanswered requests would hold the shared request queue.
|
||||
const responder = () => {
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
if (r.request.url.endsWith('/periodos')) r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: '2025-S2', tipo: 'semestre' }] });
|
||||
else r.flush(null, { status: 404, statusText: 'Missing' });
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
};
|
||||
responder();
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
responder();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const tarjeta = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => d.componentInstance as IndicadorCatalogCard)
|
||||
.find(c => c.indicador.id === 'cama_birads_456_mastografia')!;
|
||||
const pedidos = () => http.match(r => /cama_birads_456_(mastografia|paciente)\/datos$/.test(r.url));
|
||||
function abrir(e: IndicadorDatos = examenes(LAB_E), p: IndicadorDatos = pacientes(LAB_P)) {
|
||||
tarjeta().setVisible(true); fixture.detectChanges();
|
||||
const r = pedidos();
|
||||
expect(r.map(q => q.request.url).sort()).toEqual(['/cama/indicadores/cama_birads_456_mastografia/datos', '/cama/indicadores/cama_birads_456_paciente/datos']);
|
||||
expect(r.every(q => q.request.params.get('periodos') === '2025-S2')).toBe(true);
|
||||
for (const q of r) q.flush(q.request.url.includes('mastografia') ? e : p);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
it('el resumen dibuja una sola tarjeta para mastografías y pacientes, y no dibuja el socio ni biopsias', () => {
|
||||
// Fails if the patients' indicator keeps a card of its own beside the pair.
|
||||
const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
// Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary.
|
||||
expect(titulos).toEqual(['Porcentaje individual de mastografías']);
|
||||
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('1 indicador publicado');
|
||||
});
|
||||
it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => {
|
||||
abrir();
|
||||
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
|
||||
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
|
||||
expect(h3).toEqual(['Mastografías por categoría, 2025-S2', 'Pacientes y mastografías, 2025-S2']);
|
||||
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
expect(graficas).toHaveLength(2);
|
||||
expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 2]);
|
||||
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
|
||||
expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]);
|
||||
expect(texto('app-indicador-conteos-pareados')).toContain('no se calcula la razón de mastografías por paciente');
|
||||
expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato');
|
||||
});
|
||||
it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => {
|
||||
abrir(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' }));
|
||||
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
|
||||
expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '15'], ['BI-RADS 5', 'Pendiente', '18'], ['BI-RADS 6', 'Pendiente', '0']]);
|
||||
expect(root().textContent).toContain('Pacientes pendientes');
|
||||
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2);
|
||||
});
|
||||
it('una respuesta incompatible no dibuja cifras y lo dice', () => {
|
||||
// Fails if a pair of responses that are not the two indicators is drawn as if it were.
|
||||
abrir(examenes(LAB_E), pacientes(LAB_P, { categorias: { BIRADS_4: {}, BIRADS_5: {}, BIRADS_6: {} } }));
|
||||
expect(root().querySelector('app-indicador-conteos-pareados [role=alert]')?.textContent).toContain('Respuesta incompatible');
|
||||
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
expect(root().querySelector('.published-values')).toBeNull();
|
||||
});
|
||||
it('un error de red no filtra su cuerpo, no dibuja cifras y el reintento vuelve a pedir los dos conteos', () => {
|
||||
tarjeta().setVisible(true); fixture.detectChanges();
|
||||
for (const q of pedidos()) {
|
||||
if (q.request.url.includes('paciente')) q.flush('private', { status: 500, statusText: 'Error' });
|
||||
else q.flush(examenes(LAB_E));
|
||||
}
|
||||
fixture.detectChanges();
|
||||
const alerta = root().querySelector('app-indicador-conteos-pareados [role=alert]');
|
||||
expect(alerta).not.toBeNull(); expect(alerta!.textContent).not.toContain('private');
|
||||
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
(alerta!.querySelector('button') as HTMLButtonElement).click(); fixture.detectChanges();
|
||||
expect(pedidos().length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
// Two C2 indicators of the same finding: the exams by BI-RADS category and the patients by their most severe one.
|
||||
//
|
||||
// What the kit publishes (indicadores_kit, cama/familias/birads, version 0.2.0 of both):
|
||||
// - exams: each exam counts once, in its own category;
|
||||
// - patients: each patient counts once per period, in the category of the most severe exam of that period,
|
||||
// so the patient categories are mutually exclusive and their sum is a number of different patients.
|
||||
// Adding categories inside one indicator is therefore a count of the same unit. What is not allowed is mixing
|
||||
// the two: the exams of a category include those of patients whose most severe exam is another category, so
|
||||
// no ratio of exams to patients is computed, and patients are never derived from exams.
|
||||
export interface GrupoConteo { id: string; etiqueta: string; categorias: readonly string[]; }
|
||||
export interface ParConteos {
|
||||
dominio: Dominio;
|
||||
examenes: string;
|
||||
pacientes: string;
|
||||
// Exam categories in severity order, as the donut draws them.
|
||||
categoriasExamen: readonly string[];
|
||||
// Rows of the bars: a BI-RADS family and the categories of both indicators that add up to it.
|
||||
grupos: readonly GrupoConteo[];
|
||||
// Versions of the patient indicator whose definition was checked as above; another version is not added up.
|
||||
versionesPacientes: readonly string[];
|
||||
unidades: { examenes: string; pacientes: string };
|
||||
}
|
||||
export const PARES_CONTEOS: readonly ParConteos[] = [
|
||||
{ dominio: 'cama', examenes: 'cama_birads_456_mastografia', pacientes: 'cama_birads_456_paciente',
|
||||
categoriasExamen: ['B4', 'B4A', 'B4B', 'B4C', 'B5', 'B6'],
|
||||
grupos: [
|
||||
{ id: 'BIRADS_4', etiqueta: 'BI-RADS 4', categorias: ['B4', 'B4A', 'B4B', 'B4C'] },
|
||||
{ id: 'BIRADS_5', etiqueta: 'BI-RADS 5', categorias: ['B5'] },
|
||||
{ id: 'BIRADS_6', etiqueta: 'BI-RADS 6', categorias: ['B6'] },
|
||||
],
|
||||
versionesPacientes: ['0.2.0'],
|
||||
unidades: { examenes: 'mastografías', pacientes: 'pacientes' } },
|
||||
];
|
||||
// The card of the exams draws the pair; the patients' indicator is its partner and has no card of its own.
|
||||
export const parConteos = (dominio: Dominio, id: string) => PARES_CONTEOS.find(p => p.dominio === dominio && p.examenes === id);
|
||||
export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly string[]) =>
|
||||
PARES_CONTEOS.some(p => p.dominio === dominio && p.pacientes === id && ids.includes(p.examenes));
|
||||
|
||||
// The kit publishes a 4 without subcategory as «B4», with no colour.
|
||||
const ETIQUETA_RESPALDO: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
|
||||
const COLOR_RESPALDO: Readonly<Record<string, string>> = { B4: '#E9C08C' };
|
||||
const COLOR_NEUTRO = '#8A9199';
|
||||
|
||||
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
|
||||
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
|
||||
export interface ModeloConteos {
|
||||
periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[];
|
||||
// False when the patients' version is not one whose definition was checked: their cells stay unknown.
|
||||
pacientesVerificados: boolean; notas: string[];
|
||||
}
|
||||
export class ConteosIncompatibles extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const fail = (message: string): never => { throw new ConteosIncompatibles(message); };
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
// A suppressed, unpublished or invalid cell is unknown, never zero.
|
||||
function cuenta(filas: Record<string, unknown>[], periodo: string, categoria: string): number | null {
|
||||
const fila = filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria && f['grupo'] === 'TOTAL' && (f['estrato'] ?? null) === null);
|
||||
return fila && fila['suprimido'] === 0 && typeof fila['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 ? fila['n'] : null;
|
||||
}
|
||||
const sumar = (valores: (number | null)[]) => valores.some(v => v === null) ? null : valores.reduce<number>((s, v) => s + v!, 0);
|
||||
|
||||
/** One model per period both responses publish, in chronological order. */
|
||||
export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacientes: IndicadorDatos, tipo: string): ModeloConteos[] {
|
||||
for (const [d, id] of [[examenes, par.examenes], [pacientes, par.pacientes]] as const) {
|
||||
if (d.id !== id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || !Array.isArray(d.filas) || !registro(d['categorias'])) {
|
||||
fail('Los datos no corresponden a los conteos por mastografía y por paciente.');
|
||||
}
|
||||
}
|
||||
if (examenes['unidad'] !== 'examen' || pacientes['unidad'] !== 'paciente') fail('Las unidades publicadas no son mastografías y pacientes.');
|
||||
const catExamenes = examenes['categorias'] as Record<string, unknown>, catPacientes = pacientes['categorias'] as Record<string, unknown>;
|
||||
const etiqueta = (cat: Record<string, unknown>, id: string) => {
|
||||
const publicada = registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : '';
|
||||
return publicada && publicada !== id ? publicada : ETIQUETA_RESPALDO[id] ?? id;
|
||||
};
|
||||
const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO;
|
||||
const todas = par.grupos.flatMap(g => g.categorias);
|
||||
if (par.categoriasExamen.some(id => !Object.hasOwn(catExamenes, id)) || todas.some(id => !Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id))) {
|
||||
fail('Las categorías de mastografías y pacientes no coinciden.');
|
||||
}
|
||||
const verificados = par.versionesPacientes.includes(String(pacientes['version'] ?? ''));
|
||||
const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort();
|
||||
const filasE = examenes.filas as Record<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
|
||||
return periodos.map(periodo => ({
|
||||
periodo,
|
||||
examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) })),
|
||||
// Only the exams the response reports apart; an indicator that lists no such category has none.
|
||||
sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
|
||||
filas: par.grupos.map(g => ({
|
||||
id: g.id, etiqueta: g.etiqueta,
|
||||
pacientes: verificados ? sumar(g.categorias.map(id => cuenta(filasP, periodo, id))) : null,
|
||||
examenes: sumar(g.categorias.map(id => cuenta(filasE, periodo, id))),
|
||||
})),
|
||||
pacientesVerificados: verificados,
|
||||
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
|
||||
}));
|
||||
}
|
||||
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
|
||||
|
||||
/** Exams by category around their total; nothing is drawn when a cell is unknown. */
|
||||
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
||||
const total = totalExamenes(m);
|
||||
if (!total) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
|
||||
return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)),
|
||||
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside',
|
||||
text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '<br>' + percentNumber(100 * v / total) + ' %'),
|
||||
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
|
||||
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
|
||||
layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text },
|
||||
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
|
||||
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }] }, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
|
||||
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
|
||||
const nombres = { pacientes: `${par.unidades.pacientes} (su categoría más grave)`, examenes: par.unidades.examenes };
|
||||
const textoDe = (v: number | null, clave: 'pacientes' | 'examenes') =>
|
||||
v !== null ? miles(v) : clave === 'pacientes' && !m.pacientesVerificados ? 'Pendiente' : 'Sin dato';
|
||||
const traza = (clave: 'pacientes' | 'examenes', color: string) => ({
|
||||
type: 'bar', orientation: 'h', name: nombres[clave], y, x: m.filas.map(f => f[clave]), marker: { color },
|
||||
text: m.filas.map(f => textoDe(f[clave], clave)), textposition: 'outside', cliponaxis: false,
|
||||
hovertemplate: `%{y}: %{x} ${nombres[clave]}<extra></extra>` });
|
||||
const maximo = Math.max(1, ...m.filas.map(f => f.examenes ?? 0), ...m.filas.map(f => f.pacientes ?? 0));
|
||||
return { data: [traza('pacientes', '#7A8794'), traza('examenes', '#C26A2B')],
|
||||
layout: { autosize: true, height: 400, barmode: 'group', bargap: .3, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 16, l: 96, r: 70, b: 56 }, legend: { orientation: 'h', y: -0.14, itemclick: false, itemdoubleclick: false },
|
||||
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
|
||||
xaxis: { range: [0, maximo * 1.18], gridcolor: p.grid, zeroline: false, fixedrange: true } }, config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<h2>Datos y definiciones · {{ domainNames[dominio] }}</h2>
|
||||
<h2>Datos y definiciones de {{ domainNames[dominio] }}</h2>
|
||||
<section aria-labelledby="domain-info-title">
|
||||
<h3 id="domain-info-title">Información del dominio</h3>
|
||||
<p>Dominio: {{ domainNames[dominio] }}.</p>
|
||||
@if (dominio === 'cacu') { <p>Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo espécimen fue insatisfactorio.</p> }
|
||||
@if (!loading && !error && periodTypes.length) {
|
||||
<p>Periodicidad disponible:
|
||||
@for (tipo of periodTypes; track tipo; let last = $last) { {{ periodNames[tipo] }}{{ last ? '.' : ', ' }} }
|
||||
@@ -29,10 +29,6 @@
|
||||
@if (item.tipos_periodo.length) {
|
||||
<ul>@for (tipo of item.tipos_periodo; track tipo) { <li>{{ periodNames[tipo] }}</li> }</ul>
|
||||
} @else { <p>Pendiente de información.</p> }
|
||||
<h4>Cómo interpretar este indicador</h4>
|
||||
@if (interpretation(item).length) {
|
||||
<ul>@for (line of interpretation(item); track $index) { <li>{{ line }}</li> }</ul>
|
||||
}
|
||||
@if (opened.has(dominio + ':' + item.id)) {
|
||||
<app-indicador-metadata [dominio]="dominio" [indicador]="item.id" />
|
||||
} @else {
|
||||
@@ -43,14 +39,3 @@
|
||||
}
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="definitions-methodology-title">
|
||||
<h3 id="definitions-methodology-title">Interpretación y metodología</h3>
|
||||
<p>Ten en cuenta estas limitaciones al consultar las gráficas.</p>
|
||||
<ul>
|
||||
<li>Un valor nulo significa que no hay un valor disponible; un cero es un valor observado. Los datos suprimidos tampoco representan un cero.</li>
|
||||
<li>{{ periodInterpretation }}</li>
|
||||
<li>Los periodos se presentan sin consolidar datos de distintos periodos, grupos o estratos.</li>
|
||||
<li>Los intervalos de confianza, cuando están disponibles, describen incertidumbre y no garantizan certeza poblacional; su amplitud puede verse afectada por un tamaño de muestra pequeño.</li>
|
||||
</ul>
|
||||
<p>Uso para investigación; la información no constituye aprobación clínica ni establece metas institucionales. Las notas de cada gráfica incluyen detalles adicionales para interpretar los datos mostrados.</p>
|
||||
</section>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user